I have this test
import unittest
class TestName(unittest.TestCase):
def setUp(self):
self.name = "Bob"
self.expected_name = "Bob"
def test_name(self):
# ... some operation over self.name
print self.name
self.assertEquals(self.name, self.expected_name)
if __name__ == '__main__':
unittest.main(verbosity=2)
how I can run instances for the test ?
run the same test for a list of inputs and outputs (["Bob", "Alice", ...]
) , maybe like
TestName(name="Bob", expected_name="Bob")
TestName(name="Alice", expected_name="Alice")
TestCase is used to create test cases by subclassing it. The last block of the code at the bottom allows us to run all the tests just by running the file.
Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.
Note that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings.
Q 10 - Which of the following is correct about a Unit Test Case? A - A Unit Test Case is a part of code which ensures that the another part of code (method) works as expected.
Check out DDT (Data-Driven/Decorated Tests).
DDT allows you to multiply a test case by running it with different test data, making it appear as multiple test cases.
consider this example, using DDT:
import unittest
from ddt import ddt, data, unpack
@ddt
class TestName(unittest.TestCase):
# simple decorator usage:
@data(1, 2)
def test_greater_than_zero(self, value):
self.assertGreater(value, 0)
# passing data in tuples to achieve the
# scenarios from your given example:
@data(('Bob', 'Bob'), ('Alice', 'Alice'))
@unpack
def test_name(self, first_value, second_value):
name, expected_name = first_value, second_value
self.assertEquals(name, expected_name)
if __name__ == '__main__':
unittest.main(verbosity=2)
I defined 2 test methods in the above code, but 4 test cases will be run, using the data I supplied in the decorator.
Output:
test_greater_than_zero_1 (__main__.TestName) ... ok
test_greater_than_zero_2 (__main__.TestName) ... ok
test_name_('Alice', 'Alice') (__main__.TestName) ... ok
test_name_('Bob', 'Bob') (__main__.TestName) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.000s
OK
I would use a mixin or a metaclass here, as unittest looks for classes, not instances.
class TestMixin (object):
def test_name ():
print self.name
class TestName (unittest.TestCase, TestMixin):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With