LearnFrenzy
Sign in Take a free test

Python Programming interview · Set 15 of 19

Testing, Debugging and Logging in Python

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Code you can trust

Testing and debugging questions reveal how you work day to day. Show pytest fluency, sensible mocking, a calm debugging method and production-grade logging.

  • pytestTests, fixtures and parametrize.
  • IsolationMocks, monkeypatch and test types.
  • DiagnosisTracebacks, pdb and logging.

Teams hire developers who ship code that keeps working. Expect questions on how you test functions, fake external services, debug a failing script and log what production is doing. Answers use pytest, the de facto standard.

1. Write a simple pytest test.

pytest discovers files named test_*.py and functions starting with test_, and uses plain assert with detailed failure messages. Test behaviour, including edge cases and errors.

# discounts.py
def apply_discount(price: float, percent: float) -> float:
    if not 0 <= percent <= 100:
        raise ValueError("percent must be between 0 and 100")
    return round(price * (100 - percent) / 100, 2)

# test_discounts.py
import pytest
from discounts import apply_discount

def test_applies_discount():
    assert apply_discount(500, 10) == 450

def test_rejects_invalid_percent():
    with pytest.raises(ValueError):
        apply_discount(500, 120)

2. What are fixtures and why use them?

Fixtures provide reusable setup and teardown for tests — a database connection, a temporary file, a test client. Tests ask for a fixture by naming it as a parameter. yield fixtures run cleanup after the test; scopes (function, module, session) control how often setup runs.

import pytest

@pytest.fixture
def cart():
    return Cart(user="asha")

@pytest.fixture
def db(tmp_path):
    conn = sqlite3.connect(tmp_path / "test.db")
    yield conn               # test runs here
    conn.close()             # teardown

def test_empty_cart_total(cart):
    assert cart.total() == 0

3. How does parametrize help?

It runs one test function with many inputs, each reported separately — much clearer than loops inside a test.

@pytest.mark.parametrize("text, expected", [
    ("racecar", True),
    ("A man, a plan, a canal: Panama", True),
    ("hello", False),
    ("", True),
])
def test_is_palindrome(text, expected):
    assert is_palindrome(text) is expected

4. How do you test code that calls an external API?

Replace the external call with a fake using unittest.mock (or pytest's monkeypatch) so tests are fast, repeatable and do not hit the real service. Patch where the name is looked up, not where it is defined, and assert both the result and how the dependency was called.

from unittest.mock import patch

# weather.py: import requests; def is_rainy(city): return requests.get(...).json()["rain"] > 0

def test_is_rainy():
    with patch("weather.requests.get") as fake_get:
        fake_get.return_value.json.return_value = {"rain": 4}
        assert is_rainy("Pune") is True
        fake_get.assert_called_once()

5. Unit, integration and end-to-end tests — what is the difference?

Unit tests check one function or class in isolation — many, fast. Integration tests check pieces working together, such as code plus a real database. End-to-end tests drive the whole system as a user would — few, slower. A healthy suite looks like a pyramid: most at the bottom, few at the top.


6. How do you debug a failing Python program?

Read the full traceback from the bottom up — the last line is the error, the frames above show how you got there. Reproduce with a small input. Use breakpoint() to drop into pdb (or your IDE debugger) and inspect variables, step with n, step into with s, continue with c. Add a regression test once fixed.

def total_price(items):
    total = 0
    for item in items:
        breakpoint()              # pauses here: inspect item, total
        total += item["price"] * item["qty"]
    return total

7. Why use logging instead of print?

logging gives severity levels (DEBUG to CRITICAL), timestamps, module names, configurable outputs (console, files, log services) and can be switched on or off without editing code. Use module-level loggers, lazy %s formatting and logger.exception() inside except blocks to capture tracebacks. Never log passwords or personal data.

import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)

def charge(order_id, amount):
    logger.info("charging order %s amount %s", order_id, amount)
    try:
        gateway.charge(order_id, amount)
    except GatewayError:
        logger.exception("charge failed for order %s", order_id)
        raise

8. What is test coverage and is 100% the goal?

Coverage measures which lines (and branches) your tests execute — pytest --cov with pytest-cov. It finds untested code, but high coverage does not prove good tests: a test can run a line without checking anything. Aim for strong coverage of business logic and edge cases rather than a number.

pip install pytest pytest-cov
pytest --cov=app --cov-report=term-missing

Remember

Key points

  • Plain assert in pytest

    Rich failure messages for free.

  • Patch where it is used

    patch("module.requests.get").

  • breakpoint() to debug

    Inspect state instead of guessing.

  • logging, not print

    Levels, context and tracebacks.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the difference between Mock and MagicMock? Intermediate

    MagicMock also supports magic methods such as __len__ and __iter__; otherwise they behave the same. patch creates a MagicMock by default.

  2. 2 What is test-driven development? Basic

    Write a failing test first, write the minimum code to pass it, then refactor — repeated in small steps. It produces testable designs and a safety net.

  3. 3 How do you test code that depends on the current time? Intermediate

    Inject a clock (pass now as a parameter or dependency), or freeze time with a library such as freezegun or time-machine.

  4. 4 pytest vs unittest? Basic

    unittest is in the standard library with class-based tests and assert methods; pytest needs less boilerplate, has fixtures and plugins, and also runs unittest tests.

  5. 5 How do you debug a process running in production? Advanced

    Use structured logs and metrics first, then tools like py-spy dump to see live stack traces without stopping it; reproduce locally with the same input once you know where it fails.

  6. 6 What should a good unit test look like? Basic

    Fast, independent, deterministic and focused on one behaviour, with a descriptive name and the Arrange–Act–Assert structure.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links