getting-started.rst
Overview
The [getting-started.rst](/projects/286/67223) file serves as a beginner-friendly introductory guide to using the **pytest** testing framework. It provides step-by-step instructions on installing pytest, writing and running simple tests, grouping tests in classes, asserting exceptions, and leveraging pytest's built-in fixtures. This document is designed to quickly onboard new users to pytest's core features and best practices, enabling them to write and organize tests effectively.
This file is primarily a tutorial/reference document, not executable code. It uses reStructuredText markup to structure content and includes code snippets, command-line examples, and notes to illustrate pytest usage.
Detailed Explanations
1. Installation of pytest
Purpose
Guide the user to install pytest, ensuring they have Python 3.8+ or PyPy3, and verify the installation.
Instructions
Run
pip install -U pytestto install or upgrade pytest.Verify installation by running
pytest --version.
Example
pip install -U pytest
pytest --version
2. Creating Your First Test
Purpose
Demonstrates how to write a simple test function in a file named `test_sample.py`.
Sample Code
# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
Explanation
The function
funcadds 1 to its argument.The test
test_answerasserts thatfunc(3)equals 5, which intentionally fails (sincefunc(3)returns 4).Running
pytestwill discover the test and report the failure, showing intermediate values to help debug.
Usage
Run the test:
pytest
3. Running Multiple Tests
Purpose
Explains pytest’s test discovery mechanism.
Details
pytest automatically finds and runs all test files matching
test_*.pyor*_test.py.It recursively searches current directory and subdirectories.
Follows pytest's standard test discovery rules.
4. Asserting Exceptions with pytest.raises
Purpose
How to verify that code raises expected exceptions.
Sample Code
# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
Explanation
The test passes if
SystemExitis raised.Use
pytest -qfor quiet output.
Usage
pytest -q test_sysexit.py
5. Grouping Multiple Tests in a Class
Purpose
Shows how to organize multiple tests within a class, improving organization and sharing fixtures or marks.
Sample Code
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
Notes
Class name must start with
Testfor pytest to recognize it.Each test gets a unique instance of the class to maintain isolation.
Class-level attributes are shared across tests in the class.
Example of Instance Isolation
# content of test_class_demo.py
class TestClassDemoInstance:
value = 0
def test_one(self):
self.value = 1
assert self.value == 1
def test_two(self):
assert self.value == 1 # This will fail because `value` reset to 0
6. Using Built-in Fixtures (e.g., tmp_path)
Purpose
Demonstrates how to request pytest built-in resources like temporary directories.
Sample Code
# content of test_tmp_path.py
def test_needsfiles(tmp_path):
print(tmp_path)
assert 0
Explanation
Declaring
tmp_pathas a function argument requests a unique temporary directory.pytest creates this directory automatically for each test invocation.
Usage
pytest -q test_tmp_path.py
7. Additional Resources
The guide references other pytest documents for advanced topics:
Command line usage
Working with existing test suites
Marking tests
Fixtures usage
Plugins development
Best practices for virtual environments and test layouts
Implementation Details and Algorithms
This file is a documentation/tutorial resource and does not implement algorithms or executable logic. It relies on pytest’s conventions:
Test discovery by filename and naming conventions.
Assertion rewriting for enhanced introspection.
Fixture injection based on test function signatures.
Class-based test grouping with isolated instances.
It illustrates these concepts via code snippets and command-line examples.
Interaction with Other Parts of the System
This file is part of the pytest documentation set.
It references other documentation topics like
assertraises,test discovery, andfixtureswhich are implemented in other files/modules.It acts as the entry point for new users learning pytest before they explore advanced features or plugin development.
The code snippets can be run independently and interact with the pytest testing framework installed in the user’s Python environment.
Mermaid Diagram
The following flowchart shows the main sections (functions/concepts) covered in the guide and their relationships:
flowchart TD
A[Install pytest] --> B[Create First Test]
B --> C[Run Multiple Tests]
C --> D[Assert Exceptions]
D --> E[Group Tests in Classes]
E --> F[Use Built-in Fixtures]
F --> G[Explore Additional Resources]
style A fill:#f9f,stroke:#333,stroke-width:1px
style G fill:#bbf,stroke:#333,stroke-width:1px
Summary
[getting-started.rst](/projects/286/67223) is a comprehensive beginner's tutorial for pytest that covers installation, writing and running tests, asserting exceptions, organizing tests into classes, and using built-in fixtures. It is an essential starting point for new users to pytest, supported by clear examples and detailed explanations. The file is integral to the pytest documentation ecosystem and guides users towards more advanced pytest features and best practices.