0% found this document useful (0 votes)
17 views3 pages

Python Unittest Framework Guide

Uploaded by

gaurshetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

Python Unittest Framework Guide

Uploaded by

gaurshetty
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

2 --------------------------------------------------------------------
3 UnitTest:
4 --------------------------------------------------------------------
5 The unittest unit testing [Link] supports test automation, sharing of setup and
shutdown code for tests, aggregation of tests.
6
7 # test fixture:
8 This represents the preparation needed to perform one or more tests, and any associate
cleanup actions. This may involve, for example, creating temporary or proxy databases,
directories, or starting a server process.
9
10 # test case:
11 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.
12
13 # test suite:
14 This is a collection of test cases, test suites, or both. This is used to aggregate
tests that should be executed together. Test suites are implemented by the TestSuite
class.
15
16 # test runner:
17 This is a component which orchestrates the execution of tests and provides the outcome
to the user. The runner may use a graphical interface, a textual interface, or return a
special value to indicate the results of executing the tests.
18
19 Nominclature rules:
20 --------------------
21 1. File/Module name:
22 "test_*.py" or "*_test.py"
23 2. Class name:
24 "TestEmp:" or "EmpTest:" or any name with or without test word in name
25 3. Method/function name:
26 always name should start with test only
27
28 Rules for executing the unittest:
29 ---------------------------------
30 1. import unittest
31 2. write a program to test in sepetate file or in same
32 3. import the test program if in other module
33 4. create testcase class by inheriting the [Link]
34 5. create test method inside class, name of the method must start with 'test'
35 6. Use assert statement in the test method
36 7. finally call main() method from the unittest module
37
38 eg.
39 import unittest
40 def add(x,y):
41 return x + y
42
43 class SimpleTest([Link]):
44 def testadd1(self):
45 [Link](add(4,5),9)
46
47 if __name__ == '__main__':
48 [Link]()
49
50 8. to run above test use command : python [Link]
51 C:\Python27>python [Link]
52 .
53 ----------------------------------------------------------------------
54 Ran 1 test in 0.000s
55 OK
56
57 9. the following three could be the possible ourcomes of the test:
58
59 OK : The test passes
60 FAIL : The test does not pass and raises an AssertionError exception
61 ERROR : The test raises an exception other than AssertionError.
62 These outcomes are displayed on the console by '.', 'F' and 'E' respectively.
63 ------------------------------------------------------------------------------
64
65 Command line interface:
66 # to run all the tests in a folder then nevigate to that folder
67 python -m unittest
68 # to run the module or file use below command:
69 python -m unittest [Link]
70 # to run only perticular test class from module then use command:
71 python -m unittest test_module.TestClass
72 # to run particular method from testclass of any module
73 python -m unittest test_module.TestClass.test_method
74 #===================================
75 # List of all command line options:
76 #===================================
77 1. -h, --help
78 # Show help massage and exit
79 2. -v, --verbose
80 # Verbose output/ detailed output
81 3. -q, --quiet
82 # Minimal output/ less output
83 4. -f, --failfast
84 # Stop on first failure
85 5. -c, --catch
86 # Catch control-C and display results
87 # if interupted by ctrl+c still it completes current task and display result upto
current task
88 6. -b, --buffer
89 # Buffer stdout and stderr during test runs
90 7. -k TESTNAMEPATTERNS
91 # Only run tests which match the given substring
92 8. -s START, --start-directory START
93 # Directory to start discovery ('.' default)
94 10. -p PATTERN, --pattern PATTERN
95 # Pattern to match tests ('test*.py' default)
96 11. -t TOP, --top-level-directory TOP
97 # Top level directory of project
98 ------------------------------------------------------------------------------
99
100 # Fixtures
101 There can be numerous tests written inside a TestCase class. These test methods may need
database connection, temporary files or other resources to be initialized.
102
103 1. setUp()
104 # this runs before every testcase
105 # it is used to prepare prerequisit/testdata for the tests
106 2. tearDown()
107 # this runs after every testcase
108 # it is used to cleanup prerequisit/testdata for the tests
109 3. setUpClass()
110 # this runs once before test module
111 # it is used to prepare database/logging/prerequisit for the tests
112 4. tearDownClass()
113 # this runs once after test module
114 # it is used to cleanup prerequisit/testdata for the tests
115 5. run(result = None)
116 # Run the test, collecting the result into the test result object passed as result.
117 6. skipTest(reason)
118 # Calling this during a test method or setUp() skips the current test.
119 7. debug()
120 # Run the test without collecting the result.
121 8. shortDescription()
122 # Returns a one-line description of the test.
123
124
125
126
127
128
129
130
131
132
133
134
135
136

Common questions

Powered by AI

A test runner in the unittest framework is responsible for orchestrating the execution of tests and providing feedback on the results to the user. It can operate via various interfaces, like graphical or textual, and can return specific values to indicate the results of tests. This component is essential as it processes the results from test suites and cases, and presents the outcomes, including details on any errors or failures .

The unittest framework uses 'test suites' to manage the grouping and execution of multiple test cases. A test suite is a collection of test cases and/or other test suites that can be executed together. This allows for the aggregation of tests, supporting organized and cohesive test execution, which is managed by the TestSuite class .

The setUp() and tearDown() methods in the unittest framework are part of the test fixtures. setUp() is executed before every test case to prepare the prerequisite data or environment needed for the test. Conversely, tearDown() runs after every test case to clean up any data or environment used during the test. These methods ensure tests start with a known state and that resources are properly freed after tests complete .

The TestCase class in the unittest framework is the fundamental building block for creating a new test case. It provides methods and tools to create individual tests that assert expected outcomes. By using TestCase as a base class, developers can create multiple test methods within a single class, each performing assertions on specific responses to given inputs, supporting a structured approach to unit testing .

The unittest framework enforces consistent naming conventions through various rules. Test file names should follow patterns like 'test_*.py' or '*_test.py'. The class names for tests can include 'Test' in them, and test method names must start with 'test'. Consistent naming is crucial as it allows automatic test discovery and execution, organizes the test suite clearly, and ensures maintainability and readability of the test code .

In the unittest framework, the 'test fixture' represents all the necessary preparations required for performing one or more tests, as well as any associated cleanup actions. This can include setting up temporary databases, directories, or starting server processes. The test fixture is essential because it ensures that each test starts in a controlled environment, reducing side effects from previous tests and ensuring the reliability and consistency of test results .

The use of assert statements within test methods in the unittest framework is advantageous because these statements are pivotal in confirming that the code behaves as expected. Assertions automatically trigger an error if the specified condition is false, enabling clear identification of failures. This leads to better maintenance since the expected and actual outputs are concisely compared, providing a straightforward mechanism for developers to validate logic and ensure software correctness .

Shared setup and teardown procedures, such as setUpClass() and tearDownClass(), enhance test automation by allowing certain prerequisite setups and cleanups to occur once before and after all tests within a module. This minimizes repetitive setup and teardown across tests, streamlining the testing process, reducing redundancy, and potentially improving performance by only executing resource-intensive operations once .

The possible outcomes of a test run using the unittest framework are: OK, indicating the test has passed; FAIL, indicating the test has not passed and raises an AssertionError exception; and ERROR, indicating the test raises an exception other than AssertionError. On the console, these outcomes are displayed by '.', 'F', and 'E' respectively .

The command line interface for the unittest framework supports precise control over test execution using various options. Specific commands include running all tests in a directory by navigating there and using 'python -m unittest', running modules or files with 'python -m unittest test1.py', running specific test classes or methods, and employing options like '-v' for verbose output, '-f' to stop on the first failure, and '-k' to only run tests matching a given pattern. These options enable flexible and targeted test execution and debugging .

You might also like