1import os
2import tempfile
3import unittest
4from contextlib import contextmanager
5
6from bangaranga import does_the_banga_rang, TheBangaDoesNotRangError
7
8
9class DoesTheBangaRangTests(unittest.TestCase):
10 @contextmanager
11 def file_with_content(self, content):
12 fd, path = tempfile.mkstemp(text=True)
13
14 try:
15 with os.fdopen(fd, "w", encoding="utf-8") as file:
16 file.write(content)
17
18 yield path
19 finally:
20 if os.path.exists(path):
21 os.remove(path)
22
23 def assert_bangaranga_count(self, content, expected_count):
24 with self.file_with_content(content) as path:
25 self.assertEqual(does_the_banga_rang(path), expected_count)
26
27 def test_returns_one_when_bangaranga_is_a_whole_word(self):
28 self.assert_bangaranga_count("bangaranga", 1)
29
30 def test_returns_two_when_banga_and_ranga_appear_in_order(self):
31 self.assert_bangaranga_count("The banga is doing some ranga!", 2)
32
33 def test_returns_three_when_three_words_form_bangaranga(self):
34 self.assert_bangaranga_count("bang a small ranga", 3)
35
36 def test_returns_minimum_number_of_words_when_multiple_solutions_exist(self):
37 self.assert_bangaranga_count("bang a banga ranga bangaranga", 1)
38
39 def test_is_case_insensitive(self):
40 self.assert_bangaranga_count("BANGA something RANGA", 2)
41
42 def test_words_must_appear_in_the_correct_order(self):
43 self.assert_bangaranga_count("ranga banga", 0)
44
45 def test_returns_zero_when_words_do_not_form_the_whole_target(self):
46 self.assert_bangaranga_count("Does the banga rang?", 0)
47
48 def test_does_not_use_substrings_inside_larger_words(self):
49 self.assert_bangaranga_count(
50 "xxbangaranga bangaranga1 _bangaranga_",
51 0,
52 )
53
54 def test_returns_zero_when_file_has_no_matching_words(self):
55 self.assert_bangaranga_count("123 !!! ---", 0)
56
57 def test_raises_custom_error_when_file_cannot_be_read(self):
58 with tempfile.TemporaryDirectory() as directory:
59 missing_file_path = os.path.join(directory, "missing.txt")
60
61 with self.assertRaises(TheBangaDoesNotRangError):
62 does_the_banga_rang(missing_file_path)
63
64
65if __name__ == "__main__":
66 unittest.main()
..........
----------------------------------------------------------------------
Ran 10 tests in 0.066s
OK
31.05.2026 18:14
31.05.2026 18:15