Selenium Unittest in Python [1]

https://www.seleniumeasy.com/python/selenium-webdriver-unittest-example
To support test automation, we need ‘unittest’ unit testing framework was originally inspired by JUnit. Unittest is included test module by default in the Python standard library. 
Unittest supports test automation, by sharing setup and shutdown code for tests. The setUp() and tearDown() methods allows to define set of instructions /commands to be executed before and after each test method. If the setUp() method it self raises an exception while executing tests, the test methods will not be executed. But If setUp() is executed successfully, tearDown() will run even if the test method is passed or not.
Below section demonstrates a quick look on unittest features using Selenium Webdriver:

import unittest
from selenium import webdriver

class InputFormsCheck(unittest.TestCase):

    #Opening browser.
    def setUp(self):
        self.driver = webdriver.Chrome(r"C:\Program Files\chromedriver.exe")
 
    #Testing Single Input Field.    
    def test_singleInputField(self):
        pageUrl = "http://www.seleniumeasy.com/test/basic-first-form-demo.html"
        driver=self.driver
        driver.maximize_window()
        driver.get(pageUrl)

        #Finding "Single input form" input text field by id. And sending keys(entering data) in it.
        eleUserMessage = driver.find_element_by_id("user-message")
        eleUserMessage.clear()
        eleUserMessage.send_keys("Test Python")

        #Finding "Show Your Message" button element by css selector using both id and class name. And clicking it.
        eleShowMsgBtn=driver.find_element_by_css_selector('#get-input > .btn')
        eleShowMsgBtn.click()

        #Checking whether the input text and output text are same using assertion.
        eleYourMsg=driver.find_element_by_id("display")
        assert "Test Python" in eleYourMsg.text
 
    # Closing the browser.
    def tearDown(self):
        self.driver.close()

# This line sets the variable “__name__” to have a value “__main__”.
# If this file is being imported from another module then “__name__” will be set to the other module's name.
if __name__ == "__main__":
    unittest.main()
C:\Users\zhuby\hans\testcase>main.py
DevTools listening on ws://127.0.0.1:57826/devtools/browser/6f03e012-bed9-4e5c-9775-7f79a3bf8770
.
Ran 1 test in 9.061s
OK

What is the above program doing ?

Step 1: It Opens chrome browser
Step 2: Enters the URL and maximize the browser
Step 3: Enters text ‘Test Python’ in the input text field
Step 4: Clicks on a button
Step 5: Finally, it checks for the text we have entered and the closes the browser.

2 Replies to “Selenium Unittest in Python [1]”

Leave a Reply

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