Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest setUpClass not working

I am trying to get started with unittest, but I am having a problem getting setUpClass() to work. Here is my test code...

import unittest

class TestRepGen(unittest.TestCase):
    """ Contains methods for training data testing """

    testvar = None

    @classmethod
    def setUpClass(cls):
        cls.testvar = 6

    def test_method(self):
        """ Ensure data is selected """
        self.assertIsNotNone(self.testvar,"self.testvar is None!")

# run tests
if __name__ == '__main__':
    unittest.main()

The assert error message is displayed, indicating that self.testvar == None, and has not been changed by setUpClass(). Is there something wrong with my code?

I get the same result if I run the code from within my IDE (Wing), or directly from the command line. For the record, I am using Python 3.2.1 under Windows7.

like image 895
Alan Harris-Reid Avatar asked Aug 11 '11 04:08

Alan Harris-Reid


People also ask

How do I run a Unittest in Python?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.

How do you use assertRaises in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

How do I test a class in Python?

First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest. TestCase, and lastly, write a series of methods to test all the cases of your function's behavior. First, you need to import a unittest and the function you want to test, formatted_name() .


1 Answers

setUpClass is new to the unittest framework as of 2.7 and 3.2. If you want to use it with an older version you will need to use nose as your test runner instead of unittest.

like image 171
Zanson Avatar answered Oct 07 '22 12:10

Zanson