C
Python/Testing/Lesson 22

Getting Started with pytest

1 hr·theory
Python

Getting Started with pytest

🎯 By the end of this lesson

After finishing this lesson, you will be able to confidently do the following three things.

  • ✅ Explain why Python became the standard language for AI/data
  • ✅ Set up venv + requirements.txt for Python 3.x
  • ✅ Use the 4 built-in functions: print / input / type / dir

Keep these learning goals as a checklist, and close the lesson once you can answer all of them.

pytest — Code + Execution Output

pytest = Python's standard testing framework (used by Django, FastAPI, numpy, and more). Any function whose name starts with test_ is automatically discovered.


1. Installation + First Test

bash
$ pip install pytest
python
# test_math.py
def add(a, b):
    return a + b

def test_add_normal():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2
bash
$ pytest test_math.py
# ============= 2 passed in 0.05s =============

2. Detailed Error on Failure

python
def test_fail():
    assert add(2, 3) == 6        # ❌ 5 != 6
code
FAILED test_math.py::test_fail
assert 5 == 6
 +  where 5 = add(2, 3)

3. Exception Assertion

python
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by 0")
    return a / b

def test_raises_exception_on_zero_division():
    with pytest.raises(ValueError, match="Cannot divide by 0"):
        divide(10, 0)

4. Parameterization — Multiple Cases at Once

python
import pytest

@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5),
    (-1, -1, -2),
    (0, 0, 0),
    (100, 200, 300),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

# 4 tests run automatically

5. Fixture — Shared Setup

python
import pytest

@pytest.fixture
def user():
    return {"name": "Hong Gil-dong", "age": 28}

def test_name(user):                       # fixture automatically injected
    assert user["name"] == "Hong Gil-dong"

def test_age(user):
    assert user["age"] >= 18

One-line Summary

def test_X(): assert ... + parametrize + fixture — these three cover 95% of cases.

💻 Basic Usage of pytest
# Installation: pip install pytest

# test_example.py
def test_addition():
    assert 1 + 1 == 2

def test_string():
    assert "hello".upper() == "HELLO"

# Exception test
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

# Parameterized test
@pytest.mark.parametrize("input,expected", [
    (1, 1),
    (2, 4),
    (3, 9),
])
def test_square(input, expected):
    assert input ** 2 == expected

# Markers (conditional execution)
@pytest.mark.skip(reason="Not yet implemented")
def test_not_implemented():
    pass

@pytest.mark.skipif(True, reason="Conditional skip")
def test_conditional():
    pass

# Execution
# pytest                    # All tests
# pytest test_example.py    # Specific file
# pytest -v                 # Detailed output
# pytest -k "square"        # Name filter

💡 Key Points

1. File names: test_.py or _test.py
2. Function names: test_ prefix
3. Verify simply with a single assert statement

Python is used across many fields thanks to its concise and readable syntax. As an interpreted language, it can be executed immediately in a REPL environment. Follow the PEP 8 coding style guide and autoformat with Black/autopep8. Use type hints to improve code readability and IDE support. Manage packages with pip and set up virtual environments with venv/conda.

🐍 Try It Out — Getting Started with pytest

Run the concepts above as actual code. The fastest way to learn is to change values and see the behavior for yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts in this lesson lets you give specific instructions to AI. Instead of a vague 'fix this,' make vocabulary-driven requests — that is the starting point for saving tokens.

  • "Add pytest unit tests + parametrize to this function"
  • "Extract this fixture into conftest.py"

Why This Saves Tokens

Without knowing the concepts, you receive an AI response and still have to ask "What does that mean?" again. That follow-up question is what eats your tokens. Learn the concept once and the conversation ends in one round.

Introduction to pytest - Python