1. Mocking
Question: What is mocking and when should you use it?
Mocking is creating a fake version of an external service or object to test behavior in isolation. Use it when the real object is impractical to incorporate into the unit test (e.g., database calls, API requests).
from unittest.mock import MagicMock
# ... usage example
2. Pytest Fixtures
Question: What are pytest fixtures?
Fixtures are functions, which will run before each test function to which it is applied. They are used to feed some data to the tests such as database connections, URLs to test, or some sort of input data.
3. TDD (Test Driven Development)
Question: Explain the TDD cycle.
Red-Green-Refactor:
- Red: Write a failing test for a new feature.
- Green: Write the minimum code necessary to pass the test.
- Refactor: Improve the code while keeping the test passing.
4. Parametrization
Question: How do you run the same test with different inputs in pytest?
Using the @pytest.mark.parametrize decorator.
@pytest.mark.parametrize("input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 54),
])
def test_eval(input, expected):
assert eval(input) == expected
5. Coverage
Question: What is Code Coverage and is 100% coverage necessary?
Definition: A metric that measures the percentage of your code that is executed when your tests run.
Necessity: 100% coverage is a good goal but not always practical or indicative of bug-free code. It's more important to test critical paths and edge cases than to blindly chase a number.