← Back to libraryQuestion 202 of 468
🐍PythonBeginner

pytest Basics

📌 Definition:

pytest is the most popular Python test framework. Tests are plain functions named test_* using the assert statement; pytest auto-discovers them and gives rich failure output.

📖 Detailed Explanation:

You write def test_login(): assert result == expected in a file named test_*.py or *_test.py, and run pytest. No boilerplate class or special assert methods are required — pytest rewrites plain assert to show detailed diffs on failure. Useful flags: -v (verbose), -k 'expr' (select by name), -m marker (by marker), -x (stop on first failure), --maxfail, and -s (show prints). pytest integrates fixtures, parametrization, plugins (pytest-html, pytest-xdist for parallelism), and works with Selenium/requests. Its low ceremony makes it the default choice for test automation in Python.

🔑 Key Points:
  • Test functions named test_* with plain assert
  • Auto-discovery of test_*.py / *_test.py
  • Rich assert introspection (detailed failure diffs)
  • Flags: -v, -k, -m, -x, -s; plugins for HTML/parallel
🌍 Real-World Example:

A quick API check: def test_status(): assert requests.get(url).status_code == 200 — pytest discovers and runs it, and on failure shows the actual status code inline.

🎯 Scenario-Based Interview Question:

Why can pytest use a plain assert while unittest needs self.assertEqual?