Reporting automation results to TestRail using Python

We have been hard at work integrating our Python based GUI automation framework (that uses the Page Object pattern) with a test case management tool for reporting purposes. In this post we will show you how to report the results of your automated checks to a visual test case management tool – TestRail. TestRail offers a free trial – so you can sign up for free and follow this post.


Why this post?

In most automated checks, we are able to judge the outcome as ‘pass’ or ‘fail’ by comparing the expected result to the actual result. Tracking, reporting and sharing the test results is important. Excel and email rarely scale and need a lot of maintenance. Continuous Integration servers are great for engineers – but non-technical stakeholders prefer something more visual. At Qxf2, we love TestRail – a visual test case management software. We got you started with TestRail in an earlier post. In this post, we are going to show you how automation can update test results directly on to TestRail.


Report automation results to TestRail using Python

We’ll need to perform the following steps to report test results automatically to TestRail
1. Get the TestRail API
2. Connect (authentication) to your TestRail instance
3. Write the logic to update test results to TestRail
4. Identify your test case id on TestRail
5. Modify your test script to report to TestRail
 
 
1. Get the TestRail API
TestRail provides a useful REST API for automated tests to directly report results on to TestRail. The API provides the functionality to authenticate API requests, provides seamless JSON encoding/decoding and has generic support for read and write requests. We will write some useful wrappers around TestRail’s official API binding for Python.
Before we proceed, please download the testrail.py from here and follow the installation instructions.

2. Connect to your TestRail instance
We prefer separating any credentials we use into separate files. For this tutorial, we have created testrail.env that looks something like this:
testrail.env

TESTRAIL_URL=https://.testrail.com
[email protected]
TESTRAIL_PASSWORD=test

We then created a file that wraps around TestRail’s API called TestRail.py. In this file we implemented a method to connect to the TestRail instance.

"""
TestRail integration
"""
import dotenv,os,testrail,Conf_Reader
 
def get_testrail_client():
    "Get the TestRail account credentials from the testrail.env file"
    testrail_file = os.path.join(os.path.dirname(__file__),'testrail.env')
    #Get the TestRail Url
    testrail_url = Conf_Reader.get_value(testrail_file,'TESTRAIL_URL')
    client = testrail.APIClient(testrail_url)
    #Get and set the TestRail User and Password
    client.user = Conf_Reader.get_value(testrail_file,'TESTRAIL_USER')
    client.password = Conf_Reader.get_value(testrail_file,'TESTRAIL_PASSWORD')
 
    return client

Now we have an object that can connect to your TestRail instance!

3. Write the logic to update test results to TestRail
TestRail needs to know two things to go an update a test case result:
a. the test run id
b. the test case id

We need both because we can have multiple test runs for the same set of test cases. So our script should be able to update the test results into TestRail for a particular test run and specific test case. For this we need to know the test case id and the test run id. We implemented the update_testrail method. This method can be called from the test script with appropriate parameters so that the test results are recorded in TestRail for the specific case id and run id.

def update_testrail(case_id,run_id,result_flag,msg=""):
    "Update TestRail for a given run_id and case_id"
    update_flag = False
    #Get the TestRail client account details
    client = get_testrail_client()
 
    #Update the result in TestRail using send_post function. 
    #Parameters for add_result_for_case is the combination of runid and case id. 
    #status_id is 1 for Passed, 2 For Blocked, 4 for Retest and 5 for Failed
    status_id = 1 if result_flag is True else 5
 
    if run_id is not None:
        try:
            result = client.send_post(
                'add_result_for_case/%s/%s'%(run_id,case_id),
                {'status_id': status_id, 'comment': msg })
        except Exception,e:
            print 'Exception in update_testrail() updating TestRail.'
            print 'PYTHON SAYS: '
            print e
        else:
            print 'Updated test result for case: %s in test run: %s with msg:%s'%(case_id,run_id,msg)
 
    return update_flag

NOTE: Test case ids stay constant across test runs in TestRail. However each test run is assigned a unique id. To automatically obtain your run id based on your test run name, you can implement something similar to this code snippet:

    def get_project_id(project_name):
        "Get the project ID using project name"
        client = get_testrail_client()
        project_id=None
        projects = client.send_get('get_projects')
        for project in projects:
            if project['name'] == project_name: 
                project_id = project['id']
                #project_found_flag=True
                break
        return project_id
 
    def get_run_id(test_run_name,project_name):
        "Get the run ID using test name and project name"
        run_id=None
        client = get_testrail_client()
        project_id = get_project_id(project_name)
        try:
            test_runs = client.send_get('get_runs/%s'%(project_id))
        except Exception,e:
            print 'Exception in update_testrail() updating TestRail.'
            print 'PYTHON SAYS: '
            print e
            return None
        else:
            for test_run in test_runs:
                 if test_run['name'] == test_run_name:
                     run_id = test_run['id']
                     break
            return run_id

4. Identify your test case id on TestRail
To obtain the test case id, simply visit your project on TestRail, navigate to Test Cases section and look for the integer in the ID column next to your test case.

TestRail case ids

5. Modify your test script to report to TestRail
Now you can modify your existing test scripts to report to TestRail. Here is a code sample that shows you how to use the method you wrote earlier:
Test Script

#Code to automate test case goes here
.
.
#Update TestRail
    case_id = 125 #Case id of your test case 
    if (result_flag):
        msg = "Successfully updated the example form"
    else:
        msg = "Failed to update the example form"
    Test_Rail.update_testrail(case_id,test_run_id,result_flag,msg=msg)

Hope this post helps you offload the manual task of updating the test results in TestRail! Get all this code for free in our open-sourced Python test automation framework based on the page object pattern. We strongly recommend you check it out!


Subscribe to our weekly Newsletter


View a sample



49 thoughts on “Reporting automation results to TestRail using Python

  1. Hello,
    Can I ask you one question
    Explain me in details, whence you take result_flag?
    If you can, show the result_flag in code

    1. Hi,
      We use result_flag to validate if a particular step passed/failed.

      #Set Phone number in form
      result_flag = test_obj.set_phone(phone)
      test_obj.log_result(result_flag,
                          positive="Phone number was successfully set for phone: %sn"%phone,
                          negative="Failed to set phone number: %s nOn url: %sn"%(phone,test_obj.get_current_url()))
       #Update TestRail
       case_id = testrail_file.test_example_form_phone
       test_obj.report_to_testrail(case_id,test_run_id,result_flag)
  2. Hi,
    Can you pls help me in getting the multiple testcases using multiple test suite ids. Using the below snippet I can get testcases that are releated to the specific testsuite
    from testrail import *
    client = APIClient(‘https://XXXX’)
    client.user = ‘…..’
    client.password = ‘….’
    case = client.send_get(‘get_cases/1&suite_id=3881’)
    print(case)

  3. Need help in fetching testcases using multiple testsuite id
    from testrail import *
    client = APIClient(‘…..’)
    client.user = ‘…..’
    client.password = ‘….’
    case = client.send_get(‘get_cases/1&suite_id=xxx’)
    print(case)

    1. Kranthi, I looked at the TestRail API docs also and couldn’t find any details about using multiple suite id’s. Will surely let you know if I find any information.

      Thanks
      Indira Nellutla

  4. Hi, I have a Framework using Behave (gherkin), where every scenarios is a test case.

    How can I update a testrail run having this sintax? Where should I put the test case id?

    Thanks

      1. Thank you Rohan, I did check behave-testrail-reporter but it was difficult to understand, instead I used the example from this page with minor changes, and to use it with behave was really easy:

        I create a step like: Then I will run the following test case: “439”
        That step saves into the context variable (special global variable from behave) the tc_id, then using the test_rail.py I update the testplan with the tc_result + tc_id at the after_scenario

        🙂

  5. Hi
    I have a jenkins job to run CI automation tests and i want to report results back to Test rail how can i do this? please help

    1. Hi,
      Here you just need to modify your test to post a report to TestRail as per blog. CI (Jenkins) is only responsible for triggering your test. If your test capable to post report to TestRail, then you don’t worry about CI.

    1. Namita,

      I am not too clear on your requirement but here are my thoughts
      If you want to create JIRA issues as part of the test automation and then link those issues to TestRail, you can use JIRA’s API to create the issue first and then include the issue ID as part of the defects field when you submit a test result to TestRail. There are Python bindings to access TestRail’s API

      Ref:- https://discuss.gurock.com/t/how-do-i-intergrate-testrail-with-jira-by-using-push/2049

      I hope this information helps!

  6. how to pass custom fields via pytest automation and post in testrail.
    I have purest-testrail plugin integrated with purest framework. When I. run automation tests to post. in test rail, the test results are posted with Untested as the test run status.
    This is because field Platform is not passed.
    How can I pass this custom. field “Platform” via automation so that the tes trun status is updated correctly

    1. Hi Shilpa,

      I am not sure in case you are running your tests with xdist to run the tests, If yes I found following stackoverflow article which can be helpful to you:
      https://stackoverflow.com/questions/57097553/how-to-aggregate-test-results-to-publish-to-testrail-after-executing-pytest-test

      Also, I found an open issue on the pytest-testrail GitHub about the support of the custom field, as a check would you please check if you add any custom field manually in the testrail then after execution, the field values are displayed in the test run report. Below is the github link:
      https://github.com/allankp/pytest-testrail/issues/120

      Regards,
      Rahul

Leave a Reply

Your email address will not be published. Required fields are marked *