Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Created February 8, 2019 15:40
Show Gist options
  • Save hectorcanto/cced9be3f33fc0eaec4f51fc13fd3fc9 to your computer and use it in GitHub Desktop.
Save hectorcanto/cced9be3f33fc0eaec4f51fc13fd3fc9 to your computer and use it in GitHub Desktop.
Two examples using parametrize to test several inputs with the same test.
"""
Parametrize allows you to run the same test with different inputs and expectations.
Each input will result in a separated test.
As first parameter of the mark, you name the variables in a string, separated by commas.
As second parameter, you input an iterable (a list) with tuples of the values of each case variables.
"""
import pytest
def make_sum(a, b):
return sum([a, b])
# Check the docs here: https://docs.pytest.org/en/latest/parametrize.html
@pytest.mark.parametrize("first_summand, seccond_summand, expected", [
(1, 1, 2),
(1, 2, 3),
(1, -1, 0),
(12, 12, 24)
])
def test_parametrize(first_summand, seccond_summand, expected):
assert make_sum(first_summand, seccond_summand) == expected
# An example of test checking an exception rises. Negative test is also importatnt
@pytest.mark.parametrize("first_summand, seccond_summand, excepction", [
(1, "a", TypeError),
(1, [2], TypeError),
])
def test_parametrize_exception(first_summand, seccond_summand, excepction):
with pytest.raises(excepction):
make_sum(first_summand, seccond_summand)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment