Create virtualenv for python
everytime jenkins call a sh command, a new enviroment will be setup. Therefore virtual enviroment has to be activated everytime. Or make a .bashrc
node {
stage 'Preparing VirtualEnv'
if (!fileExists('.env')){
echo 'Creating virtualenv ...'
sh 'virtualenv --no-site-packages .env'
}
if (fileExists('requirements/preinstall.txt')) {
sh """
. .env/bin/activate
pip install -r requirements/preinstall.txt
"""
}
...
sh """
. .env/bin/activate
pip install -r requirements/test.txt
"""
}
stage("Unittests") {
sh """
. .env/bin/activate
./manage.py test --noinput
"""
}
}
or run it in one shell
sh """
. .env/bin/activate
if [[ -f requirements/preinstall.txt ]]; then
pip install -r requirements/preinstall.txt
fi
pip install -r requirements/test.txt
./manage.py test --noinput
"""
or run a shell script
bash script
#!/usr/bin/env bash
CURRENT_DIR=$(dirname $(readlink -f $0))
/usr/bin/python3 -m venv venv
source "${CURRENT_DIR}/venv/bin/activate"
pip install -r requirements.txt
RESULT=$?
if [[ ${RESULT} -eq 0 ]]; then
printf "virtual env created successfully\n"
pytest -v -o junit_family=xunit1 --cov-report xml:test/coverage.xml --junitxml=test/results.xml
else
printf "could not start virtual env\n"
fi
Jenkins create a folder when it make a clone from your project like this:
/var/lib/jenkins/workspace/job-name@script
For this to work you must set the file as executable if you are in a linux environment and then call the shell script.
Something like this:
// Permission to execute
sh "chmod +x -R ${env.WORKSPACE}/../${env.JOB_NAME}@script"
// Call SH
sh "${env.WORKSPACE}/../${env.JOB_NAME}@script/script.sh"
or
dir ('<your new directory>') {
sh('./build.sh')
}