0
0
PyTesttesting~8 mins

Running PyTest in Jenkins - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Running PyTest in Jenkins
Folder Structure for PyTest Project
project-root/
├── tests/
│   ├── test_example.py
│   └── conftest.py
├── src/
│   └── application_code.py
├── pytest.ini
├── requirements.txt
└── Jenkinsfile
  
Test Framework Layers
  • Tests: Located in tests/ folder, contains test cases using PyTest syntax.
  • Fixtures: Defined in conftest.py for setup and teardown reusable code.
  • Application Code: In src/ folder, the code under test.
  • Configuration: pytest.ini for PyTest settings and markers.
  • CI Pipeline: Jenkinsfile defines Jenkins build and test steps.
Configuration Patterns
  • pytest.ini: Configure test markers, addopts (e.g., --junitxml=reports/result.xml), and test paths.
  • Environment Variables: Use Jenkins environment variables to pass credentials or environment info securely.
  • Jenkinsfile: Define stages for installing dependencies, running tests, and archiving reports.
    pipeline {
      agent any
      stages {
        stage('Install') {
          steps {
            sh 'python -m venv venv'
            sh './venv/bin/pip install -r requirements.txt'
          }
        }
        stage('Test') {
          steps {
            sh './venv/bin/pytest --junitxml=reports/result.xml'
          }
        }
      }
      post {
        always {
          junit 'reports/result.xml'
          archiveArtifacts artifacts: 'reports/**', allowEmptyArchive: true
        }
      }
    }
Test Reporting and CI/CD Integration
  • JUnit XML Reports: PyTest generates result.xml for Jenkins to parse test results.
  • Jenkins JUnit Plugin: Reads XML reports to show pass/fail and test details in Jenkins UI.
  • Archiving Artifacts: Save logs and reports for later review.
  • Pipeline Feedback: Jenkins marks build as failed if tests fail, enabling quick feedback.
Best Practices for Running PyTest in Jenkins
  • Use virtual environments to isolate dependencies in Jenkins builds.
  • Generate machine-readable test reports (JUnit XML) for Jenkins integration.
  • Keep test data and credentials out of code; use Jenkins credentials and environment variables.
  • Structure Jenkinsfile with clear stages: setup, test, report.
  • Archive test reports and logs for debugging failed builds.
Self Check

Where in this framework structure would you add a new fixture to set up a database connection for tests?

Key Result
Organize PyTest tests and configuration for Jenkins CI with clear folder structure, JUnit reporting, and pipeline stages.