Created
July 13, 2020 03:20
-
-
Save Sharadh/74873c799113a1f3a78878893efb7ec8 to your computer and use it in GitHub Desktop.
Code snippet to accompany blogpost on 5 pytest best practices
This file contains hidden or 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 | |
def divide(a, b): | |
return a / b | |
@pytest.mark.parametrize("a, b, expected, is_error", [ | |
(1, 1, 1, False), | |
(42, 1, 42, False), | |
(84, 2, 42, False), | |
(42, "b", TypeError, True), | |
("a", 42, TypeError, True), | |
(42, 0, ZeroDivisionError, True), | |
]) | |
def test_divide_antipattern(a, b, expected, is_error): | |
if is_error: | |
with pytest.raises(expected): | |
divide(a, b) | |
else: | |
assert divide(a, b) == expected | |
@pytest.mark.parametrize("a, b, expected", [ | |
(1, 1, 1), | |
(42, 1, 42), | |
(84, 2, 42), | |
]) | |
def test_divide_ok(a, b, expected): | |
assert divide(a, b) == expected | |
@pytest.mark.parametrize("a, b, expected", [ | |
(42, "b", TypeError), | |
("a", 42, TypeError), | |
(42, 0, ZeroDivisionError), | |
]) | |
def test_divide_error(a, b, expected): | |
with pytest.raises(expected): | |
divide(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment