Informational 1,000 words 12 prompts ready Updated 05 Apr 2026

pytest basics: assertions, test files, and discovery rules

Informational article in the Testing Python Projects with pytest topical map — Getting started with pytest content group. 12 copy-paste AI prompts for ChatGPT, Claude & Gemini covering SEO outline, body writing, meta tags, internal links, and Twitter/X & LinkedIn posts.

← Back to Testing Python Projects with pytest 12 Prompts • 4 Phases
Overview

pytest basics: assertions, test files, and discovery rules: pytest discovers tests by default by collecting functions named test_* and test classes named Test* from files that match the two filename patterns test_*.py and *_test.py, recursively under the current directory and its subdirectories. This behavior follows pytest's default collection rules and will import test modules to inspect for callables; test discovery will skip directories named with a leading dot or those excluded via pytest.ini patterns. The filename patterns are the single most important factor to ensure runnable tests in both local environments and CI. Test modules are imported with standard Python import semantics, so package layout and sys.path affect discovery.

Collection uses a mix of import-time introspection and AST-level analysis plus pytest's assert rewriting to produce rich failure diffs and local variable values, which distinguishes pytest from unittest and plain assert statements. Tools such as tox and CI runners invoke pytest's collector, which applies pytest naming conventions and discovery patterns from pytest.ini, pytest.conf, or pyproject.toml to include or ignore paths. The test collector looks for functions, methods, and classes, then creates nodes that are executed by the runner; fixtures declared in conftest.py provide dependency injection across collected tests. Command-line flags like -k for substring selection and -q for quieter output alter what the collector runs without changing file layout. Plugins such as pytest-xdist or coverage integrate at collection and runtime.

A frequent misconception is that plain Python assert yields the same output across runners; in reality pytest's assert rewriting transforms assert expressions at import time so failures include evaluated operands and inline diffs, unlike unittest's self.assertEqual style, which explains why raw assert formatting may look sparse outside pytest. Another common pitfall is incorrect naming: files like testsinstead.py or classes named TestMath without test_ prefixed functions will not be collected, breaking pytest test discovery. Misplacing conftest.py in the wrong package root can hide fixtures from subpackages in CI, causing inexplicable fixture lookup errors. Correct adherence to pytest test files naming and conftest.py fixtures placement prevents most discovery-related failures. Selection flags like -k can hide absent tests during collection and thus obscure true collection results.

Practical steps include naming test files using the test_*.py or *_test.py patterns, writing test functions named test_* or methods in classes named Test*, relying on pytest assertions so assert rewriting yields informative diffs, and placing shared fixtures in conftest.py at the repository root or package root so CI sees them. Running pytest with -q and using -k expressions helps narrow runs during development while preserving discovery rules for CI. The rest of this page provides a structured, step-by-step framework for writing pytest tests, arranging pytest test files, and configuring discovery rules for reliable local and CI execution.

How to use this prompt kit:
  1. Work through prompts in order — each builds on the last.
  2. Click any prompt card to expand it, then click Copy Prompt.
  3. Paste into Claude, ChatGPT, or any AI chat. No editing needed.
  4. For prompts marked "paste prior output", paste the AI response from the previous step first.
Article Brief

how does pytest discover tests

pytest basics: assertions, test files, and discovery rules

authoritative, conversational, practical

Getting started with pytest

Python developers (beginner to intermediate) who want a compact, actionable guide to writing assertions, organizing test files, and understanding pytest discovery so tests run reliably in local and CI environments

A tightly-focused 1,000-word practical guide that distills the three most common pytest entry barriers—assertions, test file structure, and discovery rules—into copy/paste examples, config snippets, common pitfalls and quick fixes, so readers can get reproducible tests fast.

  • pytest assertions
  • pytest test discovery
  • pytest test files
  • writing pytest tests
  • assert statement vs pytest assert
  • conftest.py fixtures
  • pytest naming conventions
  • pytest discovery patterns
  • pytest -k -q flags
Planning Phase
1

1. Article Outline

Full structural blueprint with H2/H3 headings and per-section notes

You are creating a ready-to-write outline for a 1000-word technical blog article titled: pytest basics: assertions, test files, and discovery rules. Intent: informational—teach developers how to write assertions, organize test files, and understand pytest discovery so tests run predictably in local and CI. Write a complete article structure including: H1, all H2s, H3 subheadings (when needed), and a word-count target for each section such that the total is ~1000 words. For each section add 1–2 concise notes describing exactly what must be covered (examples, commands, code snippets, warnings, and best practices). Include which code examples to include (exact filenames and short snippets to show). Prioritize clarity for beginners but include small advanced tips where appropriate. Also include one-line suggestions for internal links and an ideal anchor sentence placeholder in the outline. Output: a structured outline ready to write, presented as plain hierarchical headings with per-section word targets and notes.
2

2. Research Brief

Key entities, stats, studies, and angles to weave in

You are creating a concise research brief for the article "pytest basics: assertions, test files, and discovery rules". Provide 8–12 named items (entities, tools, studies, stats, expert names, trending angles) the writer MUST weave into the article. For each item include a one-line note explaining why it belongs and how it should be referenced (example: cite, show command, link docs). Include: pytest docs pages, key pytest CLI flags, conftest.py, common CI platforms, and at least two authoritative external sources or studies (with URLs) that validate test automation benefits or best practices. Also list 2 trending angles (e.g., pytest in CI pipelines, migrating from unittest). Output: a numbered list of items with a one-line rationale for each.
Writing Phase
3

3. Introduction Section

Hook + context-setting opening (300-500 words) that scores low bounce

You are writing the introduction for the article titled "pytest basics: assertions, test files, and discovery rules". The audience is beginner-to-intermediate Python developers who want actionable guidance. Write a 300–500 word opening that includes: 1) a single-sentence hook that highlights a common pain (flaky tests, discovery confusion), 2) a brief context paragraph explaining why assertions, file organization, and discovery rules matter, 3) a clear thesis statement that promises specific outcomes, and 4) a short preview of what the reader will learn (three bullet-like sentences embedded in paragraph form). Use an authoritative but friendly tone, include one inline code example of a simple pytest assertion, and avoid heavy jargon. End with a transition sentence leading into the first H2. Output: only the intro section text, ready to paste into the article.
4

4. Body Sections (Full Draft)

All H2 body sections written in full — paste the outline from Step 1 first

Setup: Paste the outline produced in Step 1 at the top of your message before this prompt. You are now writing all H2 body sections for the article "pytest basics: assertions, test files, and discovery rules". Follow the outline exactly. For each H2 block write the full section before moving to the next. Include H3 subsections, code examples (properly formatted inline code), command-line examples, and short annotated snippets for clarity. Provide transition sentences between sections that guide the reader. Target total article length ~1000 words (intro + body + conclusion combined); assume the intro will be 300–500 words and the conclusion 200–300 words, so allocate ~300–500 words across body sections. Use concrete examples: filenames like tests/test_math.py, conftest.py, and demonstrate pytest discovery commands (pytest -q, pytest -k, pytest -m). Include at least three short code examples: (1) a simple assertion, (2) a test file showing naming conventions and fixtures import, (3) an example conftest.py fixture. Warn about 3 common pitfalls with quick fixes (naming, import paths, conftest placement). Keep language clear, actionable, and concise. Output: the complete body sections text only, ready to publish.
5

5. Authority & E-E-A-T Signals

Expert quotes, study citations, and first-person experience signals

You are producing E-E-A-T signals for the article "pytest basics: assertions, test files, and discovery rules". Provide: A) five suggested short expert quotes (one sentence each) with a suggested speaker name and concise credential (e.g., 'Nadia Eghbal, Python testing author'), B) three real studies/reports or authoritative pages to cite (include title, publisher, year, and URL), and C) four first-person experience-based sentences the article author can personalise to signal hands-on experience (each sentence ready to paste). Each quote and citation should be clearly tied to assertions, test organization, or discovery rules. Output: a structured list grouped by A, B, and C.
6

6. FAQ Section

10 Q&A pairs targeting PAA, voice search, and featured snippets

You are writing a FAQ block for the article "pytest basics: assertions, test files, and discovery rules" intended to capture People Also Ask and featured snippets. Produce 10 Q&A pairs. Each question should be a short, natural language query users ask (voice-search friendly). Each answer should be 2–4 sentences, conversational, specific, and include one example or command where helpful. Cover topics like: what pytest asserts do, difference between assert and unittest, how pytest discovers tests, naming conventions for test files and functions, where conftest.py goes, how to run a single test, and common discovery problems. Output: numbered Q&A pairs ready to append to the article.
7

7. Conclusion & CTA

Punchy summary + clear next-step CTA + pillar article link

You are writing the conclusion for "pytest basics: assertions, test files, and discovery rules." Write a 200–300 word closing that: 1) concisely recaps the key takeaways (assertion best practices, file naming and placement, discovery commands and common fixes), 2) gives a clear, single CTA telling the reader exactly what to do next (for example: run a quick test, add a conftest fixture, or follow a link to the pillar guide), and 3) include one sentence with an explicit link text to the pillar article: "Getting Started with pytest: A Complete Guide to Writing and Running Python Tests" (format it as a plain sentence referencing the pillar). Keep tone encouraging and action-oriented. Output: the conclusion paragraph(s) only.
Publishing Phase
8

8. Meta Tags & Schema

Title tag, meta desc, OG tags, Article + FAQPage JSON-LD

You are generating SEO metadata and schema for the article "pytest basics: assertions, test files, and discovery rules". Produce: (a) a title tag 55–60 characters optimized for the primary keyword, (b) a meta description 148–155 characters that includes the primary keyword and a CTA, (c) an Open Graph title, (d) an Open Graph description, and (e) a complete JSON-LD block containing Article schema plus FAQPage with the 10 FAQs from Step 6 embedded. Make sure the JSON-LD follows schema.org structure and includes headline, description, author placeholder, datePublished placeholder, and the FAQ Q&A entries. Output: return the metadata and JSON-LD as formatted code only (no extra commentary).
10

10. Image Strategy

6 images with alt text, type, and placement notes

You are creating an image strategy for the article "pytest basics: assertions, test files, and discovery rules." Recommend 6 images: for each include (a) a short descriptive filename suggestion, (b) what the image shows (visual caption), (c) exactly where in the article to place it (which section or sentence), (d) the SEO-optimised alt text including the primary keyword, and (e) the recommended type (photo, screenshot, diagram, or infographic). For code screenshots, specify which code block should be captured (e.g., tests/test_math.py snippet). Also include one recommendation for an accessible image caption and a suggestion for including code copy buttons for screenshots. Output: a bulleted list of 6 image specs ready for design.
Distribution Phase
11

11. Social Media Posts

X/Twitter thread + LinkedIn post + Pinterest description

You are writing platform-native social copy for the article "pytest basics: assertions, test files, and discovery rules." Produce three items: A) an X/Twitter thread opener plus 3 follow-up tweets (each tweet max 280 characters) that tease the article and include one code snippet or command, B) a LinkedIn post (150–200 words) in a professional tone with a strong hook, one actionable insight, and a CTA linking to the article, and C) a Pinterest description (80–100 words) keyword-rich, describing what the pin is about and why readers should click. Use the primary keyword naturally in each output and include suggested hashtags (3–5) for each platform. Output: three clearly separated sections labeled X, LinkedIn, and Pinterest.
12

12. Final SEO Review

Paste your draft — AI audits E-E-A-T, keywords, structure, and gaps

Paste the full article draft of "pytest basics: assertions, test files, and discovery rules" after this prompt. You are performing a final SEO audit. Check and report on: 1) primary and secondary keyword placement (title, first 100 words, H2s, first paragraph of each H2), 2) E-E-A-T gaps (author info, quotes, citations), 3) readability estimate and suggestions to reach a clear, scannable level, 4) heading hierarchy and H-tag misuse, 5) duplicate-angle risk compared to typical top-10 results, 6) content freshness signals (date, version of pytest referenced), and 7) five specific improvement suggestions with exact sentence edits or additions (copyable). Output: a structured audit checklist and the five suggested inline edits. Do not change the draft—only annotate and suggest.
Common Mistakes
  • Using bare Python assert formatting without showing pytest's introspection benefits, leaving beginners confused why failures show rich diffs.
  • Naming test files/functions incorrectly (e.g., testsinstead.py or TestMath instead of tests/test_math.py and test_* functions) which prevents discovery.
  • Placing conftest.py in the wrong directory causing fixtures not to be discovered in subpackages or CI runs.
  • Assuming pytest will run modules that aren’t importable from the project root — missing __init__.py or wrong PYTHONPATH leads to import errors.
  • Not documenting the pytest version and CLI flags used, causing reproducibility problems between local and CI environments.
  • Overloading assertions with complex logic instead of small, single-assert tests that give clearer failure signals.
  • Relying on relative imports in test files that work locally but fail in CI due to different working directories.
Pro Tips
  • Always show one-line pytest commands in examples (pytest -q and pytest tests/test_math.py::test_add) — readers copy them directly into terminals.
  • Include a minimal conftest.py with a fixture example and explain the discovery rule: conftest applies to subdirectories; place it at test package root.
  • For CI tips, recommend pinning pytest version and running pytest --maxfail=1 --disable-warnings to get fast, noisy failures during builds.
  • When showing assertions, include an example with multiple comparisons and note pytest's enhanced assertion rewriting so readers don't need assertEqual.
  • Add an explicit 'How to debug discovery' checklist: run pytest -vv, check naming, run python -c 'import sys; print(sys.path)' in CI step, and ensure tests run from project root.
  • Provide both file-based and module-based examples (tests/test_math.py and package/tests/test_math.py) to address different repo layouts.
  • Mention the common migration pitfall from unittest: avoid mixing unittest.TestCase methods with pytest-style asserts unless necessary, and show the equivalent pytest pattern.