Pytest Testing Idioms: Difference between revisions
Jump to navigation
Jump to search
Line 4: | Line 4: | ||
=Overview= | =Overview= | ||
A function that starts with <code>test</code> is automatically considered a test to be executed. | A function that starts with <code>test</code> is automatically considered a test to be executed. | ||
<font color=darkkhaki> | |||
A test function can be injected with a test fixture: Available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory.</code> | |||
=Tested Code is Supposed to Throw Exception= | =Tested Code is Supposed to Throw Exception= |
Revision as of 05:52, 12 March 2022
External
Internal
Overview
A function that starts with test
is automatically considered a test to be executed.
A test function can be injected with a test fixture: Available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory.
Tested Code is Supposed to Throw Exception
import pytest
def test_something_that_should_throw_exception():
with pytest.raises(Exception) as info:
my_method()
If the tested code raises a more specific exception, you can use that instead:
def test_something_that_should_throw_exception():
with pytest.raises(ValueError) as info:
my_method()
This tests the exception arguments:
def test_something_that_should_throw_exception():
with pytest.raises(ValueError) as info:
my_method()
# important: interaction with 'info' must take place outside the with block
assert info.value.args[0] == "some message"
assert "some message" in str(info.value)
Also see: