Coverage for cogapp/test_cogapp.py: 29.27%
921 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 06:49 -0500
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 06:49 -0500
1"""Test cogapp."""
3import io
4import os
5import os.path
6import random
7import re
8import shutil
9import stat
10import sys
11import tempfile
12import threading
13from unittest import TestCase
15from .cogapp import Cog, CogOptions, CogGenerator
16from .cogapp import CogError, CogUsageError, CogGeneratedError, CogUserException
17from .cogapp import __version__, main
18from .hashhandler import HashHandler
19from .makefiles import make_files
20from .options import Markers, description
21from .whiteutils import reindent_block
24class CogTestsInMemory(TestCase):
25 """Test cases for cogapp.Cog()"""
27 def test_no_cog(self):
28 strings = [
29 "",
30 " ",
31 " \t \t \tx",
32 "hello",
33 "the cat\nin the\nhat.",
34 "Horton\n\tHears A\n\t\tWho",
35 ]
36 for s in strings:
37 self.assertEqual(Cog().process_string(s), s)
39 def test_simple(self):
40 infile = """\
41 Some text.
42 //[[[cog
43 import cog
44 cog.outl("This is line one\\n")
45 cog.outl("This is line two")
46 //]]]
47 gobbledegook.
48 //[[[end]]]
49 epilogue.
50 """
52 outfile = """\
53 Some text.
54 //[[[cog
55 import cog
56 cog.outl("This is line one\\n")
57 cog.outl("This is line two")
58 //]]]
59 This is line one
61 This is line two
62 //[[[end]]]
63 epilogue.
64 """
66 self.assertEqual(Cog().process_string(infile), outfile)
68 def test_empty_cog(self):
69 # The cog clause can be totally empty. Not sure why you'd want it,
70 # but it works.
71 infile = """\
72 hello
73 //[[[cog
74 //]]]
75 //[[[end]]]
76 goodbye
77 """
79 infile = reindent_block(infile)
80 self.assertEqual(Cog().process_string(infile), infile)
82 def test_multiple_cogs(self):
83 # One file can have many cog chunks, even abutting each other.
84 infile = """\
85 //[[[cog
86 cog.out("chunk1")
87 //]]]
88 chunk1
89 //[[[end]]]
90 //[[[cog
91 cog.out("chunk2")
92 //]]]
93 chunk2
94 //[[[end]]]
95 between chunks
96 //[[[cog
97 cog.out("chunk3")
98 //]]]
99 chunk3
100 //[[[end]]]
101 """
103 infile = reindent_block(infile)
104 self.assertEqual(Cog().process_string(infile), infile)
106 def test_trim_blank_lines(self):
107 infile = """\
108 //[[[cog
109 cog.out("This is line one\\n", trimblanklines=True)
110 cog.out('''
111 This is line two
112 ''', dedent=True, trimblanklines=True)
113 cog.outl("This is line three", trimblanklines=True)
114 //]]]
115 This is line one
116 This is line two
117 This is line three
118 //[[[end]]]
119 """
121 infile = reindent_block(infile)
122 self.assertEqual(Cog().process_string(infile), infile)
124 def test_trim_empty_blank_lines(self):
125 infile = """\
126 //[[[cog
127 cog.out("This is line one\\n", trimblanklines=True)
128 cog.out('''
129 This is line two
130 ''', dedent=True, trimblanklines=True)
131 cog.out('', dedent=True, trimblanklines=True)
132 cog.outl("This is line three", trimblanklines=True)
133 //]]]
134 This is line one
135 This is line two
136 This is line three
137 //[[[end]]]
138 """
140 infile = reindent_block(infile)
141 self.assertEqual(Cog().process_string(infile), infile)
143 def test_trim_blank_lines_with_last_partial(self):
144 infile = """\
145 //[[[cog
146 cog.out("This is line one\\n", trimblanklines=True)
147 cog.out("\\nLine two\\nLine three", trimblanklines=True)
148 //]]]
149 This is line one
150 Line two
151 Line three
152 //[[[end]]]
153 """
155 infile = reindent_block(infile)
156 self.assertEqual(Cog().process_string(infile), infile)
158 def test_cog_out_dedent(self):
159 infile = """\
160 //[[[cog
161 cog.out("This is the first line\\n")
162 cog.out('''
163 This is dedent=True 1
164 This is dedent=True 2
165 ''', dedent=True, trimblanklines=True)
166 cog.out('''
167 This is dedent=False 1
168 This is dedent=False 2
169 ''', dedent=False, trimblanklines=True)
170 cog.out('''
171 This is dedent=default 1
172 This is dedent=default 2
173 ''', trimblanklines=True)
174 cog.out("This is the last line\\n")
175 //]]]
176 This is the first line
177 This is dedent=True 1
178 This is dedent=True 2
179 This is dedent=False 1
180 This is dedent=False 2
181 This is dedent=default 1
182 This is dedent=default 2
183 This is the last line
184 //[[[end]]]
185 """
187 infile = reindent_block(infile)
188 self.assertEqual(Cog().process_string(infile), infile)
190 def test22_end_of_line(self):
191 # In Python 2.2, this cog file was not parsing because the
192 # last line is indented but didn't end with a newline.
193 infile = """\
194 //[[[cog
195 import cog
196 for i in range(3):
197 cog.out("%d\\n" % i)
198 //]]]
199 0
200 1
201 2
202 //[[[end]]]
203 """
205 infile = reindent_block(infile)
206 self.assertEqual(Cog().process_string(infile), infile)
208 def test_indented_code(self):
209 infile = """\
210 first line
211 [[[cog
212 import cog
213 for i in range(3):
214 cog.out("xx%d\\n" % i)
215 ]]]
216 xx0
217 xx1
218 xx2
219 [[[end]]]
220 last line
221 """
223 infile = reindent_block(infile)
224 self.assertEqual(Cog().process_string(infile), infile)
226 def test_prefixed_code(self):
227 infile = """\
228 --[[[cog
229 --import cog
230 --for i in range(3):
231 -- cog.out("xx%d\\n" % i)
232 --]]]
233 xx0
234 xx1
235 xx2
236 --[[[end]]]
237 """
239 infile = reindent_block(infile)
240 self.assertEqual(Cog().process_string(infile), infile)
242 def test_prefixed_indented_code(self):
243 infile = """\
244 prologue
245 --[[[cog
246 -- import cog
247 -- for i in range(3):
248 -- cog.out("xy%d\\n" % i)
249 --]]]
250 xy0
251 xy1
252 xy2
253 --[[[end]]]
254 """
256 infile = reindent_block(infile)
257 self.assertEqual(Cog().process_string(infile), infile)
259 def test_bogus_prefix_match(self):
260 infile = """\
261 prologue
262 #[[[cog
263 import cog
264 # This comment should not be clobbered by removing the pound sign.
265 for i in range(3):
266 cog.out("xy%d\\n" % i)
267 #]]]
268 xy0
269 xy1
270 xy2
271 #[[[end]]]
272 """
274 infile = reindent_block(infile)
275 self.assertEqual(Cog().process_string(infile), infile)
277 def test_no_final_newline(self):
278 # If the cog'ed output has no final newline,
279 # it shouldn't eat up the cog terminator.
280 infile = """\
281 prologue
282 [[[cog
283 import cog
284 for i in range(3):
285 cog.out("%d" % i)
286 ]]]
287 012
288 [[[end]]]
289 epilogue
290 """
292 infile = reindent_block(infile)
293 self.assertEqual(Cog().process_string(infile), infile)
295 def test_no_output_at_all(self):
296 # If there is absolutely no cog output, that's ok.
297 infile = """\
298 prologue
299 [[[cog
300 i = 1
301 ]]]
302 [[[end]]]
303 epilogue
304 """
306 infile = reindent_block(infile)
307 self.assertEqual(Cog().process_string(infile), infile)
309 def test_purely_blank_line(self):
310 # If there is a blank line in the cog code with no whitespace
311 # prefix, that should be OK.
313 infile = """\
314 prologue
315 [[[cog
316 import sys
317 cog.out("Hello")
318 $
319 cog.out("There")
320 ]]]
321 HelloThere
322 [[[end]]]
323 epilogue
324 """
326 infile = reindent_block(infile.replace("$", ""))
327 self.assertEqual(Cog().process_string(infile), infile)
329 def test_empty_outl(self):
330 # Alexander Belchenko suggested the string argument to outl should
331 # be optional. Does it work?
333 infile = """\
334 prologue
335 [[[cog
336 cog.outl("x")
337 cog.outl()
338 cog.outl("y")
339 cog.out() # Also optional, a complete no-op.
340 cog.outl(trimblanklines=True)
341 cog.outl("z")
342 ]]]
343 x
345 y
347 z
348 [[[end]]]
349 epilogue
350 """
352 infile = reindent_block(infile)
353 self.assertEqual(Cog().process_string(infile), infile)
355 def test_first_line_num(self):
356 infile = """\
357 fooey
358 [[[cog
359 cog.outl("started at line number %d" % cog.firstLineNum)
360 ]]]
361 started at line number 2
362 [[[end]]]
363 blah blah
364 [[[cog
365 cog.outl("and again at line %d" % cog.firstLineNum)
366 ]]]
367 and again at line 8
368 [[[end]]]
369 """
371 infile = reindent_block(infile)
372 self.assertEqual(Cog().process_string(infile), infile)
374 def test_compact_one_line_code(self):
375 infile = """\
376 first line
377 hey: [[[cog cog.outl("hello %d" % (3*3*3*3)) ]]] looky!
378 get rid of this!
379 [[[end]]]
380 last line
381 """
383 outfile = """\
384 first line
385 hey: [[[cog cog.outl("hello %d" % (3*3*3*3)) ]]] looky!
386 hello 81
387 [[[end]]]
388 last line
389 """
391 infile = reindent_block(infile)
392 self.assertEqual(Cog().process_string(infile), reindent_block(outfile))
394 def test_inside_out_compact(self):
395 infile = """\
396 first line
397 hey?: ]]] what is this? [[[cog strange!
398 get rid of this!
399 [[[end]]]
400 last line
401 """
402 with self.assertRaisesRegex(
403 CogError, r"^infile.txt\(2\): Cog code markers inverted$"
404 ):
405 Cog().process_string(reindent_block(infile), "infile.txt")
407 def test_sharing_globals(self):
408 infile = """\
409 first line
410 hey: [[[cog s="hey there" ]]] looky!
411 [[[end]]]
412 more literal junk.
413 [[[cog cog.outl(s) ]]]
414 [[[end]]]
415 last line
416 """
418 outfile = """\
419 first line
420 hey: [[[cog s="hey there" ]]] looky!
421 [[[end]]]
422 more literal junk.
423 [[[cog cog.outl(s) ]]]
424 hey there
425 [[[end]]]
426 last line
427 """
429 infile = reindent_block(infile)
430 self.assertEqual(Cog().process_string(infile), reindent_block(outfile))
432 def test_assert_in_cog_code(self):
433 # Check that we can test assertions in cog code in the test framework.
434 infile = """\
435 [[[cog
436 assert 1 == 2, "Oops"
437 ]]]
438 [[[end]]]
439 """
440 infile = reindent_block(infile)
441 with self.assertRaisesRegex(CogUserException, "AssertionError: Oops"):
442 Cog().process_string(infile)
444 def test_cog_previous(self):
445 # Check that we can access the previous run's output.
446 infile = """\
447 [[[cog
448 assert cog.previous == "Hello there!\\n", "WTF??"
449 cog.out(cog.previous)
450 cog.outl("Ran again!")
451 ]]]
452 Hello there!
453 [[[end]]]
454 """
456 outfile = """\
457 [[[cog
458 assert cog.previous == "Hello there!\\n", "WTF??"
459 cog.out(cog.previous)
460 cog.outl("Ran again!")
461 ]]]
462 Hello there!
463 Ran again!
464 [[[end]]]
465 """
467 infile = reindent_block(infile)
468 self.assertEqual(Cog().process_string(infile), reindent_block(outfile))
470 def test_unrelated_triple_closing_brackets(self):
471 # Python code with accurate type annotations may have triple closing brackets.
472 # The Python code may be embedded in other files with cog usage,
473 # such as RST files or GitHub workflows. Cog must not error on this input.
474 # The example below is a fully-valid, executable GitHub workflow.
475 infile = """\
476 on:
477 push:
478 jobs:
479 demo:
480 runs-on: ubuntu-latest
481 steps:
482 - shell: bash
483 run: |
484 # [[[cog cog.outl("echo 'hello'") ]]]
485 echo 'hello'
486 # [[[end]]]
487 - shell: python
488 run: |
489 def demo() -> tuple[tuple[tuple[str]]]:
490 # This is what's being tested ^^^
491 #
492 return ((("hello world",),),)
493 print(demo()[0][0][0])
494 """
496 infile = reindent_block(infile)
497 self.assertEqual(Cog().process_string(infile), infile)
500class CogOptionsTests(TestCase):
501 """Test the CogOptions class."""
503 def test_equality(self):
504 o = CogOptions()
505 p = CogOptions()
506 self.assertEqual(o, p)
507 o.parse_args(["-r"])
508 self.assertNotEqual(o, p)
509 p.parse_args(["-r"])
510 self.assertEqual(o, p)
512 def test_cloning(self):
513 o = CogOptions()
514 o.parse_args(["-I", "fooey", "-I", "booey", "-s", " /*x*/"])
515 p = o.clone()
516 self.assertEqual(o, p)
517 p.parse_args(["-I", "huey", "-D", "foo=quux"])
518 self.assertNotEqual(o, p)
519 q = CogOptions()
520 q.parse_args(
521 [
522 "-I",
523 "fooey",
524 "-I",
525 "booey",
526 "-s",
527 " /*x*/",
528 "-I",
529 "huey",
530 "-D",
531 "foo=quux",
532 ]
533 )
534 self.assertEqual(p, q)
536 def test_combining_flags(self):
537 # Single-character flags can be combined.
538 o = CogOptions()
539 o.parse_args(["-e", "-r", "-z"])
540 p = CogOptions()
541 p.parse_args(["-erz"])
542 self.assertEqual(o, p)
544 def test_markers(self):
545 o = Markers.from_arg("a b c")
546 self.assertEqual("a", o.begin_spec)
547 self.assertEqual("b", o.end_spec)
548 self.assertEqual("c", o.end_output)
550 def test_markers_switch(self):
551 o = CogOptions()
552 o.parse_args(["--markers", "a b c"])
553 self.assertEqual("a", o.begin_spec)
554 self.assertEqual("b", o.end_spec)
555 self.assertEqual("c", o.end_output)
558class FileStructureTests(TestCase):
559 """Test that we're properly strict about the structure of files."""
561 def is_bad(self, infile, msg=None):
562 infile = reindent_block(infile)
563 with self.assertRaisesRegex(CogError, "^" + re.escape(msg) + "$"):
564 Cog().process_string(infile, "infile.txt")
566 def test_begin_no_end(self):
567 infile = """\
568 Fooey
569 #[[[cog
570 cog.outl('hello')
571 """
572 self.is_bad(infile, "infile.txt(2): Cog block begun but never ended.")
574 def test_no_eoo(self):
575 infile = """\
576 Fooey
577 #[[[cog
578 cog.outl('hello')
579 #]]]
580 """
581 self.is_bad(infile, "infile.txt(4): Missing '[[[end]]]' before end of file.")
583 infile2 = """\
584 Fooey
585 #[[[cog
586 cog.outl('hello')
587 #]]]
588 #[[[cog
589 cog.outl('goodbye')
590 #]]]
591 """
592 self.is_bad(infile2, "infile.txt(5): Unexpected '[[[cog'")
594 def test_start_with_eoo(self):
595 infile = """\
596 #[[[end]]]
597 """
598 self.is_bad(infile, "infile.txt(1): Unexpected '[[[end]]]'")
600 infile2 = """\
601 #[[[cog
602 cog.outl('hello')
603 #]]]
604 #[[[end]]]
605 #[[[end]]]
606 """
607 self.is_bad(infile2, "infile.txt(5): Unexpected '[[[end]]]'")
609 def test_no_end(self):
610 infile = """\
611 #[[[cog
612 cog.outl("hello")
613 #[[[end]]]
614 """
615 self.is_bad(infile, "infile.txt(3): Unexpected '[[[end]]]'")
617 infile2 = """\
618 #[[[cog
619 cog.outl('hello')
620 #]]]
621 #[[[end]]]
622 #[[[cog
623 cog.outl("hello")
624 #[[[end]]]
625 """
626 self.is_bad(infile2, "infile.txt(7): Unexpected '[[[end]]]'")
628 def test_two_begins(self):
629 infile = """\
630 #[[[cog
631 #[[[cog
632 cog.outl("hello")
633 #]]]
634 #[[[end]]]
635 """
636 self.is_bad(infile, "infile.txt(2): Unexpected '[[[cog'")
638 infile2 = """\
639 #[[[cog
640 cog.outl("hello")
641 #]]]
642 #[[[end]]]
643 #[[[cog
644 #[[[cog
645 cog.outl("hello")
646 #]]]
647 #[[[end]]]
648 """
649 self.is_bad(infile2, "infile.txt(6): Unexpected '[[[cog'")
651 def test_two_ends(self):
652 infile = """\
653 #[[[cog
654 cog.outl("hello")
655 #]]]
656 #]]]
657 #[[[end]]]
658 """
659 self.is_bad(infile, "infile.txt(4): Unexpected ']]]'")
661 infile2 = """\
662 #[[[cog
663 cog.outl("hello")
664 #]]]
665 #[[[end]]]
666 #[[[cog
667 cog.outl("hello")
668 #]]]
669 #]]]
670 #[[[end]]]
671 """
672 self.is_bad(infile2, "infile.txt(8): Unexpected ']]]'")
675class CogErrorTests(TestCase):
676 """Test cases for cog.error()."""
678 def test_error_msg(self):
679 infile = """\
680 [[[cog cog.error("This ain't right!")]]]
681 [[[end]]]
682 """
684 infile = reindent_block(infile)
685 with self.assertRaisesRegex(CogGeneratedError, "^This ain't right!$"):
686 Cog().process_string(infile)
688 def test_error_no_msg(self):
689 infile = """\
690 [[[cog cog.error()]]]
691 [[[end]]]
692 """
694 infile = reindent_block(infile)
695 with self.assertRaisesRegex(
696 CogGeneratedError, "^Error raised by cog generator.$"
697 ):
698 Cog().process_string(infile)
700 def test_no_error_if_error_not_called(self):
701 infile = """\
702 --[[[cog
703 --import cog
704 --for i in range(3):
705 -- if i > 10:
706 -- cog.error("Something is amiss!")
707 -- cog.out("xx%d\\n" % i)
708 --]]]
709 xx0
710 xx1
711 xx2
712 --[[[end]]]
713 """
715 infile = reindent_block(infile)
716 self.assertEqual(Cog().process_string(infile), infile)
719class CogGeneratorGetCodeTests(TestCase):
720 """Tests for CogGenerator.getCode()."""
722 def setUp(self):
723 # All tests get a generator to use, and short same-length names for
724 # the functions we're going to use.
725 self.gen = CogGenerator()
726 self.m = self.gen.parse_marker
727 self.parse_line = self.gen.parse_line
729 def test_empty(self):
730 self.m("// [[[cog")
731 self.m("// ]]]")
732 self.assertEqual(self.gen.get_code(), "")
734 def test_simple(self):
735 self.m("// [[[cog")
736 self.parse_line(' print "hello"')
737 self.parse_line(' print "bye"')
738 self.m("// ]]]")
739 self.assertEqual(self.gen.get_code(), 'print "hello"\nprint "bye"')
741 def test_compressed1(self):
742 # For a while, I supported compressed code blocks, but no longer.
743 self.m('// [[[cog: print """')
744 self.parse_line("// hello")
745 self.parse_line("// bye")
746 self.m('// """)]]]')
747 self.assertEqual(self.gen.get_code(), "hello\nbye")
749 def test_compressed2(self):
750 # For a while, I supported compressed code blocks, but no longer.
751 self.m('// [[[cog: print """')
752 self.parse_line("hello")
753 self.parse_line("bye")
754 self.m('// """)]]]')
755 self.assertEqual(self.gen.get_code(), "hello\nbye")
757 def test_compressed3(self):
758 # For a while, I supported compressed code blocks, but no longer.
759 self.m("// [[[cog")
760 self.parse_line('print """hello')
761 self.parse_line("bye")
762 self.m('// """)]]]')
763 self.assertEqual(self.gen.get_code(), 'print """hello\nbye')
765 def test_compressed4(self):
766 # For a while, I supported compressed code blocks, but no longer.
767 self.m('// [[[cog: print """')
768 self.parse_line("hello")
769 self.parse_line('bye""")')
770 self.m("// ]]]")
771 self.assertEqual(self.gen.get_code(), 'hello\nbye""")')
773 def test_no_common_prefix_for_markers(self):
774 # It's important to be able to use #if 0 to hide lines from a
775 # C++ compiler.
776 self.m("#if 0 //[[[cog")
777 self.parse_line("\timport cog, sys")
778 self.parse_line("")
779 self.parse_line("\tprint sys.argv")
780 self.m("#endif //]]]")
781 self.assertEqual(self.gen.get_code(), "import cog, sys\n\nprint sys.argv")
784class TestCaseWithTempDir(TestCase):
785 def new_cog(self):
786 """Initialize the cog members for another run."""
787 # Create a cog engine, and catch its output.
788 self.cog = Cog()
789 self.output = io.StringIO()
790 self.cog.set_output(stdout=self.output, stderr=self.output)
792 def setUp(self):
793 # Create a temporary directory.
794 self.tempdir = os.path.join(
795 tempfile.gettempdir(), "testcog_tempdir_" + str(random.random())[2:]
796 )
797 os.mkdir(self.tempdir)
798 self.olddir = os.getcwd()
799 os.chdir(self.tempdir)
800 self.new_cog()
802 def tearDown(self):
803 os.chdir(self.olddir)
804 # Get rid of the temporary directory.
805 shutil.rmtree(self.tempdir)
807 def assertFilesSame(self, file_name1, file_name2):
808 with open(os.path.join(self.tempdir, file_name1), "rb") as f1:
809 text1 = f1.read()
810 with open(os.path.join(self.tempdir, file_name2), "rb") as f2:
811 text2 = f2.read()
812 self.assertEqual(text1, text2)
814 def assertFileContent(self, fname, content):
815 absname = os.path.join(self.tempdir, fname)
816 with open(absname, "rb") as f:
817 file_content = f.read()
818 self.assertEqual(file_content, content.encode("utf-8"))
821class ArgumentHandlingTests(TestCaseWithTempDir):
822 def test_argument_failure(self):
823 # Return value 2 means usage problem.
824 self.assertEqual(self.cog.main(["argv0", "-j"]), 2)
825 output = self.output.getvalue()
826 self.assertIn("unrecognized arguments: -j", output)
827 with self.assertRaisesRegex(CogUsageError, r"^No files to process$"):
828 self.cog.callable_main(["argv0"])
829 with self.assertRaisesRegex(CogUsageError, r"^unrecognized arguments: -j$"):
830 self.cog.callable_main(["argv0", "-j"])
832 def test_no_dash_o_and_at_file(self):
833 make_files({"cogfiles.txt": "# Please run cog"})
834 with self.assertRaisesRegex(CogUsageError, r"^Can't use -o with @file$"):
835 self.cog.callable_main(["argv0", "-o", "foo", "@cogfiles.txt"])
837 def test_no_dash_o_and_amp_file(self):
838 make_files({"cogfiles.txt": "# Please run cog"})
839 with self.assertRaisesRegex(CogUsageError, r"^Can't use -o with &file$"):
840 self.cog.callable_main(["argv0", "-o", "foo", "&cogfiles.txt"])
842 def test_no_diff_without_check(self):
843 with self.assertRaisesRegex(
844 CogUsageError, r"^Can't use --diff without --check$"
845 ):
846 self.cog.callable_main(["argv0", "--diff"])
848 def test_dash_v(self):
849 self.assertEqual(self.cog.main(["argv0", "-v"]), 0)
850 output = self.output.getvalue()
851 self.assertEqual("Cog version %s\n" % __version__, output)
853 def produces_help(self, args):
854 self.new_cog()
855 argv = ["argv0"] + args.split()
856 self.assertEqual(self.cog.main(argv), 0)
857 output = self.output.getvalue()
858 self.assertRegex(output, f"^{re.escape(description)}.*")
860 def test_dash_h(self):
861 # -h, --help, or -? anywhere on the command line should just print help.
862 self.produces_help("-h")
863 self.produces_help("--help")
864 self.produces_help("-?")
865 self.produces_help("fooey.txt -h")
866 self.produces_help("fooey.txt --help")
867 self.produces_help("-o -r @fooey.txt -? @booey.txt")
869 def test_dash_o_and_dash_r(self):
870 d = {
871 "cogfile.txt": """\
872 # Please run cog
873 """
874 }
876 make_files(d)
877 with self.assertRaisesRegex(
878 CogUsageError, r"^Can't use -o with -r \(they are opposites\)$"
879 ):
880 self.cog.callable_main(["argv0", "-o", "foo", "-r", "cogfile.txt"])
882 def test_dash_z(self):
883 d = {
884 "test.cog": """\
885 // This is my C++ file.
886 //[[[cog
887 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
888 for fn in fnames:
889 cog.outl("void %s();" % fn)
890 //]]]
891 """,
892 "test.out": """\
893 // This is my C++ file.
894 //[[[cog
895 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
896 for fn in fnames:
897 cog.outl("void %s();" % fn)
898 //]]]
899 void DoSomething();
900 void DoAnotherThing();
901 void DoLastThing();
902 """,
903 }
905 make_files(d)
906 with self.assertRaisesRegex(
907 CogError, r"^test.cog\(6\): Missing '\[\[\[end\]\]\]' before end of file.$"
908 ):
909 self.cog.callable_main(["argv0", "-r", "test.cog"])
910 self.new_cog()
911 self.cog.callable_main(["argv0", "-r", "-z", "test.cog"])
912 self.assertFilesSame("test.cog", "test.out")
914 def test_bad_dash_d(self):
915 with self.assertRaisesRegex(
916 CogUsageError, r"^argument -D: takes a name=value argument$"
917 ):
918 self.cog.callable_main(["argv0", "-Dfooey", "cog.txt"])
919 with self.assertRaisesRegex(
920 CogUsageError, r"^argument -D: takes a name=value argument$"
921 ):
922 self.cog.callable_main(["argv0", "-D", "fooey", "cog.txt"])
924 def test_bad_markers(self):
925 with self.assertRaisesRegex(
926 CogUsageError,
927 r"^argument --markers: requires 3 values separated by spaces, could not parse 'X'$",
928 ):
929 self.cog.callable_main(["argv0", "--markers=X"])
930 with self.assertRaisesRegex(
931 CogUsageError,
932 r"^argument --markers: requires 3 values separated by spaces, could not parse 'A B C D'$",
933 ):
934 self.cog.callable_main(["argv0", "--markers=A B C D"])
937class TestMain(TestCaseWithTempDir):
938 def setUp(self):
939 super().setUp()
940 self.old_argv = sys.argv[:]
941 self.old_stderr = sys.stderr
942 sys.stderr = io.StringIO()
944 def tearDown(self):
945 sys.stderr = self.old_stderr
946 sys.argv = self.old_argv
947 sys.modules.pop("mycode", None)
948 super().tearDown()
950 def test_main_function(self):
951 sys.argv = ["argv0", "-Z"]
952 ret = main()
953 self.assertEqual(ret, 2)
954 stderr = sys.stderr.getvalue()
955 self.assertEqual(stderr, "unrecognized arguments: -Z\n(for help use --help)\n")
957 files = {
958 "test.cog": """\
959 //[[[cog
960 def func():
961 import mycode
962 mycode.boom()
963 //]]]
964 //[[[end]]]
965 -----
966 //[[[cog
967 func()
968 //]]]
969 //[[[end]]]
970 """,
971 "mycode.py": """\
972 def boom():
973 [][0]
974 """,
975 }
977 def test_error_report(self):
978 self.check_error_report()
980 def test_error_report_with_prologue(self):
981 self.check_error_report("-p", "#1\n#2")
983 def check_error_report(self, *args):
984 """Check that the error report is right."""
985 make_files(self.files)
986 sys.argv = ["argv0"] + list(args) + ["-r", "test.cog"]
987 main()
988 expected = reindent_block("""\
989 Traceback (most recent call last):
990 File "test.cog", line 9, in <module>
991 func()
992 File "test.cog", line 4, in func
993 mycode.boom()
994 File "MYCODE", line 2, in boom
995 [][0]
996 IndexError: list index out of range
997 """)
998 expected = expected.replace("MYCODE", os.path.abspath("mycode.py"))
999 assert expected == sys.stderr.getvalue()
1001 def test_error_in_prologue(self):
1002 make_files(self.files)
1003 sys.argv = ["argv0", "-p", "import mycode; mycode.boom()", "-r", "test.cog"]
1004 main()
1005 expected = reindent_block("""\
1006 Traceback (most recent call last):
1007 File "<prologue>", line 1, in <module>
1008 import mycode; mycode.boom()
1009 File "MYCODE", line 2, in boom
1010 [][0]
1011 IndexError: list index out of range
1012 """)
1013 expected = expected.replace("MYCODE", os.path.abspath("mycode.py"))
1014 assert expected == sys.stderr.getvalue()
1017class TestFileHandling(TestCaseWithTempDir):
1018 def test_simple(self):
1019 d = {
1020 "test.cog": """\
1021 // This is my C++ file.
1022 //[[[cog
1023 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1024 for fn in fnames:
1025 cog.outl("void %s();" % fn)
1026 //]]]
1027 //[[[end]]]
1028 """,
1029 "test.out": """\
1030 // This is my C++ file.
1031 //[[[cog
1032 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1033 for fn in fnames:
1034 cog.outl("void %s();" % fn)
1035 //]]]
1036 void DoSomething();
1037 void DoAnotherThing();
1038 void DoLastThing();
1039 //[[[end]]]
1040 """,
1041 }
1043 make_files(d)
1044 self.cog.callable_main(["argv0", "-r", "test.cog"])
1045 self.assertFilesSame("test.cog", "test.out")
1046 output = self.output.getvalue()
1047 self.assertIn("(changed)", output)
1049 def test_print_output(self):
1050 d = {
1051 "test.cog": """\
1052 // This is my C++ file.
1053 //[[[cog
1054 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1055 for fn in fnames:
1056 print("void %s();" % fn)
1057 //]]]
1058 //[[[end]]]
1059 """,
1060 "test.out": """\
1061 // This is my C++ file.
1062 //[[[cog
1063 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1064 for fn in fnames:
1065 print("void %s();" % fn)
1066 //]]]
1067 void DoSomething();
1068 void DoAnotherThing();
1069 void DoLastThing();
1070 //[[[end]]]
1071 """,
1072 }
1074 make_files(d)
1075 self.cog.callable_main(["argv0", "-rP", "test.cog"])
1076 self.assertFilesSame("test.cog", "test.out")
1077 output = self.output.getvalue()
1078 self.assertIn("(changed)", output)
1080 def test_wildcards(self):
1081 d = {
1082 "test.cog": """\
1083 // This is my C++ file.
1084 //[[[cog
1085 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1086 for fn in fnames:
1087 cog.outl("void %s();" % fn)
1088 //]]]
1089 //[[[end]]]
1090 """,
1091 "test2.cog": """\
1092 // This is my C++ file.
1093 //[[[cog
1094 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1095 for fn in fnames:
1096 cog.outl("void %s();" % fn)
1097 //]]]
1098 //[[[end]]]
1099 """,
1100 "test.out": """\
1101 // This is my C++ file.
1102 //[[[cog
1103 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1104 for fn in fnames:
1105 cog.outl("void %s();" % fn)
1106 //]]]
1107 void DoSomething();
1108 void DoAnotherThing();
1109 void DoLastThing();
1110 //[[[end]]]
1111 """,
1112 "not_this_one.cog": """\
1113 // This is my C++ file.
1114 //[[[cog
1115 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1116 for fn in fnames:
1117 cog.outl("void %s();" % fn)
1118 //]]]
1119 //[[[end]]]
1120 """,
1121 "not_this_one.out": """\
1122 // This is my C++ file.
1123 //[[[cog
1124 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1125 for fn in fnames:
1126 cog.outl("void %s();" % fn)
1127 //]]]
1128 //[[[end]]]
1129 """,
1130 }
1132 make_files(d)
1133 self.cog.callable_main(["argv0", "-r", "t*.cog"])
1134 self.assertFilesSame("test.cog", "test.out")
1135 self.assertFilesSame("test2.cog", "test.out")
1136 self.assertFilesSame("not_this_one.cog", "not_this_one.out")
1137 output = self.output.getvalue()
1138 self.assertIn("(changed)", output)
1140 def test_output_file(self):
1141 # -o sets the output file.
1142 d = {
1143 "test.cog": """\
1144 // This is my C++ file.
1145 //[[[cog
1146 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1147 for fn in fnames:
1148 cog.outl("void %s();" % fn)
1149 //]]]
1150 //[[[end]]]
1151 """,
1152 "test.out": """\
1153 // This is my C++ file.
1154 //[[[cog
1155 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
1156 for fn in fnames:
1157 cog.outl("void %s();" % fn)
1158 //]]]
1159 void DoSomething();
1160 void DoAnotherThing();
1161 void DoLastThing();
1162 //[[[end]]]
1163 """,
1164 }
1166 make_files(d)
1167 for outdir in ["", "out/", "out/deeper/", "out/a/b/c/"]:
1168 with self.subTest(outdir=outdir):
1169 self.cog.callable_main(
1170 ["argv0", "-o", f"{outdir}test.cogged", "test.cog"]
1171 )
1172 self.assertFilesSame(f"{outdir}test.cogged", "test.out")
1174 def test_at_file(self):
1175 d = {
1176 "one.cog": """\
1177 //[[[cog
1178 cog.outl("hello world")
1179 //]]]
1180 //[[[end]]]
1181 """,
1182 "one.out": """\
1183 //[[[cog
1184 cog.outl("hello world")
1185 //]]]
1186 hello world
1187 //[[[end]]]
1188 """,
1189 "two.cog": """\
1190 //[[[cog
1191 cog.outl("goodbye cruel world")
1192 //]]]
1193 //[[[end]]]
1194 """,
1195 "two.out": """\
1196 //[[[cog
1197 cog.outl("goodbye cruel world")
1198 //]]]
1199 goodbye cruel world
1200 //[[[end]]]
1201 """,
1202 "cogfiles.txt": """\
1203 # Please run cog
1204 one.cog
1206 two.cog
1207 """,
1208 }
1210 make_files(d)
1211 self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"])
1212 self.assertFilesSame("one.cog", "one.out")
1213 self.assertFilesSame("two.cog", "two.out")
1214 output = self.output.getvalue()
1215 self.assertIn("(changed)", output)
1217 def test_nested_at_file(self):
1218 d = {
1219 "one.cog": """\
1220 //[[[cog
1221 cog.outl("hello world")
1222 //]]]
1223 //[[[end]]]
1224 """,
1225 "one.out": """\
1226 //[[[cog
1227 cog.outl("hello world")
1228 //]]]
1229 hello world
1230 //[[[end]]]
1231 """,
1232 "two.cog": """\
1233 //[[[cog
1234 cog.outl("goodbye cruel world")
1235 //]]]
1236 //[[[end]]]
1237 """,
1238 "two.out": """\
1239 //[[[cog
1240 cog.outl("goodbye cruel world")
1241 //]]]
1242 goodbye cruel world
1243 //[[[end]]]
1244 """,
1245 "cogfiles.txt": """\
1246 # Please run cog
1247 one.cog
1248 @cogfiles2.txt
1249 """,
1250 "cogfiles2.txt": """\
1251 # This one too, please.
1252 two.cog
1253 """,
1254 }
1256 make_files(d)
1257 self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"])
1258 self.assertFilesSame("one.cog", "one.out")
1259 self.assertFilesSame("two.cog", "two.out")
1260 output = self.output.getvalue()
1261 self.assertIn("(changed)", output)
1263 def test_at_file_with_args(self):
1264 d = {
1265 "both.cog": """\
1266 //[[[cog
1267 cog.outl("one: %s" % ('one' in globals()))
1268 cog.outl("two: %s" % ('two' in globals()))
1269 //]]]
1270 //[[[end]]]
1271 """,
1272 "one.out": """\
1273 //[[[cog
1274 cog.outl("one: %s" % ('one' in globals()))
1275 cog.outl("two: %s" % ('two' in globals()))
1276 //]]]
1277 one: True // ONE
1278 two: False // ONE
1279 //[[[end]]]
1280 """,
1281 "two.out": """\
1282 //[[[cog
1283 cog.outl("one: %s" % ('one' in globals()))
1284 cog.outl("two: %s" % ('two' in globals()))
1285 //]]]
1286 one: False // TWO
1287 two: True // TWO
1288 //[[[end]]]
1289 """,
1290 "cogfiles.txt": """\
1291 # Please run cog
1292 both.cog -o in/a/dir/both.one -s ' // ONE' -D one=x
1293 both.cog -o in/a/dir/both.two -s ' // TWO' -D two=x
1294 """,
1295 }
1297 make_files(d)
1298 self.cog.callable_main(["argv0", "@cogfiles.txt"])
1299 self.assertFilesSame("in/a/dir/both.one", "one.out")
1300 self.assertFilesSame("in/a/dir/both.two", "two.out")
1302 def test_at_file_with_bad_arg_combo(self):
1303 d = {
1304 "both.cog": """\
1305 //[[[cog
1306 cog.outl("one: %s" % ('one' in globals()))
1307 cog.outl("two: %s" % ('two' in globals()))
1308 //]]]
1309 //[[[end]]]
1310 """,
1311 "cogfiles.txt": """\
1312 # Please run cog
1313 both.cog
1314 both.cog -d # This is bad: -r and -d
1315 """,
1316 }
1318 make_files(d)
1319 with self.assertRaisesRegex(
1320 CogUsageError,
1321 r"^Can't use -d with -r \(or you would delete all your source!\)$",
1322 ):
1323 self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"])
1325 def test_at_file_with_tricky_filenames(self):
1326 def fix_backslashes(files_txt):
1327 """Make the contents of a files.txt sensitive to the platform."""
1328 if sys.platform != "win32":
1329 files_txt = files_txt.replace("\\", "/")
1330 return files_txt
1332 d = {
1333 "one 1.cog": """\
1334 //[[[cog cog.outl("hello world") ]]]
1335 """,
1336 "one.out": """\
1337 //[[[cog cog.outl("hello world") ]]]
1338 hello world //xxx
1339 """,
1340 "subdir": {
1341 "subback.cog": """\
1342 //[[[cog cog.outl("down deep with backslashes") ]]]
1343 """,
1344 "subfwd.cog": """\
1345 //[[[cog cog.outl("down deep with slashes") ]]]
1346 """,
1347 },
1348 "subback.out": """\
1349 //[[[cog cog.outl("down deep with backslashes") ]]]
1350 down deep with backslashes //yyy
1351 """,
1352 "subfwd.out": """\
1353 //[[[cog cog.outl("down deep with slashes") ]]]
1354 down deep with slashes //zzz
1355 """,
1356 "cogfiles.txt": fix_backslashes("""\
1357 # Please run cog
1358 'one 1.cog' -s ' //xxx'
1359 subdir\\subback.cog -s ' //yyy'
1360 subdir/subfwd.cog -s ' //zzz'
1361 """),
1362 }
1364 make_files(d)
1365 self.cog.callable_main(["argv0", "-z", "-r", "@cogfiles.txt"])
1366 self.assertFilesSame("one 1.cog", "one.out")
1367 self.assertFilesSame("subdir/subback.cog", "subback.out")
1368 self.assertFilesSame("subdir/subfwd.cog", "subfwd.out")
1370 def test_amp_file(self):
1371 d = {
1372 "code": {
1373 "files_to_cog": """\
1374 # A locally resolved file name.
1375 test.cog
1376 """,
1377 "test.cog": """\
1378 //[[[cog
1379 import myampsubmodule
1380 //]]]
1381 //[[[end]]]
1382 """,
1383 "test.out": """\
1384 //[[[cog
1385 import myampsubmodule
1386 //]]]
1387 Hello from myampsubmodule
1388 //[[[end]]]
1389 """,
1390 "myampsubmodule.py": """\
1391 import cog
1392 cog.outl("Hello from myampsubmodule")
1393 """,
1394 }
1395 }
1397 make_files(d)
1398 print(os.path.abspath("code/test.out"))
1399 self.cog.callable_main(["argv0", "-r", "&code/files_to_cog"])
1400 self.assertFilesSame("code/test.cog", "code/test.out")
1402 def run_with_verbosity(self, verbosity):
1403 d = {
1404 "unchanged.cog": """\
1405 //[[[cog
1406 cog.outl("hello world")
1407 //]]]
1408 hello world
1409 //[[[end]]]
1410 """,
1411 "changed.cog": """\
1412 //[[[cog
1413 cog.outl("goodbye cruel world")
1414 //]]]
1415 //[[[end]]]
1416 """,
1417 "cogfiles.txt": """\
1418 unchanged.cog
1419 changed.cog
1420 """,
1421 }
1423 make_files(d)
1424 self.cog.callable_main(
1425 ["argv0", "-r", "--verbosity=" + verbosity, "@cogfiles.txt"]
1426 )
1427 output = self.output.getvalue()
1428 return output
1430 def test_verbosity0(self):
1431 output = self.run_with_verbosity("0")
1432 self.assertEqual(output, "")
1434 def test_verbosity1(self):
1435 output = self.run_with_verbosity("1")
1436 self.assertEqual(output, "Cogging changed.cog (changed)\n")
1438 def test_verbosity2(self):
1439 output = self.run_with_verbosity("2")
1440 self.assertEqual(
1441 output, "Cogging unchanged.cog\nCogging changed.cog (changed)\n"
1442 )
1444 def test_change_dir(self):
1445 # The code can change directories, cog will move us back.
1446 d = {
1447 "sub": {
1448 "data.txt": "Hello!",
1449 },
1450 "test.cog": """\
1451 //[[[cog
1452 import os
1453 os.chdir("sub")
1454 cog.outl(open("data.txt").read())
1455 //]]]
1456 //[[[end]]]
1457 """,
1458 "test.out": """\
1459 //[[[cog
1460 import os
1461 os.chdir("sub")
1462 cog.outl(open("data.txt").read())
1463 //]]]
1464 Hello!
1465 //[[[end]]]
1466 """,
1467 }
1469 make_files(d)
1470 self.cog.callable_main(["argv0", "-r", "test.cog"])
1471 self.assertFilesSame("test.cog", "test.out")
1472 output = self.output.getvalue()
1473 self.assertIn("(changed)", output)
1476class CogTestLineEndings(TestCaseWithTempDir):
1477 """Tests for -U option (force LF line-endings in output)."""
1479 lines_in = [
1480 "Some text.",
1481 "//[[[cog",
1482 'cog.outl("Cog text")',
1483 "//]]]",
1484 "gobbledegook.",
1485 "//[[[end]]]",
1486 "epilogue.",
1487 "",
1488 ]
1490 lines_out = [
1491 "Some text.",
1492 "//[[[cog",
1493 'cog.outl("Cog text")',
1494 "//]]]",
1495 "Cog text",
1496 "//[[[end]]]",
1497 "epilogue.",
1498 "",
1499 ]
1501 def test_output_native_eol(self):
1502 make_files({"infile": "\n".join(self.lines_in)})
1503 self.cog.callable_main(["argv0", "-o", "outfile", "infile"])
1504 self.assertFileContent("outfile", os.linesep.join(self.lines_out))
1506 def test_output_lf_eol(self):
1507 make_files({"infile": "\n".join(self.lines_in)})
1508 self.cog.callable_main(["argv0", "-U", "-o", "outfile", "infile"])
1509 self.assertFileContent("outfile", "\n".join(self.lines_out))
1511 def test_replace_native_eol(self):
1512 make_files({"test.cog": "\n".join(self.lines_in)})
1513 self.cog.callable_main(["argv0", "-r", "test.cog"])
1514 self.assertFileContent("test.cog", os.linesep.join(self.lines_out))
1516 def test_replace_lf_eol(self):
1517 make_files({"test.cog": "\n".join(self.lines_in)})
1518 self.cog.callable_main(["argv0", "-U", "-r", "test.cog"])
1519 self.assertFileContent("test.cog", "\n".join(self.lines_out))
1522class CogTestCharacterEncoding(TestCaseWithTempDir):
1523 def test_simple(self):
1524 d = {
1525 "test.cog": b"""\
1526 // This is my C++ file.
1527 //[[[cog
1528 cog.outl("// Unicode: \xe1\x88\xb4 (U+1234)")
1529 //]]]
1530 //[[[end]]]
1531 """,
1532 "test.out": b"""\
1533 // This is my C++ file.
1534 //[[[cog
1535 cog.outl("// Unicode: \xe1\x88\xb4 (U+1234)")
1536 //]]]
1537 // Unicode: \xe1\x88\xb4 (U+1234)
1538 //[[[end]]]
1539 """.replace(b"\n", os.linesep.encode()),
1540 }
1542 make_files(d)
1543 self.cog.callable_main(["argv0", "-r", "test.cog"])
1544 self.assertFilesSame("test.cog", "test.out")
1545 output = self.output.getvalue()
1546 self.assertIn("(changed)", output)
1548 def test_file_encoding_option(self):
1549 d = {
1550 "test.cog": b"""\
1551 // \xca\xee\xe4\xe8\xf0\xe2\xea\xe0 Windows
1552 //[[[cog
1553 cog.outl("\xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe")
1554 //]]]
1555 //[[[end]]]
1556 """,
1557 "test.out": b"""\
1558 // \xca\xee\xe4\xe8\xf0\xe2\xea\xe0 Windows
1559 //[[[cog
1560 cog.outl("\xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe")
1561 //]]]
1562 \xd1\xfa\xe5\xf8\xfc \xe5\xf9\xb8 \xfd\xf2\xe8\xf5 \xec\xff\xe3\xea\xe8\xf5 \xf4\xf0\xe0\xed\xf6\xf3\xe7\xf1\xea\xe8\xf5 \xe1\xf3\xeb\xee\xea \xe4\xe0 \xe2\xfb\xef\xe5\xe9 \xf7\xe0\xfe
1563 //[[[end]]]
1564 """.replace(b"\n", os.linesep.encode()),
1565 }
1567 make_files(d)
1568 self.cog.callable_main(["argv0", "-n", "cp1251", "-r", "test.cog"])
1569 self.assertFilesSame("test.cog", "test.out")
1570 output = self.output.getvalue()
1571 self.assertIn("(changed)", output)
1574class TestCaseWithImports(TestCaseWithTempDir):
1575 """Automatic resetting of sys.modules for tests that import modules.
1577 When running tests which import modules, the sys.modules list
1578 leaks from one test to the next. This test case class scrubs
1579 the list after each run to keep the tests isolated from each other.
1581 """
1583 def setUp(self):
1584 super().setUp()
1585 self.sysmodulekeys = list(sys.modules)
1587 def tearDown(self):
1588 modstoscrub = [
1589 modname for modname in sys.modules if modname not in self.sysmodulekeys
1590 ]
1591 for modname in modstoscrub:
1592 del sys.modules[modname]
1593 super().tearDown()
1596class CogIncludeTests(TestCaseWithImports):
1597 dincludes = {
1598 "test.cog": """\
1599 //[[[cog
1600 import mymodule
1601 //]]]
1602 //[[[end]]]
1603 """,
1604 "test.out": """\
1605 //[[[cog
1606 import mymodule
1607 //]]]
1608 Hello from mymodule
1609 //[[[end]]]
1610 """,
1611 "test2.out": """\
1612 //[[[cog
1613 import mymodule
1614 //]]]
1615 Hello from mymodule in inc2
1616 //[[[end]]]
1617 """,
1618 "include": {
1619 "mymodule.py": """\
1620 import cog
1621 cog.outl("Hello from mymodule")
1622 """
1623 },
1624 "inc2": {
1625 "mymodule.py": """\
1626 import cog
1627 cog.outl("Hello from mymodule in inc2")
1628 """
1629 },
1630 "inc3": {
1631 "someothermodule.py": """\
1632 import cog
1633 cog.outl("This is some other module.")
1634 """
1635 },
1636 }
1638 def test_need_include_path(self):
1639 # Try it without the -I, to see that an ImportError happens.
1640 make_files(self.dincludes)
1641 msg = "(ImportError|ModuleNotFoundError): No module named '?mymodule'?"
1642 with self.assertRaisesRegex(CogUserException, msg):
1643 self.cog.callable_main(["argv0", "-r", "test.cog"])
1645 def test_include_path(self):
1646 # Test that -I adds include directories properly.
1647 make_files(self.dincludes)
1648 self.cog.callable_main(["argv0", "-r", "-I", "include", "test.cog"])
1649 self.assertFilesSame("test.cog", "test.out")
1651 def test_two_include_paths(self):
1652 # Test that two -I's add include directories properly.
1653 make_files(self.dincludes)
1654 self.cog.callable_main(
1655 ["argv0", "-r", "-I", "include", "-I", "inc2", "test.cog"]
1656 )
1657 self.assertFilesSame("test.cog", "test.out")
1659 def test_two_include_paths2(self):
1660 # Test that two -I's add include directories properly.
1661 make_files(self.dincludes)
1662 self.cog.callable_main(
1663 ["argv0", "-r", "-I", "inc2", "-I", "include", "test.cog"]
1664 )
1665 self.assertFilesSame("test.cog", "test2.out")
1667 def test_useless_include_path(self):
1668 # Test that the search will continue past the first directory.
1669 make_files(self.dincludes)
1670 self.cog.callable_main(
1671 ["argv0", "-r", "-I", "inc3", "-I", "include", "test.cog"]
1672 )
1673 self.assertFilesSame("test.cog", "test.out")
1675 def test_sys_path_is_unchanged(self):
1676 d = {
1677 "bad.cog": """\
1678 //[[[cog cog.error("Oh no!") ]]]
1679 //[[[end]]]
1680 """,
1681 "good.cog": """\
1682 //[[[cog cog.outl("Oh yes!") ]]]
1683 //[[[end]]]
1684 """,
1685 }
1687 make_files(d)
1688 # Is it unchanged just by creating a cog engine?
1689 oldsyspath = sys.path[:]
1690 self.new_cog()
1691 self.assertEqual(oldsyspath, sys.path)
1692 # Is it unchanged for a successful run?
1693 self.new_cog()
1694 self.cog.callable_main(["argv0", "-r", "good.cog"])
1695 self.assertEqual(oldsyspath, sys.path)
1696 # Is it unchanged for a successful run with includes?
1697 self.new_cog()
1698 self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "good.cog"])
1699 self.assertEqual(oldsyspath, sys.path)
1700 # Is it unchanged for a successful run with two includes?
1701 self.new_cog()
1702 self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "-I", "quux", "good.cog"])
1703 self.assertEqual(oldsyspath, sys.path)
1704 # Is it unchanged for a failed run?
1705 self.new_cog()
1706 with self.assertRaisesRegex(CogError, r"^Oh no!$"):
1707 self.cog.callable_main(["argv0", "-r", "bad.cog"])
1708 self.assertEqual(oldsyspath, sys.path)
1709 # Is it unchanged for a failed run with includes?
1710 self.new_cog()
1711 with self.assertRaisesRegex(CogError, r"^Oh no!$"):
1712 self.cog.callable_main(["argv0", "-r", "-I", "xyzzy", "bad.cog"])
1713 self.assertEqual(oldsyspath, sys.path)
1714 # Is it unchanged for a failed run with two includes?
1715 self.new_cog()
1716 with self.assertRaisesRegex(CogError, r"^Oh no!$"):
1717 self.cog.callable_main(
1718 ["argv0", "-r", "-I", "xyzzy", "-I", "quux", "bad.cog"]
1719 )
1720 self.assertEqual(oldsyspath, sys.path)
1722 def test_sub_directories(self):
1723 # Test that relative paths on the command line work, with includes.
1725 d = {
1726 "code": {
1727 "test.cog": """\
1728 //[[[cog
1729 import mysubmodule
1730 //]]]
1731 //[[[end]]]
1732 """,
1733 "test.out": """\
1734 //[[[cog
1735 import mysubmodule
1736 //]]]
1737 Hello from mysubmodule
1738 //[[[end]]]
1739 """,
1740 "mysubmodule.py": """\
1741 import cog
1742 cog.outl("Hello from mysubmodule")
1743 """,
1744 }
1745 }
1747 make_files(d)
1748 # We should be able to invoke cog without the -I switch, and it will
1749 # auto-include the current directory
1750 self.cog.callable_main(["argv0", "-r", "code/test.cog"])
1751 self.assertFilesSame("code/test.cog", "code/test.out")
1754class CogTestsInFiles(TestCaseWithTempDir):
1755 def test_warn_if_no_cog_code(self):
1756 # Test that the -e switch warns if there is no Cog code.
1757 d = {
1758 "with.cog": """\
1759 //[[[cog
1760 cog.outl("hello world")
1761 //]]]
1762 hello world
1763 //[[[end]]]
1764 """,
1765 "without.cog": """\
1766 There's no cog
1767 code in this file.
1768 """,
1769 }
1771 make_files(d)
1772 self.cog.callable_main(["argv0", "-e", "with.cog"])
1773 output = self.output.getvalue()
1774 self.assertNotIn("Warning", output)
1775 self.new_cog()
1776 self.cog.callable_main(["argv0", "-e", "without.cog"])
1777 output = self.output.getvalue()
1778 self.assertIn("Warning: no cog code found in without.cog", output)
1779 self.new_cog()
1780 self.cog.callable_main(["argv0", "without.cog"])
1781 output = self.output.getvalue()
1782 self.assertNotIn("Warning", output)
1784 def test_file_name_props(self):
1785 d = {
1786 "cog1.txt": """\
1787 //[[[cog
1788 cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile))
1789 //]]]
1790 this is cog1.txt in, cog1.txt out
1791 [[[end]]]
1792 """,
1793 "cog1.out": """\
1794 //[[[cog
1795 cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile))
1796 //]]]
1797 This is cog1.txt in, cog1.txt out
1798 [[[end]]]
1799 """,
1800 "cog1out.out": """\
1801 //[[[cog
1802 cog.outl("This is %s in, %s out" % (cog.inFile, cog.outFile))
1803 //]]]
1804 This is cog1.txt in, cog1out.txt out
1805 [[[end]]]
1806 """,
1807 }
1809 make_files(d)
1810 self.cog.callable_main(["argv0", "-r", "cog1.txt"])
1811 self.assertFilesSame("cog1.txt", "cog1.out")
1812 self.new_cog()
1813 self.cog.callable_main(["argv0", "-o", "cog1out.txt", "cog1.txt"])
1814 self.assertFilesSame("cog1out.txt", "cog1out.out")
1816 def test_globals_dont_cross_files(self):
1817 # Make sure that global values don't get shared between files.
1818 d = {
1819 "one.cog": """\
1820 //[[[cog s = "This was set in one.cog" ]]]
1821 //[[[end]]]
1822 //[[[cog cog.outl(s) ]]]
1823 //[[[end]]]
1824 """,
1825 "one.out": """\
1826 //[[[cog s = "This was set in one.cog" ]]]
1827 //[[[end]]]
1828 //[[[cog cog.outl(s) ]]]
1829 This was set in one.cog
1830 //[[[end]]]
1831 """,
1832 "two.cog": """\
1833 //[[[cog
1834 try:
1835 cog.outl(s)
1836 except NameError:
1837 cog.outl("s isn't set!")
1838 //]]]
1839 //[[[end]]]
1840 """,
1841 "two.out": """\
1842 //[[[cog
1843 try:
1844 cog.outl(s)
1845 except NameError:
1846 cog.outl("s isn't set!")
1847 //]]]
1848 s isn't set!
1849 //[[[end]]]
1850 """,
1851 "cogfiles.txt": """\
1852 # Please run cog
1853 one.cog
1855 two.cog
1856 """,
1857 }
1859 make_files(d)
1860 self.cog.callable_main(["argv0", "-r", "@cogfiles.txt"])
1861 self.assertFilesSame("one.cog", "one.out")
1862 self.assertFilesSame("two.cog", "two.out")
1863 output = self.output.getvalue()
1864 self.assertIn("(changed)", output)
1866 def test_remove_generated_output(self):
1867 d = {
1868 "cog1.txt": """\
1869 //[[[cog
1870 cog.outl("This line was generated.")
1871 //]]]
1872 This line was generated.
1873 //[[[end]]]
1874 This line was not.
1875 """,
1876 "cog1.out": """\
1877 //[[[cog
1878 cog.outl("This line was generated.")
1879 //]]]
1880 //[[[end]]]
1881 This line was not.
1882 """,
1883 "cog1.out2": """\
1884 //[[[cog
1885 cog.outl("This line was generated.")
1886 //]]]
1887 This line was generated.
1888 //[[[end]]]
1889 This line was not.
1890 """,
1891 }
1893 make_files(d)
1894 # Remove generated output.
1895 self.cog.callable_main(["argv0", "-r", "-x", "cog1.txt"])
1896 self.assertFilesSame("cog1.txt", "cog1.out")
1897 self.new_cog()
1898 # Regenerate the generated output.
1899 self.cog.callable_main(["argv0", "-r", "cog1.txt"])
1900 self.assertFilesSame("cog1.txt", "cog1.out2")
1901 self.new_cog()
1902 # Remove the generated output again.
1903 self.cog.callable_main(["argv0", "-r", "-x", "cog1.txt"])
1904 self.assertFilesSame("cog1.txt", "cog1.out")
1906 def test_msg_call(self):
1907 infile = """\
1908 #[[[cog
1909 cog.msg("Hello there!")
1910 #]]]
1911 #[[[end]]]
1912 """
1913 infile = reindent_block(infile)
1914 self.assertEqual(self.cog.process_string(infile), infile)
1915 output = self.output.getvalue()
1916 self.assertEqual(output, "Message: Hello there!\n")
1918 def test_error_message_has_no_traceback(self):
1919 # Test that a Cog error is printed to stderr with no traceback.
1921 d = {
1922 "cog1.txt": """\
1923 //[[[cog
1924 cog.outl("This line was newly")
1925 cog.outl("generated by cog")
1926 cog.outl("blah blah.")
1927 //]]]
1928 Xhis line was newly
1929 generated by cog
1930 blah blah.
1931 //[[[end]]] (sum: qFQJguWta5)
1932 """,
1933 }
1935 make_files(d)
1936 stderr = io.StringIO()
1937 self.cog.set_output(stderr=stderr)
1938 self.cog.main(["argv0", "-c", "-r", "cog1.txt"])
1939 self.assertEqual(self.output.getvalue(), "Cogging cog1.txt\n")
1940 self.assertEqual(
1941 stderr.getvalue(),
1942 "cog1.txt(9): Output has been edited! Delete old checksum to unprotect.\n",
1943 )
1945 def test_dash_d(self):
1946 d = {
1947 "test.cog": """\
1948 --[[[cog cog.outl("Defined fooey as " + fooey) ]]]
1949 --[[[end]]]
1950 """,
1951 "test.kablooey": """\
1952 --[[[cog cog.outl("Defined fooey as " + fooey) ]]]
1953 Defined fooey as kablooey
1954 --[[[end]]]
1955 """,
1956 "test.einstein": """\
1957 --[[[cog cog.outl("Defined fooey as " + fooey) ]]]
1958 Defined fooey as e=mc2
1959 --[[[end]]]
1960 """,
1961 }
1963 make_files(d)
1964 self.cog.callable_main(["argv0", "-r", "-D", "fooey=kablooey", "test.cog"])
1965 self.assertFilesSame("test.cog", "test.kablooey")
1966 make_files(d)
1967 self.cog.callable_main(["argv0", "-r", "-Dfooey=kablooey", "test.cog"])
1968 self.assertFilesSame("test.cog", "test.kablooey")
1969 make_files(d)
1970 self.cog.callable_main(["argv0", "-r", "-Dfooey=e=mc2", "test.cog"])
1971 self.assertFilesSame("test.cog", "test.einstein")
1972 make_files(d)
1973 self.cog.callable_main(
1974 ["argv0", "-r", "-Dbar=quux", "-Dfooey=kablooey", "test.cog"]
1975 )
1976 self.assertFilesSame("test.cog", "test.kablooey")
1977 make_files(d)
1978 self.cog.callable_main(
1979 ["argv0", "-r", "-Dfooey=kablooey", "-Dbar=quux", "test.cog"]
1980 )
1981 self.assertFilesSame("test.cog", "test.kablooey")
1982 make_files(d)
1983 self.cog.callable_main(
1984 ["argv0", "-r", "-Dfooey=gooey", "-Dfooey=kablooey", "test.cog"]
1985 )
1986 self.assertFilesSame("test.cog", "test.kablooey")
1988 def test_output_to_stdout(self):
1989 d = {
1990 "test.cog": """\
1991 --[[[cog cog.outl('Hey there!') ]]]
1992 --[[[end]]]
1993 """
1994 }
1996 make_files(d)
1997 stderr = io.StringIO()
1998 self.cog.set_output(stderr=stderr)
1999 self.cog.callable_main(["argv0", "test.cog"])
2000 output = self.output.getvalue()
2001 outerr = stderr.getvalue()
2002 self.assertEqual(
2003 output, "--[[[cog cog.outl('Hey there!') ]]]\nHey there!\n--[[[end]]]\n"
2004 )
2005 self.assertEqual(outerr, "")
2007 def test_read_from_stdin(self):
2008 stdin = io.StringIO("--[[[cog cog.outl('Wow') ]]]\n--[[[end]]]\n")
2010 def restore_stdin(old_stdin):
2011 sys.stdin = old_stdin
2013 self.addCleanup(restore_stdin, sys.stdin)
2014 sys.stdin = stdin
2016 stderr = io.StringIO()
2017 self.cog.set_output(stderr=stderr)
2018 self.cog.callable_main(["argv0", "-"])
2019 output = self.output.getvalue()
2020 outerr = stderr.getvalue()
2021 self.assertEqual(output, "--[[[cog cog.outl('Wow') ]]]\nWow\n--[[[end]]]\n")
2022 self.assertEqual(outerr, "")
2024 def test_suffix_output_lines(self):
2025 d = {
2026 "test.cog": """\
2027 Hey there.
2028 ;[[[cog cog.outl('a\\nb\\n \\nc') ]]]
2029 ;[[[end]]]
2030 Good bye.
2031 """,
2032 "test.out": """\
2033 Hey there.
2034 ;[[[cog cog.outl('a\\nb\\n \\nc') ]]]
2035 a (foo)
2036 b (foo)
2037 """ # These three trailing spaces are important.
2038 # The suffix is not applied to completely blank lines.
2039 """
2040 c (foo)
2041 ;[[[end]]]
2042 Good bye.
2043 """,
2044 }
2046 make_files(d)
2047 self.cog.callable_main(["argv0", "-r", "-s", " (foo)", "test.cog"])
2048 self.assertFilesSame("test.cog", "test.out")
2050 def test_empty_suffix(self):
2051 d = {
2052 "test.cog": """\
2053 ;[[[cog cog.outl('a\\nb\\nc') ]]]
2054 ;[[[end]]]
2055 """,
2056 "test.out": """\
2057 ;[[[cog cog.outl('a\\nb\\nc') ]]]
2058 a
2059 b
2060 c
2061 ;[[[end]]]
2062 """,
2063 }
2065 make_files(d)
2066 self.cog.callable_main(["argv0", "-r", "-s", "", "test.cog"])
2067 self.assertFilesSame("test.cog", "test.out")
2069 def test_hellish_suffix(self):
2070 d = {
2071 "test.cog": """\
2072 ;[[[cog cog.outl('a\\n\\nb') ]]]
2073 """,
2074 "test.out": """\
2075 ;[[[cog cog.outl('a\\n\\nb') ]]]
2076 a /\\n*+([)]><
2078 b /\\n*+([)]><
2079 """,
2080 }
2082 make_files(d)
2083 self.cog.callable_main(["argv0", "-z", "-r", "-s", r" /\n*+([)]><", "test.cog"])
2084 self.assertFilesSame("test.cog", "test.out")
2086 def test_prologue(self):
2087 d = {
2088 "test.cog": """\
2089 Some text.
2090 //[[[cog cog.outl(str(math.sqrt(2))[:12])]]]
2091 //[[[end]]]
2092 epilogue.
2093 """,
2094 "test.out": """\
2095 Some text.
2096 //[[[cog cog.outl(str(math.sqrt(2))[:12])]]]
2097 1.4142135623
2098 //[[[end]]]
2099 epilogue.
2100 """,
2101 }
2103 make_files(d)
2104 self.cog.callable_main(["argv0", "-r", "-p", "import math", "test.cog"])
2105 self.assertFilesSame("test.cog", "test.out")
2107 def test_threads(self):
2108 # Test that the implicitly imported cog module is actually different for
2109 # different threads.
2110 numthreads = 20
2112 d = {}
2113 for i in range(numthreads):
2114 d[f"f{i}.cog"] = (
2115 "x\n" * i
2116 + "[[[cog\n"
2117 + f"assert cog.firstLineNum == int(FIRST) == {i + 1}\n"
2118 + "]]]\n"
2119 + "[[[end]]]\n"
2120 )
2121 make_files(d)
2123 results = []
2125 def thread_main(num):
2126 try:
2127 ret = Cog().main(
2128 ["cog.py", "-r", "-D", f"FIRST={num + 1}", f"f{num}.cog"]
2129 )
2130 assert ret == 0
2131 except Exception as exc: # pragma: no cover (only happens on test failure)
2132 results.append(exc)
2133 else:
2134 results.append(None)
2136 ts = [
2137 threading.Thread(target=thread_main, args=(i,)) for i in range(numthreads)
2138 ]
2139 for t in ts:
2140 t.start()
2141 for t in ts:
2142 t.join()
2143 assert results == [None] * numthreads
2146class CheckTests(TestCaseWithTempDir):
2147 def run_check(self, args, status=0):
2148 actual_status = self.cog.main(["argv0", "--check"] + args)
2149 print(self.output.getvalue())
2150 self.assertEqual(status, actual_status)
2152 def assert_made_files_unchanged(self, d):
2153 for name, content in d.items():
2154 content = reindent_block(content)
2155 if os.name == "nt":
2156 content = content.replace("\n", "\r\n")
2157 self.assertFileContent(name, content)
2159 def test_check_no_cog(self):
2160 d = {
2161 "hello.txt": """\
2162 Hello.
2163 """,
2164 }
2165 make_files(d)
2166 self.run_check(["hello.txt"], status=0)
2167 self.assertEqual(self.output.getvalue(), "Checking hello.txt\n")
2168 self.assert_made_files_unchanged(d)
2170 def test_check_good(self):
2171 d = {
2172 "unchanged.cog": """\
2173 //[[[cog
2174 cog.outl("hello world")
2175 //]]]
2176 hello world
2177 //[[[end]]]
2178 """,
2179 }
2180 make_files(d)
2181 self.run_check(["unchanged.cog"], status=0)
2182 self.assertEqual(self.output.getvalue(), "Checking unchanged.cog\n")
2183 self.assert_made_files_unchanged(d)
2185 def test_check_bad(self):
2186 d = {
2187 "changed.cog": """\
2188 //[[[cog
2189 cog.outl("goodbye world")
2190 //]]]
2191 hello world
2192 //[[[end]]]
2193 """,
2194 }
2195 make_files(d)
2196 self.run_check(["changed.cog"], status=5)
2197 self.assertEqual(
2198 self.output.getvalue(), "Checking changed.cog (changed)\nCheck failed\n"
2199 )
2200 self.assert_made_files_unchanged(d)
2202 def test_check_bad_with_diff(self):
2203 d = {
2204 "skittering.cog": """\
2205 //[[[cog
2206 for i in range(5): cog.outl(f"number {i}")
2207 cog.outl("goodbye world")
2208 //]]]
2209 number 0
2210 number 1
2211 number 2
2212 number 3
2213 number 4
2214 hello world
2215 //[[[end]]]
2216 """,
2217 }
2218 make_files(d)
2219 self.run_check(["--diff", "skittering.cog"], status=5)
2220 output = """\
2221 Checking skittering.cog (changed)
2222 --- current skittering.cog
2223 +++ changed skittering.cog
2224 @@ -7,5 +7,5 @@
2225 number 2
2226 number 3
2227 number 4
2228 -hello world
2229 +goodbye world
2230 //[[[end]]]
2231 Check failed
2232 """
2233 self.assertEqual(self.output.getvalue(), reindent_block(output))
2234 self.assert_made_files_unchanged(d)
2236 def test_check_bad_with_message(self):
2237 d = {
2238 "changed.cog": """\
2239 //[[[cog
2240 cog.outl("goodbye world")
2241 //]]]
2242 hello world
2243 //[[[end]]]
2244 """,
2245 }
2246 make_files(d)
2247 self.run_check(
2248 ["--check-fail-msg=Run `make cogged` to fix", "changed.cog"], status=5
2249 )
2250 self.assertEqual(
2251 self.output.getvalue(),
2252 "Checking changed.cog (changed)\nCheck failed: Run `make cogged` to fix\n",
2253 )
2254 self.assert_made_files_unchanged(d)
2256 def test_check_mixed(self):
2257 d = {
2258 "unchanged.cog": """\
2259 //[[[cog
2260 cog.outl("hello world")
2261 //]]]
2262 hello world
2263 //[[[end]]]
2264 """,
2265 "changed.cog": """\
2266 //[[[cog
2267 cog.outl("goodbye world")
2268 //]]]
2269 hello world
2270 //[[[end]]]
2271 """,
2272 }
2273 make_files(d)
2274 for verbosity, output in [
2275 ("0", "Check failed\n"),
2276 ("1", "Checking changed.cog (changed)\nCheck failed\n"),
2277 (
2278 "2",
2279 "Checking unchanged.cog\nChecking changed.cog (changed)\nCheck failed\n",
2280 ),
2281 ]:
2282 self.new_cog()
2283 self.run_check(
2284 ["--verbosity=%s" % verbosity, "unchanged.cog", "changed.cog"], status=5
2285 )
2286 self.assertEqual(self.output.getvalue(), output)
2287 self.assert_made_files_unchanged(d)
2289 def test_check_with_good_checksum(self):
2290 d = {
2291 "good.txt": """\
2292 //[[[cog
2293 cog.outl("This line was newly")
2294 cog.outl("generated by cog")
2295 cog.outl("blah blah.")
2296 //]]]
2297 This line was newly
2298 generated by cog
2299 blah blah.
2300 //[[[end]]] (checksum: a8540982e5ad6b95c9e9a184b26f4346)
2301 """,
2302 }
2303 make_files(d)
2304 # Have to use -c with --check if there are checksums in the file.
2305 self.run_check(["-c", "good.txt"], status=0)
2306 self.assertEqual(self.output.getvalue(), "Checking good.txt\n")
2307 self.assert_made_files_unchanged(d)
2309 def test_check_with_bad_checksum(self):
2310 d = {
2311 "bad.txt": """\
2312 //[[[cog
2313 cog.outl("This line was newly")
2314 cog.outl("generated by cog")
2315 cog.outl("blah blah.")
2316 //]]]
2317 This line was newly
2318 generated by cog
2319 blah blah.
2320 //[[[end]]] (checksum: a9999999e5ad6b95c9e9a184b26f4346)
2321 """,
2322 }
2323 make_files(d)
2324 # Have to use -c with --check if there are checksums in the file.
2325 self.run_check(["-c", "bad.txt"], status=1)
2326 self.assertEqual(
2327 self.output.getvalue(),
2328 "Checking bad.txt\nbad.txt(9): Output has been edited! Delete old checksum to unprotect.\n",
2329 )
2330 self.assert_made_files_unchanged(d)
2332 def test_check_with_good_sum(self):
2333 d = {
2334 "good.txt": """\
2335 //[[[cog
2336 cog.outl("This line was newly")
2337 cog.outl("generated by cog")
2338 cog.outl("blah blah.")
2339 //]]]
2340 This line was newly
2341 generated by cog
2342 blah blah.
2343 //[[[end]]] (sum: qFQJguWta5)
2344 """,
2345 }
2346 make_files(d)
2347 # Have to use -c with --check if there are checksums in the file.
2348 self.run_check(["-c", "good.txt"], status=0)
2349 self.assertEqual(self.output.getvalue(), "Checking good.txt\n")
2350 self.assert_made_files_unchanged(d)
2352 def test_check_with_bad_sum(self):
2353 d = {
2354 "bad.txt": """\
2355 //[[[cog
2356 cog.outl("This line was newly")
2357 cog.outl("generated by cog")
2358 cog.outl("blah blah.")
2359 //]]]
2360 This line was newly
2361 generated by cog
2362 blah blah.
2363 //[[[end]]] (sum: qZmZmeWta5)
2364 """,
2365 }
2366 make_files(d)
2367 # Have to use -c with --check if there are checksums in the file.
2368 self.run_check(["-c", "bad.txt"], status=1)
2369 self.assertEqual(
2370 self.output.getvalue(),
2371 "Checking bad.txt\nbad.txt(9): Output has been edited! Delete old checksum to unprotect.\n",
2372 )
2373 self.assert_made_files_unchanged(d)
2376class WritabilityTests(TestCaseWithTempDir):
2377 d = {
2378 "test.cog": """\
2379 //[[[cog
2380 for fn in ['DoSomething', 'DoAnotherThing', 'DoLastThing']:
2381 cog.outl("void %s();" % fn)
2382 //]]]
2383 //[[[end]]]
2384 """,
2385 "test.out": """\
2386 //[[[cog
2387 for fn in ['DoSomething', 'DoAnotherThing', 'DoLastThing']:
2388 cog.outl("void %s();" % fn)
2389 //]]]
2390 void DoSomething();
2391 void DoAnotherThing();
2392 void DoLastThing();
2393 //[[[end]]]
2394 """,
2395 }
2397 if os.name == "nt": 2397 ↛ 2399line 2397 didn't jump to line 2399 because the condition on line 2397 was never true
2398 # for Windows
2399 cmd_w_args = "attrib -R %s"
2400 cmd_w_asterisk = "attrib -R *"
2401 else:
2402 # for unix-like
2403 cmd_w_args = "chmod +w %s"
2404 cmd_w_asterisk = "chmod +w *"
2406 def setUp(self):
2407 super().setUp()
2408 make_files(self.d)
2409 self.testcog = os.path.join(self.tempdir, "test.cog")
2410 os.chmod(self.testcog, stat.S_IREAD) # Make the file readonly.
2411 assert not os.access(self.testcog, os.W_OK)
2413 def tearDown(self):
2414 os.chmod(self.testcog, stat.S_IWRITE) # Make the file writable again.
2415 super().tearDown()
2417 def test_readonly_no_command(self):
2418 with self.assertRaisesRegex(CogError, "^Can't overwrite test.cog$"):
2419 self.cog.callable_main(["argv0", "-r", "test.cog"])
2420 assert not os.access(self.testcog, os.W_OK)
2422 def test_readonly_with_command(self):
2423 self.cog.callable_main(["argv0", "-r", "-w", self.cmd_w_args, "test.cog"])
2424 self.assertFilesSame("test.cog", "test.out")
2425 assert os.access(self.testcog, os.W_OK)
2427 def test_readonly_with_command_with_no_slot(self):
2428 self.cog.callable_main(["argv0", "-r", "-w", self.cmd_w_asterisk, "test.cog"])
2429 self.assertFilesSame("test.cog", "test.out")
2430 assert os.access(self.testcog, os.W_OK)
2432 def test_readonly_with_ineffectual_command(self):
2433 with self.assertRaisesRegex(CogError, "^Couldn't make test.cog writable$"):
2434 self.cog.callable_main(["argv0", "-r", "-w", "echo %s", "test.cog"])
2435 assert not os.access(self.testcog, os.W_OK)
2438class ChecksumTests(TestCaseWithTempDir):
2439 def test_create_checksum_output(self):
2440 d = {
2441 "cog1.txt": """\
2442 //[[[cog
2443 cog.outl("This line was generated.")
2444 //]]]
2445 This line was generated.
2446 //[[[end]]] what
2447 This line was not.
2448 """,
2449 "cog1.out": """\
2450 //[[[cog
2451 cog.outl("This line was generated.")
2452 //]]]
2453 This line was generated.
2454 //[[[end]]] (sum: itsT+1m5lq) what
2455 This line was not.
2456 """,
2457 }
2459 make_files(d)
2460 self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"])
2461 self.assertFilesSame("cog1.txt", "cog1.out")
2463 def test_check_checksum_output(self):
2464 d = {
2465 "cog1.txt": """\
2466 //[[[cog
2467 cog.outl("This line was newly")
2468 cog.outl("generated by cog")
2469 cog.outl("blah blah.")
2470 //]]]
2471 This line was generated.
2472 //[[[end]]] (sum: itsT+1m5lq) end
2473 """,
2474 "cog1.out": """\
2475 //[[[cog
2476 cog.outl("This line was newly")
2477 cog.outl("generated by cog")
2478 cog.outl("blah blah.")
2479 //]]]
2480 This line was newly
2481 generated by cog
2482 blah blah.
2483 //[[[end]]] (sum: qFQJguWta5) end
2484 """,
2485 }
2487 make_files(d)
2488 self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"])
2489 self.assertFilesSame("cog1.txt", "cog1.out")
2491 def test_check_old_checksum_format(self):
2492 # Test that old checksum format can still be read
2493 d = {
2494 "cog1.txt": """\
2495 //[[[cog
2496 cog.outl("This line was newly")
2497 cog.outl("generated by cog")
2498 cog.outl("blah blah.")
2499 //]]]
2500 This line was generated.
2501 //[[[end]]] (checksum: 8adb13fb59b996a1c7f0065ea9f3d893) end
2502 """,
2503 "cog1.out": """\
2504 //[[[cog
2505 cog.outl("This line was newly")
2506 cog.outl("generated by cog")
2507 cog.outl("blah blah.")
2508 //]]]
2509 This line was newly
2510 generated by cog
2511 blah blah.
2512 //[[[end]]] (sum: qFQJguWta5) end
2513 """,
2514 }
2516 make_files(d)
2517 self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"])
2518 self.assertFilesSame("cog1.txt", "cog1.out")
2520 def test_excise_with_checksum_removes_hash(self):
2521 # -x -c must drop the checksum entirely, not leave an empty (sum: ).
2522 d = {
2523 "cog1.txt": """\
2524 //[[[cog
2525 cog.outl("This line was generated.")
2526 //]]]
2527 This line was generated.
2528 //[[[end]]] (sum: itsT+1m5lq)
2529 This line was not.
2530 """,
2531 "cog1.out": """\
2532 //[[[cog
2533 cog.outl("This line was generated.")
2534 //]]]
2535 //[[[end]]]
2536 This line was not.
2537 """,
2538 "cog1.out2": """\
2539 //[[[cog
2540 cog.outl("This line was generated.")
2541 //]]]
2542 This line was generated.
2543 //[[[end]]] (sum: itsT+1m5lq)
2544 This line was not.
2545 """,
2546 }
2548 make_files(d)
2549 self.cog.callable_main(["argv0", "-r", "-x", "-c", "cog1.txt"])
2550 self.assertFilesSame("cog1.txt", "cog1.out")
2551 self.new_cog()
2552 self.cog.callable_main(["argv0", "-r", "-c", "cog1.txt"])
2553 self.assertFilesSame("cog1.txt", "cog1.out2")
2555 def test_remove_checksum_output(self):
2556 d = {
2557 "cog1.txt": """\
2558 //[[[cog
2559 cog.outl("This line was newly")
2560 cog.outl("generated by cog")
2561 cog.outl("blah blah.")
2562 //]]]
2563 This line was generated.
2564 //[[[end]]] (sum: itsT+1m5lq) fooey
2565 """,
2566 "cog1.out": """\
2567 //[[[cog
2568 cog.outl("This line was newly")
2569 cog.outl("generated by cog")
2570 cog.outl("blah blah.")
2571 //]]]
2572 This line was newly
2573 generated by cog
2574 blah blah.
2575 //[[[end]]] fooey
2576 """,
2577 }
2579 make_files(d)
2580 self.cog.callable_main(["argv0", "-r", "cog1.txt"])
2581 self.assertFilesSame("cog1.txt", "cog1.out")
2583 def test_tampered_checksum_output(self):
2584 d = {
2585 "cog1.txt": """\
2586 //[[[cog
2587 cog.outl("This line was newly")
2588 cog.outl("generated by cog")
2589 cog.outl("blah blah.")
2590 //]]]
2591 Xhis line was newly
2592 generated by cog
2593 blah blah.
2594 //[[[end]]] (sum: qFQJguWta5)
2595 """,
2596 "cog2.txt": """\
2597 //[[[cog
2598 cog.outl("This line was newly")
2599 cog.outl("generated by cog")
2600 cog.outl("blah blah.")
2601 //]]]
2602 This line was newly
2603 generated by cog
2604 blah blah!
2605 //[[[end]]] (sum: qFQJguWta5)
2606 """,
2607 "cog3.txt": """\
2608 //[[[cog
2609 cog.outl("This line was newly")
2610 cog.outl("generated by cog")
2611 cog.outl("blah blah.")
2612 //]]]
2614 This line was newly
2615 generated by cog
2616 blah blah.
2617 //[[[end]]] (sum: qFQJguWta5)
2618 """,
2619 "cog4.txt": """\
2620 //[[[cog
2621 cog.outl("This line was newly")
2622 cog.outl("generated by cog")
2623 cog.outl("blah blah.")
2624 //]]]
2625 This line was newly
2626 generated by cog
2627 blah blah..
2628 //[[[end]]] (sum: qFQJguWta5)
2629 """,
2630 "cog5.txt": """\
2631 //[[[cog
2632 cog.outl("This line was newly")
2633 cog.outl("generated by cog")
2634 cog.outl("blah blah.")
2635 //]]]
2636 This line was newly
2637 generated by cog
2638 blah blah.
2639 extra
2640 //[[[end]]] (sum: qFQJguWta5)
2641 """,
2642 "cog6.txt": """\
2643 //[[[cog
2644 cog.outl("This line was newly")
2645 cog.outl("generated by cog")
2646 cog.outl("blah blah.")
2647 //]]]
2648 //[[[end]]] (sum: qFQJguWta5)
2649 """,
2650 }
2652 make_files(d)
2653 with self.assertRaisesRegex(
2654 CogError,
2655 r"^cog1.txt\(9\): Output has been edited! Delete old checksum to unprotect.$",
2656 ):
2657 self.cog.callable_main(["argv0", "-c", "cog1.txt"])
2658 with self.assertRaisesRegex(
2659 CogError,
2660 r"^cog2.txt\(9\): Output has been edited! Delete old checksum to unprotect.$",
2661 ):
2662 self.cog.callable_main(["argv0", "-c", "cog2.txt"])
2663 with self.assertRaisesRegex(
2664 CogError,
2665 r"^cog3.txt\(10\): Output has been edited! Delete old checksum to unprotect.$",
2666 ):
2667 self.cog.callable_main(["argv0", "-c", "cog3.txt"])
2668 with self.assertRaisesRegex(
2669 CogError,
2670 r"^cog4.txt\(9\): Output has been edited! Delete old checksum to unprotect.$",
2671 ):
2672 self.cog.callable_main(["argv0", "-c", "cog4.txt"])
2673 with self.assertRaisesRegex(
2674 CogError,
2675 r"^cog5.txt\(10\): Output has been edited! Delete old checksum to unprotect.$",
2676 ):
2677 self.cog.callable_main(["argv0", "-c", "cog5.txt"])
2678 with self.assertRaisesRegex(
2679 CogError,
2680 r"^cog6.txt\(6\): Output has been edited! Delete old checksum to unprotect.$",
2681 ):
2682 self.cog.callable_main(["argv0", "-c", "cog6.txt"])
2684 def test_argv_isnt_modified(self):
2685 argv = ["argv0", "-v"]
2686 orig_argv = argv[:]
2687 self.cog.callable_main(argv)
2688 self.assertEqual(argv, orig_argv)
2691class CustomMarkerTests(TestCaseWithTempDir):
2692 def test_customer_markers(self):
2693 d = {
2694 "test.cog": """\
2695 //{{
2696 cog.outl("void %s();" % "MyFunction")
2697 //}}
2698 //{{end}}
2699 """,
2700 "test.out": """\
2701 //{{
2702 cog.outl("void %s();" % "MyFunction")
2703 //}}
2704 void MyFunction();
2705 //{{end}}
2706 """,
2707 }
2709 make_files(d)
2710 self.cog.callable_main(["argv0", "-r", "--markers={{ }} {{end}}", "test.cog"])
2711 self.assertFilesSame("test.cog", "test.out")
2713 def test_truly_wacky_markers(self):
2714 # Make sure the markers are properly re-escaped.
2715 d = {
2716 "test.cog": """\
2717 //**(
2718 cog.outl("void %s();" % "MyFunction")
2719 //**)
2720 //**(end)**
2721 """,
2722 "test.out": """\
2723 //**(
2724 cog.outl("void %s();" % "MyFunction")
2725 //**)
2726 void MyFunction();
2727 //**(end)**
2728 """,
2729 }
2731 make_files(d)
2732 self.cog.callable_main(
2733 ["argv0", "-r", "--markers=**( **) **(end)**", "test.cog"]
2734 )
2735 self.assertFilesSame("test.cog", "test.out")
2737 def test_change_just_one_marker(self):
2738 d = {
2739 "test.cog": """\
2740 //**(
2741 cog.outl("void %s();" % "MyFunction")
2742 //]]]
2743 //[[[end]]]
2744 """,
2745 "test.out": """\
2746 //**(
2747 cog.outl("void %s();" % "MyFunction")
2748 //]]]
2749 void MyFunction();
2750 //[[[end]]]
2751 """,
2752 }
2754 make_files(d)
2755 self.cog.callable_main(
2756 ["argv0", "-r", "--markers=**( ]]] [[[end]]]", "test.cog"]
2757 )
2758 self.assertFilesSame("test.cog", "test.out")
2761class BlakeTests(TestCaseWithTempDir):
2762 # Blake Winton's contributions.
2763 def test_delete_code(self):
2764 # -o sets the output file.
2765 d = {
2766 "test.cog": """\
2767 // This is my C++ file.
2768 //[[[cog
2769 fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
2770 for fn in fnames:
2771 cog.outl("void %s();" % fn)
2772 //]]]
2773 Some Sample Code Here
2774 //[[[end]]]Data Data
2775 And Some More
2776 """,
2777 "test.out": """\
2778 // This is my C++ file.
2779 void DoSomething();
2780 void DoAnotherThing();
2781 void DoLastThing();
2782 And Some More
2783 """,
2784 }
2786 make_files(d)
2787 self.cog.callable_main(["argv0", "-d", "-o", "test.cogged", "test.cog"])
2788 self.assertFilesSame("test.cogged", "test.out")
2790 def test_delete_code_with_dash_r_fails(self):
2791 d = {
2792 "test.cog": """\
2793 // This is my C++ file.
2794 """
2795 }
2797 make_files(d)
2798 with self.assertRaisesRegex(
2799 CogUsageError,
2800 r"^Can't use -d with -r \(or you would delete all your source!\)$",
2801 ):
2802 self.cog.callable_main(["argv0", "-r", "-d", "test.cog"])
2804 def test_setting_globals(self):
2805 # Blake Winton contributed a way to set the globals that will be used in
2806 # processFile().
2807 d = {
2808 "test.cog": """\
2809 // This is my C++ file.
2810 //[[[cog
2811 for fn in fnames:
2812 cog.outl("void %s();" % fn)
2813 //]]]
2814 Some Sample Code Here
2815 //[[[end]]]""",
2816 "test.out": """\
2817 // This is my C++ file.
2818 void DoBlake();
2819 void DoWinton();
2820 void DoContribution();
2821 """,
2822 }
2824 make_files(d)
2825 globals = {}
2826 globals["fnames"] = ["DoBlake", "DoWinton", "DoContribution"]
2827 self.cog.options.delete_code = True
2828 self.cog.process_file("test.cog", "test.cogged", globals=globals)
2829 self.assertFilesSame("test.cogged", "test.out")
2832class ErrorCallTests(TestCaseWithTempDir):
2833 def test_error_call_has_no_traceback(self):
2834 # Test that cog.error() doesn't show a traceback.
2835 d = {
2836 "error.cog": """\
2837 //[[[cog
2838 cog.error("Something Bad!")
2839 //]]]
2840 //[[[end]]]
2841 """,
2842 }
2844 make_files(d)
2845 self.cog.main(["argv0", "-r", "error.cog"])
2846 output = self.output.getvalue()
2847 self.assertEqual(output, "Cogging error.cog\nError: Something Bad!\n")
2849 def test_real_error_has_traceback(self):
2850 # Test that a genuine error does show a traceback.
2851 d = {
2852 "error.cog": """\
2853 //[[[cog
2854 raise RuntimeError("Hey!")
2855 //]]]
2856 //[[[end]]]
2857 """,
2858 }
2860 make_files(d)
2861 self.cog.main(["argv0", "-r", "error.cog"])
2862 output = self.output.getvalue()
2863 msg = "Actual output:\n" + output
2864 self.assertTrue(
2865 output.startswith("Cogging error.cog\nTraceback (most recent"), msg
2866 )
2867 self.assertIn("RuntimeError: Hey!", output)
2870class HashHandlerTests(TestCase):
2871 """Test cases for HashHandler functionality."""
2873 def setUp(self):
2874 self.handler = HashHandler("[[[end]]]")
2876 def test_validate_hash_with_base64_mismatch(self):
2877 # Test the base64 validation branch with a mismatch
2878 line = "//[[[end]]] (sum: wronghas12)" # 10 chars to match regex
2879 expected_hash = "a8540982e5ad6b95c9e9a184b26f4346"
2881 with self.assertRaises(ValueError) as cm:
2882 self.handler.validate_hash(line, expected_hash)
2883 self.assertEqual(
2884 str(cm.exception),
2885 "Output has been edited! Delete old checksum to unprotect.",
2886 )
2888 def test_validate_hash_with_base64_match(self):
2889 # Test the base64 validation branch with a match
2890 line = "//[[[end]]] (sum: qFQJguWta5)"
2891 expected_hash = "a8540982e5ad6b95c9e9a184b26f4346"
2893 # Should not raise an exception
2894 result = self.handler.validate_hash(line, expected_hash)
2895 self.assertTrue(result)
2898# Things not yet tested:
2899# - A bad -w command (currently fails silently).