Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Python

Unit Testing with Selenium-Python

2022-07-18

What is selenium?

Selenium automates browser. It performs all actions which human can do. Like form submission, button clicks, mouse actions, checking page content.

What is Unit tests?

It’s a small test case, which tests single function or small code. With this, we are sure that small part of code/functionality works as we expected.

Selenium + Unit Tests

We use selenium to write unit tests, to test user interface functionalities like user login, check page content, etc.

Pip install selenium

Example 1:

Test if we have at least one link with name “Web Development” in https://micropyramid.com

import unittest
from selenium import webdriver

GECKO_DRIVER_PATH = '/home/ravi/earth/autods/autoorders/geckodriver'

class FindLink(unittest.TestCase):

   def setUp(self):
       self.driver = webdriver.Firefox(executable_path=GECKO_DRIVER_PATH)
      
   def test_link(self):
       self.driver.get("https://micropyramid.com/")
       web_dev_link = self.driver.find_elements_by_partial_link_text('Web Development')
       # Test atleast we have one link with name  "Web Development"
       self.assertIsNotNone(web_dev_link)

   def tearDown(self):
       self.driver.quit()

if __name__ == '__main__':
   unittest.main()

Set Up Method: This method will initially called before calling your test method. You can write text fixtures or set up environment to run tests, etc. In above set up method, I've initialized firefox web browser. 

TearDown Method: called immediately after every test case finish execution. You can write any cleanup code. In above method, we closed opened firefox browser.

Test_link: Every test case name should start with test_ name. Here we simply calling selenium method to find all elements with a name. “Web Development”.

Example 2:

class TestLogin(unittest.TestCase):

   def setUp(self):
       self.driver = webdriver.Firefox(executable_path=GECKO_DRIVER_PATH)

   def test_search_by_text(self):
       self.driver.get("https://peeljobs.com/")
       email = self.driver.find_element_by_name("email")
       email.clear()
       email.send_keys("[email protected]")
       email = self.driver.find_element_by_name("password")
       email.clear()
       email.send_keys("test123")
       sbmt_button = self.driver.find_element_by_xpath('.//button[@class="btn btn-default login_form_button"]')
       sbmt_button.click()
       time.sleep(2)
       self.assertTrue("[email protected]" in self.driver.find_element_by_id("account_email"))

   def tearDown(self):
       self.driver.quit()