Package: testproject-python-sdk
TestProject OpenSDK for PythonTestProjectis aFreeTest Automation platform for Web, Mobile and API testing.To get familiar with the TestProject, visit our maindocumentationwebsite.TestProject SDK is a single, integrated interface to scripting with the most popular open source test automation frameworks.From now on, you can effortlessly execute Selenium and Appium native tests using a single automation platform that already takes care of all the complex setup, maintenance and configs.With one unified SDK available across multiple languages, developers and testers receive a go-to toolset, solving some of the greatest challenges in open source test automation.With TestProject SDK, users save a bunch of time and enjoy the following benefits out of the box:100% open source and available as aPyPIproject.5-minute simple Selenium and Appium setup with a singleAgentdeployment.Automatic test reports in HTML/PDF format (including screenshots).Collaborative reporting dashboards with execution history and RESTful API support.Always up-to-date with the latest and stable Selenium driver version.A simplified, familiar syntax for both web and mobile applications.Complete test runner capabilities for both local and remote executions, anywhere.Cross platform support for Mac, Windows, Linux and Docker.Ability to store and execute tests locally on any source control tool, such as Git.Getting startedTo get started, you need to complete the following prerequisites checklist:Login to your account athttps://app.testproject.io/orregister a new one.Downloadand install an Agent for your operating system or pull a container fromDocker Hub.Run the Agent andregister itwith your Account.Get a development token from theIntegrations / SDKpage.InstallationThe TestProject Python SDK isavailable on PyPI. All you need to do is add it as a Python module using:pip3 install testproject-python-sdkand you’re good to go.Minimum Python version required is 3.6Test DevelopmentUsing a TestProject driver is identical to using a Selenium driver. Once you have added the SDK as a dependency to your project, changing the import statement is enough in most cases.You can create a TestProject-powered version of a test using Chrome by using the TestProject Chrome driver:# from selenium import webdriver  <-- replace this importfromsrc.testproject.sdk.driversimportwebdriverdeftest_create_a_chrome_driver_instance():driver=webdriver.Chrome()# Your test code goes heredriver.quit()Here’s an example of a complete test that is using the Chrome driver from the TestProject SDK:fromsrc.testproject.sdk.driversimportwebdriverdefsimple_test():driver=webdriver.Chrome()driver.get("https://example.testproject.io/web/")driver.find_element_by_css_selector("#name").send_keys("John Smith")driver.find_element_by_css_selector("#password").send_keys("12345")driver.find_element_by_css_selector("#login").click()passed=driver.find_element_by_css_selector("#logout").is_displayed()print("Test passed")ifpassedelseprint("Test failed")driver.quit()if__name__=="__main__":simple_test()DriversThe TestProject SDK overrides standard Selenium/Appium drivers with extended functionality.The examples shown in this document are based on Chrome. The SDK works in the same way for all other supported browsers:FirefoxSafariEdgeInternet ExplorerAndroid apps (using Appium)iOS apps (using Appium)Generic driver (for non-UI tests)WebDriverWaitIn order to use Selenium’s WebDriverWait with TestProject SDK all you need to do is import it directly from the SDK classes instead of from selenium’s libraries.An example can be seenhere.Development tokenThe SDK uses a development token for communication with the Agent and the TestProject platform.
To configure your development token for use with the SDK, you have to specify it in an environment variableTP_DEV_TOKEN.Alternatively, you can pass in your developer token as an argument to the driver constructor:deftest_create_a_chrome_driver_instance():driver=webdriver.Chrome(token='YOUR_TOKEN_GOES_HERE')# Your test code goes heredriver.quit()> If a token is specified in both the driver constructor and in an environment variable, the token in the environment will be the one used.TestProject AgentBy default, drivers communicate with the local Agent listening onhttp://localhost:8585.
This value can be overridden by setting theTP_AGENT_URLenvironment variable to the correct Agent address, or pass it in the driver constructor.Remote AgentBy default, drivers communicate with the local Agent listening onhttp://localhost:8585.Agent URL (host and port), can be also provided explicitly using this constructor usingagent_urlparameter:driver=webdriver.Chrome(agent_url='http://remote-ip:port')NOTE:By default, the agent binds to localhost.
In order to allow the SDK to communicate with agents running on a remote machine (On the same network), the agent should bind to an external interface.
For additional documentation on how to achieve such, please refer [here](https://docs.testproject.io/testproject-agents/testproject-agent-cli#start)Remote (Cloud) DriverBy default, TestProject Agent communicates with the local Selenium or Appium server.
In order to initialize a remote driver for cloud providers such as SauceLabs or BrowserStack,
a custom capabilitycloud:URLshould be set, for example:SauceLabsdefdriver():chrome_options=ChromeOptions()chrome_options.set_capability("cloud:URL","https://{USERNAME}:{PASSWORD}@ondemand.us-west-1.saucelabs.com:443/wd/hub")driver=webdriver.Chrome(chrome_options=chrome_options,projectname="Examples")yielddriverdriver.quit()BrowserStackdefdriver():chrome_options=ChromeOptions()chrome_options.set_capability("cloud:URL","https://{USERNAME}:{PASSWORD}@hub-cloud.browserstack.com/wd/hub")driver=webdriver.Chrome(chrome_options=chrome_options,projectname="Examples")yielddriverdriver.quit()ReportsBy default, the TestProject SDK reports all executed driver commands and their results to the TestProject Cloud.
This allows us to create and display detailed HTML reports and statistics in your project dashboards.Reports can be completely disabled using this driver constructor:deftest_disable_reporting():driver=webdriver.Chrome(disable_reports=True)# no reports will be created for this testdriver.quit()Implicit project and job namesThe SDK will attempt to infer Project and Job names when you use pytest or unittest. For example:when usingpytest, tests in themy_tests.pymodule in thee2e_tests/chromepackage will be reported with a project namee2e_tests.chromeand job namemy_tests.when usingunittest, tests in themy_tests.pymodule in thee2e_tests/chromepackage will be reported with a project namechromeand job namemy_tests.Examples using inferred project and job names:pytestunittestExplicit project and job namesProject and Job names can be also specified explicitly using this constructor:deftest_specify_project_and_job_names_in_driver_constructor():driver=webdriver.Chrome(projectname='My custom project',jobname='My custom job')# Your test code goes heredriver.quit()or using the@reportdecorator:fromsrc.testproject.decoratorimportreport@report(project='My project',job='My job')deftest_specify_project_and_job_name_in_decorator():driver=webdriver.Chrome()# Your test code goes heredriver.quit()Examples using explicitly specified project and job names:pytestunittestReporting extensionsReporting extensions extend the TestProject SDK reporting capabilities by intercepting unit testing framework assertion errors and reporting them as failed steps.This functionality can be added by decorating your test method with the@report_assertion_errorsdecorator.This decorator has an optional boolean argument ‘screenshot’ that will decide if failed assertions will include screenshots in the report.fromsrc.testproject.decoratorimportreport_assertion_errors@report_assertion_errorsdeftest_automatically_report_assertion_error():driver=webdriver.Chrome()assert1==2# This assertion will be reported automatically as a failed stepdriver.quit()@report_assertion_errors(screenshot=False)deftest_automatically_report_assertion_error_without_screenshots():driver=webdriver.Chrome()assert1==2# This assertion will be reported automatically as a failed step and no screenshot will be takendriver.quit()Here is a working example forpytest, and here is one forunittest.Please make sure to follow the advice givenhereto ensure correct test name reporting.Test reportsAutomatic test reportingTests are reported automatically when a test ends or when thequit()command is called on the driver.
This behavior can be overridden or disabled (see theDisabling Reportssection below).In order to determine whether a test has ended, the call stack is inspected, searching for the current test method.
When the test name is different from the latest known test name, it is concluded that the execution of the previous test has ended.
This is supported for both pytest and unittest.To override the inferring of the test name and specify a custom test name instead, you can use the@reportdecorator:fromsrc.testproject.decoratorimportreport@report(test='My test name')deftest_specify_test_name_in_decorator():driver=webdriver.Chrome()# Your test code goes heredriver.quit()Here is a complete example usingautomatic reporting.Manual test reportingTo report tests manually, you can usedriver.report().test():deftest_report_test_manually():driver=webdriver.Chrome()# Your test code goes heredriver.report().test(name='My test name',passed=True)driver.quit()Reporting stepsSteps are reported automatically for every driver commands that is executed.
If this feature is disabled, or you would like to add steps manually, you can usedriver.report().step():deftest_report_step_manually():driver=webdriver.Chrome()# Your test code goes heredriver.report().step(description='My step description',message='An additional message',passed=False,screenshot=True,element=element_search_criteria_object,inputs=dict_of_input_parameters,outputs=dict_of_output_parameters)driver.quit()Here is a complete example usingmanual test reporting of tests and steps.Step settingsStep settings allow controlling driver default execution and reporting behavior such as:Default timeout.Sleep duration Before/After step execution.Screenshot capturing logic.Execution result inversion.Here is an example on how to take a screenshot upon any driver command executed:deftest_use_step_settings():driver=webdriver.Chrome()# Using StepSettings for the whole test.driver.step_settings=StepSettings(screenshot_condition=TakeScreenshotConditionType.Always)# Your test code goes here - all driver commands will use the defined step_settingsdriver.quit()Single step settings overrideFor convenience we can also use the StepSettings inside a ‘with’ compound statement called DriverStepSettings.Here is an example on how a single step can be used with different step settings.
By default, screenshots are taken on step failures only, the following example demonstrates how to override this
behavior and take a screenshot when a step passes:deftest_use_single_step_settings():driver=webdriver.Chrome()# A single step we want to run with an overriding StepSettings.withDriverStepSettings(driver,StepSettings(screenshot_condition=TakeScreenshotConditionType.Success)):driver.get("https://example.testproject.io/web/")# Screenshot will be taken only if step passes.driver.get("https://example.testproject.io/web/")# Screenshot will be taken only if step fails (default).Disabling reportsIf reports were not disabled when the driver was created, they can be disabled or enabled later.
However, if reporting was explicitly disabled when the driver was created, theycannotbe enabled later.Disable all reportsThe following will temporarily disable all reporting:deftest_temporarily_disable_all_reporting_then_reenable_it_later():driver=webdriver.Chrome()driver.report().disable_reports(True)driver.find_element_by_id('your_element_id').click()# This statement will not be reporteddriver.report().disable_reports(False)driver.quit()Disable automatic test reportsThe following will disable automatic reporting of tests.
All steps will end up in a single test report, unless tests are reported manually usingdriver.report().test():deftest_disable_automatic_test_reporting():driver=webdriver.Chrome()driver.report().disable_auto_test_reports(True)# Tests will not be reported automatically from here ondriver.quit()Disable driver command reportsThe following will disable driver command reporting, which results in the reporting of tests that will have no steps, unless reported manually usingdriver.report().step():deftest_disable_automatic_reporting():driver=webdriver.Chrome()driver.report().disable_command_reports(True)# From here on, driver commands will not be reported automaticallydriver.quit()Disable driver command redactionWhen driver commands are being reported, the SDK will, by default, redact the values typed into sensitive elements
by replacing the actual text with three asterisks (***) in the report. Elements are considered sensitive if they:have an attributetypewith valuepassword(all browsers and platforms)are of typeXCUIElementTypeSecureTextField(iOS / XCUITest only)This redaction of sensitive commands can be disabled, if desired:deftest_disable_driver_command_report_redaction():driver=webdriver.Chrome()driver.report().disable_redaction(True)# From here on, driver commands will not be redacteddriver.quit()If no test name is specified using the decorator, the test method name will be used as the test name in the report.The importance of usingquit()Even more so than with regular Selenium- or Appium-based tests, it is important to make sure that you call thequit()method of your TestProject driver object at the end of every test that uses the TestProject SDK.Upon callingquit(), the SDK will send all remaining report items to the Agent, ensuring that your report on the TestProject platform is complete.Tip for pytest users: use apytest fixtureto ensure thatquit()is called at the end of the test, even when an error occurred during test execution:importpytest@pytest.fixturedefdriver():driver=webdriver.Chrome()yielddriverdriver.quit()deftest_using_pytest_fixture(driver):driver.get("https://example.testproject.io/web")Tip for unittest users: use thesetUp()andtearDown()methodsfor driver creation and destroying:importunittestclassChromeTest(unittest.TestCase):defsetUp(self):self.driver=webdriver.Chrome()deftest_using_unittest_setup_and_teardown(self):driver.get("https://example.testproject.io/web")deftearDown(self):self.driver.quit()Cloud and Local ReportBy default, the execution report is uploaded to the cloud, and a local report is created, as an HTML file in a temporary folder.At the end of execution, the report is uploaded to the cloud and SDK outputs to the console/terminal the path for a local report file:Execution Report: {temporary_folder}/report.htmlThis behavior can be controlled, by requesting only aLOCALor only aCLOUDreport.When the Agent is offline, and only a _cloud_ report is requested, execution will fail with appropriate message.Via a driver constructor:driver=webdriver.Chrome(report_type=ReportType.LOCAL)Control Path and Name of Generated ReportBy default, the local reports name is the timestamp of the test execution, and the path is the reports directory in the agent data folder.The SDK provides a way to override the default values of the generated local reports name and path.Via driver constructor:driver=ChromeDriver(chrome_options=ChromeOptions(),report_name="Python Local report",report_path="/my_executions/reports);LoggingThe TestProject Python SDK uses theloggingframework built into Python.
The default logging level isINFOand the default logging format is%(asctime)s %(levelname)s %(message)s, which results in log entries formatted like this:13:37:45 INFO Usinghttp://localhost:8585as the Agent URLIf you wish, you can override the default log configuration:Forpytestusers, it is recommended to provide alternative valuesin your pytest.iniUsers ofunittestcan override the configuration by setting theTP_LOG_LEVELand / orTP_LOG_FORMATenvironment variables, respectively, to the desired valuesSeethis pagefor a list of accepted logging levels andlook herefor more information on how to define a custom logging format.Behave SupportThe SDK also supports automatic reporting of Behave features, scenarios and steps using the @behave_reporter decorator.It will disable the reporting of driver commands and automatic reporting of tests.
Instead, it will report:A test for every scenario in a feature fileAll steps in a scenario as steps in the corresponding testSteps are automatically marked as passed or failed, to create comprehensive living documentation from your
specifications on TestProject Cloud.To enable Behave feature reporting, in your environment.py decorate one or more of the following methods:method used to initialize your driver (usually before_all or before_feature to store the driver in the behave context)after_stepafter_scenarioStoring the driver in the context provides direct access to the driver throughout the program
such as in the step implementations.@behave_reporterdefbefore_all(context):context.driver=webdriver.Chrome(projectname="Behave BDD")@behave_reporterdefafter_step(context,step):pass@behave_reporterdefafter_scenario(context,scenario):passBy default, screenshots are taken only when step fail in your test, if you would like to change
the behavior to always take a screenshot, pass the screenshot argument asTruein your decorator.@behave_reporter(screenshot=True)defafter_step(context,step):passAddon ProxyOne of the greatest features of the TestProject platform is the ability to execute a code written by someone else.
It can be your account colleagues, writing actions that you can reuse, or TestProject community users creating addons and solving common automation challenges.To get started, download a source file with the proxy class for the Action(s) you want to execute.
It can be done by navigating to theAddons page, opening an addon,
and clicking on theProxylink at the bottom left corner of the popup.Now, let’s pretend that one of your colleagues coded and uploaded an Addon naming it -Example Addon.
To use it in your test, download its proxy source file, add it to your project and invoke the actions using the following driver method:driver.addons().execute()That expects an instance of theActionProxyclass. For example:# Use Addon proxy to invoke 'Clear Fields' Actiondriver.addons().execute(ClearFieldsAction())Another example using ‘Type Random Phone’ Action:# Use Addon proxy to invoke 'Type Random Phone' Action# Notice how the action parameters are provided using an action proxy convenience methoddriver.addons().execute(TypeRandomPhoneAction("1",10),by=By.CSS_SELECTOR,by_value="#phone")Refer to theAddon Proxy Testfor complete example source.ExamplesHere is a list of all examples for the different drivers that are supported by this SDK:WebChrome testFirefox testSafari testEdge testInternet Explorer testAddon Proxy TestAndroidAndroid native testAndroid native appWeb test on mobile ChromeiOSiOS native testiOS native appWeb test on mobile SafariLicenseThe TestProject Python SDK is licensed under the LICENSE file in the root directory of the project source tree.