0
0
PyTesttesting~8 mins

Arrange-Act-Assert pattern in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Arrange-Act-Assert pattern
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   ├── test_user.py
│   └── __init__.py
├── src/
│   ├── calculator.py
│   └── __init__.py
├── conftest.py
├── pytest.ini
└── requirements.txt
Test Framework Layers
  • Arrange: Setup test data and environment. Usually done inside test functions or fixtures in conftest.py.
  • Act: Execute the action or function under test, e.g., calling a function from src/calculator.py.
  • Assert: Verify the outcome using assert statements in test functions inside tests/.
  • Utilities: Helper functions or fixtures in conftest.py or separate utility modules.
  • Configuration: Settings in pytest.ini and environment variables.
Configuration Patterns
  • pytest.ini: Configure pytest options like markers, test paths, and logging.
  • Environment Variables: Store sensitive data like credentials outside code, accessed via os.environ.
  • Fixtures: Use @pytest.fixture in conftest.py to setup reusable test data or states.
  • Command Line Options: Use pytest --browser=chrome or similar to select test parameters dynamically.
Test Reporting and CI/CD Integration
  • pytest built-in reports: Use pytest -v for verbose output showing pass/fail per test.
  • Plugins: Use pytest-html to generate HTML reports for easy sharing.
  • CI/CD: Integrate pytest runs in pipelines (GitHub Actions, Jenkins) to run tests on every commit.
  • Fail Fast: Use --maxfail=1 to stop on first failure during CI runs.
Best Practices for Arrange-Act-Assert in pytest
  • Clear Separation: Keep arrange, act, and assert steps clearly separated in test functions for readability.
  • Use Fixtures: Use pytest fixtures to handle arrange steps and keep tests clean.
  • Single Assert per Test: Prefer one main assert per test to isolate failures clearly.
  • Descriptive Test Names: Name tests to describe the behavior being tested.
  • Keep Tests Independent: Each test should not depend on others; arrange all needed data inside or via fixtures.
Self Check

Where in this framework structure would you add a new fixture to prepare test data for user login tests?

Key Result
Arrange-Act-Assert pattern organizes tests into clear setup, action, and verification steps for clarity and maintainability.