1
+ from unittest .mock import patch
2
+
3
+ from colors import print_colors
4
+
5
+ NOT_VALID = 'Not a valid color'
6
+
7
+
8
+ def call_print_colors ():
9
+ # some people prefer sys.exit instead of break
10
+ try :
11
+ print_colors ()
12
+ except SystemExit :
13
+ pass
14
+
15
+
16
+ @patch ("builtins.input" , side_effect = ['quit' ])
17
+ def test_straight_quit (input_mock , capsys ):
18
+ # user only enter quit, program prints bye and breaks loop
19
+ call_print_colors ()
20
+ actual = capsys .readouterr ()[0 ].strip ()
21
+ expected = 'bye'
22
+ assert actual == expected
23
+
24
+
25
+ @patch ("builtins.input" , side_effect = ['blue' , 'quit' ])
26
+ def test_one_valid_color_then_quit (input_mock , capsys ):
27
+ # user enters blue = valid color so print it
28
+ # then user enters quit so break out of loop = end program
29
+ call_print_colors ()
30
+ actual = capsys .readouterr ()[0 ].strip ()
31
+ expected = 'blue\n bye'
32
+ assert actual == expected
33
+
34
+
35
+ @patch ("builtins.input" , side_effect = ['green' , 'quit' ])
36
+ def test_one_invalid_color_then_quit (input_mock , capsys ):
37
+ # user enters green which is not in VALID_COLORS so continue the loop,
38
+ # user then enters quit so loop breaks (end function / program)
39
+ call_print_colors ()
40
+ actual = capsys .readouterr ()[0 ].strip ()
41
+ expected = f'{ NOT_VALID } \n bye'
42
+ assert actual == expected
43
+
44
+
45
+ @patch ("builtins.input" , side_effect = ['white' , 'red' , 'quit' ])
46
+ def test_invalid_then_valid_color_then_quit (nput_mock , capsys ):
47
+ # white is not a valid color so continue the loop,
48
+ # then user enters red which is valid so print it, then quit
49
+ call_print_colors ()
50
+ actual = capsys .readouterr ()[0 ].strip ()
51
+ expected = f'{ NOT_VALID } \n red\n bye'
52
+ assert actual == expected
53
+
54
+
55
+ @patch ("builtins.input" , side_effect = ['yellow' , 'orange' , 'quit' ])
56
+ def test_valid_then_invalid_color_then_quit (input_mock , capsys ):
57
+ # yellow is a valid color so print it, user then enters orange
58
+ # which is not a valid color so continue loop, lastly user
59
+ # enters quit so exit loop = reaching end function / program
60
+ call_print_colors ()
61
+ actual = capsys .readouterr ()[0 ].strip ()
62
+ expected = f'yellow\n { NOT_VALID } \n bye'
63
+ assert actual == expected
0 commit comments