Package: pytest-zebrunner
Zebrunner PyTest reporting agentThe official Zebrunner PyTest agent provides the reporting functionality. It can automatically track Selenium sessions
and send the info about session details to Zebrunner backend. It can be easily integrated into a project by just installing the library
and adding the configuration file.Including reporting into your project is easy - just install the agent and provide minimal valid configuration for reporting.Inclusion into your projectpip install pytest-zebrunnerConfiguring reporting of test executionsAfter the installation, reporting is disabled by default. It won't send any data to the Zebrunner service without a valid configuration.It is currently possible to provide the configuration via:Environment variablesYAML filepyproject.toml,command argumentsare in plans for future releases.via environment variablesThe following configuration parameters are recognized by the agent:REPORTING_ENABLED- enables or disables reporting. The default value istrue.REPORTING_SERVER_HOSTNAME- mandatory if reporting is enabled. It is Zebrunner server hostname. It can be obtained in Zebrunner on the 'Account & profile' page under the 'Service URL' section;REPORTING_SERVER_ACCESS_TOKEN- mandatory if reporting is enabled. Access token must be used to perform API calls. It can be obtained in Zebrunner on the 'Account & profile' page under the 'Token' section;REPORTING_PROJECT_KEY- optional value. It is the project that the test run belongs to. The default value isDEF. You can manage projects in Zebrunner in the appropriate section;REPORTING_RUN_DISPLAY_NAME- optional value. It is the display name of the test run. The default value isDefault Suite;REPORTING_RUN_BUILD- optional value. It is the build number that is associated with the test run. It can depict either the test build number or the application build number;REPORTING_RUN_ENVIRONMENT- optional value. It is the environment where the tests will run;REPORTING_SEND_LOGS- Sends test logs to Zebrunner. Default:true;REPORTING_NOTIFICATION_NOTIFY_ON_EACH_FAILURE- optional value. Specifies whether Zebrunner should send notification to Slack/Teams on each test failure. The notifications will be sent even if the suite is still running. The default value isfalse;REPORTING_NOTIFICATION_SLACK_CHANNELS- optional value. The list of comma-separated Slack channels to send notifications to. Notification will be sent only if Slack integration is properly configured in Zebrunner with valid credentials for the project the tests are reported to. Zebrunner can send two type of notifications: on each test failure (if appropriate property is enabled) and on suite finish;REPORTING_NOTIFICATION_MS_TEAMS_CHANNELS- optional value. The list of comma-separated Microsoft Teams channels to send notifications to. Notification will be sent only if Teams integration is configured in Zebrunner project with valid webhooks for the channels. Zebrunner can send two type of notifications: on each test failure (if appropriate property is enabled) and on suite finish;REPORTING_NOTIFICATION_EMAILS- optional value. The list of comma-separated emails to send notifications to. This type of notification does not require further configuration on Zebrunner side. Unlike other notification mechanisms, Zebrunner can send emails only on suite finish;REPORTING_RUN_TREAT_SKIPS_AS_FAILURES- optional value. If value is false all test-runs with skipped & passed tests
would be marked as passed.Agent also recognizes.envfile in the resources root folder.via YAML fileAgent recognizes agent.yaml or agent.yml file in the resources root folder. It is currently not possible to configure an alternative file location.Below is a sample configuration file:reporting:enabled:trueproject-key:DEFsend-logs:trueserver:hostname:localhost:8080access-token:<token>notification:notify-on-each-failure:trueslack-channels:automation, dev-teamms-teams-channels:automation, qa-teamemails:example@example.comrun:treat_skips_as_failures:falsedisplay-name:Nightly Regression Suitebuild:1.12.1.96-SNAPSHOTenvironment:TEST-1reporting.enabled- enables or disables reporting. The default value istrue;reporting.server.hostname- mandatory if reporting is enabled. Zebrunner server hostname. Can be obtained in Zebrunner on the 'Account & profile' page under the 'Service URL' section;reporting.server.access-token- mandatory if reporting is enabled. Access token must be used to perform API calls. Can be obtained in Zebrunner on the 'Account & profile' page under the 'Token' section;reporting.project-key- optional value. The project that the test run belongs to. The default value isDEF. You can manage projects in Zebrunner in the appropriate section;reporting.send-logs- Sends test logs to Zebrunner. Default:truereporting.run.display-name- optional value. The display name of the test run. The default value is Default Suite;reporting.run.build- optional value. The build number that is associated with the test run. It can depict either the test build number or the application build number;reporting.run.environment- optional value. The environment in which the tests will run.reporting.notification.notify-on-each-failure- optional value. Specifies whether Zebrunner should send notification to Slack/Teams on each test failure. The notifications will be sent even if the suite is still running. The default value isfalse;reporting.notification.slack-channels- optional value. The list of comma-separated Slack channels to send notifications to. Notification will be sent only if Slack integration is properly configured in Zebrunner with valid credentials for the project the tests are reported to. Zebrunner can send two type of notifications: on each test failure (if appropriate property is enabled) and on suite finish;reporting.notification.ms-teams-channels- optional value. The list of comma-separated Microsoft Teams channels to send notifications to. Notification will be sent only if Teams integration is configured in Zebrunner project with valid webhooks for the channels. Zebrunner can send two type of notifications: on each test failure (if appropriate property is enabled) and on suite finish;reporting.notification.emails- optional value. The list of comma-separated emails to send notifications to. This type of notification does not require further configuration on Zebrunner side. Unlike other notification mechanisms, Zebrunner can send emails only on suite finish;reporting.run.treat-skips-as-failures- optional value. If value is false all test-runs with skipped & passed tests
would be marked as passed.If the required configurations are not provided, there is a warning displayed in logs with the problem description and the names of options
which need to be specified. Parameter names are case insensitive and can be written in upper and lower registers.Collecting test logsTo send logs to Zebrunner you need to add a ZebrunnerHandler to your logger.Add logger configuration to yourpytest.inifile:[pytest]
testpaths = tests

log_cli = true
log_level = notset
log_format = [%(asctime)s] [%(levelname)s] - %(name)s - %(message)s
log_date_format = %Y-%m-%d %H:%M:%Sand add this code to your project:importloggingfrompytest_zebrunner.zebrunner_loggingimportZebrunnerHandlerlogger=logging.getLogger(__name__)# It might be any logger that you created earlierlogger.addHandler(ZebrunnerHandler())Or you can configure logging via Yaml file:logger.yamlversion:1disable_existing_loggers:Falseformatters:simple:format:'%(asctime)s-%(name)s-%(levelname)s-%(message)s'datefmt:'%Y-%m-%d%H:%M:%S'handlers:console:class:logging.StreamHandlerlevel:NOTSETformatter:simplestream:ext://sys.stdoutzebrunner:class:pytest_zebrunner.zebrunner_logging.ZebrunnerHandlerlevel:NOTSETformatter:simpleloggers:development:level:NOTSEThandlers:[console,zebrunner]propagate:noroot:level:NOTSEThandlers:[console]and add this code to your project:# Logger configuring# Load the config filewithopen('logger.yaml','rt')asf:config=yaml.safe_load(f.read())# Configure the logging module with the config filelogging.config.dictConfig(config)# Get a logger objectlogger=logging.getLogger('development')[!NOTE]
The logger must be invoked before the tests run.Collecting captured screenshotSometimes it may be useful to have the ability to track captured screenshots in scope of Zebrunner Reporting. The agent comes
with the API allowing you to send your screenshots to Zebrunner, so that they could be attached to the test.frompytest_zebrunnerimportattach_test_screenshotdeftest_something():...driver.save_screenshot("path_to_screenshot.png")# Capture screenshot with selenium driverattach_test_screenshot("path_to_screenshot.png")...Additional reporting capabilitiesIMPORTANT: All attachments to tests can only be done while some test is running.
All attachments to a test run can only be done while a pytest test session is active.Tracking test maintainerYou may want to add transparency to the process of automation maintenance by having an engineer responsible for
evolution of specific tests or test classes. Zebrunner comes with a concept of a maintainer - a person that can be
assigned to maintain tests. In order to keep track of those, the agent comes with the@pytest.mark.maintainerannotation.See a sample test bellow:@pytest.mark.maintainer("username_of_maintainer")deftest_something():...Attaching labelsIn some cases, it may be useful to attach some meta information related to a test. The agent comes with a concept of a label.
Label is a key-value pair associated with a test. The key and value are represented by astr. Labels can be attached to
tests and test runs.There is a repeatable label mark that can be used to attach labels to a test. There is also a API to attach labels during test or execution.
The agent has functions that can be used to attach labels.frompytest_zebrunnerimportattach_test_label,attach_test_run_label@pytest.mark.label("name","value")deftest_something():...attach_test_label("test-label","some value")attach_test_run_label("test-run-label","value")...The test from the sample above attaches 3 test-level labels.Reverting test registrationIn some cases it might be handy not to register test execution in Zebrunner. This may be caused by very special circumstances of test environment or execution conditions.Zebrunner agent comes with a convenient method revert_registration() from CurrentTest class for reverting test registration at runtime. The following code snippet shows a case where test is not reported on Monday.fromdatetimeimportdatefrompytest_zebrunnerimportCurrentTestdeftest_something()->None:...ifdate.today().weekday()==0:CurrentTest.revert_registration()...Overriding run attributesThis section contains information on agent APIs allowing to manipulate test run attributes during runtime.Setting build at runtimeAll the configuration mechanisms listed above provide possibility to declaratively set test run build. But there might be cases when actual build becomes available only at runtime.For such cases Zebrunner agent has a special method that can be used at any moment of the suite execution:# conftest.pyfrompytest_zebrunnerimportCurrentTestRun@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:CurrentTestRun.set_build("1.0.0")In the above example, thepytest_sessionstarthook resolves and sets the test run build.Setting localeIf you want to get full reporting experience and collect as much information in Zebrunner as its possible, you may want to report the test run locale.For this, Zebrunner agent has a special method that can be used at any moment of the suite execution:# conftest.pyfrompytest_zebrunnerimportCurrentTestRun@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:CurrentTestRun.set_locale("<your-locale>")In the above example, thepytest_sessionstarthook resolves and sets the test run locale.Overriding platformA test run in Zebrunner may have platform associated with the run. If there is at least one initiatedRemotedriver session within the test run, then its platform will be displayed as a platform of the whole test run. Even if subsequentRemotedrivers are initiated on another platform, the very first one will be displayed as the run platform.In some cases you may want to override the platform of the firstRemotedriver session. Another problem is that it is not possible to specifyAPIas a platform.Zebrunner provides two special methods to solve both of these problems:CurrentTestRun.set_platform(name)andCurrentTestRun.set_platform_version(name, version).
In the example below, the hook sets the API as a platform associated with the current test run.# conftest.pyfrompytest_zebrunnerimportCurrentTestRun@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:CurrentTestRun.set_platform("API")Collecting additional artifactsIn case your tests or an entire test run produce some artifacts, it may be useful to track them in Zebrunner.
The agent comes with a few convenient methods for uploading artifacts in Zebrunner and linking them to the currently running test or test run.
Artifacts and artifact references can be attached using functions fromattachmentsmodule. Together with an artifact
or artifact reference, you must provide the display name. For the file, this name must contain the file extension that
reflects the actual content of the file. If the file extension does not match the file content, this file will not be
saved in Zebrunner. Artifact reference can have an arbitrary name.Attaching artifact to testfrompytest_zebrunnerimportattach_test_artifactdeftest_something():...attach_test_artifact("path_to_artifact")...or with mark:@pytest.mark.artifact("path_to_artifact")deftest_something():...Attaching artifact reference to testfrompytest_zebrunnerimportattach_test_artifact_referencedeftest_something():...attach_test_artifact_reference("name","reference")...or with mark:@pytest.mark.artifact_reference("name","reference")deftest_something():...Attaching artifact to test runfrompytest_zebrunnerimportattach_test_run_artifactattach_test_run_artifact("path_to_artifact")Attaching artifact reference to test runfrompytest_zebrunnerimportattach_test_run_artifact_referenceattach_test_run_artifact_reference("name","reference")Artifact uploading process is performed in the foreground now, so it will block the execution thread while sending.
The background uploading will be available in upcoming releases.Syncing test executions with TCM systemsZebrunner provides an ability to upload test results to test case management systems (TCMs) on test run finish. For some TCMs it is possible to upload results in real-time during the test run execution.This functionality is currently supported for Zebrunner TCM, TestRail, Xray, Zephyr Squad and Zephyr Scale.Zebrunner TCMFor successful upload of test run results in Zebrunner TCM, one step must be performed:Configuration is performed on the tests sideConfigurationZebrunner agent has a specialZebrunnerclass with a bunch of methods to control results upload:#set_test_case_key(str)or@pytest.mark.zebrunner_test_case_key(str):   Mandatory. Using these mechanisms you can set Zebrunner's TCM case associated with specific automated test. It is highly recommended using the@pytest.mark.zebrunner_test_case_keyannotation instead of static method invocation. Use the static method only for special cases.#disable_sync():   Optional. Disables result upload. This method must be invoked before all tests.#enable_real_time_sync():   Optional. Enables real-time results upload. In this mode, result of test execution will be uploaded immediately after test finish. This method must be invoked before all tests.#set_run_id(str):   Optional. Adds result into existing Zebrunner test run. This method must be invoked before all tests.Example#conftest.pyfrompytest_zebrunner.tcmimportZebrunner@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:Zebrunner.set_run_id("<run-id>")# orZebrunner.disable_sync()# orZebrunner.enable_real_time_sync()# test_file.pyimportpytestfrompytest_zebrunner.tcmimportZebrunner@pytest.mark.zebrunner_test_case_key("<test-case-key-1>")@pytest.mark.zebrunner_test_case_key("<test-case-key-2>","<test-case-key-3>")defawesome_test1():...defawesome_test2():...Zebrunner.set_test_case_key("<test-case-key-4>")...TestRailFor successful upload of test run results in TestRail, two steps must be performed:Integration with TestRail is configured and enabled for Zebrunner projectConfiguration is performed on the tests sideConfigurationZebrunner agent has a specialTestRailclass with a bunch of methods to control results upload:#set_suite_id(str):   Mandatory. The method sets TestRail suite id for current test run. This method must be invoked before all tests. Thus, it should be invoked frompytest_sessionstarthook.#set_case_id(str)or@pytest.mark.test_rail_case_id(str):   Mandatory. Using these mechanisms you can set TestRail's case associated with specific automated test. It is highly recommended using the@pytest.mark.test_rail_case_idannotation instead of static method invocation. Use the static method only for special cases#disable_sync():   Optional. Disables result upload. Same as#set_suite_id(str), this method must be invoked before all tests#include_all_test_cases_in_new_run():   Optional. Includes all cases from suite into newly created run in TestRail. Same as#set_suite_id(str), this method must be invoked before all tests#enable_real_time_sync():   Optional. Enables real-time results upload. In this mode, result of test execution will be uploaded immediately after test finish. This method also automatically invokes#include_all_test_cases_in_new_run(). Same as#set_suite_id(str), this method must be invoked before all tests#set_run_id(str):   Optional. Adds result into existing TestRail run. If not provided, test run is treated as new. Same as#set_suite_id(str), this method must be invoked before all tests#set_run_name(str):   Optional. Sets custom name for new TestRail run. By default, Zebrunner test run name is used. Same as#set_suite_id(str), this method must be invoked before all tests#set_milestone(str):   Optional. Adds result in TestRail milestone with the given name. Same as#set_suite_id(str), this method must be invoked before all tests#set_assignee(str):   Optional. Sets TestRail run assignee. Same as#set_suite_id(str), this method must be invoked before all testsBy default, a new run containing only cases assigned to the tests will be created in TestRail on test run finish.ExampleIn the example below, a new run with name "Best run ever" will be created in TestRail on test run finish. Suite id is321and assignee is "Deve Loper". Results of theawesome_test1will be uploaded as result of cases with id10000,10001,10002. Results of theawesome_test2will be uploaded as result of case with id20000.#conftest.pyfrompytest_zebrunner.tcmimportTestRail@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:TestRail.set_suite_id("321");TestRail.set_run_name("Best run ever");TestRail.set_assignee("Deve Loper");# test_file.pyimportpytestfrompytest_zebrunner.tcmimportTestRail@pytest.mark.test_rail_case_id("10000")@pytest.mark.test_rail_case_id("10001","10002")defawesome_test1():...defawesome_test2():...TestRail.set_case_id("20000")...XrayFor successful upload of test run results in Xray two steps must be performed:Xray integration is configured and enabled in Zebrunner projectXray configuration is performed on the tests sideConfigurationZebrunner agent has a specialXrayclass with a bunch of methods to control results upload:#set_execution_key(str):   Mandatory. The method sets Xray execution key. This method must be invoked before all tests. Thus, it should be invoked frompytest_sessionstarthook.#set_test_key(str)or@pytest.mark.xray_test_key(str):   Mandatory. Using these mechanisms you can set test keys associated with specific automated test. It is highly recommended using the@pytest.mark.xray_test_key(str)mark instead of static method invocation. Use the static method only for special cases#disable_sync():   Optional. Disables result upload. Same as#set_execution_key(str), this method must be invoked before all tests#enable_real_time_sync():   Optional. Enables real-time results upload. In this mode, result of test execution will be uploaded immediately after test finish. Same as#set_execution_key(str), this method must be invoked before all testsBy default, results will be uploaded to Xray on test run finish.ExampleIn the example below, results will be uploaded to execution with keyZBR-42. Results of theawesome_test1will be uploaded as result of tests with keyZBR-10000,ZBR-10001,ZBR-10002. Results of theawesome_test2will be uploaded as result of test with keyZBR-20000.#conftest.pyfrompytest_zebrunner.tcmimportXray@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:Xray.set_execution_key("ZBR-42")# test_file.pyimportpytestfrompytest_zebrunner.tcmimportXray@pytest.mark.xray_test_key("ZBR-10000")@pytest.mark.xray_test_key("ZBR-10001","ZBR-10002")defawesome_test1():...defawesome_test2():...Xray.set_case_id("ZBR-20000")...ZephyrFor successful upload of test run results in Zephyr two steps must be performed:Zephyr integration is configured and enabled in Zebrunner projectZephyr configuration is performed on the tests sideDescribed steps work for both Zephyr Squad and Zephyr Scale.ConfigurationZebrunner agent has a specialZephyrclass with a bunch of methods to control results upload:#set_test_cycle_key(str):   Mandatory. The method sets Zephyr test cycle key. This method must be invoked before all tests. Thus, it should be invoked frompytest_sessionstarthook.#set_jira_project_key(str):   Mandatory. Sets Zephyr Jira project key. Same as#set_test_cycle_key(str), this method must be invoked before all tests#set_test_case_key(str)or@pytest.mark.zephyr_test_case_key(str):   Mandatory. Using these mechanisms you can set test case keys associated with specific automated test. It is highly recommended using the@pytest.mark.zephyr_test_case_key(str)mark instead of static method invocation. Use the static method only for special cases#disable_sync():   Optional. Disables result upload. Same as#set_test_cycle_key(str), this method must be invoked before all tests#enable_real_time_sync():   Optional. Enables real-time results upload. In this mode, result of test execution will be uploaded immediately after test finish. Same as#set_test_cycle_key(str), this method must be invoked before all testsBy default, results will be uploaded to Zephyr on test run finish.ExampleIn the example below, results will be uploaded to test cycle with keyZBR-R42from project with keyZBR. Results of theawesome_test1will be uploaded as result of tests with keyZBR-T10000,ZBR-T10001,ZBR-T10002. Results of theawesome_test2will be uploaded as result of test with keyZBR-T20000.#conftest.pyfrompytest_zebrunner.tcmimportZephyr@pytest.hookimpl(trylast=True)defpytest_sessionstart(session:Session)->None:Zephyr.set_test_cycle_key("ZBR-R42");Zephyr.set_jira_project_key("ZBR");# test_file.pyimportpytestfrompytest_zebrunner.tcmimportZephyr@pytest.mark.zephyr_test_key("ZBR-T10000")@pytest.mark.zephyr_test_key("ZBR-T10001","ZBR-T10002")defawesome_test1():...defawesome_test2():...Zephyr.set_test_case_key("ZBR-T20000")...Selenium WebDriver supportThe Zebrunner test agent is capable of tracking tests along with remote Selenium WebDriver sessions.Capturing session artifactsZebrunner supports 3 types of test session artifacts:Video recordingSession logVNC streamingTest agent itself does not capture those artifacts since it has no control over underlying Selenium Grid implementation, however, it is possible to attach appropriate artifact references by providing specially designed set of driver session capabilities (enabling capabilities) - see the table below for more details. Only theTruevalue is considered as trigger to save the link.ArtifactDisplay nameEnabling capabilityDefault referenceReference overriding capabilityVideo recordingVideoenableVideoartifacts/test-sessions/<session-id>/video.mp4videoLinkSession logLogenableLogartifacts/test-sessions/<session-id>/session.loglogLinkVNC streamingenableVNC<provider-integration-host>/ws/vnc/<session-id>vncLinkThedisplay nameis the name of the artifact that will be displayed on Zebrunner UI. This value is predefined and unfortunately can not be changed at the moment.Thedefault referenceis a reference to a location, where artifact isexpected to residein S3-compatible storage once created by test environment - it is important that it stays in sync with test environment configuration. It is possible to override references if needed by providingreference overriding capabilities. Note, that special<session-id>placeholder is supported and can be used as part of the value of those capabilities allowing runtime session id (generated by WebDriver) to be included into actual reference value.VNC streamingVNC is an artifact of a special type. They don't have a name and are not displayed among other artifacts. They are displayed in the video section on Zebrunner UI during session execution and are dropped off on session close.Default reference to the VNC streaming is based onprovidercapability. Value of this capability will be converted to preconfigured integration fromTest Environment Providergroup. The resolved integration must have a filled in URL property and be enabled in order to save the link to VNC streaming. The<provider-integration-host>placeholder of the default link will be replaced by the host of the obtained integration URL. Also, thehttpprotocol in the VNC streaming url will be automatically replaced byws, andhttpsprotocol will be replaced bywss. Currently, we only support Selenium, Zebrunner and MCloud integrations.ExamplesThe following code snippet shows the creation ofRemoteweb driver with enabled VNC streaming, video recording and session log artifacts, but overrides the link to VNC streaming. The<session-id>placeholder ofvncLinkcapability will be replaced by the actual session id.definit_driver()->Remote:options=ChromeOptions()options.set_capability("enableVNC","true")options.set_capability("vncLink","wss://example.com/vnc/<session-id>")options.set_capability("enableVideo","true")options.set_capability("enableLog","true")returnRemote(...,options=options,...)=== "Zebrunner Selenium Grid"deftest_something():hub_url='https://username:password@engine.zebrunner.com/wd/hub'options=ChromeOptions()options.set_capability("enableVNC","true")options.set_capability("vncLink","wss://example.com/vnc/<session-id>")options.set_capability("enableVideo","true")options.set_capability("enableLog","true")options.set_capability("zebrunner:provider","ZEBRUNNER")driver=Remote(command_executor=hub_url,options=options,...)...=== "BrowserStack"deftest_something():hub_url='https://username:password@hub-cloud.browserstack.com/wd/hub'options=ChromeOptions()...driver=Remote(command_executor=hub_url,options=options)...ContributionTo check out the project and build from the source, do the following:git clone git://github.com/zebrunner/python-agent-pytest.git
cd python-agent-pytestLicenseZebrunner reporting agent for PyTest is released under version 2.0 of theApache License.