A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.,The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.,A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.,For this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.000 s OK
test_isupper(__main__.TestStringMethods)...ok test_split(__main__.TestStringMethods)...ok test_upper(__main__.TestStringMethods)...ok -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.001 s OK
python - m unittest test_module1 test_module2 python - m unittest test_module.TestClass python - m unittest test_module.TestClass.test_method
python - m unittest tests / test_something.py
python - m unittest - v test_module
You can configure your test loader to run only tests with a certain prefix:
loader = unittest.TestLoader() loader.testMethodPrefix = "test_prefix" # default value is "test" suite1 = loader.discover('Test1', pattern = "Test*.py") suite2 = loader.discover('Test2', pattern = "Test*.py") alltests = unittest.TestSuite((suite1, suite2)) unittest.TextTestRunner(verbosity = 2).run(alltests)
Is there a way to run some specific test cases from file test1.py and test2.py where I can explicitly add those testcases to the suite1 and suite 2 in the above code.,If Test1.py contains a testcase name test_system in the class Test1, how can TestLoader load that specific test case instead of running all the testcases in that module.,The above code runs four test cases which is expected.,Both the test files have two test cases each.
Unit smoke.py Test1 Test1.py Test2 Test2.py
suite1 = unittest.TestLoader().discover('Test1', pattern = "Test*.py")
suite2 = unittest.TestLoader().discover('Test2', pattern = "Test*.py")
alltests = unittest.TestSuite((suite1, suite2))
unittest.TextTestRunner(verbosity = 2).run(alltests)
loader = unittest.TestLoader() loader.testMethodPrefix = "test_prefix" # default value is "test" suite1 = loader.discover('Test1', pattern = "Test*.py") suite2 = loader.discover('Test2', pattern = "Test*.py") alltests = unittest.TestSuite((suite1, suite2)) unittest.TextTestRunner(verbosity = 2).run(alltests)
test case − This is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.,The unittest module provides classes that make it easy to support these qualities for a set of tests.,Python's testing framework provides a useful mechanism by which test case instances can be grouped together according to the features they test. This mechanism is made available by TestSuite class in unittest module.,The nose.tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in unittest.TestCase.
Step 7 − Finally, call main() method from the unittest module.
import unittest
def add(x, y):
return x + y
class SimpleTest(unittest.TestCase):
def testadd1(self):
self.assertEquals(add(4, 5), 9)
if __name__ == '__main__':
unittest.main()
Step 8 − Run the above script from the command line.
C: \Python27 > python SimpleTest.py . -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 1 test in 0.000 s OK
The unittest module can be used from the command line to run single or multiple tests.
python - m unittest test1 python - m unittest test_module.TestClass python - m unittest test_module.TestClass.test_method
In the following example, two tests are written inside the TestCase class. They test result of addition and subtraction of two values. The setup() method initializes the arguments based on shortDescription() of each test. teardown() method will be executed at the end of each test.
import unittest
class simpleTest2(unittest.TestCase):
def setUp(self):
self.a = 10
self.b = 20
name = self.shortDescription()
if name == "Add":
self.a = 10
self.b = 20
print name, self.a, self.b
if name == "sub":
self.a = 50
self.b = 60
print name, self.a, self.b
def tearDown(self):
print '\nend of test', self.shortDescription()
def testadd(self):
""
"Add"
""
result = self.a + self.b
self.assertTrue(result == 100)
def testsub(self):
""
"sub"
""
result = self.a - self.b
self.assertTrue(result == -10)
if __name__ == '__main__':
unittest.main()
Run the above code from the command line. It gives the following output −
C: \Python27 > python test2.py
Add 10 20
F
end of test Add
sub 50 60
end of test sub
. ===
=== === === === === === === === === === === === === === === === === === === === =
FAIL: testadd(__main__.simpleTest2)
Add
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
File "test2.py", line 21, in testadd
self.assertTrue(result == 100)
AssertionError: False is not true
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 2 tests in 0.015 s
FAILED(failures = 1)
For this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. Set-up and tear-down functions can also be provided.,Since it is a common pattern to create a TestCase subclass with many similarly named test functions, unittest provides a TestLoader class that can be used to automate the process of creating a test suite and populating it with individual tests. For example,,Test case instances are grouped together according to the features they test. unittest provides a mechanism for this: the test suite, represented by unittest‘s TestSuite class:,Each TestCase instance represents a single test, but each concrete subclass may be used to define multiple tests — the concrete class represents a single test fixture. The fixture is created and cleaned up for each test case.
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.000 s OK
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) unittest.TextTestRunner(verbosity = 2).run(suite)
test_choice(__main__.TestSequenceFunctions)...ok test_sample(__main__.TestSequenceFunctions)...ok test_shuffle(__main__.TestSequenceFunctions)...ok -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.110 s OK
import unittest
class DefaultWidgetSizeTestCase(unittest.TestCase):
def runTest(self):
widget = Widget('The widget')
self.assertEqual(widget.size(), (50, 50), 'incorrect default size')
testCase = DefaultWidgetSizeTestCase()
The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.,Test case instances are grouped together according to the features they test. unittest provides a mechanism for this: the test suite, represented by unittest‘s TestSuite class:,A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.,Return a suite of all tests cases contained in the given module. This method searches module for classes derived from TestCase and creates an instance of the class for each test method defined for the class.
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception
for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1, 2, 3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.000 s OK
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) unittest.TextTestRunner(verbosity = 2).run(suite)
test_choice(__main__.TestSequenceFunctions)...ok test_sample(__main__.TestSequenceFunctions)...ok test_shuffle(__main__.TestSequenceFunctions)...ok -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.110 s OK
python - m unittest test_module1 test_module2 python - m unittest test_module.TestClass python - m unittest test_module.TestClass.test_method
python - m unittest - v test_module
Test Suite – It acts as a container for grouping test cases. With the help of a test suite, you can combine a set of test cases representing specific functionalities of the application under test.,Test Loader – It’s a Python class which loads test cases and suites created locally or from an external data source like a file. It releases a TestSuite object that carries those cases and suites.,The Unittest module has a TestSuite class which makes it easy to create an end to end Selenium Python Test Suite. With this feature, we can combine various tests into logical groups and turn them into a unified test suite. All of this is achievable by using the TestSuite, TestLoader, and TestRunner classes.,The TestLoader class reads all the test methods from the specified test files that contain the definition of the test suite. Then, the TestRunner class take control of the test suite and run all the tests specified. Below is the command to run the new test suite script.
Look at the code below to get a feel of the test class.
import unittest
from selenium
import webdriver
class SearchText(unittest.TestCase):
In our example, we are using the setup() method to create an instance of Firefox, set up the properties, and navigate to the main page of the application before executing the actual test.
import unittest
from selenium
import webdriver
class SearchText(unittest.TestCase):
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://www.google.com/")
Similar to the <setup()> method, test methods get implemented in the TestCase class. While adding these methods, it’s a good practice to prefix their names with the word test. Having such a name helps Test Runner distinguish between a test and other methods. Check out the below script to demonstrate the given Selenium Python example.
import unittest
from selenium
import webdriver
class SearchText(unittest.TestCase):
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://www.google.com/")
def test_search_by_text(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
# enter search keyword and submit
self.search_field.send_keys("Selenium WebDriver Interview questions")
self.search_field.submit()
#get the list of elements which are displayed after the search
#currently on result page usingfind_elements_by_class_namemethod
lists = self.driver.find_elements_by_class_name("r")
no = len(lists)
self.assertEqual(10, len(lists))
Below is the piece of code to facilitate command line execution. We’ll need to add it in our test script towards the end.
if __name__ == '__main__':
unittest.main()
After adding these lines, save the test as a standard Python script and name it as <selenium-python-test.py>. Then, try to execute it from the command line by using the following command.
python selenium - python - test.py