Files

149 lines
6.5 KiB
Python

import contextlib
import io
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from wait_for import main
TOOL = pathlib.Path(__file__).resolve().parents[1] / "wait-for"
class Clock:
"""A fake clock whose sleep advances time and runs the next of the steps given, one per sleep."""
def __init__(self, *steps):
self.now = 0.0
self.steps = list(steps)
def monotonic(self) -> float:
return self.now
def sleep(self, seconds: float):
self.now += seconds
if self.steps:
self.steps.pop(0)()
class WaitFor(unittest.TestCase):
def setUp(self):
self.file = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "report.md")
def test_prints_the_first_line_matching_the_pattern_once_the_file_holds_it(self):
clock = Clock(lambda: self.file.write_text("running\n"), lambda: self.file.write_text("running\n== 3 passed in 1s ==\nFull log: x\n"))
self.assertEqual(main.waited(str(self.file), r"passed|failed", 60, clock), "== 3 passed in 1s ==")
self.assertEqual(clock.now, 2 * main.POLL_SECONDS)
def test_without_a_pattern_prints_the_last_line_once_the_file_holds_anything(self):
clock = Clock(lambda: self.file.write_text(""), lambda: self.file.write_text("# Report\nNo findings.\n"))
self.assertEqual(main.waited(str(self.file), None, 60, clock), "No findings.")
def test_a_file_already_holding_the_line_returns_at_once(self):
self.file.write_text("done\n")
clock = Clock()
self.assertEqual(main.waited(str(self.file), "done", 60, clock), "done")
self.assertEqual(clock.now, 0)
def test_gives_up_at_the_timeout_naming_the_file_and_its_last_line(self):
self.file.write_text("still running\n")
clock = Clock()
self.assertEqual(main.waited(str(self.file), "passed", 30, clock), Failure(f"{self.file} held no line matching `passed` after 30 s; its last line: still running"))
self.assertLessEqual(clock.now, 30)
def test_gives_up_on_a_file_that_never_appears(self):
self.assertEqual(main.waited(str(self.file), None, 5, Clock()), Failure(f"{self.file} did not appear in 5 s"))
def test_waits_for_a_half_written_last_line_to_end(self):
self.file.write_text("running\n== 3 passed in")
clock = Clock(lambda: self.file.write_text("running\n== 3 passed in 1s ==\n"))
self.assertEqual(main.waited(str(self.file), "passed", 60, clock), "== 3 passed in 1s ==")
def test_takes_a_last_line_without_a_newline_once_a_poll_finds_it_unchanged(self):
self.file.write_text("# Report\nNo findings.")
clock = Clock()
self.assertEqual(main.waited(str(self.file), None, 60, clock), "No findings.")
self.assertEqual(clock.now, main.POLL_SECONDS)
def test_takes_a_whole_line_at_once_beside_a_half_written_one(self):
self.file.write_text("a\nb\npart")
clock = Clock()
self.assertEqual(main.waited(str(self.file), "b", 60, clock), "b")
self.assertEqual(clock.now, 0)
self.file.write_text("done\n")
self.assertEqual(main.waited(str(self.file), None, 60, clock), "done")
self.assertEqual(clock.now, 0)
def test_matches_no_part_of_a_half_written_first_line(self):
self.file.write_text("part")
clock = Clock(lambda: self.file.write_text("partial\n"))
self.assertEqual(main.waited(str(self.file), "p", 60, clock), "partial")
def test_reads_a_line_that_is_not_utf_8(self):
self.file.write_bytes(b"caf\xe9 passed\n")
self.assertEqual(main.waited(str(self.file), "passed", 60, Clock()), "caf\ufffd passed")
def test_an_empty_file_gives_up_saying_it_held_nothing_and_no_last_line(self):
self.file.write_text("")
clock = Clock()
self.assertEqual(main.waited(str(self.file), None, 3, clock), Failure(f"{self.file} held no text after 3 s"))
self.assertEqual(clock.now, 3)
def test_sleeps_only_the_time_left_before_the_timeout(self):
clock = Clock()
main.waited(str(self.file), None, 3, clock)
self.assertEqual(clock.now, 3)
clock = Clock()
main.waited(str(self.file), None, 2.5, clock)
self.assertEqual(clock.now, 2.5)
def test_a_folder_fails_at_once_naming_it(self):
self.assertEqual(main.waited(str(self.file.parent), None, 60, Clock()), Failure(f"cannot read {self.file.parent}: Is a directory"))
def test_main_prints_the_line_or_the_reason_and_gives_the_exit_code(self):
self.file.write_text("== 1 passed ==\n")
for argv, expected in (
([str(self.file), "passed", "--timeout", "5"], (0, "== 1 passed ==\n", "")),
(["--help"], (0, main.__doc__.strip() + "\n", "")),
(["-h"], (0, main.__doc__.strip() + "\n", "")),
(["--help", str(self.file)], (0, main.__doc__.strip() + "\n", "")),
([str(self.file), "("], (1, "", "wait-for: cannot read the pattern `(`: missing ), unterminated subpattern at position 0\n")),
):
with self.subTest(argv=argv):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, Clock())
self.assertEqual((code, out.getvalue(), err.getvalue()), expected)
def test_arguments_take_the_timeout_anywhere_and_refuse_a_bad_one(self):
self.assertEqual(main.arguments(["--timeout", "1.5", "f", "p"]), ("f", "p", 1.5))
self.assertEqual(main.arguments(["f"]), ("f", None, 540.0))
self.assertEqual(main.arguments(["f", "--timeout", "0.5"]), ("f", None, 0.5))
for timeout in ("0", "-1", "x", "1.", None):
with self.subTest(timeout=timeout):
argv = ["f", "--timeout"] + ([timeout] if timeout else [])
self.assertEqual(main.arguments(argv), Failure(f"give --timeout a number of seconds above 0; {main.USAGE}"))
for argv in ([], ["f", "a", "b"]):
with self.subTest(argv=argv):
self.assertEqual(main.arguments(argv), Failure(main.USAGE))
def test_the_command_prints_the_line_a_file_holds(self):
self.file.write_text("== 1 passed in 0.1s ==\n")
result = subprocess.run([sys.executable, str(TOOL), str(self.file), "passed", "--timeout", "20"], capture_output=True, text=True, timeout=10)
self.assertEqual((result.returncode, result.stdout, result.stderr), (0, "== 1 passed in 0.1s ==\n", ""))
def test_refuses_a_bad_pattern_timeout_or_argument_count_waiting_for_nothing(self):
for argv in ([], [str(self.file), "("], [str(self.file), "--timeout", "0"], [str(self.file), "--timeout", "x"], [str(self.file), "a", "b"]):
with self.subTest(argv=argv):
result = subprocess.run([sys.executable, str(TOOL), *argv], capture_output=True, text=True, timeout=10)
self.assertEqual((result.returncode, result.stdout), (1, ""))
self.assertIn("wait-for: ", result.stderr)
if __name__ == "__main__":
unittest.main()