Hide keyboard shortcuts

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/>. 

21 

22import glob 

23import os 

24import shutil 

25import unittest 

26import urllib.parse 

27import responses 

28 

29try: 

30 import boto3 

31 import botocore 

32 from moto import mock_s3 

33except ImportError: 

34 boto3 = None 

35 

36 def mock_s3(cls): 

37 """A no-op decorator in case moto mock_s3 can not be imported. 

38 """ 

39 return cls 

40 

41from lsst.daf.butler import ButlerURI 

42from lsst.daf.butler.core._butlerUri.s3utils import (setAwsEnvCredentials, 

43 unsetAwsEnvCredentials) 

44from lsst.daf.butler.tests.utils import makeTestTempDir, removeTestTempDir 

45 

46TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

47 

48 

49class FileURITestCase(unittest.TestCase): 

50 """Concrete tests for local files""" 

51 

52 def setUp(self): 

53 # Use a local tempdir because on macOS the temp dirs use symlinks 

54 # so relsymlink gets quite confused. 

55 self.tmpdir = makeTestTempDir(TESTDIR) 

56 

57 def tearDown(self): 

58 removeTestTempDir(self.tmpdir) 

59 

60 def testFile(self): 

61 file = os.path.join(self.tmpdir, "test.txt") 

62 uri = ButlerURI(file) 

63 self.assertFalse(uri.exists(), f"{uri} should not exist") 

64 self.assertEqual(uri.ospath, file) 

65 

66 content = "abcdefghijklmnopqrstuv\n" 

67 uri.write(content.encode()) 

68 self.assertTrue(os.path.exists(file), "File should exist locally") 

69 self.assertTrue(uri.exists(), f"{uri} should now exist") 

70 self.assertEqual(uri.read().decode(), content) 

71 self.assertEqual(uri.size(), len(content.encode())) 

72 

73 with self.assertRaises(FileNotFoundError): 

74 ButlerURI("file/not/there.txt").size() 

75 

76 # Check that creating a URI from a URI returns the same thing 

77 uri2 = ButlerURI(uri) 

78 self.assertEqual(uri, uri2) 

79 self.assertEqual(id(uri), id(uri2)) 

80 

81 with self.assertRaises(ValueError): 

82 # Scheme-less URIs are not allowed to support non-file roots 

83 # at the present time. This may change in the future to become 

84 # equivalent to ButlerURI.join() 

85 ButlerURI("a/b.txt", root=ButlerURI("s3://bucket/a/b/")) 

86 

87 def testExtension(self): 

88 file = ButlerURI(os.path.join(self.tmpdir, "test.txt")) 

89 self.assertEqual(file.updatedExtension(None), file) 

90 self.assertEqual(file.updatedExtension(".txt"), file) 

91 self.assertEqual(id(file.updatedExtension(".txt")), id(file)) 

92 

93 fits = file.updatedExtension(".fits.gz") 

94 self.assertEqual(fits.basename(), "test.fits.gz") 

95 self.assertEqual(fits.updatedExtension(".jpeg").basename(), "test.jpeg") 

96 

97 def testRelative(self): 

98 """Check that we can get subpaths back from two URIs""" 

99 parent = ButlerURI(self.tmpdir, forceDirectory=True, forceAbsolute=True) 

100 self.assertTrue(parent.isdir()) 

101 child = ButlerURI(os.path.join(self.tmpdir, "dir1", "file.txt"), forceAbsolute=True) 

102 

103 self.assertEqual(child.relative_to(parent), "dir1/file.txt") 

104 

105 not_child = ButlerURI("/a/b/dir1/file.txt") 

106 self.assertIsNone(not_child.relative_to(parent)) 

107 self.assertFalse(not_child.isdir()) 

108 

109 not_directory = ButlerURI(os.path.join(self.tmpdir, "dir1", "file2.txt")) 

110 self.assertIsNone(child.relative_to(not_directory)) 

111 

112 # Relative URIs 

113 parent = ButlerURI("a/b/", forceAbsolute=False) 

114 child = ButlerURI("a/b/c/d.txt", forceAbsolute=False) 

115 self.assertFalse(child.scheme) 

116 self.assertEqual(child.relative_to(parent), "c/d.txt") 

117 

118 # File URI and schemeless URI 

119 parent = ButlerURI("file:/a/b/c/") 

120 child = ButlerURI("e/f/g.txt", forceAbsolute=False) 

121 

122 # If the child is relative and the parent is absolute we assume 

123 # that the child is a child of the parent unless it uses ".." 

124 self.assertEqual(child.relative_to(parent), "e/f/g.txt") 

125 

126 child = ButlerURI("../e/f/g.txt", forceAbsolute=False) 

127 self.assertIsNone(child.relative_to(parent)) 

128 

129 child = ButlerURI("../c/e/f/g.txt", forceAbsolute=False) 

130 self.assertEqual(child.relative_to(parent), "e/f/g.txt") 

131 

132 # Test non-file root with relative path. 

133 child = ButlerURI("e/f/g.txt", forceAbsolute=False) 

134 parent = ButlerURI("s3://hello/a/b/c/") 

135 self.assertEqual(child.relative_to(parent), "e/f/g.txt") 

136 

137 # Test with different netloc 

138 child = ButlerURI("http://my.host/a/b/c.txt") 

139 parent = ButlerURI("http://other.host/a/") 

140 self.assertIsNone(child.relative_to(parent), f"{child}.relative_to({parent})") 

141 

142 # Schemeless absolute child. 

143 # Schemeless absolute URI is constructed using root= parameter. 

144 parent = ButlerURI("file:///a/b/c/") 

145 child = ButlerURI("d/e.txt", root=parent) 

146 self.assertEqual(child.relative_to(parent), "d/e.txt", f"{child}.relative_to({parent})") 

147 

148 parent = ButlerURI("c/", root="/a/b/") 

149 self.assertEqual(child.relative_to(parent), "d/e.txt", f"{child}.relative_to({parent})") 

150 

151 # Absolute schemeless child with relative parent will always fail. 

152 parent = ButlerURI("d/e.txt", forceAbsolute=False) 

153 self.assertIsNone(child.relative_to(parent), f"{child}.relative_to({parent})") 

154 

155 def testParents(self): 

156 """Test of splitting and parent walking.""" 

157 parent = ButlerURI(self.tmpdir, forceDirectory=True, forceAbsolute=True) 

158 child_file = parent.join("subdir/file.txt") 

159 self.assertFalse(child_file.isdir()) 

160 child_subdir, file = child_file.split() 

161 self.assertEqual(file, "file.txt") 

162 self.assertTrue(child_subdir.isdir()) 

163 self.assertEqual(child_file.dirname(), child_subdir) 

164 self.assertEqual(child_file.basename(), file) 

165 self.assertEqual(child_file.parent(), child_subdir) 

166 derived_parent = child_subdir.parent() 

167 self.assertEqual(derived_parent, parent) 

168 self.assertTrue(derived_parent.isdir()) 

169 self.assertEqual(child_file.parent().parent(), parent) 

170 

171 def testEnvVar(self): 

172 """Test that environment variables are expanded.""" 

173 

174 with unittest.mock.patch.dict(os.environ, {"MY_TEST_DIR": "/a/b/c"}): 

175 uri = ButlerURI("${MY_TEST_DIR}/d.txt") 

176 self.assertEqual(uri.path, "/a/b/c/d.txt") 

177 self.assertEqual(uri.scheme, "file") 

178 

179 # This will not expand 

180 uri = ButlerURI("${MY_TEST_DIR}/d.txt", forceAbsolute=False) 

181 self.assertEqual(uri.path, "${MY_TEST_DIR}/d.txt") 

182 self.assertFalse(uri.scheme) 

183 

184 def testMkdir(self): 

185 tmpdir = ButlerURI(self.tmpdir) 

186 newdir = tmpdir.join("newdir/seconddir") 

187 newdir.mkdir() 

188 self.assertTrue(newdir.exists()) 

189 newfile = newdir.join("temp.txt") 

190 newfile.write("Data".encode()) 

191 self.assertTrue(newfile.exists()) 

192 

193 def testTransfer(self): 

194 src = ButlerURI(os.path.join(self.tmpdir, "test.txt")) 

195 content = "Content is some content\nwith something to say\n\n" 

196 src.write(content.encode()) 

197 

198 for mode in ("copy", "link", "hardlink", "symlink", "relsymlink"): 

199 dest = ButlerURI(os.path.join(self.tmpdir, f"dest_{mode}.txt")) 

200 dest.transfer_from(src, transfer=mode) 

201 self.assertTrue(dest.exists(), f"Check that {dest} exists (transfer={mode})") 

202 

203 with open(dest.ospath, "r") as fh: 

204 new_content = fh.read() 

205 self.assertEqual(new_content, content) 

206 

207 if mode in ("symlink", "relsymlink"): 

208 self.assertTrue(os.path.islink(dest.ospath), f"Check that {dest} is symlink") 

209 

210 # If the source and destination are hardlinks of each other 

211 # the transfer should work even if overwrite=False. 

212 if mode in ("link", "hardlink"): 

213 dest.transfer_from(src, transfer=mode) 

214 else: 

215 with self.assertRaises(FileExistsError, 

216 msg=f"Overwrite of {dest} should not be allowed ({mode})"): 

217 dest.transfer_from(src, transfer=mode) 

218 

219 dest.transfer_from(src, transfer=mode, overwrite=True) 

220 

221 os.remove(dest.ospath) 

222 

223 b = src.read() 

224 self.assertEqual(b.decode(), new_content) 

225 

226 nbytes = 10 

227 subset = src.read(size=nbytes) 

228 self.assertEqual(len(subset), nbytes) 

229 self.assertEqual(subset.decode(), content[:nbytes]) 

230 

231 with self.assertRaises(ValueError): 

232 src.transfer_from(src, transfer="unknown") 

233 

234 def testTransferIdentical(self): 

235 """Test overwrite of identical files.""" 

236 dir1 = ButlerURI(os.path.join(self.tmpdir, "dir1"), forceDirectory=True) 

237 dir1.mkdir() 

238 dir2 = os.path.join(self.tmpdir, "dir2") 

239 os.symlink(dir1.ospath, dir2) 

240 

241 # Write a test file. 

242 src_file = dir1.join("test.txt") 

243 content = "0123456" 

244 src_file.write(content.encode()) 

245 

246 # Construct URI to destination that should be identical. 

247 dest_file = ButlerURI(os.path.join(dir2), forceDirectory=True).join("test.txt") 

248 self.assertTrue(dest_file.exists()) 

249 self.assertNotEqual(src_file, dest_file) 

250 

251 # Transfer it over itself. 

252 dest_file.transfer_from(src_file, transfer="symlink", overwrite=True) 

253 new_content = dest_file.read().decode() 

254 self.assertEqual(content, new_content) 

255 

256 def testResource(self): 

257 u = ButlerURI("resource://lsst.daf.butler/configs/datastore.yaml") 

258 self.assertTrue(u.exists(), f"Check {u} exists") 

259 

260 content = u.read().decode() 

261 self.assertTrue(content.startswith("datastore:")) 

262 

263 truncated = u.read(size=9).decode() 

264 self.assertEqual(truncated, "datastore") 

265 

266 d = ButlerURI("resource://lsst.daf.butler/configs", forceDirectory=True) 

267 self.assertTrue(u.exists(), f"Check directory {d} exists") 

268 

269 j = d.join("datastore.yaml") 

270 self.assertEqual(u, j) 

271 self.assertFalse(j.dirLike) 

272 self.assertFalse(j.isdir()) 

273 not_there = d.join("not-there.yaml") 

274 self.assertFalse(not_there.exists()) 

275 

276 bad = ButlerURI("resource://bad.module/not.yaml") 

277 multi = ButlerURI.mexists([u, bad, not_there]) 

278 self.assertTrue(multi[u]) 

279 self.assertFalse(multi[bad]) 

280 self.assertFalse(multi[not_there]) 

281 

282 def testEscapes(self): 

283 """Special characters in file paths""" 

284 src = ButlerURI("bbb/???/test.txt", root=self.tmpdir, forceAbsolute=True) 

285 self.assertFalse(src.scheme) 

286 src.write(b"Some content") 

287 self.assertTrue(src.exists()) 

288 

289 # abspath always returns a file scheme 

290 file = src.abspath() 

291 self.assertTrue(file.exists()) 

292 self.assertIn("???", file.ospath) 

293 self.assertNotIn("???", file.path) 

294 

295 file = file.updatedFile("tests??.txt") 

296 self.assertNotIn("??.txt", file.path) 

297 file.write(b"Other content") 

298 self.assertEqual(file.read(), b"Other content") 

299 

300 src = src.updatedFile("tests??.txt") 

301 self.assertIn("??.txt", src.path) 

302 self.assertEqual(file.read(), src.read(), f"reading from {file.ospath} and {src.ospath}") 

303 

304 # File URI and schemeless URI 

305 parent = ButlerURI("file:" + urllib.parse.quote("/a/b/c/de/??/")) 

306 child = ButlerURI("e/f/g.txt", forceAbsolute=False) 

307 self.assertEqual(child.relative_to(parent), "e/f/g.txt") 

308 

309 child = ButlerURI("e/f??#/g.txt", forceAbsolute=False) 

310 self.assertEqual(child.relative_to(parent), "e/f??#/g.txt") 

311 

312 child = ButlerURI("file:" + urllib.parse.quote("/a/b/c/de/??/e/f??#/g.txt")) 

313 self.assertEqual(child.relative_to(parent), "e/f??#/g.txt") 

314 

315 self.assertEqual(child.relativeToPathRoot, "a/b/c/de/??/e/f??#/g.txt") 

316 

317 # Schemeless so should not quote 

318 dir = ButlerURI("bbb/???/", root=self.tmpdir, forceAbsolute=True, forceDirectory=True) 

319 self.assertIn("???", dir.ospath) 

320 self.assertIn("???", dir.path) 

321 self.assertFalse(dir.scheme) 

322 

323 # dir.join() morphs into a file scheme 

324 new = dir.join("test_j.txt") 

325 self.assertIn("???", new.ospath, f"Checking {new}") 

326 new.write(b"Content") 

327 

328 new2name = "###/test??.txt" 

329 new2 = dir.join(new2name) 

330 self.assertIn("???", new2.ospath) 

331 new2.write(b"Content") 

332 self.assertTrue(new2.ospath.endswith(new2name)) 

333 self.assertEqual(new.read(), new2.read()) 

334 

335 fdir = dir.abspath() 

336 self.assertNotIn("???", fdir.path) 

337 self.assertIn("???", fdir.ospath) 

338 self.assertEqual(fdir.scheme, "file") 

339 fnew = dir.join("test_jf.txt") 

340 fnew.write(b"Content") 

341 

342 fnew2 = fdir.join(new2name) 

343 fnew2.write(b"Content") 

344 self.assertTrue(fnew2.ospath.endswith(new2name)) 

345 self.assertNotIn("###", fnew2.path) 

346 

347 self.assertEqual(fnew.read(), fnew2.read()) 

348 

349 # Test that children relative to schemeless and file schemes 

350 # still return the same unquoted name 

351 self.assertEqual(fnew2.relative_to(fdir), new2name, f"{fnew2}.relative_to({fdir})") 

352 self.assertEqual(fnew2.relative_to(dir), new2name, f"{fnew2}.relative_to({dir})") 

353 self.assertEqual(new2.relative_to(fdir), new2name, f"{new2}.relative_to({fdir})") 

354 self.assertEqual(new2.relative_to(dir), new2name, f"{new2}.relative_to({dir})") 

355 

356 # Check for double quoting 

357 plus_path = "/a/b/c+d/" 

358 with self.assertLogs(level="WARNING"): 

359 uri = ButlerURI(urllib.parse.quote(plus_path), forceDirectory=True) 

360 self.assertEqual(uri.ospath, plus_path) 

361 

362 # Check that # is not escaped for schemeless URIs 

363 hash_path = "/a/b#/c&d#xyz" 

364 hpos = hash_path.rfind("#") 

365 uri = ButlerURI(hash_path) 

366 self.assertEqual(uri.ospath, hash_path[:hpos]) 

367 self.assertEqual(uri.fragment, hash_path[hpos + 1:]) 

368 

369 def testHash(self): 

370 """Test that we can store URIs in sets and as keys.""" 

371 uri1 = ButlerURI(TESTDIR) 

372 uri2 = uri1.join("test/") 

373 s = {uri1, uri2} 

374 self.assertIn(uri1, s) 

375 

376 d = {uri1: "1", uri2: "2"} 

377 self.assertEqual(d[uri2], "2") 

378 

379 def testWalk(self): 

380 """Test ButlerURI.walk().""" 

381 test_dir_uri = ButlerURI(TESTDIR) 

382 

383 file = test_dir_uri.join("config/basic/butler.yaml") 

384 found = list(ButlerURI.findFileResources([file])) 

385 self.assertEqual(found[0], file) 

386 

387 # Compare against the full local paths 

388 expected = set(p for p in glob.glob(os.path.join(TESTDIR, "config", "**"), recursive=True) 

389 if os.path.isfile(p)) 

390 found = set(u.ospath for u in ButlerURI.findFileResources([test_dir_uri.join("config")])) 

391 self.assertEqual(found, expected) 

392 

393 # Now solely the YAML files 

394 expected_yaml = set(glob.glob(os.path.join(TESTDIR, "config", "**", "*.yaml"), recursive=True)) 

395 found = set(u.ospath for u in ButlerURI.findFileResources([test_dir_uri.join("config")], 

396 file_filter=r".*\.yaml$")) 

397 self.assertEqual(found, expected_yaml) 

398 

399 # Now two explicit directories and a file 

400 expected = set(glob.glob(os.path.join(TESTDIR, "config", "**", "basic", "*.yaml"), recursive=True)) 

401 expected.update(set(glob.glob(os.path.join(TESTDIR, "config", "**", "templates", "*.yaml"), 

402 recursive=True))) 

403 expected.add(file.ospath) 

404 

405 found = set(u.ospath for u in ButlerURI.findFileResources([file, test_dir_uri.join("config/basic"), 

406 test_dir_uri.join("config/templates")], 

407 file_filter=r".*\.yaml$")) 

408 self.assertEqual(found, expected) 

409 

410 # Group by directory -- find everything and compare it with what 

411 # we expected to be there in total. We expect to find 9 directories 

412 # containing yaml files so make sure we only iterate 9 times. 

413 found_yaml = set() 

414 counter = 0 

415 for uris in ButlerURI.findFileResources([file, test_dir_uri.join("config/")], 

416 file_filter=r".*\.yaml$", grouped=True): 

417 found = set(u.ospath for u in uris) 

418 if found: 

419 counter += 1 

420 

421 found_yaml.update(found) 

422 

423 self.assertEqual(found_yaml, expected_yaml) 

424 self.assertEqual(counter, 9) 

425 

426 # Grouping but check that single files are returned in a single group 

427 # at the end 

428 file2 = test_dir_uri.join("config/templates/templates-bad.yaml") 

429 found = list(ButlerURI.findFileResources([file, file2, test_dir_uri.join("config/dbAuth")], 

430 grouped=True)) 

431 self.assertEqual(len(found), 2) 

432 self.assertEqual(list(found[1]), [file, file2]) 

433 

434 with self.assertRaises(ValueError): 

435 list(file.walk()) 

436 

437 def testRootURI(self): 

438 """Test ButlerURI.root_uri().""" 

439 uri = ButlerURI("https://www.notexist.com:8080/file/test") 

440 uri2 = ButlerURI("s3://www.notexist.com/file/test") 

441 self.assertEqual(uri.root_uri().geturl(), "https://www.notexist.com:8080/") 

442 self.assertEqual(uri2.root_uri().geturl(), "s3://www.notexist.com/") 

443 

444 def testJoin(self): 

445 """Test .join method.""" 

446 

447 root_str = "s3://bucket/hsc/payload/" 

448 root = ButlerURI(root_str) 

449 

450 self.assertEqual(root.join("b/test.txt").geturl(), f"{root_str}b/test.txt") 

451 add_dir = root.join("b/c/d/") 

452 self.assertTrue(add_dir.isdir()) 

453 self.assertEqual(add_dir.geturl(), f"{root_str}b/c/d/") 

454 

455 quote_example = "b&c.t@x#t" 

456 needs_quote = root.join(quote_example) 

457 self.assertEqual(needs_quote.unquoted_path, f"/hsc/payload/{quote_example}") 

458 

459 other = ButlerURI("file://localhost/test.txt") 

460 self.assertEqual(root.join(other), other) 

461 self.assertEqual(other.join("b/new.txt").geturl(), "file://localhost/b/new.txt") 

462 

463 joined = ButlerURI("s3://bucket/hsc/payload/").join(ButlerURI("test.qgraph", forceAbsolute=False)) 

464 self.assertEqual(joined, ButlerURI("s3://bucket/hsc/payload/test.qgraph")) 

465 

466 with self.assertRaises(ValueError): 

467 ButlerURI("s3://bucket/hsc/payload/").join(ButlerURI("test.qgraph")) 

468 

469 def testTemporary(self): 

470 with ButlerURI.temporary_uri(suffix=".json") as tmp: 

471 self.assertEqual(tmp.getExtension(), ".json", f"uri: {tmp}") 

472 self.assertTrue(tmp.isabs(), f"uri: {tmp}") 

473 self.assertFalse(tmp.exists(), f"uri: {tmp}") 

474 tmp.write(b"abcd") 

475 self.assertTrue(tmp.exists(), f"uri: {tmp}") 

476 self.assertTrue(tmp.isTemporary) 

477 self.assertFalse(tmp.exists(), f"uri: {tmp}") 

478 

479 tmpdir = ButlerURI(self.tmpdir, forceDirectory=True) 

480 with ButlerURI.temporary_uri(prefix=tmpdir, suffix=".yaml") as tmp: 

481 # Use a specified tmpdir and check it is okay for the file 

482 # to not be created. 

483 self.assertFalse(tmp.exists(), f"uri: {tmp}") 

484 self.assertTrue(tmpdir.exists(), f"uri: {tmpdir} still exists") 

485 

486 

487@unittest.skipIf(not boto3, "Warning: boto3 AWS SDK not found!") 

488@mock_s3 

489class S3URITestCase(unittest.TestCase): 

490 """Tests involving S3""" 

491 

492 bucketName = "any_bucket" 

493 """Bucket name to use in tests""" 

494 

495 def setUp(self): 

496 # Local test directory 

497 self.tmpdir = makeTestTempDir(TESTDIR) 

498 

499 # set up some fake credentials if they do not exist 

500 self.usingDummyCredentials = setAwsEnvCredentials() 

501 

502 # MOTO needs to know that we expect Bucket bucketname to exist 

503 s3 = boto3.resource("s3") 

504 s3.create_bucket(Bucket=self.bucketName) 

505 

506 def tearDown(self): 

507 s3 = boto3.resource("s3") 

508 bucket = s3.Bucket(self.bucketName) 

509 try: 

510 bucket.objects.all().delete() 

511 except botocore.exceptions.ClientError as e: 

512 if e.response["Error"]["Code"] == "404": 

513 # the key was not reachable - pass 

514 pass 

515 else: 

516 raise 

517 

518 bucket = s3.Bucket(self.bucketName) 

519 bucket.delete() 

520 

521 # unset any potentially set dummy credentials 

522 if self.usingDummyCredentials: 

523 unsetAwsEnvCredentials() 

524 

525 shutil.rmtree(self.tmpdir, ignore_errors=True) 

526 

527 def makeS3Uri(self, path): 

528 return f"s3://{self.bucketName}/{path}" 

529 

530 def testTransfer(self): 

531 src = ButlerURI(os.path.join(self.tmpdir, "test.txt")) 

532 content = "Content is some content\nwith something to say\n\n" 

533 src.write(content.encode()) 

534 self.assertTrue(src.exists()) 

535 self.assertEqual(src.size(), len(content.encode())) 

536 

537 dest = ButlerURI(self.makeS3Uri("test.txt")) 

538 self.assertFalse(dest.exists()) 

539 

540 with self.assertRaises(FileNotFoundError): 

541 dest.size() 

542 

543 dest.transfer_from(src, transfer="copy") 

544 self.assertTrue(dest.exists()) 

545 

546 dest2 = ButlerURI(self.makeS3Uri("copied.txt")) 

547 dest2.transfer_from(dest, transfer="copy") 

548 self.assertTrue(dest2.exists()) 

549 

550 local = ButlerURI(os.path.join(self.tmpdir, "copied.txt")) 

551 local.transfer_from(dest2, transfer="copy") 

552 with open(local.ospath, "r") as fd: 

553 new_content = fd.read() 

554 self.assertEqual(new_content, content) 

555 

556 with self.assertRaises(ValueError): 

557 dest2.transfer_from(local, transfer="symlink") 

558 

559 b = dest.read() 

560 self.assertEqual(b.decode(), new_content) 

561 

562 nbytes = 10 

563 subset = dest.read(size=nbytes) 

564 self.assertEqual(len(subset), nbytes) # Extra byte comes back 

565 self.assertEqual(subset.decode(), content[:nbytes]) 

566 

567 with self.assertRaises(FileExistsError): 

568 dest.transfer_from(src, transfer="copy") 

569 

570 dest.transfer_from(src, transfer="copy", overwrite=True) 

571 

572 def testWalk(self): 

573 """Test that we can list an S3 bucket""" 

574 # Files we want to create 

575 expected = ("a/x.txt", "a/y.txt", "a/z.json", "a/b/w.txt", "a/b/c/d/v.json") 

576 expected_uris = [ButlerURI(self.makeS3Uri(path)) for path in expected] 

577 for uri in expected_uris: 

578 # Doesn't matter what we write 

579 uri.write("123".encode()) 

580 

581 # Find all the files in the a/ tree 

582 found = set(uri.path for uri in ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("a/"))])) 

583 self.assertEqual(found, {uri.path for uri in expected_uris}) 

584 

585 # Find all the files in the a/ tree but group by folder 

586 found = ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("a/"))], 

587 grouped=True) 

588 expected = (("/a/x.txt", "/a/y.txt", "/a/z.json"), ("/a/b/w.txt",), ("/a/b/c/d/v.json",)) 

589 

590 for got, expect in zip(found, expected): 

591 self.assertEqual(tuple(u.path for u in got), expect) 

592 

593 # Find only JSON files 

594 found = set(uri.path for uri in ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("a/"))], 

595 file_filter=r"\.json$")) 

596 self.assertEqual(found, {uri.path for uri in expected_uris if uri.path.endswith(".json")}) 

597 

598 # JSON files grouped by directory 

599 found = ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("a/"))], 

600 file_filter=r"\.json$", grouped=True) 

601 expected = (("/a/z.json",), ("/a/b/c/d/v.json",)) 

602 

603 for got, expect in zip(found, expected): 

604 self.assertEqual(tuple(u.path for u in got), expect) 

605 

606 # Check pagination works with large numbers of files. S3 API limits 

607 # us to 1000 response per list_objects call so create lots of files 

608 created = set() 

609 counter = 1 

610 n_dir1 = 1100 

611 while counter <= n_dir1: 

612 new = ButlerURI(self.makeS3Uri(f"test/file{counter:04d}.txt")) 

613 new.write(f"{counter}".encode()) 

614 created.add(str(new)) 

615 counter += 1 

616 counter = 1 

617 # Put some in a subdirectory to make sure we are looking in a 

618 # hierarchy. 

619 n_dir2 = 100 

620 while counter <= n_dir2: 

621 new = ButlerURI(self.makeS3Uri(f"test/subdir/file{counter:04d}.txt")) 

622 new.write(f"{counter}".encode()) 

623 created.add(str(new)) 

624 counter += 1 

625 

626 found = ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("test/"))]) 

627 self.assertEqual({str(u) for u in found}, created) 

628 

629 # Again with grouping. 

630 found = list(ButlerURI.findFileResources([ButlerURI(self.makeS3Uri("test/"))], grouped=True)) 

631 self.assertEqual(len(found), 2) 

632 dir_1 = list(found[0]) 

633 dir_2 = list(found[1]) 

634 self.assertEqual(len(dir_1), n_dir1) 

635 self.assertEqual(len(dir_2), n_dir2) 

636 

637 def testWrite(self): 

638 s3write = ButlerURI(self.makeS3Uri("created.txt")) 

639 content = "abcdefghijklmnopqrstuv\n" 

640 s3write.write(content.encode()) 

641 self.assertEqual(s3write.read().decode(), content) 

642 

643 def testTemporary(self): 

644 s3root = ButlerURI(self.makeS3Uri("rootdir"), forceDirectory=True) 

645 with ButlerURI.temporary_uri(prefix=s3root, suffix=".json") as tmp: 

646 self.assertEqual(tmp.getExtension(), ".json", f"uri: {tmp}") 

647 self.assertEqual(tmp.scheme, "s3", f"uri: {tmp}") 

648 self.assertEqual(tmp.parent(), s3root) 

649 basename = tmp.basename() 

650 content = "abcd" 

651 tmp.write(content.encode()) 

652 self.assertTrue(tmp.exists(), f"uri: {tmp}") 

653 self.assertFalse(tmp.exists()) 

654 

655 # Again without writing anything, to check that there is no complaint 

656 # on exit of context manager. 

657 with ButlerURI.temporary_uri(prefix=s3root, suffix=".json") as tmp: 

658 self.assertFalse(tmp.exists()) 

659 # Check that the file has a different name than before. 

660 self.assertNotEqual(tmp.basename(), basename, f"uri: {tmp}") 

661 self.assertFalse(tmp.exists()) 

662 

663 def testRelative(self): 

664 """Check that we can get subpaths back from two URIs""" 

665 parent = ButlerURI(self.makeS3Uri("rootdir"), forceDirectory=True) 

666 child = ButlerURI(self.makeS3Uri("rootdir/dir1/file.txt")) 

667 

668 self.assertEqual(child.relative_to(parent), "dir1/file.txt") 

669 

670 not_child = ButlerURI(self.makeS3Uri("/a/b/dir1/file.txt")) 

671 self.assertFalse(not_child.relative_to(parent)) 

672 

673 not_s3 = ButlerURI(os.path.join(self.tmpdir, "dir1", "file2.txt")) 

674 self.assertFalse(child.relative_to(not_s3)) 

675 

676 def testQuoting(self): 

677 """Check that quoting works.""" 

678 parent = ButlerURI(self.makeS3Uri("rootdir"), forceDirectory=True) 

679 subpath = "rootdir/dir1+/file?.txt" 

680 child = ButlerURI(self.makeS3Uri(urllib.parse.quote(subpath))) 

681 

682 self.assertEqual(child.relative_to(parent), "dir1+/file?.txt") 

683 self.assertEqual(child.basename(), "file?.txt") 

684 self.assertEqual(child.relativeToPathRoot, subpath) 

685 self.assertIn("%", child.path) 

686 self.assertEqual(child.unquoted_path, "/" + subpath) 

687 

688 

689# Mock required environment variables during tests 

690@unittest.mock.patch.dict(os.environ, {"LSST_BUTLER_WEBDAV_AUTH": "TOKEN", 

691 "LSST_BUTLER_WEBDAV_TOKEN_FILE": os.path.join( 

692 TESTDIR, "config/testConfigs/webdav/token"), 

693 "LSST_BUTLER_WEBDAV_CA_BUNDLE": "/path/to/ca/certs"}) 

694class WebdavURITestCase(unittest.TestCase): 

695 

696 def setUp(self): 

697 serverRoot = "www.not-exists.orgx" 

698 existingFolderName = "existingFolder" 

699 existingFileName = "existingFile" 

700 notExistingFileName = "notExistingFile" 

701 

702 self.baseURL = ButlerURI( 

703 f"https://{serverRoot}", forceDirectory=True) 

704 self.existingFileButlerURI = ButlerURI( 

705 f"https://{serverRoot}/{existingFolderName}/{existingFileName}") 

706 self.notExistingFileButlerURI = ButlerURI( 

707 f"https://{serverRoot}/{existingFolderName}/{notExistingFileName}") 

708 self.existingFolderButlerURI = ButlerURI( 

709 f"https://{serverRoot}/{existingFolderName}", forceDirectory=True) 

710 self.notExistingFolderButlerURI = ButlerURI( 

711 f"https://{serverRoot}/{notExistingFileName}", forceDirectory=True) 

712 

713 # Need to declare the options 

714 responses.add(responses.OPTIONS, 

715 self.baseURL.geturl(), 

716 status=200, headers={"DAV": "1,2,3"}) 

717 

718 # Used by ButlerHttpURI.exists() 

719 responses.add(responses.HEAD, 

720 self.existingFileButlerURI.geturl(), 

721 status=200, headers={'Content-Length': '1024'}) 

722 responses.add(responses.HEAD, 

723 self.notExistingFileButlerURI.geturl(), 

724 status=404) 

725 

726 # Used by ButlerHttpURI.read() 

727 responses.add(responses.GET, 

728 self.existingFileButlerURI.geturl(), 

729 status=200, 

730 body=str.encode("It works!")) 

731 responses.add(responses.GET, 

732 self.notExistingFileButlerURI.geturl(), 

733 status=404) 

734 

735 # Used by ButlerHttpURI.write() 

736 responses.add(responses.PUT, 

737 self.existingFileButlerURI.geturl(), 

738 status=201) 

739 

740 # Used by ButlerHttpURI.transfer_from() 

741 responses.add(responses.Response(url=self.existingFileButlerURI.geturl(), 

742 method="COPY", 

743 headers={"Destination": self.existingFileButlerURI.geturl()}, 

744 status=201)) 

745 responses.add(responses.Response(url=self.existingFileButlerURI.geturl(), 

746 method="COPY", 

747 headers={"Destination": self.notExistingFileButlerURI.geturl()}, 

748 status=201)) 

749 responses.add(responses.Response(url=self.existingFileButlerURI.geturl(), 

750 method="MOVE", 

751 headers={"Destination": self.notExistingFileButlerURI.geturl()}, 

752 status=201)) 

753 

754 # Used by ButlerHttpURI.remove() 

755 responses.add(responses.DELETE, 

756 self.existingFileButlerURI.geturl(), 

757 status=200) 

758 responses.add(responses.DELETE, 

759 self.notExistingFileButlerURI.geturl(), 

760 status=404) 

761 

762 # Used by ButlerHttpURI.mkdir() 

763 responses.add(responses.HEAD, 

764 self.existingFolderButlerURI.geturl(), 

765 status=200, headers={'Content-Length': '1024'}) 

766 responses.add(responses.HEAD, 

767 self.baseURL.geturl(), 

768 status=200, headers={'Content-Length': '1024'}) 

769 responses.add(responses.HEAD, 

770 self.notExistingFolderButlerURI.geturl(), 

771 status=404) 

772 responses.add(responses.Response(url=self.notExistingFolderButlerURI.geturl(), 

773 method="MKCOL", 

774 status=201)) 

775 responses.add(responses.Response(url=self.existingFolderButlerURI.geturl(), 

776 method="MKCOL", 

777 status=403)) 

778 

779 @responses.activate 

780 def testExists(self): 

781 

782 self.assertTrue(self.existingFileButlerURI.exists()) 

783 self.assertFalse(self.notExistingFileButlerURI.exists()) 

784 

785 self.assertEqual(self.existingFileButlerURI.size(), 1024) 

786 with self.assertRaises(FileNotFoundError): 

787 self.notExistingFileButlerURI.size() 

788 

789 @responses.activate 

790 def testRemove(self): 

791 

792 self.assertIsNone(self.existingFileButlerURI.remove()) 

793 with self.assertRaises(FileNotFoundError): 

794 self.notExistingFileButlerURI.remove() 

795 

796 @responses.activate 

797 def testMkdir(self): 

798 

799 # The mock means that we can't check this now exists 

800 self.notExistingFolderButlerURI.mkdir() 

801 

802 # This should do nothing 

803 self.existingFolderButlerURI.mkdir() 

804 

805 with self.assertRaises(ValueError): 

806 self.notExistingFileButlerURI.mkdir() 

807 

808 @responses.activate 

809 def testRead(self): 

810 

811 self.assertEqual(self.existingFileButlerURI.read().decode(), "It works!") 

812 self.assertNotEqual(self.existingFileButlerURI.read().decode(), "Nope.") 

813 with self.assertRaises(FileNotFoundError): 

814 self.notExistingFileButlerURI.read() 

815 

816 @responses.activate 

817 def testWrite(self): 

818 

819 self.assertIsNone(self.existingFileButlerURI.write(data=str.encode("Some content."))) 

820 with self.assertRaises(FileExistsError): 

821 self.existingFileButlerURI.write(data=str.encode("Some content."), overwrite=False) 

822 

823 @responses.activate 

824 def testTransfer(self): 

825 

826 self.assertIsNone(self.notExistingFileButlerURI.transfer_from( 

827 src=self.existingFileButlerURI)) 

828 self.assertIsNone(self.notExistingFileButlerURI.transfer_from( 

829 src=self.existingFileButlerURI, 

830 transfer="move")) 

831 with self.assertRaises(FileExistsError): 

832 self.existingFileButlerURI.transfer_from(src=self.existingFileButlerURI) 

833 with self.assertRaises(ValueError): 

834 self.notExistingFileButlerURI.transfer_from( 

835 src=self.existingFileButlerURI, 

836 transfer="unsupported") 

837 

838 def testParent(self): 

839 

840 self.assertEqual(self.existingFolderButlerURI.geturl(), 

841 self.notExistingFileButlerURI.parent().geturl()) 

842 self.assertEqual(self.baseURL.geturl(), 

843 self.baseURL.parent().geturl()) 

844 self.assertEqual(self.existingFileButlerURI.parent().geturl(), 

845 self.existingFileButlerURI.dirname().geturl()) 

846 

847 

848if __name__ == "__main__": 848 ↛ 849line 848 didn't jump to line 849, because the condition on line 848 was never true

849 unittest.main()