Writing Your First pytest Tests
Understand test discovery, assert statements, and test structure.
Writing Your First pytest Tests is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Installing pytest
Install pytest with pip. It has no mandatory configuration — it discovers tests automatically.
# pip install pytest
# Run all tests
# pytest
# Run a specific file
# pytest test_math.pyA Simple Test Function
pytest collects any function starting with test_. Use plain assert statements — pytest rewrites them for detailed output.
# test_math.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0Test Files and Discovery
pytest discovers test files named test_*.py or *_test.py and collects functions named test_* or classes named Test*.
tests/
test_utils.py
test_models.py
conftest.py # shared fixturesGrouping Tests in Classes
Group related tests in a class prefixed with Test. No unittest.TestCase required.
class TestCalculator:
def test_add(self):
assert 1 + 1 == 2
def test_multiply(self):
assert 3 * 4 == 12Testing Exceptions
Use pytest.raises as a context manager to assert that specific exceptions are raised.
import pytest
def divide(a, b):
if b == 0:
raise ZeroDivisionError("cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError, match="cannot divide"):
divide(10, 0)The -v Flag
Run pytest with -v (verbose) to see each test name and its pass/fail status.
# pytest -v
# test_math.py::test_add PASSED
# test_math.py::test_add_negative PASSED
# Show print output too:
# pytest -v -sSkipping Tests
Use @pytest.mark.skip or @pytest.mark.skipif to skip tests conditionally.
import pytest, sys
@pytest.mark.skip(reason="not implemented yet")
def test_future_feature():
assert False
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_only():
assert TrueMarking Tests as Expected Failures
@pytest.mark.xfail marks a test you expect to fail. It passes if it fails and warns if it unexpectedly passes.
import pytest
@pytest.mark.xfail(reason="known bug #42")
def test_buggy():
assert 1 == 2 # will fail, but that's expectedassert Rewriting
pytest rewrites assert statements to show the values that caused a failure — much more useful than a bare AssertionError.
def test_list_equal():
result = [1, 2, 4]
expected = [1, 2, 3]
assert result == expected
# AssertionError:
# assert [1, 2, 4] == [1, 2, 3]
# At index 2 diff: 4 != 3conftest.py
conftest.py is automatically loaded by pytest. Put shared fixtures and plugins here without importing them explicitly.
# conftest.py
import pytest
@pytest.fixture
def sample_data():
return {"key": "value"}
# Any test file in the same dir can use sample_data as a parameterRunning Subsets of Tests
Use -k to run tests matching a keyword expression.
# Run tests containing "add"
# pytest -k "add"
# Run tests NOT containing "slow"
# pytest -k "not slow"
# Run a specific test
# pytest test_math.py::test_addQuick Check
What prefix must a pytest test function name start with to be discovered automatically?
Recap
pytest requires no boilerplate: name files test_*.py, name functions test_*, and use plain assert. Use pytest.raises for exceptions, -v for verbosity, and conftest.py for shared fixtures.
Frequently asked questions
Is the “Writing Your First pytest Tests” lesson free?
Yes — the full text of “Writing Your First pytest Tests” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Writing Your First pytest Tests”?
Understand test discovery, assert statements, and test structure. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Writing Your First pytest Tests” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Writing Your First pytest Tests
- Fixtures and Setup/Teardown
- Parametrize and Test Coverage
- Mocking with unittest.mock