39

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.

2 Answers 2

40

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')
Sign up to request clarification or add additional context in comments.

5 Comments

How would this be different from creating the object directly. ie: def setUp(self): cls_mine = baz().
@Pradyot Mine's on the class and your's would be on the instance. I personally would probably set it up in the setUp method, but that's just a matter of preference.
@Pradyot setUp() is called before every test method, whereas setUpClass() is called once before all tests. Any expensive operations that many of your tests can take advantage of, should go in setUpClass().
‘access the global class atribute _mine through self’, is this generic Python language rule?
@user1633272 Yep. Testing that theory: class A: <\n> b = 42 <\n> def c(self): print(self.b). Using it with A().b() shows 42.
6

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.

2 Comments

what are the advantages of setUpTestData over setUpClass?
If you need to set up the same initial database state for each test within the test class, setUpTestData should be quicker. This is because it has database transaction support: all the tests will be wrapped in the same transaction, setUpTestData run only once within that transaction, and then each test will roll back to what the setUpTestData set up before running.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.