Debian Codegraph @

python/mozbuild/mozpack/test/test_files.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 from mozbuild.dirutils import ensureParentDir
6 from mozbuild.util import ensure_bytes
7 from mozpack.errors import ErrorMessage, errors
8 from mozpack.files import (
9 AbsoluteSymlinkFile,
10 ComposedFinder,
11 DeflatedFile,
12 Dest,
13 ExistingFile,
14 ExtractedTarFile,
15 File,
16 FileFinder,
17 GeneratedFile,
18 HardlinkFile,
19 JarFinder,
20 ManifestFile,
21 MercurialFile,
22 MercurialRevisionFinder,
23 MinifiedCommentStripped,
24 MinifiedJavaScript,
25 PreprocessedFile,
26 TarFinder,
27 )
28
29 # We don't have hglib installed everywhere.
30 try:
31 import hglib
32 except ImportError:
33 hglib = None
34
35 import os
36 import platform
37 import random
38 import sys
39 import tarfile
40 import unittest
41 from io import BytesIO, StringIO
42 from tempfile import mkdtemp
43
44 import mozfile
45 import mozunit
46
47 import mozpack.path as mozpath
48 from mozpack.chrome.manifest import (
49 ManifestContent,
50 ManifestLocale,
51 ManifestOverride,
52 ManifestResource,
53 )
54 from mozpack.mozjar import JarReader, JarWriter
55
56
57 class TestWithTmpDir(unittest.TestCase):
58 def setUp(self):
59 self.tmpdir = mkdtemp()
60
61 self.symlink_supported = False
62 self.hardlink_supported = False
63
64 # See comment in mozpack.files.AbsoluteSymlinkFile
65 if hasattr(os, "symlink") and platform.system() != "Windows":
66 dummy_path = self.tmppath("dummy_file")
67 with open(dummy_path, "a"):
68 pass
69
70 try:
71 os.symlink(dummy_path, self.tmppath("dummy_symlink"))
72 os.remove(self.tmppath("dummy_symlink"))
73 except OSError:
74 pass
75 finally:
76 os.remove(dummy_path)
77
78 self.symlink_supported = True
79
80 if hasattr(os, "link"):
81 dummy_path = self.tmppath("dummy_file")
82 with open(dummy_path, "a"):
83 pass
84
85 try:
86 os.link(dummy_path, self.tmppath("dummy_hardlink"))
87 os.remove(self.tmppath("dummy_hardlink"))
88 except OSError:
89 pass
90 finally:
91 os.remove(dummy_path)
92
93 self.hardlink_supported = True
94
95 def tearDown(self):
96 mozfile.rmtree(self.tmpdir)
97
98 def tmppath(self, relpath):
99 return os.path.normpath(os.path.join(self.tmpdir, relpath))
100
101
102 class MockDest(BytesIO, Dest):
103 def __init__(self):
104 BytesIO.__init__(self)
105 self.mode = None
106
107 def read(self, length=-1):
108 if self.mode != "r":
109 self.seek(0)
110 self.mode = "r"
111 return BytesIO.read(self, length)
112
113 def write(self, data):
114 if self.mode != "w":
115 self.seek(0)
116 self.truncate(0)
117 self.mode = "w"
118 return BytesIO.write(self, data)
119
120 def exists(self):
121 return True
122
123 def close(self):
124 if self.mode:
125 self.mode = None
126
127
128 class DestNoWrite(Dest):
129 def write(self, data):
130 raise RuntimeError
131
132
133 class TestDest(TestWithTmpDir):
134 def test_dest(self):
135 dest = Dest(self.tmppath("dest"))
136 self.assertFalse(dest.exists())
137 dest.write(b"foo")
138 self.assertTrue(dest.exists())
139 dest.write(b"foo")
140 self.assertEqual(dest.read(4), b"foof")
141 self.assertEqual(dest.read(), b"oo")
142 self.assertEqual(dest.read(), b"")
143 dest.write(b"bar")
144 self.assertEqual(dest.read(4), b"bar")
145 dest.close()
146 self.assertEqual(dest.read(), b"bar")
147 dest.write(b"foo")
148 dest.close()
149 dest.write(b"qux")
150 self.assertEqual(dest.read(), b"qux")
151
152
153 rand = bytes(
154 random.choice(b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
155 for i in range(131597)
156 )
157 samples = [
158 b"",
159 b"test",
160 b"fooo",
161 b"same",
162 b"same",
163 b"Different and longer",
164 rand,
165 rand,
166 rand[:-1] + b"_",
167 b"test",
168 ]
169
170
171 class TestFile(TestWithTmpDir):
172 def test_file(self):
173 """
174 Check that File.copy yields the proper content in the destination file
175 in all situations that trigger different code paths:
176 - different content
177 - different content of the same size
178 - same content
179 - long content
180 """
181 src = self.tmppath("src")
182 dest = self.tmppath("dest")
183
184 for content in samples:
185 with open(src, "wb") as tmp:
186 tmp.write(content)
187 # Ensure the destination file, when it exists, is older than the
188 # source
189 if os.path.exists(dest):
190 time = os.path.getmtime(src) - 1
191 os.utime(dest, (time, time))
192 f = File(src)
193 f.copy(dest)
194 self.assertEqual(content, open(dest, "rb").read())
195 self.assertEqual(content, f.open().read())
196 self.assertEqual(content, f.open().read())
197
198 def test_file_dest(self):
199 """
200 Similar to test_file, but for a destination object instead of
201 a destination file. This ensures the destination object is being
202 used properly by File.copy, ensuring that other subclasses of Dest
203 will work.
204 """
205 src = self.tmppath("src")
206 dest = MockDest()
207
208 for content in samples:
209 with open(src, "wb") as tmp:
210 tmp.write(content)
211 f = File(src)
212 f.copy(dest)
213 self.assertEqual(content, dest.getvalue())
214
215 def test_file_open(self):
216 """
217 Test whether File.open returns an appropriately reset file object.
218 """
219 src = self.tmppath("src")
220 content = b"".join(samples)
221 with open(src, "wb") as tmp:
222 tmp.write(content)
223
224 f = File(src)
225 self.assertEqual(content[:42], f.open().read(42))
226 self.assertEqual(content, f.open().read())
227
228 def test_file_no_write(self):
229 """
230 Test various conditions where File.copy is expected not to write
231 in the destination file.
232 """
233 src = self.tmppath("src")
234 dest = self.tmppath("dest")
235
236 with open(src, "wb") as tmp:
237 tmp.write(b"test")
238
239 # Initial copy
240 f = File(src)
241 f.copy(dest)
242
243 # Ensure subsequent copies won't trigger writes
244 f.copy(DestNoWrite(dest))
245 self.assertEqual(b"test", open(dest, "rb").read())
246
247 # When the source file is newer, but with the same content, no copy
248 # should occur
249 time = os.path.getmtime(src) - 1
250 os.utime(dest, (time, time))
251 f.copy(DestNoWrite(dest))
252 self.assertEqual(b"test", open(dest, "rb").read())
253
254 # When the source file is older than the destination file, even with
255 # different content, no copy should occur.
256 with open(src, "wb") as tmp:
257 tmp.write(b"fooo")
258 time = os.path.getmtime(dest) - 1
259 os.utime(src, (time, time))
260 f.copy(DestNoWrite(dest))
261 self.assertEqual(b"test", open(dest, "rb").read())
262
263 # Double check that under conditions where a copy occurs, we would get
264 # an exception.
265 time = os.path.getmtime(src) - 1
266 os.utime(dest, (time, time))
267 self.assertRaises(RuntimeError, f.copy, DestNoWrite(dest))
268
269 # skip_if_older=False is expected to force a copy in this situation.
270 f.copy(dest, skip_if_older=False)
271 self.assertEqual(b"fooo", open(dest, "rb").read())
272
273
274 class TestAbsoluteSymlinkFile(TestWithTmpDir):
275 def test_absolute_relative(self):
276 AbsoluteSymlinkFile("/foo")
277
278 with self.assertRaisesRegex(ValueError, "Symlink target not absolute"):
279 AbsoluteSymlinkFile("./foo")
280
281 def test_symlink_file(self):
282 source = self.tmppath("test_path")
283 with open(source, "w") as fh:
284 fh.write("Hello world")
285
286 s = AbsoluteSymlinkFile(source)
287 dest = self.tmppath("symlink")
288 self.assertTrue(s.copy(dest))
289
290 if self.symlink_supported:
291 self.assertTrue(os.path.islink(dest))
292 link = os.readlink(dest)
293 self.assertEqual(link, source)
294 else:
295 self.assertTrue(os.path.isfile(dest))
296 content = open(dest).read()
297 self.assertEqual(content, "Hello world")
298
299 def test_replace_file_with_symlink(self):
300 # If symlinks are supported, an existing file should be replaced by a
301 # symlink.
302 source = self.tmppath("test_path")
303 with open(source, "w") as fh:
304 fh.write("source")
305
306 dest = self.tmppath("dest")
307 with open(dest, "a"):
308 pass
309
310 s = AbsoluteSymlinkFile(source)
311 s.copy(dest, skip_if_older=False)
312
313 if self.symlink_supported:
314 self.assertTrue(os.path.islink(dest))
315 link = os.readlink(dest)
316 self.assertEqual(link, source)
317 else:
318 self.assertTrue(os.path.isfile(dest))
319 content = open(dest).read()
320 self.assertEqual(content, "source")
321
322 def test_replace_symlink(self):
323 if not self.symlink_supported:
324 return
325
326 source = self.tmppath("source")
327 with open(source, "a"):
328 pass
329
330 dest = self.tmppath("dest")
331
332 os.symlink(self.tmppath("bad"), dest)
333 self.assertTrue(os.path.islink(dest))
334
335 s = AbsoluteSymlinkFile(source)
336 self.assertTrue(s.copy(dest))
337
338 self.assertTrue(os.path.islink(dest))
339 link = os.readlink(dest)
340 self.assertEqual(link, source)
341
342 def test_noop(self):
343 if not hasattr(os, "symlink") or sys.platform == "win32":
344 return
345
346 source = self.tmppath("source")
347 dest = self.tmppath("dest")
348
349 with open(source, "a"):
350 pass
351
352 os.symlink(source, dest)
353 link = os.readlink(dest)
354 self.assertEqual(link, source)
355
356 s = AbsoluteSymlinkFile(source)
357 self.assertFalse(s.copy(dest))
358
359 link = os.readlink(dest)
360 self.assertEqual(link, source)
361
362
363 class TestHardlinkFile(TestWithTmpDir):
364 def test_absolute_relative(self):
365 HardlinkFile("/foo")
366 HardlinkFile("./foo")
367
368 def test_hardlink_file(self):
369 source = self.tmppath("test_path")
370 with open(source, "w") as fh:
371 fh.write("Hello world")
372
373 s = HardlinkFile(source)
374 dest = self.tmppath("hardlink")
375 self.assertTrue(s.copy(dest))
376
377 if self.hardlink_supported:
378 source_stat = os.stat(source)
379 dest_stat = os.stat(dest)
380 self.assertEqual(source_stat.st_dev, dest_stat.st_dev)
381 self.assertEqual(source_stat.st_ino, dest_stat.st_ino)
382 else:
383 self.assertTrue(os.path.isfile(dest))
384 with open(dest) as f:
385 content = f.read()
386 self.assertEqual(content, "Hello world")
387
388 def test_replace_file_with_hardlink(self):
389 # If hardlink are supported, an existing file should be replaced by a
390 # symlink.
391 source = self.tmppath("test_path")
392 with open(source, "w") as fh:
393 fh.write("source")
394
395 dest = self.tmppath("dest")
396 with open(dest, "a"):
397 pass
398
399 s = HardlinkFile(source)
400 s.copy(dest, skip_if_older=False)
401
402 if self.hardlink_supported:
403 source_stat = os.stat(source)
404 dest_stat = os.stat(dest)
405 self.assertEqual(source_stat.st_dev, dest_stat.st_dev)
406 self.assertEqual(source_stat.st_ino, dest_stat.st_ino)
407 else:
408 self.assertTrue(os.path.isfile(dest))
409 with open(dest) as f:
410 content = f.read()
411 self.assertEqual(content, "source")
412
413 def test_replace_hardlink(self):
414 if not self.hardlink_supported:
415 raise unittest.SkipTest("hardlink not supported")
416
417 source = self.tmppath("source")
418 with open(source, "a"):
419 pass
420
421 dest = self.tmppath("dest")
422
423 os.link(source, dest)
424
425 s = HardlinkFile(source)
426 self.assertFalse(s.copy(dest))
427
428 source_stat = os.lstat(source)
429 dest_stat = os.lstat(dest)
430 self.assertEqual(source_stat.st_dev, dest_stat.st_dev)
431 self.assertEqual(source_stat.st_ino, dest_stat.st_ino)
432
433 def test_noop(self):
434 if not self.hardlink_supported:
435 raise unittest.SkipTest("hardlink not supported")
436
437 source = self.tmppath("source")
438 dest = self.tmppath("dest")
439
440 with open(source, "a"):
441 pass
442
443 os.link(source, dest)
444
445 s = HardlinkFile(source)
446 self.assertFalse(s.copy(dest))
447
448 source_stat = os.lstat(source)
449 dest_stat = os.lstat(dest)
450 self.assertEqual(source_stat.st_dev, dest_stat.st_dev)
451 self.assertEqual(source_stat.st_ino, dest_stat.st_ino)
452
453
454 class TestPreprocessedFile(TestWithTmpDir):
455 def test_preprocess(self):
456 """
457 Test that copying the file invokes the preprocessor
458 """
459 src = self.tmppath("src")
460 dest = self.tmppath("dest")
461
462 with open(src, "wb") as tmp:
463 tmp.write(b"#ifdef FOO\ntest\n#endif")
464
465 f = PreprocessedFile(src, depfile_path=None, marker="#", defines={"FOO": True})
466 self.assertTrue(f.copy(dest))
467
468 self.assertEqual(b"test\n", open(dest, "rb").read())
469
470 def test_preprocess_file_no_write(self):
471 """
472 Test various conditions where PreprocessedFile.copy is expected not to
473 write in the destination file.
474 """
475 src = self.tmppath("src")
476 dest = self.tmppath("dest")
477 depfile = self.tmppath("depfile")
478
479 with open(src, "wb") as tmp:
480 tmp.write(b"#ifdef FOO\ntest\n#endif")
481
482 # Initial copy
483 f = PreprocessedFile(
484 src, depfile_path=depfile, marker="#", defines={"FOO": True}
485 )
486 self.assertTrue(f.copy(dest))
487
488 # Ensure subsequent copies won't trigger writes
489 self.assertFalse(f.copy(DestNoWrite(dest)))
490 self.assertEqual(b"test\n", open(dest, "rb").read())
491
492 # When the source file is older than the destination file, even with
493 # different content, no copy should occur.
494 with open(src, "wb") as tmp:
495 tmp.write(b"#ifdef FOO\nfooo\n#endif")
496 time = os.path.getmtime(dest) - 1
497 os.utime(src, (time, time))
498 self.assertFalse(f.copy(DestNoWrite(dest)))
499 self.assertEqual(b"test\n", open(dest, "rb").read())
500
501 # skip_if_older=False is expected to force a copy in this situation.
502 self.assertTrue(f.copy(dest, skip_if_older=False))
503 self.assertEqual(b"fooo\n", open(dest, "rb").read())
504
505 def test_preprocess_file_dependencies(self):
506 """
507 Test that the preprocess runs if the dependencies of the source change
508 """
509 src = self.tmppath("src")
510 dest = self.tmppath("dest")
511 incl = self.tmppath("incl")
512 deps = self.tmppath("src.pp")
513
514 with open(src, "wb") as tmp:
515 tmp.write(b"#ifdef FOO\ntest\n#endif")
516
517 with open(incl, "wb") as tmp:
518 tmp.write(b"foo bar")
519
520 # Initial copy
521 f = PreprocessedFile(src, depfile_path=deps, marker="#", defines={"FOO": True})
522 self.assertTrue(f.copy(dest))
523
524 # Update the source so it #includes the include file.
525 with open(src, "wb") as tmp:
526 tmp.write(b"#include incl\n")
527 time = os.path.getmtime(dest) + 1
528 os.utime(src, (time, time))
529 self.assertTrue(f.copy(dest))
530 self.assertEqual(b"foo bar", open(dest, "rb").read())
531
532 # If one of the dependencies changes, the file should be updated. The
533 # mtime of the dependency is set after the destination file, to avoid
534 # both files having the same time.
535 with open(incl, "wb") as tmp:
536 tmp.write(b"quux")
537 time = os.path.getmtime(dest) + 1
538 os.utime(incl, (time, time))
539 self.assertTrue(f.copy(dest))
540 self.assertEqual(b"quux", open(dest, "rb").read())
541
542 # Perform one final copy to confirm that we don't run the preprocessor
543 # again. We update the mtime of the destination so it's newer than the
544 # input files. This would "just work" if we weren't changing
545 time = os.path.getmtime(incl) + 1
546 os.utime(dest, (time, time))
547 self.assertFalse(f.copy(DestNoWrite(dest)))
548
549 def test_replace_symlink(self):
550 """
551 Test that if the destination exists, and is a symlink, the target of
552 the symlink is not overwritten by the preprocessor output.
553 """
554 if not self.symlink_supported:
555 return
556
557 source = self.tmppath("source")
558 dest = self.tmppath("dest")
559 pp_source = self.tmppath("pp_in")
560 deps = self.tmppath("deps")
561
562 with open(source, "a"):
563 pass
564
565 os.symlink(source, dest)
566 self.assertTrue(os.path.islink(dest))
567
568 with open(pp_source, "wb") as tmp:
569 tmp.write(b"#define FOO\nPREPROCESSED")
570
571 f = PreprocessedFile(
572 pp_source, depfile_path=deps, marker="#", defines={"FOO": True}
573 )
574 self.assertTrue(f.copy(dest))
575
576 self.assertEqual(b"PREPROCESSED", open(dest, "rb").read())
577 self.assertFalse(os.path.islink(dest))
578 self.assertEqual(b"", open(source, "rb").read())
579
580
581 class TestExistingFile(TestWithTmpDir):
582 def test_required_missing_dest(self):
583 with self.assertRaisesRegex(ErrorMessage, "Required existing file"):
584 f = ExistingFile(required=True)
585 f.copy(self.tmppath("dest"))
586
587 def test_required_existing_dest(self):
588 p = self.tmppath("dest")
589 with open(p, "a"):
590 pass
591
592 f = ExistingFile(required=True)
593 f.copy(p)
594
595 def test_optional_missing_dest(self):
596 f = ExistingFile(required=False)
597 f.copy(self.tmppath("dest"))
598
599 def test_optional_existing_dest(self):
600 p = self.tmppath("dest")
601 with open(p, "a"):
602 pass
603
604 f = ExistingFile(required=False)
605 f.copy(p)
606
607
608 class TestGeneratedFile(TestWithTmpDir):
609 def test_generated_file(self):
610 """
611 Check that GeneratedFile.copy yields the proper content in the
612 destination file in all situations that trigger different code paths
613 (see TestFile.test_file)
614 """
615 dest = self.tmppath("dest")
616
617 for content in samples:
618 f = GeneratedFile(content)
619 f.copy(dest)
620 self.assertEqual(content, open(dest, "rb").read())
621
622 def test_generated_file_open(self):
623 """
624 Test whether GeneratedFile.open returns an appropriately reset file
625 object.
626 """
627 content = b"".join(samples)
628 f = GeneratedFile(content)
629 self.assertEqual(content[:42], f.open().read(42))
630 self.assertEqual(content, f.open().read())
631
632 def test_generated_file_no_write(self):
633 """
634 Test various conditions where GeneratedFile.copy is expected not to
635 write in the destination file.
636 """
637 dest = self.tmppath("dest")
638
639 # Initial copy
640 f = GeneratedFile(b"test")
641 f.copy(dest)
642
643 # Ensure subsequent copies won't trigger writes
644 f.copy(DestNoWrite(dest))
645 self.assertEqual(b"test", open(dest, "rb").read())
646
647 # When using a new instance with the same content, no copy should occur
648 f = GeneratedFile(b"test")
649 f.copy(DestNoWrite(dest))
650 self.assertEqual(b"test", open(dest, "rb").read())
651
652 # Double check that under conditions where a copy occurs, we would get
653 # an exception.
654 f = GeneratedFile(b"fooo")
655 self.assertRaises(RuntimeError, f.copy, DestNoWrite(dest))
656
657 def test_generated_file_function(self):
658 """
659 Test GeneratedFile behavior with functions.
660 """
661 dest = self.tmppath("dest")
662 data = {
663 "num_calls": 0,
664 }
665
666 def content():
667 data["num_calls"] += 1
668 return b"content"
669
670 f = GeneratedFile(content)
671 self.assertEqual(data["num_calls"], 0)
672 f.copy(dest)
673 self.assertEqual(data["num_calls"], 1)
674 self.assertEqual(b"content", open(dest, "rb").read())
675 self.assertEqual(b"content", f.open().read())
676 self.assertEqual(b"content", f.read())
677 self.assertEqual(len(b"content"), f.size())
678 self.assertEqual(data["num_calls"], 1)
679
680 f.content = b"modified"
681 f.copy(dest)
682 self.assertEqual(data["num_calls"], 1)
683 self.assertEqual(b"modified", open(dest, "rb").read())
684 self.assertEqual(b"modified", f.open().read())
685 self.assertEqual(b"modified", f.read())
686 self.assertEqual(len(b"modified"), f.size())
687
688 f.content = content
689 self.assertEqual(data["num_calls"], 1)
690 self.assertEqual(b"content", f.read())
691 self.assertEqual(data["num_calls"], 2)
692
693
694 class TestDeflatedFile(TestWithTmpDir):
695 def test_deflated_file(self):
696 """
697 Check that DeflatedFile.copy yields the proper content in the
698 destination file in all situations that trigger different code paths
699 (see TestFile.test_file)
700 """
701 src = self.tmppath("src.jar")
702 dest = self.tmppath("dest")
703
704 contents = {}
705 with JarWriter(src) as jar:
706 for content in samples:
707 name = "".join(
708 random.choice(
709 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
710 )
711 for i in range(8)
712 )
713 jar.add(name, content, compress=True)
714 contents[name] = content
715
716 for j in JarReader(src):
717 f = DeflatedFile(j)
718 f.copy(dest)
719 self.assertEqual(contents[j.filename], open(dest, "rb").read())
720
721 def test_deflated_file_open(self):
722 """
723 Test whether DeflatedFile.open returns an appropriately reset file
724 object.
725 """
726 src = self.tmppath("src.jar")
727 content = b"".join(samples)
728 with JarWriter(src) as jar:
729 jar.add("content", content)
730
731 f = DeflatedFile(JarReader(src)["content"])
732 self.assertEqual(content[:42], f.open().read(42))
733 self.assertEqual(content, f.open().read())
734
735 def test_deflated_file_no_write(self):
736 """
737 Test various conditions where DeflatedFile.copy is expected not to
738 write in the destination file.
739 """
740 src = self.tmppath("src.jar")
741 dest = self.tmppath("dest")
742
743 with JarWriter(src) as jar:
744 jar.add("test", b"test")
745 jar.add("test2", b"test")
746 jar.add("fooo", b"fooo")
747
748 jar = JarReader(src)
749 # Initial copy
750 f = DeflatedFile(jar["test"])
751 f.copy(dest)
752
753 # Ensure subsequent copies won't trigger writes
754 f.copy(DestNoWrite(dest))
755 self.assertEqual(b"test", open(dest, "rb").read())
756
757 # When using a different file with the same content, no copy should
758 # occur
759 f = DeflatedFile(jar["test2"])
760 f.copy(DestNoWrite(dest))
761 self.assertEqual(b"test", open(dest, "rb").read())
762
763 # Double check that under conditions where a copy occurs, we would get
764 # an exception.
765 f = DeflatedFile(jar["fooo"])
766 self.assertRaises(RuntimeError, f.copy, DestNoWrite(dest))
767
768
769 class TestManifestFile(TestWithTmpDir):
770 def test_manifest_file(self):
771 f = ManifestFile("chrome")
772 f.add(ManifestContent("chrome", "global", "toolkit/content/global/"))
773 f.add(ManifestResource("chrome", "gre-resources", "toolkit/res/"))
774 f.add(ManifestResource("chrome/pdfjs", "pdfjs", "./"))
775 f.add(ManifestContent("chrome/pdfjs", "pdfjs", "pdfjs"))
776 f.add(ManifestLocale("chrome", "browser", "en-US", "en-US/locale/browser/"))
777
778 f.copy(self.tmppath("chrome.manifest"))
779 self.assertEqual(
780 open(self.tmppath("chrome.manifest")).readlines(),
781 [
782 "content global toolkit/content/global/\n",
783 "resource gre-resources toolkit/res/\n",
784 "resource pdfjs pdfjs/\n",
785 "content pdfjs pdfjs/pdfjs\n",
786 "locale browser en-US en-US/locale/browser/\n",
787 ],
788 )
789
790 self.assertRaises(
791 ValueError,
792 f.remove,
793 ManifestContent("", "global", "toolkit/content/global/"),
794 )
795 self.assertRaises(
796 ValueError,
797 f.remove,
798 ManifestOverride(
799 "chrome",
800 "chrome://global/locale/netError.dtd",
801 "chrome://browser/locale/netError.dtd",
802 ),
803 )
804
805 f.remove(ManifestContent("chrome", "global", "toolkit/content/global/"))
806 self.assertRaises(
807 ValueError,
808 f.remove,
809 ManifestContent("chrome", "global", "toolkit/content/global/"),
810 )
811
812 f.copy(self.tmppath("chrome.manifest"))
813 content = open(self.tmppath("chrome.manifest"), "rb").read()
814 self.assertEqual(content[:42], f.open().read(42))
815 self.assertEqual(content, f.open().read())
816
817
818 # Compiled typelib for the following IDL:
819 # interface foo;
820 # [scriptable, uuid(5f70da76-519c-4858-b71e-e3c92333e2d6)]
821 # interface bar {
822 # void bar(in foo f);
823 # };
824 # We need to make this [scriptable] so it doesn't get deleted from the
825 # typelib. We don't need to make the foo interfaces below [scriptable],
826 # because they will be automatically included by virtue of being an
827 # argument to a method of |bar|.
828 bar_xpt = GeneratedFile(
829 b"\x58\x50\x43\x4F\x4D\x0A\x54\x79\x70\x65\x4C\x69\x62\x0D\x0A\x1A"
830 + b"\x01\x02\x00\x02\x00\x00\x00\x7B\x00\x00\x00\x24\x00\x00\x00\x5C"
831 + b"\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
832 + b"\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x5F"
833 + b"\x70\xDA\x76\x51\x9C\x48\x58\xB7\x1E\xE3\xC9\x23\x33\xE2\xD6\x00"
834 + b"\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x0D\x00\x66\x6F\x6F\x00"
835 + b"\x62\x61\x72\x00\x62\x61\x72\x00\x00\x00\x00\x01\x00\x00\x00\x00"
836 + b"\x09\x01\x80\x92\x00\x01\x80\x06\x00\x00\x80"
837 )
838
839 # Compiled typelib for the following IDL:
840 # [uuid(3271bebc-927e-4bef-935e-44e0aaf3c1e5)]
841 # interface foo {
842 # void foo();
843 # };
844 foo_xpt = GeneratedFile(
845 b"\x58\x50\x43\x4F\x4D\x0A\x54\x79\x70\x65\x4C\x69\x62\x0D\x0A\x1A"
846 + b"\x01\x02\x00\x01\x00\x00\x00\x57\x00\x00\x00\x24\x00\x00\x00\x40"
847 + b"\x80\x00\x00\x32\x71\xBE\xBC\x92\x7E\x4B\xEF\x93\x5E\x44\xE0\xAA"
848 + b"\xF3\xC1\xE5\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x09\x00"
849 + b"\x66\x6F\x6F\x00\x66\x6F\x6F\x00\x00\x00\x00\x01\x00\x00\x00\x00"
850 + b"\x05\x00\x80\x06\x00\x00\x00"
851 )
852
853 # Compiled typelib for the following IDL:
854 # [uuid(7057f2aa-fdc2-4559-abde-08d939f7e80d)]
855 # interface foo {
856 # void foo();
857 # };
858 foo2_xpt = GeneratedFile(
859 b"\x58\x50\x43\x4F\x4D\x0A\x54\x79\x70\x65\x4C\x69\x62\x0D\x0A\x1A"
860 + b"\x01\x02\x00\x01\x00\x00\x00\x57\x00\x00\x00\x24\x00\x00\x00\x40"
861 + b"\x80\x00\x00\x70\x57\xF2\xAA\xFD\xC2\x45\x59\xAB\xDE\x08\xD9\x39"
862 + b"\xF7\xE8\x0D\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x09\x00"
863 + b"\x66\x6F\x6F\x00\x66\x6F\x6F\x00\x00\x00\x00\x01\x00\x00\x00\x00"
864 + b"\x05\x00\x80\x06\x00\x00\x00"
865 )
866
867
868 class TestMinifiedCommentStripped(TestWithTmpDir):
869 def test_minified_comment_stripped(self):
870 propLines = [
871 "# Comments are removed",
872 "foo = bar",
873 "",
874 "# Another comment",
875 ]
876 prop = GeneratedFile("\n".join(propLines))
877 self.assertEqual(
878 MinifiedCommentStripped(prop).open().readlines(), [b"foo = bar\n", b"\n"]
879 )
880 open(self.tmppath("prop"), "w").write("\n".join(propLines))
881 MinifiedCommentStripped(File(self.tmppath("prop"))).copy(self.tmppath("prop2"))
882 self.assertEqual(open(self.tmppath("prop2")).readlines(), ["foo = bar\n", "\n"])
883
884
885 class TestMinifiedJavaScript(TestWithTmpDir):
886 orig_lines = [
887 "// Comment line",
888 'let foo = "bar";',
889 "var bar = true;",
890 "",
891 "// Another comment",
892 ]
893
894 def test_minified_javascript(self):
895 orig_f = GeneratedFile("\n".join(self.orig_lines))
896 min_f = MinifiedJavaScript(orig_f)
897
898 mini_lines = min_f.open().readlines()
899 self.assertTrue(mini_lines)
900 self.assertTrue(len(mini_lines) < len(self.orig_lines))
901
902 def _verify_command(self, code):
903 our_dir = os.path.abspath(os.path.dirname(__file__))
904 return [
905 sys.executable,
906 os.path.join(our_dir, "support", "minify_js_verify.py"),
907 code,
908 ]
909
910 def test_minified_verify_success(self):
911 orig_f = GeneratedFile("\n".join(self.orig_lines))
912 min_f = MinifiedJavaScript(orig_f, verify_command=self._verify_command("0"))
913
914 mini_lines = [s.decode() for s in min_f.open().readlines()]
915 self.assertTrue(mini_lines)
916 self.assertTrue(len(mini_lines) < len(self.orig_lines))
917
918 def test_minified_verify_failure(self):
919 orig_f = GeneratedFile("\n".join(self.orig_lines))
920 errors.out = StringIO()
921 min_f = MinifiedJavaScript(orig_f, verify_command=self._verify_command("1"))
922
923 mini_lines = min_f.open().readlines()
924 output = errors.out.getvalue()
925 errors.out = sys.stderr
926 self.assertEqual(
927 output,
928 "warning: JS minification verification failed for <unknown>:\n"
929 "warning: Error message\n",
930 )
931 self.assertEqual(mini_lines, orig_f.open().readlines())
932
933
934 class MatchTestTemplate:
935 def prepare_match_test(self, with_dotfiles=False):
936 self.add("bar")
937 self.add("foo/bar")
938 self.add("foo/baz")
939 self.add("foo/qux/1")
940 self.add("foo/qux/bar")
941 self.add("foo/qux/2/test")
942 self.add("foo/qux/2/test2")
943 if with_dotfiles:
944 self.add("foo/.foo")
945 self.add("foo/.bar/foo")
946
947 def do_match_test(self):
948 self.do_check(
949 "",
950 [
951 "bar",
952 "foo/bar",
953 "foo/baz",
954 "foo/qux/1",
955 "foo/qux/bar",
956 "foo/qux/2/test",
957 "foo/qux/2/test2",
958 ],
959 )
960 self.do_check(
961 "*",
962 [
963 "bar",
964 "foo/bar",
965 "foo/baz",
966 "foo/qux/1",
967 "foo/qux/bar",
968 "foo/qux/2/test",
969 "foo/qux/2/test2",
970 ],
971 )
972 self.do_check(
973 "foo/qux", ["foo/qux/1", "foo/qux/bar", "foo/qux/2/test", "foo/qux/2/test2"]
974 )
975 self.do_check("foo/b*", ["foo/bar", "foo/baz"])
976 self.do_check("baz", [])
977 self.do_check("foo/foo", [])
978 self.do_check("foo/*ar", ["foo/bar"])
979 self.do_check("*ar", ["bar"])
980 self.do_check("*/bar", ["foo/bar"])
981 self.do_check(
982 "foo/*ux", ["foo/qux/1", "foo/qux/bar", "foo/qux/2/test", "foo/qux/2/test2"]
983 )
984 self.do_check(
985 "foo/q*ux",
986 ["foo/qux/1", "foo/qux/bar", "foo/qux/2/test", "foo/qux/2/test2"],
987 )
988 self.do_check("foo/*/2/test*", ["foo/qux/2/test", "foo/qux/2/test2"])
989 self.do_check("**/bar", ["bar", "foo/bar", "foo/qux/bar"])
990 self.do_check("foo/**/test", ["foo/qux/2/test"])
991 self.do_check(
992 "foo",
993 [
994 "foo/bar",
995 "foo/baz",
996 "foo/qux/1",
997 "foo/qux/bar",
998 "foo/qux/2/test",
999 "foo/qux/2/test2",
1000 ],
1001 )
1002 self.do_check(
1003 "foo/**",
1004 [
1005 "foo/bar",
1006 "foo/baz",
1007 "foo/qux/1",
1008 "foo/qux/bar",
1009 "foo/qux/2/test",
1010 "foo/qux/2/test2",
1011 ],
1012 )
1013 self.do_check("**/2/test*", ["foo/qux/2/test", "foo/qux/2/test2"])
1014 self.do_check(
1015 "**/foo",
1016 [
1017 "foo/bar",
1018 "foo/baz",
1019 "foo/qux/1",
1020 "foo/qux/bar",
1021 "foo/qux/2/test",
1022 "foo/qux/2/test2",
1023 ],
1024 )
1025 self.do_check("**/barbaz", [])
1026 self.do_check("f**/bar", ["foo/bar"])
1027
1028 def do_finder_test(self, finder):
1029 self.assertTrue(finder.contains("foo/.foo"))
1030 self.assertTrue(finder.contains("foo/.bar"))
1031 self.assertTrue("foo/.foo" in [f for f, c in finder.find("foo/.foo")])
1032 self.assertTrue("foo/.bar/foo" in [f for f, c in finder.find("foo/.bar")])
1033 self.assertEqual(
1034 sorted([f for f, c in finder.find("foo/.*")]), ["foo/.bar/foo", "foo/.foo"]
1035 )
1036 for pattern in ["foo", "**", "**/*", "**/foo", "foo/*"]:
1037 self.assertFalse("foo/.foo" in [f for f, c in finder.find(pattern)])
1038 self.assertFalse("foo/.bar/foo" in [f for f, c in finder.find(pattern)])
1039 self.assertEqual(
1040 sorted([f for f, c in finder.find(pattern)]),
1041 sorted([f for f, c in finder if mozpath.match(f, pattern)]),
1042 )
1043
1044
1045 def do_check(test, finder, pattern, result):
1046 if result:
1047 test.assertTrue(finder.contains(pattern))
1048 else:
1049 test.assertFalse(finder.contains(pattern))
1050 test.assertEqual(sorted(list(f for f, c in finder.find(pattern))), sorted(result))
1051
1052
1053 class TestFileFinder(MatchTestTemplate, TestWithTmpDir):
1054 def add(self, path):
1055 ensureParentDir(self.tmppath(path))
1056 open(self.tmppath(path), "wb").write(path.encode())
1057
1058 def do_check(self, pattern, result):
1059 do_check(self, self.finder, pattern, result)
1060
1061 def test_file_finder(self):
1062 self.prepare_match_test(with_dotfiles=True)
1063 self.finder = FileFinder(self.tmpdir)
1064 self.do_match_test()
1065 self.do_finder_test(self.finder)
1066
1067 def test_get(self):
1068 self.prepare_match_test()
1069 finder = FileFinder(self.tmpdir)
1070
1071 self.assertIsNone(finder.get("does-not-exist"))
1072 res = finder.get("bar")
1073 self.assertIsInstance(res, File)
1074 self.assertEqual(mozpath.normpath(res.path), mozpath.join(self.tmpdir, "bar"))
1075
1076 def test_ignored_dirs(self):
1077 """Ignored directories should not have results returned."""
1078 self.prepare_match_test()
1079 self.add("fooz")
1080
1081 # Present to ensure prefix matching doesn't exclude.
1082 self.add("foo/quxz")
1083
1084 self.finder = FileFinder(self.tmpdir, ignore=["foo/qux"])
1085
1086 self.do_check("**", ["bar", "foo/bar", "foo/baz", "foo/quxz", "fooz"])
1087 self.do_check("foo/*", ["foo/bar", "foo/baz", "foo/quxz"])
1088 self.do_check("foo/**", ["foo/bar", "foo/baz", "foo/quxz"])
1089 self.do_check("foo/qux/**", [])
1090 self.do_check("foo/qux/*", [])
1091 self.do_check("foo/qux/bar", [])
1092 self.do_check("foo/quxz", ["foo/quxz"])
1093 self.do_check("fooz", ["fooz"])
1094
1095 def test_ignored_files(self):
1096 """Ignored files should not have results returned."""
1097 self.prepare_match_test()
1098
1099 # Be sure prefix match doesn't get ignored.
1100 self.add("barz")
1101
1102 self.finder = FileFinder(self.tmpdir, ignore=["foo/bar", "bar"])
1103 self.do_check(
1104 "**",
1105 [
1106 "barz",
1107 "foo/baz",
1108 "foo/qux/1",
1109 "foo/qux/2/test",
1110 "foo/qux/2/test2",
1111 "foo/qux/bar",
1112 ],
1113 )
1114 self.do_check(
1115 "foo/**",
1116 [
1117 "foo/baz",
1118 "foo/qux/1",
1119 "foo/qux/2/test",
1120 "foo/qux/2/test2",
1121 "foo/qux/bar",
1122 ],
1123 )
1124
1125 def test_ignored_patterns(self):
1126 """Ignore entries with patterns should be honored."""
1127 self.prepare_match_test()
1128
1129 self.add("foo/quxz")
1130
1131 self.finder = FileFinder(self.tmpdir, ignore=["foo/qux/*"])
1132 self.do_check("**", ["foo/bar", "foo/baz", "foo/quxz", "bar"])
1133 self.do_check("foo/**", ["foo/bar", "foo/baz", "foo/quxz"])
1134
1135 def test_dotfiles(self):
1136 """Finder can find files beginning with . is configured."""
1137 self.prepare_match_test(with_dotfiles=True)
1138 self.finder = FileFinder(self.tmpdir, find_dotfiles=True)
1139 self.do_check(
1140 "**",
1141 [
1142 "bar",
1143 "foo/.foo",
1144 "foo/.bar/foo",
1145 "foo/bar",
1146 "foo/baz",
1147 "foo/qux/1",
1148 "foo/qux/bar",
1149 "foo/qux/2/test",
1150 "foo/qux/2/test2",
1151 ],
1152 )
1153
1154 def test_dotfiles_plus_ignore(self):
1155 self.prepare_match_test(with_dotfiles=True)
1156 self.finder = FileFinder(
1157 self.tmpdir, find_dotfiles=True, ignore=["foo/.bar/**"]
1158 )
1159 self.do_check(
1160 "foo/**",
1161 [
1162 "foo/.foo",
1163 "foo/bar",
1164 "foo/baz",
1165 "foo/qux/1",
1166 "foo/qux/bar",
1167 "foo/qux/2/test",
1168 "foo/qux/2/test2",
1169 ],
1170 )
1171
1172
1173 class TestJarFinder(MatchTestTemplate, TestWithTmpDir):
1174 def add(self, path):
1175 self.jar.add(path, ensure_bytes(path), compress=True)
1176
1177 def do_check(self, pattern, result):
1178 do_check(self, self.finder, pattern, result)
1179
1180 def test_jar_finder(self):
1181 self.jar = JarWriter(file=self.tmppath("test.jar"))
1182 self.prepare_match_test()
1183 self.jar.finish()
1184 reader = JarReader(file=self.tmppath("test.jar"))
1185 self.finder = JarFinder(self.tmppath("test.jar"), reader)
1186 self.do_match_test()
1187
1188 self.assertIsNone(self.finder.get("does-not-exist"))
1189 self.assertIsInstance(self.finder.get("bar"), DeflatedFile)
1190
1191
1192 class TestTarFinder(MatchTestTemplate, TestWithTmpDir):
1193 def add(self, path):
1194 self.tar.addfile(tarfile.TarInfo(name=path))
1195
1196 def do_check(self, pattern, result):
1197 do_check(self, self.finder, pattern, result)
1198
1199 def test_tar_finder(self):
1200 self.tar = tarfile.open(name=self.tmppath("test.tar.bz2"), mode="w:bz2")
1201 self.prepare_match_test()
1202 self.tar.close()
1203 with tarfile.open(name=self.tmppath("test.tar.bz2"), mode="r:bz2") as tarreader:
1204 self.finder = TarFinder(self.tmppath("test.tar.bz2"), tarreader)
1205 self.do_match_test()
1206
1207 self.assertIsNone(self.finder.get("does-not-exist"))
1208 self.assertIsInstance(self.finder.get("bar"), ExtractedTarFile)
1209
1210
1211 class TestComposedFinder(MatchTestTemplate, TestWithTmpDir):
1212 def add(self, path, content=None):
1213 # Put foo/qux files under $tmp/b.
1214 if path.startswith("foo/qux/"):
1215 real_path = mozpath.join("b", path[8:])
1216 else:
1217 real_path = mozpath.join("a", path)
1218 ensureParentDir(self.tmppath(real_path))
1219 if not content:
1220 content = path.encode()
1221 open(self.tmppath(real_path), "wb").write(content)
1222
1223 def do_check(self, pattern, result):
1224 if "*" in pattern:
1225 return
1226 do_check(self, self.finder, pattern, result)
1227
1228 def test_composed_finder(self):
1229 self.prepare_match_test()
1230 # Also add files in $tmp/a/foo/qux because ComposedFinder is
1231 # expected to mask foo/qux entirely with content from $tmp/b.
1232 ensureParentDir(self.tmppath("a/foo/qux/hoge"))
1233 open(self.tmppath("a/foo/qux/hoge"), "wb").write(b"hoge")
1234 open(self.tmppath("a/foo/qux/bar"), "wb").write(b"not the right content")
1235 self.finder = ComposedFinder(
1236 {
1237 "": FileFinder(self.tmppath("a")),
1238 "foo/qux": FileFinder(self.tmppath("b")),
1239 }
1240 )
1241 self.do_match_test()
1242
1243 self.assertIsNone(self.finder.get("does-not-exist"))
1244 self.assertIsInstance(self.finder.get("bar"), File)
1245
1246
1247 @unittest.skipUnless(hglib, "hglib not available")
1248 @unittest.skipIf(os.name == "nt", "Does not currently work in Python3 on Windows")
1249 class TestMercurialRevisionFinder(MatchTestTemplate, TestWithTmpDir):
1250 def setUp(self):
1251 super(TestMercurialRevisionFinder, self).setUp()
1252 hglib.init(self.tmpdir)
1253 self._clients = []
1254
1255 def tearDown(self):
1256 # Ensure the hg client process is closed. Otherwise, Windows
1257 # may have trouble removing the repo directory because the process
1258 # has an open handle on it.
1259 for client in getattr(self, "_clients", []):
1260 if client.server:
1261 client.close()
1262
1263 self._clients[:] = []
1264
1265 super(TestMercurialRevisionFinder, self).tearDown()
1266
1267 def _client(self):
1268 configs = (
1269 # b'' because py2 needs !unicode
1270 b'ui.username="Dummy User <[email protected]>"',
1271 )
1272 client = hglib.open(
1273 self.tmpdir.encode(),
1274 encoding=b"UTF-8", # b'' because py2 needs !unicode
1275 configs=configs,
1276 )
1277 self._clients.append(client)
1278 return client
1279
1280 def add(self, path):
1281 with self._client() as c:
1282 ensureParentDir(self.tmppath(path))
1283 with open(self.tmppath(path), "wb") as fh:
1284 fh.write(path.encode())
1285 c.add(self.tmppath(path).encode())
1286
1287 def do_check(self, pattern, result):
1288 do_check(self, self.finder, pattern, result)
1289
1290 def _get_finder(self, *args, **kwargs):
1291 f = MercurialRevisionFinder(*args, **kwargs)
1292 self._clients.append(f._client)
1293 return f
1294
1295 def test_default_revision(self):
1296 self.prepare_match_test()
1297 with self._client() as c:
1298 c.commit("initial commit")
1299
1300 self.finder = self._get_finder(self.tmpdir)
1301 self.do_match_test()
1302
1303 self.assertIsNone(self.finder.get("does-not-exist"))
1304 self.assertIsInstance(self.finder.get("bar"), MercurialFile)
1305
1306 def test_old_revision(self):
1307 with self._client() as c:
1308 with open(self.tmppath("foo"), "wb") as fh:
1309 fh.write(b"foo initial")
1310 c.add(self.tmppath("foo").encode())
1311 c.commit("initial")
1312
1313 with open(self.tmppath("foo"), "wb") as fh:
1314 fh.write(b"foo second")
1315 with open(self.tmppath("bar"), "wb") as fh:
1316 fh.write(b"bar second")
1317 c.add(self.tmppath("bar").encode())
1318 c.commit("second")
1319 # This wipes out the working directory, ensuring the finder isn't
1320 # finding anything from the filesystem.
1321 c.rawcommand([b"update", b"null"])
1322
1323 finder = self._get_finder(self.tmpdir, "0")
1324 f = finder.get("foo")
1325 self.assertEqual(f.read(), b"foo initial")
1326 self.assertEqual(f.read(), b"foo initial", "read again for good measure")
1327 self.assertIsNone(finder.get("bar"))
1328
1329 finder = self._get_finder(self.tmpdir, rev="1")
1330 f = finder.get("foo")
1331 self.assertEqual(f.read(), b"foo second")
1332 f = finder.get("bar")
1333 self.assertEqual(f.read(), b"bar second")
1334 f = None
1335
1336 def test_recognize_repo_paths(self):
1337 with self._client() as c:
1338 with open(self.tmppath("foo"), "wb") as fh:
1339 fh.write(b"initial")
1340 c.add(self.tmppath("foo").encode())
1341 c.commit("initial")
1342 c.rawcommand([b"update", b"null"])
1343
1344 finder = self._get_finder(self.tmpdir, "0", recognize_repo_paths=True)
1345 with self.assertRaises(NotImplementedError):
1346 list(finder.find(""))
1347
1348 with self.assertRaises(ValueError):
1349 finder.get("foo")
1350 with self.assertRaises(ValueError):
1351 finder.get("")
1352
1353 f = finder.get(self.tmppath("foo"))
1354 self.assertIsInstance(f, MercurialFile)
1355 self.assertEqual(f.read(), b"initial")
1356 f = None
1357
1358
1359 if __name__ == "__main__":
1360 mozunit.main()