You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何基于Git仓库在Jenkins中运行Selenium-Python自动化测试项目?

Absolutely, you can set up both scheduled weekly runs and GitHub change-triggered tests in Jenkins with just a few essential plugins and targeted configurations. Let’s walk through this step by step, tailored specifically to your Selenium/Pytest project setup.

Required Jenkins Plugins

First, install these plugins via Manage Jenkins → Plugins → Available Plugins:

  • Git Plugin: Pulls code from your GitHub repository
  • GitHub Integration Plugin: Handles webhook triggers from GitHub (simpler than setting up raw webhooks manually)
  • Email Extension Plugin: Lets you customize test result emails with more detail than Jenkins’ default email tool
  • Pytest Plugin (Optional but highly recommended): Displays formatted pytest test reports directly in Jenkins, making results easier to parse
Step 1: Jenkins Global Configuration

Before creating your project, set up core tools:

  1. Git Setup: Go to Manage Jenkins → Global Tool Configuration, find Git, and confirm it’s installed (or add it if your Jenkins server doesn’t have Git yet). Enter the path to your Git executable (e.g., /usr/bin/git on Linux).
  2. Python & Dependencies:
    • Either use your server’s existing Python installation, or add a managed Python version via the Python Installer Plugin (for consistent versions across builds).
    • Ensure your Jenkins environment can access pytest, selenium, and any other dependencies. The easiest way is to run pip install -r requirements.txt as part of your build steps (we’ll cover this later).
  3. WebDriver Configuration:
    • Avoid hardcoding WebDriver paths! Use webdriver-manager (add it to your requirements.txt) to auto-download the correct driver version for the browser on your Jenkins server.
    • If you’re running Chrome (as in your command), add headless mode to your conftest.py—Jenkins servers typically don’t have a GUI, so this is mandatory:
      @pytest.fixture(scope="class")
      def setup(request):
          browser = request.config.getoption("--browser")
          base_url = request.config.getoption("--baseURL")
          if browser == "chrome":
              options = webdriver.ChromeOptions()
              options.add_argument("--headless=new")
              options.add_argument("--no-sandbox")
              options.add_argument("--disable-dev-shm-usage")
              driver = webdriver.Chrome(options=options)
          # Add other browser configs if needed
          driver.get(base_url)
          request.cls.driver = driver
          yield
          driver.quit()
      
Step 2: Create Your Jenkins Project

Create a Freestyle project (name it something like Selenium-Smoke-Test-Suite) and configure these sections:

2.1 Source Code Management

  • Select Git, paste your GitHub repository URL.
  • Add credentials: Use a GitHub Personal Access Token (PAT) with repo permissions (GitHub no longer supports password authentication).
  • Specify the branch you want to test (e.g., */main).

2.2 Build Triggers

Enable both your desired trigger types:

  • GitHub hook trigger for GITScm polling: Check this to trigger builds whenever code is pushed to your GitHub repo. Then, set up the webhook in GitHub:
    1. Go to your GitHub repo → Settings → Webhooks → Add webhook
    2. Set Payload URL to http://<your-jenkins-server-ip-or-domain>/github-webhook/
    3. Choose Content type as application/json
    4. Under "Which events would you like to trigger this webhook?", select Just the push event (or broader events if needed)
    5. Save the webhook
  • Build periodically: Check this for weekly runs. Use a cron expression to define the schedule. For example:
    • 0 2 * * 1 runs every Monday at 2 AM (cron format: minute hour day month weekday)
    • Adjust the expression to match your desired time (use a cron generator if you’re unsure)

2.3 Build Steps

Add an Execute shell (Linux) or Execute Windows batch command (Windows) step with these commands:

# Install dependencies (run this first if your Jenkins env doesn't have them)
pip install -r requirements.txt

# Run your pytest suite
python -m pytest /test/smoke/test_suite1.py --browser=chrome --baseURL=dev --junitxml=pytest-report.xml

The --junitxml flag generates an XML report that Jenkins can parse (required if you’re using the Pytest Plugin for reporting).

2.4 Post-build Actions

Configure these to handle test reports and email notifications:

  1. Publish Pytest Test Result Report (if you installed the Pytest Plugin):
    • Set Test report XMLs to pytest-report.xml
    • This will display a detailed test result summary in Jenkins, with pass/fail counts and error logs.
  2. Editable Email Notification (from the Email Extension Plugin):
    • Set Project Recipient List to your team’s email address(es)
    • Customize the Subject (e.g., [Jenkins] Smoke Test Results - ${BUILD_STATUS})
    • In the Content field, add details like the build link, test summary, and failure logs. For example:

      Build URL: ${BUILD_URL}
      Test Status: ${BUILD_STATUS}
      Total Tests: ${TEST_COUNTS.total}
      Passed: ${TEST_COUNTS.passed}
      Failed: ${TEST_COUNTS.failed}

    • Set Trigger to "Always" (or only on failure/success, depending on your needs)
Quick Troubleshooting Tips
  • Webhook Not Triggering: Ensure your Jenkins server is publicly accessible (if using a local Jenkins instance, use a tool like ngrok to expose it temporarily for testing). Check GitHub’s webhook logs to see if requests are being sent.
  • Browser/Driver Errors: Double-check that headless mode is enabled, and webdriver-manager is correctly installing the right driver version.
  • Dependency Issues: If builds fail due to missing packages, confirm that pip install -r requirements.txt is running before your pytest command.

内容的提问来源于stack exchange,提问作者srini_sharma

火山引擎 最新活动