Tags: #pytest
pytest -svv --color=yes
# https://docs.pytest.org/
If you know a function raises an exception, then you can catch and assert against it by using pytest.raises
with pytest.raises(exceptions.CognitoException) as exc_info:
app.account.confirm(123, 'foo')
assert exc_info.typename == 'CognitoException'
assert str(exc_info.value) == 'SIGNUP_CONFIRMATION_FAILED'
Some functions (such as a command-line tool) only produce side effects (e.g. output) and don’t necessarily return a value to the caller. In order to test these types of functions Pytest let’s us capture their output.
def test_my_function(capsys):
my_function() # function that prints stuff
captured = capsys.readouterr() # Capture output
assert f"Received invalid message ..." in captured.out # Test stdout
assert f"Fatal error ..." in captured.err # Test stderr
Pytest provides a fixture called capsys
, which captures system output. All you need to use it, is to add it as parameter to your test function. Next, after calling function that is being tested, you capture the outputs in form of tuple (out, err)
, which you can then use to assert
against.
Note: you can’t use this on a
tornado.testing.AsyncHTTPTestCase
.
You can use a table matrix to cause a test to be re-run multiple times with the same input arguments, but with different input values:
@pytest.mark.parametrize("input, output", [
("1234", True),
("12345", True),
("foo/bar1_baz2-qux3.beep", False),
("<bad_stuff>", False),
("/<bad_stuff>", False),
])
def test_valid_video_id(input, output):
assert valid_video_id(input) is output
Note: mock decorators come before the pytest decorator (also you can’t use parametrize on a
tornado.testing.AsyncHTTPTestCase
).