• 15

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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):  
    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.

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')
  • 32
Reply Report
      • 1
    • 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().

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.

  • 6
Reply Report
    • 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.

Trending Tags