How do I use the unittest setUpClass method()?

Question:

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.

Asked By: urschrei

||

Answers:

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')
Answered By: Sam Dolan

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.

Answered By: seddonym
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.