Coverage for tests/test_location.py : 11%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22import copy
23import unittest
24import os.path
25import posixpath
26import pickle
27import pathlib
29from lsst.daf.butler import LocationFactory, Location, ButlerURI
30from lsst.daf.butler.core._butlerUri.utils import os2posix, posix2os
33class LocationTestCase(unittest.TestCase):
34 """Tests for Location within datastore
35 """
37 def testButlerUri(self):
38 """Tests whether ButlerURI instantiates correctly given different
39 arguments.
40 """
41 # Root to use for relative paths
42 testRoot = "/tmp/"
44 # uriStrings is a list of tuples containing test string, forceAbsolute,
45 # forceDirectory as arguments to ButlerURI and scheme, netloc and path
46 # as expected attributes. Test asserts constructed equals to expected.
47 # 1) no determinable schemes (ensures schema and netloc are not set)
48 osRelFilePath = os.path.join(testRoot, "relative/file.ext")
49 uriStrings = [
50 ("relative/file.ext", True, False, "", "", osRelFilePath),
51 ("relative/file.ext", False, False, "", "", "relative/file.ext"),
52 ("test/../relative/file.ext", True, False, "", "", osRelFilePath),
53 ("test/../relative/file.ext", False, False, "", "", "relative/file.ext"),
54 ("relative/dir", False, True, "", "", "relative/dir/")
55 ]
56 # 2) implicit file scheme, tests absolute file and directory paths
57 uriStrings.extend((
58 ("/rootDir/absolute/file.ext", True, False, "file", "", '/rootDir/absolute/file.ext'),
59 ("~/relative/file.ext", True, False, "file", "", os.path.expanduser("~/relative/file.ext")),
60 ("~/relative/file.ext", False, False, "file", "", os.path.expanduser("~/relative/file.ext")),
61 ("/rootDir/absolute/", True, False, "file", "", "/rootDir/absolute/"),
62 ("/rootDir/absolute", True, True, "file", "", "/rootDir/absolute/"),
63 ("~/rootDir/absolute", True, True, "file", "", os.path.expanduser("~/rootDir/absolute/"))
64 ))
65 # 3) explicit file scheme, absolute and relative file and directory URI
66 posixRelFilePath = posixpath.join(testRoot, "relative/file.ext")
67 uriStrings.extend((
68 ("file:///rootDir/absolute/file.ext", True, False, "file", "", "/rootDir/absolute/file.ext"),
69 ("file:relative/file.ext", True, False, "file", "", posixRelFilePath),
70 ("file:///absolute/directory/", True, False, "file", "", "/absolute/directory/"),
71 ("file:///absolute/directory", True, True, "file", "", "/absolute/directory/")
72 ))
73 # 4) S3 scheme (ensured Keys as dirs and fully specified URIs work)
74 uriStrings.extend((
75 ("s3://bucketname/rootDir/", True, False, "s3", "bucketname", "/rootDir/"),
76 ("s3://bucketname/rootDir", True, True, "s3", "bucketname", "/rootDir/"),
77 ("s3://bucketname/rootDir/relative/file.ext", True, False, "s3",
78 "bucketname", "/rootDir/relative/file.ext")
79 ))
80 # 5) HTTPS scheme
81 uriStrings.extend((
82 ("https://www.lsst.org/rootDir/", True, False, "https", "www.lsst.org", "/rootDir/"),
83 ("https://www.lsst.org/rootDir", True, True, "https", "www.lsst.org", "/rootDir/"),
84 ("https://www.lsst.org/rootDir/relative/file.ext", True, False, "https",
85 "www.lsst.org", "/rootDir/relative/file.ext")
86 ))
88 for uriInfo in uriStrings:
89 uri = ButlerURI(uriInfo[0], root=testRoot, forceAbsolute=uriInfo[1],
90 forceDirectory=uriInfo[2])
91 with self.subTest(uri=uriInfo[0]):
92 self.assertEqual(uri.scheme, uriInfo[3], "test scheme")
93 self.assertEqual(uri.netloc, uriInfo[4], "test netloc")
94 self.assertEqual(uri.path, uriInfo[5], "test path")
96 # test root becomes abspath(".") when not specified, note specific
97 # file:// scheme case
98 uriStrings = (
99 ("file://relative/file.ext", True, False, "file", "relative", "/file.ext"),
100 ("file:relative/file.ext", False, False, "file", "", os.path.abspath("relative/file.ext")),
101 ("file:relative/dir/", True, True, "file", "", os.path.abspath("relative/dir")+"/"),
102 ("relative/file.ext", True, False, "", "", os.path.abspath("relative/file.ext"))
103 )
105 for uriInfo in uriStrings:
106 uri = ButlerURI(uriInfo[0], forceAbsolute=uriInfo[1], forceDirectory=uriInfo[2])
107 with self.subTest(uri=uriInfo[0]):
108 self.assertEqual(uri.scheme, uriInfo[3], "test scheme")
109 self.assertEqual(uri.netloc, uriInfo[4], "test netloc")
110 self.assertEqual(uri.path, uriInfo[5], "test path")
112 # File replacement
113 uriStrings = (
114 ("relative/file.ext", "newfile.fits", "relative/newfile.fits"),
115 ("relative/", "newfile.fits", "relative/newfile.fits"),
116 ("https://www.lsst.org/butler/", "butler.yaml", "/butler/butler.yaml"),
117 ("s3://amazon/datastore/", "butler.yaml", "/datastore/butler.yaml"),
118 ("s3://amazon/datastore/mybutler.yaml", "butler.yaml", "/datastore/butler.yaml")
119 )
121 for uriInfo in uriStrings:
122 uri = ButlerURI(uriInfo[0], forceAbsolute=False).updatedFile(uriInfo[1])
123 with self.subTest(uri=uriInfo[0]):
124 self.assertEqual(uri.path, uriInfo[2])
126 # Check that schemeless can become file scheme
127 schemeless = ButlerURI("relative/path.ext")
128 filescheme = ButlerURI("/absolute/path.ext")
129 self.assertFalse(schemeless.scheme)
130 self.assertEqual(filescheme.scheme, "file")
131 self.assertNotEqual(type(schemeless), type(filescheme))
133 # Copy constructor
134 uri = ButlerURI("s3://amazon/datastore", forceDirectory=True)
135 uri2 = ButlerURI(uri)
136 self.assertEqual(uri, uri2)
137 uri = ButlerURI("file://amazon/datastore/file.txt")
138 uri2 = ButlerURI(uri)
139 self.assertEqual(uri, uri2)
141 # Copy constructor using subclass
142 uri3 = type(uri)(uri)
143 self.assertEqual(type(uri), type(uri3))
145 # Explicit copy
146 uri4 = copy.copy(uri3)
147 self.assertEqual(uri4, uri3)
148 uri4 = copy.deepcopy(uri3)
149 self.assertEqual(uri4, uri3)
151 def testUriRoot(self):
152 osPathRoot = pathlib.Path(__file__).absolute().root
153 rootUris = (osPathRoot, "s3://bucket", "file://localhost/", "https://a.b.com")
154 for uri_str in rootUris:
155 uri = ButlerURI(uri_str, forceDirectory=True)
156 self.assertEqual(uri.relativeToPathRoot, "./", f"Testing uri: {uri}")
157 self.assertTrue(uri.is_root, f"Testing URI {uri} is a root URI")
159 exampleLocalFile = os.path.join(osPathRoot, "a", "b", "c")
160 uriStrings = (
161 ("file://localhost/file.ext", "file.ext"),
162 (exampleLocalFile, os.path.join("a", "b", "c")),
163 ("s3://bucket/path/file.ext", "path/file.ext"),
164 ("https://host.com/a/b/c.d", "a/b/c.d"),
165 )
167 for uri_str, result in uriStrings:
168 uri = ButlerURI(uri_str)
169 self.assertEqual(uri.relativeToPathRoot, result)
171 def testUriJoin(self):
172 uri = ButlerURI("a/b/c/d", forceDirectory=True, forceAbsolute=False)
173 uri2 = uri.join("e/f/g.txt")
174 self.assertEqual(str(uri2), "a/b/c/d/e/f/g.txt", f"Checking joined URI {uri} -> {uri2}")
176 uri = ButlerURI("a/b/c/d/old.txt", forceAbsolute=False)
177 uri2 = uri.join("e/f/g.txt")
178 self.assertEqual(str(uri2), "a/b/c/d/e/f/g.txt", f"Checking joined URI {uri} -> {uri2}")
180 uri = ButlerURI("a/b/c/d", forceDirectory=True, forceAbsolute=True)
181 uri2 = uri.join("e/f/g.txt")
182 self.assertTrue(str(uri2).endswith("a/b/c/d/e/f/g.txt"), f"Checking joined URI {uri} -> {uri2}")
184 uri = ButlerURI("s3://bucket/a/b/c/d", forceDirectory=True)
185 uri2 = uri.join("newpath/newfile.txt")
186 self.assertEqual(str(uri2), "s3://bucket/a/b/c/d/newpath/newfile.txt")
188 uri = ButlerURI("s3://bucket/a/b/c/d/old.txt")
189 uri2 = uri.join("newpath/newfile.txt")
190 self.assertEqual(str(uri2), "s3://bucket/a/b/c/d/newpath/newfile.txt")
192 def testButlerUriSerialization(self):
193 """Test that we can pickle and yaml"""
194 uri = ButlerURI("a/b/c/d")
195 uri2 = pickle.loads(pickle.dumps(uri))
196 self.assertEqual(uri, uri2)
197 self.assertFalse(uri2.dirLike)
199 uri = ButlerURI("a/b/c/d", forceDirectory=True)
200 uri2 = pickle.loads(pickle.dumps(uri))
201 self.assertEqual(uri, uri2)
202 self.assertTrue(uri2.dirLike)
204 def testUriExtensions(self):
205 """Test extension extraction."""
207 files = (("file.fits.gz", ".fits.gz"),
208 ("file.fits", ".fits"),
209 ("file.fits.xz", ".fits.xz"),
210 ("file.fits.tar", ".tar"),
211 ("file", ""),
212 ("flat_i_sim_1.4_blah.fits.gz", ".fits.gz"),
213 ("flat_i_sim_1.4_blah.txt", ".txt"),
214 ("flat_i_sim_1.4_blah.fits.fz", ".fits.fz"),
215 ("flat_i_sim_1.4_blah.fits.txt", ".txt"),
216 )
218 for file, expected in files:
219 uri = ButlerURI(f"a/b/{file}")
220 self.assertEqual(uri.getExtension(), expected)
222 def testFileLocation(self):
223 root = os.path.abspath(os.path.curdir)
224 factory = LocationFactory(root)
225 print(f"Factory created: {factory}")
227 pathInStore = "relative/path/file.ext"
228 loc1 = factory.fromPath(pathInStore)
230 self.assertEqual(loc1.path, os.path.join(root, pathInStore))
231 self.assertEqual(loc1.pathInStore.path, pathInStore)
232 self.assertTrue(loc1.uri.geturl().startswith("file:///"))
233 self.assertTrue(loc1.uri.geturl().endswith("file.ext"))
234 loc1.updateExtension("fits")
235 self.assertTrue(loc1.uri.geturl().endswith("file.fits"),
236 f"Checking 'fits' extension in {loc1.uri}")
237 loc1.updateExtension("fits.gz")
238 self.assertEqual(loc1.uri.basename(), "file.fits.gz")
239 self.assertTrue(loc1.uri.geturl().endswith("file.fits.gz"),
240 f"Checking 'fits.gz' extension in {loc1.uri}")
241 self.assertEqual(loc1.getExtension(), ".fits.gz")
242 loc1.updateExtension(".jpeg")
243 self.assertTrue(loc1.uri.geturl().endswith("file.jpeg"),
244 f"Checking 'jpeg' extension in {loc1.uri}")
245 loc1.updateExtension(None)
246 self.assertTrue(loc1.uri.geturl().endswith("file.jpeg"),
247 f"Checking unchanged extension in {loc1.uri}")
248 loc1.updateExtension("")
249 self.assertTrue(loc1.uri.geturl().endswith("file"), f"Checking no extension in {loc1.uri}")
250 self.assertEqual(loc1.getExtension(), "")
252 loc2 = factory.fromPath(pathInStore)
253 loc3 = factory.fromPath(pathInStore)
254 self.assertEqual(loc2, loc3)
256 def testAbsoluteLocations(self):
257 """Using a pathInStore that refers to absolute URI."""
258 loc = Location(None, "file:///something.txt")
259 self.assertEqual(loc.pathInStore.path, "/something.txt")
260 self.assertEqual(str(loc.uri), "file:///something.txt")
262 with self.assertRaises(ValueError):
263 Location(None, "relative.txt")
265 def testRelativeRoot(self):
266 root = os.path.abspath(os.path.curdir)
267 factory = LocationFactory(os.path.curdir)
269 pathInStore = "relative/path/file.ext"
270 loc1 = factory.fromPath(pathInStore)
272 self.assertEqual(loc1.path, os.path.join(root, pathInStore))
273 self.assertEqual(loc1.pathInStore.path, pathInStore)
274 self.assertEqual(loc1.uri.scheme, "file")
276 with self.assertRaises(ValueError):
277 factory.fromPath("../something")
279 def testQuotedRoot(self):
280 """Test we can handle quoted characters."""
281 root = "/a/b/c+1/d"
282 factory = LocationFactory(root)
284 pathInStore = "relative/path/file.ext.gz"
286 for pathInStore in ("relative/path/file.ext.gz",
287 "relative/path+2/file.ext.gz",
288 "relative/path+3/file&.ext.gz"):
289 loc1 = factory.fromPath(pathInStore)
291 self.assertEqual(loc1.pathInStore.path, pathInStore)
292 self.assertEqual(loc1.path, os.path.join(root, pathInStore))
293 self.assertIn("%", str(loc1.uri))
294 self.assertEqual(loc1.getExtension(), ".ext.gz")
296 def testHttpLocation(self):
297 root = "https://www.lsst.org/butler/datastore"
298 factory = LocationFactory(root)
299 print(f"Factory created: {factory}")
301 pathInStore = "relative/path/file.ext"
302 loc1 = factory.fromPath(pathInStore)
304 self.assertEqual(loc1.path, posixpath.join("/butler/datastore", pathInStore))
305 self.assertEqual(loc1.pathInStore.path, pathInStore)
306 self.assertEqual(loc1.uri.scheme, "https")
307 self.assertEqual(loc1.uri.basename(), "file.ext")
308 loc1.updateExtension("fits")
309 self.assertTrue(loc1.uri.basename(), "file.fits")
311 def testPosix2OS(self):
312 """Test round tripping of the posix to os.path conversion helpers."""
313 testPaths = ("/a/b/c.e", "a/b", "a/b/", "/a/b", "/a/b/", "a/b/c.e")
314 for p in testPaths:
315 with self.subTest(path=p):
316 self.assertEqual(os2posix(posix2os(p)), p)
318 def testSplit(self):
319 """Tests split functionality."""
320 testRoot = "/tmp/"
322 testPaths = ("/absolute/file.ext", "/absolute/",
323 "file:///absolute/file.ext", "file:///absolute/",
324 "s3://bucket/root/file.ext", "s3://bucket/root/",
325 "https://www.lsst.org/root/file.ext", "https://www.lsst.org/root/",
326 "relative/file.ext", "relative/")
328 osRelExpected = os.path.join(testRoot, "relative")
329 expected = (("file:///absolute/", "file.ext"), ("file:///absolute/", ""),
330 ("file:///absolute/", "file.ext"), ("file:///absolute/", ""),
331 ("s3://bucket/root/", "file.ext"), ("s3://bucket/root/", ""),
332 ("https://www.lsst.org/root/", "file.ext"), ("https://www.lsst.org/root/", ""),
333 (f"file://{osRelExpected}/", "file.ext"), (f"file://{osRelExpected}/", ""))
335 for p, e in zip(testPaths, expected):
336 with self.subTest(path=p):
337 uri = ButlerURI(p, testRoot)
338 head, tail = uri.split()
339 self.assertEqual((head.geturl(), tail), e)
341 # explicit file scheme should force posixpath, check os.path is ignored
342 posixRelFilePath = posixpath.join(testRoot, "relative")
343 uri = ButlerURI("file:relative/file.ext", testRoot)
344 head, tail = uri.split()
345 self.assertEqual((head.geturl(), tail), (f"file://{posixRelFilePath}/", "file.ext"))
347 # check head can be empty and we do not get an absolute path back
348 uri = ButlerURI("file.ext", forceAbsolute=False)
349 head, tail = uri.split()
350 self.assertEqual((head.geturl(), tail), ("./", "file.ext"))
352 # ensure empty path splits to a directory URL
353 uri = ButlerURI("", forceAbsolute=False)
354 head, tail = uri.split()
355 self.assertEqual((head.geturl(), tail), ("./", ""))
357 uri = ButlerURI(".", forceAbsolute=False)
358 head, tail = uri.split()
359 self.assertEqual((head.geturl(), tail), ("./", ""))
362if __name__ == "__main__": 362 ↛ 363line 362 didn't jump to line 363, because the condition on line 362 was never true
363 unittest.main()