Created
March 14, 2017 03:21
-
-
Save AndyLPK247/650b137dbd42c802d1a995a48d4830eb to your computer and use it in GitHub Desktop.
Python Testing 101 pytest Example: Calculator Class Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
from com.automationpanda.example.calc_class import Calculator | |
# "Constants" | |
NUMBER_1 = 3.0 | |
NUMBER_2 = 2.0 | |
# Fixtures | |
@pytest.fixture | |
def calculator(): | |
return Calculator() | |
# Helpers | |
def verify_answer(expected, answer, last_answer): | |
assert expected == answer | |
assert expected == last_answer | |
# Test Cases | |
def test_last_answer_init(calculator): | |
assert calculator.last_answer == 0.0 | |
def test_add(calculator): | |
answer = calculator.add(NUMBER_1, NUMBER_2) | |
verify_answer(5.0, answer, calculator.last_answer) | |
def test_subtract(calculator): | |
answer = calculator.subtract(NUMBER_1, NUMBER_2) | |
verify_answer(1.0, answer, calculator.last_answer) | |
def test_subtract_negative(calculator): | |
answer = calculator.subtract(NUMBER_2, NUMBER_1) | |
verify_answer(-1.0, answer, calculator.last_answer) | |
def test_multiply(calculator): | |
answer = calculator.multiply(NUMBER_1, NUMBER_2) | |
verify_answer(6.0, answer, calculator.last_answer) | |
def test_divide(calculator): | |
answer = calculator.divide(NUMBER_1, NUMBER_2) | |
verify_answer(1.5, answer, calculator.last_answer) | |
def test_divide_by_zero(calculator): | |
with pytest.raises(ZeroDivisionError) as e: | |
calculator.divide(NUMBER_1, 0) | |
assert "division by zero" in str(e.value) | |
@pytest.mark.parametrize("a,b,expected", [ | |
(NUMBER_1, NUMBER_2, NUMBER_1), | |
(NUMBER_2, NUMBER_1, NUMBER_1), | |
(NUMBER_1, NUMBER_1, NUMBER_1), | |
]) | |
def test_maximum(calculator, a, b, expected): | |
answer = calculator.maximum(a, b) | |
verify_answer(expected, answer, calculator.last_answer) | |
@pytest.mark.parametrize("a,b,expected", [ | |
(NUMBER_1, NUMBER_2, NUMBER_2), | |
(NUMBER_2, NUMBER_1, NUMBER_2), | |
(NUMBER_2, NUMBER_2, NUMBER_2), | |
]) | |
def test_minimum(calculator, a, b, expected): | |
answer = calculator.minimum(a, b) | |
verify_answer(expected, answer, calculator.last_answer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i love you thanks very much