Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the unittest setUpClass method()?

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.

like image 999
urschrei Avatar asked Feb 03 '11 20:02

urschrei


People also ask

What is the purpose of using setUp and Setupclass methods from unittest TestCase class?

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.

What does unittest main () do?

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.


2 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') 
like image 107
Sam Dolan Avatar answered Sep 27 '22 16:09

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.

like image 27
seddonym Avatar answered Sep 27 '22 17:09

seddonym