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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
urschrei
  • 25,123
  • 12
  • 43
  • 84

2 Answers2

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')
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • How would this be different from creating the object directly. ie: def setUp(self): cls_mine = baz(). – Pradyot Apr 28 '14 at 15:05
  • @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. – Sam Dolan Apr 28 '14 at 19:53
  • 16
    @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()`. – Dennis May 16 '14 at 20:58
  • ‘access the global class atribute _mine through self’, is this generic Python language rule? – user1633272 Feb 28 '17 at 16:12
  • @user1633272 Yep. Testing that theory: `class A: <\n> b = 42 <\n> def c(self): print(self.b)`. Using it with `A().b()` shows `42`. – ggorlen Feb 10 '23 at 18:39
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.

seddonym
  • 16,304
  • 6
  • 66
  • 71
  • 1
    what are the advantages of setUpTestData over setUpClass? – Germán Ruelas Jun 19 '20 at 00:43
  • 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. – seddonym Jun 22 '20 at 07:53