Interview frequency: …
Short answer
Unit tests exercise a small unit (a function or class) in isolation from external dependencies and run fast, while integration tests exercise several real parts working together, such as code with a database or HTTP.
Explanation
Start with many fast unit tests for domain logic, and add integration tests where the risk lies in the contract between components: SQL queries, serialization, and framework configuration. Integration tests are slower and more brittle, but they catch bugs that mocks hide. You can separate them with pytest markers and run them in a dedicated CI stage.
Code example
# unit: Pure logic with no dependencies
def test_discount():
assert apply_discount(100, 0.2) == 80
# integration: With a real, temporary database
@pytest.mark.integration
def test_save_order(db_session):
repo = OrderRepository(db_session)
repo.add(Order(id=1, total=50))
assert repo.get(1).total == 50Common mistakes
- Mocking everything, including the database, so the tests never reveal real SQL errors.
- Turning every test into a slow end-to-end test until the team stops running them.