Coverage for tests\test_calc_class.py: 100%

39 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-26 20:30 +0800

1""" 

2test_calc_class.py contains pytest tests for the Calculator class. 

3pytest discovers tests named "test_*". 

4pytest can run test classes, but functions are a better way. 

5Each test function uses a fixture for setup. 

6Compare this example to test_calc.py in example-py-unittest. 

7""" 

8 

9import pytest 

10from com.automationpanda.example.calc_class import Calculator 

11 

12# "Constants" 

13 

14NUMBER_1 = 3.0 

15NUMBER_2 = 2.0 

16 

17 

18# Fixtures 

19 

20@pytest.fixture 

21def calculator(): 

22 return Calculator() 

23 

24 

25# Helpers 

26 

27def verify_answer(expected, answer, last_answer): 

28 assert expected == answer 

29 assert expected == last_answer 

30 

31 

32# Test Cases 

33 

34def test_last_answer_init(calculator): 

35 assert calculator.last_answer == 0.0 

36 

37 

38def test_add(calculator): 

39 answer = calculator.add(NUMBER_1, NUMBER_2) 

40 verify_answer(5.0, answer, calculator.last_answer) 

41 

42 

43def test_subtract(calculator): 

44 answer = calculator.subtract(NUMBER_1, NUMBER_2) 

45 verify_answer(1.0, answer, calculator.last_answer) 

46 

47 

48def test_subtract_negative(calculator): 

49 answer = calculator.subtract(NUMBER_2, NUMBER_1) 

50 verify_answer(-1.0, answer, calculator.last_answer) 

51 

52 

53def test_multiply(calculator): 

54 answer = calculator.multiply(NUMBER_1, NUMBER_2) 

55 verify_answer(6.0, answer, calculator.last_answer) 

56 

57 

58def test_divide(calculator): 

59 answer = calculator.divide(NUMBER_1, NUMBER_2) 

60 verify_answer(1.5, answer, calculator.last_answer) 

61 

62 

63# Test for dividing by zero catches the exception 

64# http://doc.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions 

65 

66def test_divide_by_zero(calculator): 

67 with pytest.raises(ZeroDivisionError) as e: 

68 calculator.divide(NUMBER_1, 0) 

69 assert "division by zero" in str(e.value) 

70 

71 

72# Tests for maximum and minimum use parameters 

73# To use the fixture, put it as the first function argument 

74# http://doc.pytest.org/en/latest/parametrize.html 

75 

76@pytest.mark.parametrize("a,b,expected", [ 

77 (NUMBER_1, NUMBER_2, NUMBER_1), 

78 (NUMBER_2, NUMBER_1, NUMBER_1), 

79 (NUMBER_1, NUMBER_1, NUMBER_1), 

80]) 

81def test_maximum(calculator, a, b, expected): 

82 answer = calculator.maximum(a, b) 

83 verify_answer(expected, answer, calculator.last_answer) 

84 

85 

86@pytest.mark.parametrize("a,b,expected", [ 

87 (NUMBER_1, NUMBER_2, NUMBER_2), 

88 (NUMBER_2, NUMBER_1, NUMBER_2), 

89 (NUMBER_2, NUMBER_2, NUMBER_2), 

90]) 

91def test_minimum(calculator, a, b, expected): 

92 answer = calculator.minimum(a, b) 

93 verify_answer(expected, answer, calculator.last_answer)