0
0
PyTesttesting~8 mins

First PyTest test - Framework Patterns

Choose your learning style9 modes available
Framework Mode - First PyTest test
Folder Structure
project-root/
├── tests/
│   ├── test_sample.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── pytest.ini
└── requirements.txt
  

This is a simple PyTest project layout. tests/ holds all test files. conftest.py contains shared fixtures. src/ holds application code.

Test Framework Layers
  • Test files: Functions starting with test_ inside tests/ folder. Example: test_sample.py.
  • Fixtures: Setup and teardown helpers in conftest.py to share test data or resources.
  • Application code: The code under test, usually in src/ or similar.
  • Configuration: pytest.ini to set PyTest options like markers or test paths.
Configuration Patterns

Use pytest.ini to configure PyTest behavior:

[pytest]
minversion = 7.0
addopts = -ra -q
testpaths = tests
markers =
    smoke: quick smoke tests
    regression: full regression suite
  

Use conftest.py to define fixtures for setup like database connections or test data.

For environment variables (e.g., URLs, credentials), use os.environ or python-dotenv to load from .env files.

Test Reporting and CI/CD Integration
  • PyTest outputs test results in the console by default.
  • Use plugins like pytest-html to generate HTML reports.
  • Integrate PyTest in CI/CD pipelines (GitHub Actions, Jenkins) by running pytest command.
  • Failing tests cause pipeline failure, alerting developers immediately.
Best Practices
  • Keep test functions small and focused on one behavior.
  • Name tests clearly starting with test_ so PyTest discovers them automatically.
  • Use fixtures in conftest.py to avoid repeating setup code.
  • Separate test code from application code in different folders.
  • Use pytest.ini to manage test runs and markers for easy filtering.
Self Check

Where would you add a new fixture to provide a database connection for multiple tests?

Key Result
Organize PyTest tests in a tests/ folder with fixtures in conftest.py and configure runs via pytest.ini.