Skip to main content

Python unit tests

Discover and run Python unittest tests, then publish the results in the GitLab test summary.

The default CI Tools tools image includes unittest-xml-reporting. The component starts discovery at the repository root, matches test*.py, enables Python color output, and saves one JUnit report.

Run Python unit tests​

Include common and python-unittest in .gitlab-ci.yml:

include:
- component: $CI_SERVER_FQDN/xrow-public/ci-tools/common@stable
- component: $CI_SERVER_FQDN/xrow-public/ci-tools/python-unittest@stable

Create an importable test directory before adding tests/test_sample.py:

mkdir -p tests
touch tests/__init__.py

Add the test:

import unittest


class SampleTest(unittest.TestCase):
def test_adds_numbers(self) -> None:
self.assertEqual(2 + 3, 5)

The test:python-unittest job discovers the test from . and uploads python-unittest-junit.xml. GitLab displays the result in the merge request test summary.

Select a test directory​

Set path when tests live below one directory:

include:
- component: $CI_SERVER_FQDN/xrow-public/ci-tools/common@stable
- component: $CI_SERVER_FQDN/xrow-public/ci-tools/python-unittest@stable
inputs:
path: tests

Set pattern to change the discovery file pattern. The default is test*.py.

Update an existing include​

Replace the component name python-unit-tests with python-unittest. The default job is now test:python-unittest and the default report is python-unittest-junit.xml. Update references in needs, dependencies, and report download scripts, or set name and junit-report explicitly to keep the previous job and report names. The test discovery behavior and other inputs are unchanged.

Inputs​

NameDescriptionDefaultType
------------
allow-failureShould the pipeline continue when one or more tests fail?falseboolean
imageThe image used to run the tests.${CI_TOOLS_REPO}/tools:${CI_TOOLS_COMPONENT_VERSION}string
junit-reportPath to the JUnit report shown in the GitLab test summary.python-unittest-junit.xmlstring
nameThe name of the test job.python-unitteststring
needsThe jobs that this job depends on.[]array
pathThe directory where unittest discovery starts..string
patternThe file name pattern used by unittest discovery.test*.pystring
rulesThe rules for the test job.[{"exists":["**/test*.py"],"when":"on_success"},{"when":"never"}]array
stageThe stage for the test job.teststring