I'm looking for some basic examples of the python 2.7 unittest setUpClass() method. I'm trying to test some class methods in my module, and I've gotten as far as:
import unittest import sys import mymodule class BookTests(unittest.TestCase): @classmethod def setUpClass(cls): cls._mine = mymodule.myclass('test_file.txt', 'baz')
But I have no idea how to proceed from here to write tests utilising the object I just created.
As per my comment in response to the answer by Gearon, the setUp method is meant for elements of the fixture that are common to all tests (to avoid duplicating that code in each test). I find this is often useful as removing duplication (usually) improves readability and reduces the maintenance burden.
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.
In your test methods you can now access the global class atribute _mine
through self. So you can do something like this:
def test_something(self): self.assertEqual(self._mine.attribute, 'myAttribute')
If you're using Django 1.8+, you should use the setUpTestData
method instead.
You can then set any attributes on the cls
object, and access them via the individual test methods on the self
object.
More information is in the Django docs.
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