HOW-TO · DEV
How to integrate AI test generation into a Jenkins CI/CD pipeline using a plugin
Target environment
Ubuntu 24.04 · Ollama 0.4.x
PREREQUISITES
A running Jenkins server with administrator access, an existing CI pipeline defined in a Jenkinsfile, and an AI assistant service accessible via HTTP API with an API key stored in Jenkins credentials.
What this does
This guide describes how to extend an existing Jenkins pipeline to call an AI assistant after source code is compiled, generate test cases for changed source files, and then execute those tests in a subsequent stage. The approach uses a generic HTTP request step (avoiding a specific plugin dependency) to communicate with the AI service, making the pipeline portable across Jenkins versions.
Steps
- Log in to Jenkins and navigate to Manage Jenkins → Manage Credentials. Add a "Secret text" credential with the AI service API key.
- Open the project's
Jenkinsfileand add a new pipeline stage namedGenerate Testsafter the build stage. - In the new stage, use a
httpRequeststep to send the changed source file contents to the AI endpoint, passing the relevant context and a prompt asking for pytest-compatible test code. - Parse the JSON response from the AI and extract the generated test code.
- Write the generated test code to a file in the workspace, for example
$WORKSPACE/ai_tests/test_generated.py. - Add a subsequent stage named
Run AI Teststhat runspytest $WORKSPACE/ai_tests/. - Archive the generated test files as build artifacts using
archiveArtifactsso they can be reviewed after each run. - Commit the updated
Jenkinsfileand trigger a build to verify the pipeline stages execute in order.
Verification
jenkins pipeline --job my-project --build lastStable --show console | grep -E "(Generate Tests|Run AI Tests|Test Results)"
Expected output:
[Generate Tests] AI test generation completed. 12 test functions written.
[Run AI Tests] Test Results: All tests passed (12 passed in 4.2s)
Common failures
- HTTP 401 from the AI endpoint — The API key credential ID used in the
httpRequeststep does not match the credential name stored in Jenkins. Verify the credential ID in Manage Jenkins → Credentials. - AI response is empty or malformed JSON — The AI service did not return valid JSON. Check the pipeline logs for the full response and refine the prompt to request only JSON-formatted output with a code block.
- Generated tests fail to import modules — The generated test file imports modules that are not installed in the Jenkins build environment. Add a
pip installor system package step before the test stage, or add ansys.path.insertdirective in the test file. - File write permission denied — The Jenkins agent process does not have write access to the target directory. Create the output directory in the pipeline step before writing files.
Related guides
- Configure CI/CD with GitHub Actions for AI tests (guide 27)
- Use AI to optimize Docker build times (guide 29)