Skip to main content

How To Perform Unit Testing In Python On LambdaTest Selenium Grid


Unit testing is the type of software testing in which each component is considered an individual unit and tested in an isolated environment. It means that a unit or component will be tested for its features and performance independently, without combining it with any other unit. Python allows performing unit testing very easily with the help of the “unittest” library.

LambdaTest provides an online Selenium Automation Grid platform, enabling you to run your automation scripts on combinations of 2000+ different browsers and operating systems. LambdaTest also allows you to run your Python codes on its Selenium Grid. In this post, we will see how to perform unit testing in Python on LambdaTest online cloud-based Selenium Grid.

Prerequisites To Perform Unit testing In Python With LambdaTest Selenium Grid#


All the code samples in this documentation can be found in the Unittest LambdaTest Repository on Image GitHub. You can either download or clone the repository to quickly run your tests.

  1. Global Dependencies:

    • Make sure that you have the latest Python build installed. Download and install Python from here.
    • To install python with homebrew use the command below:
    $ brew install python
  2. LambdaTest Authentication Credential

Make sure to set your LambdaTest username, and access key as the environment variable. We will be importing these in our code. You can retrieve your username and access key from your LambdaTest automation dashboard by clicking on the key icon near the help button.

  1. Setting Up Project

    • The recommended way to run your tests would be in virtualenv. It will isolate the build from other setups you may have running and ensure that the tests run with the specified versions of the modules specified in the requirements.txt file.
    pip install virtualenv
    • Create a virtual environment in your project folder the environment name is arbitrary.
    virtualenv venv
    • Activate the environment:
    source venv/bin/activate
    pip install -r requirements.txt

Writing Your First Unit Test In Python#


For this demo purpose, we will be using this Github repository.

  1. Firstly, get the LambdaTest username and accesskey from the environment variables.
username = os.environ.get("undefined")access_key = os.environ.get("undefined")

Note: For getting these environment variables, you will need to import the “os” library of Python.

import os
  1. Next we need to set the desired capability of the Selenium Grid, on which we want to run our test on LambdaTest. You can learn more about it from our Desired Capabilities guide. For this demo, we have used the below specifications:
desired_caps = {
    # Name of the build under which the test will run    "build": 'LambdaTest Python unittest demo',
    # Name of the test to run    "name": 'Py-unittest',
    # Desired operating system    "platform": 'Windows 10',
    # Desired browser    "browserName": 'firefox',
    # Desired version of browser    "version": '73'}
  1. Since we have the LambdaTest Credentials and the Desired Capabilities, we can create the Selenium Remote WebDriver instance now. Use the below code to do the same.
self.driver = webdriver.Remote(           command_executor = "http://{}:{}@hub.lambdatest.com:80/wd/hub".format(username, access_key),           desired_capabilities = desired_caps)
  1. Now we are ready to write our test and launch it. The above steps can be considered as the setup() method.

  2. In the test, we will take an example of our sample ToDo app. We will try to check two checkboxes of the list and add another item in the list. The code to do is given below:

# try:driver = self.driver
# Urldriver.get("https://lambdatest.github.io/sample-todo-app/")
# Click on check boxcheck_box_one = driver.find_element_by_name("li1")check_box_one.click()
# Click on check boxcheck_box_two = driver.find_element_by_name("li2")check_box_two.click()
# Enter item in textfieldtextfield = driver.find_element_by_id("sampletodotext")textfield.send_keys("Yey, Let's add it to list")
# Click on add buttonadd_button = driver.find_element_by_id("addbutton")add_button.click()
# Verified added itemadded_item = driver.find_element_by_xpath("//span[@class='done-false']").textprint (added_item)
  1. Once the test is performed, we can assert if our test has passed as expected or failed. Here, we will check if the added item is actually present in the list or not. Below is the code that explains how to do that.
#Assertion if "Yey, Let's add it to list" in added_item:    driver.execute_script("lambda-status=passed")
else:    driver.execute_script("lambda-status=failed")
  1. Now we just need to write the teardown() method to close the driver, after the test is complete.
self.driver.quit()

The complete code for this test is give below:

import osimport unittestimport sysfrom selenium import webdriverusername = os.environ.get("undefined")access_key = os.environ.get("undefined")class FirstSampleTest(unittest.TestCase):    # setUp runs before each test case    def setUp(self):        desired_caps = {            "build": 'LambdaTest Python unittest demo',            "name": 'Py-unittest',            "platform": 'Windows 10',            "browserName": 'firefox',            "version": '73'        }        self.driver = webdriver.Remote(           command_executor="http://{}:{}@hub.lambdatest.com:80/wd/hub".format(username, access_key),           desired_capabilities= desired_caps)    # tearDown runs after each test case    def tearDown(self):        self.driver.quit()    # test file    def test_unit_user_should_able_to_add_item(self):        # try:        driver = self.driver        # Url        driver.get("https://lambdatest.github.io/sample-todo-app/")        # Click on check box        check_box_one = driver.find_element_by_name("li1")        check_box_one.click()        # Click on check box        check_box_two = driver.find_element_by_name("li2")        check_box_two.click()        # Enter item in textfield        textfield = driver.find_element_by_id("sampletodotext")        textfield.send_keys("Yey, Let's add it to list")        # Click on add button        add_button = driver.find_element_by_id("addbutton")        add_button.click()        # Verified added item        added_item = driver.find_element_by_xpath("//span[@class='done-false']").text        print (added_item)        # Assertion - check the pass fail condition        if "Yey, Let's add it to list" in added_item:            driver.execute_script("lambda-status=passed")        else:            driver.execute_script("lambda-status=failed")if __name__ == "__main__":    unittest.main()

Running Your First Unit Test In Python On LambdaTest Selenium Grid#


Upon executing the above code, the unit test will run and you can find the details of it on your automation dashboard of LambdaTest.

automation-dashboard

Debug your executed tests, verify results, see execution video, mark bugs, and much more using the most popular cross browser testing platform – LambdaTest.

For any query or doubt, please feel free to contact us via 24×7 chat support or you can also drop a mail to [email protected].
Happy testing!

Last updated on