in a previous post, i shared a basic script to use Python Unittest. At that post, there is not any Assertion(verification). Now, let’s see power of Assertions.
after we prepare our test and its steps, we will need at some point to check results. in following example, get header title and compare it if it correct or not. there is assertEqual function in Python Unittest.
assertEqual(first, second, msg) => first and second are vakues to be compared. msg is a message to be printed if function is failed. This function compare two values, if they are equal result will be pass, but if they are not some result will be failed.
we will find following text in html code in our website: <a class=”site-description”>A Blog For Software Testing and Automation</a>
# -*- coding: UTF-8 -*- import unittest from selenium import webdriver class TestClass(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(20) self.driver.set_page_load_timeout(20) self.driver.maximize_window() def test_MahsumAkbasNet_Pass(self): self.driver.get("http://www.mahsumakbas.net") headerTitle = self.driver.find_element_by_xpath("//a[@class='site-description']").text self.assertEqual(headerTitle, "A Blog For Software Testing and Automation", "Title is wrong") def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main()
when run as python script in Eclipse, you will see following output:
.
----------------------------------------------------------------------
Ran 1 test in 11.248s
OK
let’s see a failed example. in same code change function as:
self.assertEqual(headerTitle, "Lorem ipsum dolor sit amet", "Title is wrong")
output will be:
F
======================================================================
FAIL: test_MahsumAkbasNet_Pass (__main__.TestClass)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\xxx\src\unittestpackage\mahsumakbasnetUnittest.py", line 17, in test_MahsumAkbasNet_Pass
self.assertEqual(headerTitle, "Lorem ipsum dolor sit amet", "Title is wrong")
AssertionError: Title is wrong
----------------------------------------------------------------------
Ran 1 test in 12.956s
FAILED (failures=1)
Have nice testing !!!