|
| 1 | +from unittest.mock import patch |
| 2 | +import random |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from guess import get_random_number, Game |
| 7 | + |
| 8 | + |
| 9 | +@patch.object(random, 'randint') |
| 10 | +def test_get_random_number(m): |
| 11 | + m.return_value = 17 |
| 12 | + assert get_random_number() == 17 |
| 13 | + |
| 14 | + |
| 15 | +@patch("builtins.input", side_effect=[11, '12', 'Bob', 12, 5, |
| 16 | + -1, 21, 7, None]) |
| 17 | +def test_guess(inp): |
| 18 | + game = Game() |
| 19 | + # good |
| 20 | + assert game.guess() == 11 |
| 21 | + assert game.guess() == 12 |
| 22 | + # not a number |
| 23 | + with pytest.raises(ValueError): |
| 24 | + game.guess() |
| 25 | + # already guessed 12 |
| 26 | + with pytest.raises(ValueError): |
| 27 | + game.guess() |
| 28 | + # good |
| 29 | + assert game.guess() == 5 |
| 30 | + # out of range values |
| 31 | + with pytest.raises(ValueError): |
| 32 | + game.guess() |
| 33 | + with pytest.raises(ValueError): |
| 34 | + game.guess() |
| 35 | + # good |
| 36 | + assert game.guess() == 7 |
| 37 | + # user hit enter |
| 38 | + with pytest.raises(ValueError): |
| 39 | + game.guess() |
| 40 | + |
| 41 | + |
| 42 | +def test_validate_guess(capfd): |
| 43 | + game = Game() |
| 44 | + game._answer = 2 |
| 45 | + |
| 46 | + assert not game._validate_guess(1) |
| 47 | + out, _ = capfd.readouterr() |
| 48 | + assert out.rstrip() == '1 is too low' |
| 49 | + |
| 50 | + assert not game._validate_guess(3) |
| 51 | + out, _ = capfd.readouterr() |
| 52 | + assert out.rstrip() == '3 is too high' |
| 53 | + |
| 54 | + assert game._validate_guess(2) |
| 55 | + out, _ = capfd.readouterr() |
| 56 | + assert out.rstrip() == '2 is correct!' |
| 57 | + |
| 58 | + |
| 59 | +@patch("builtins.input", side_effect=[4, 22, 9, 4, 6]) |
| 60 | +def test_game_win(inp, capfd): |
| 61 | + game = Game() |
| 62 | + game._answer = 6 |
| 63 | + |
| 64 | + game() |
| 65 | + assert game._win is True |
| 66 | + |
| 67 | + out = capfd.readouterr()[0] |
| 68 | + expected = ['4 is too low', 'Number not in range', |
| 69 | + '9 is too high', 'Already guessed', |
| 70 | + '6 is correct!', 'It took you 3 guesses'] |
| 71 | + |
| 72 | + output = [line.strip() for line |
| 73 | + in out.split('\n') if line.strip()] |
| 74 | + for line, exp in zip(output, expected): |
| 75 | + assert line == exp |
| 76 | + |
| 77 | + |
| 78 | +@patch("builtins.input", side_effect=[None, 5, 9, 14, 11, 12]) |
| 79 | +def test_game_lose(inp, capfd): |
| 80 | + game = Game() |
| 81 | + game._answer = 13 |
| 82 | + |
| 83 | + game() |
| 84 | + assert game._win is False |
0 commit comments