如何基于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.
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
Before creating your project, set up core tools:
- 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/giton Linux). - 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.txtas part of your build steps (we’ll cover this later).
- WebDriver Configuration:
- Avoid hardcoding WebDriver paths! Use
webdriver-manager(add it to yourrequirements.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()
- Avoid hardcoding WebDriver paths! Use
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
repopermissions (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:
- Go to your GitHub repo → Settings → Webhooks → Add webhook
- Set Payload URL to
http://<your-jenkins-server-ip-or-domain>/github-webhook/ - Choose Content type as
application/json - Under "Which events would you like to trigger this webhook?", select Just the push event (or broader events if needed)
- Save the webhook
- Build periodically: Check this for weekly runs. Use a cron expression to define the schedule. For example:
0 2 * * 1runs 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:
- 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.
- Set Test report XMLs to
- 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)
- 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-manageris correctly installing the right driver version. - Dependency Issues: If builds fail due to missing packages, confirm that
pip install -r requirements.txtis running before your pytest command.
内容的提问来源于stack exchange,提问作者srini_sharma




