2

In my setUpClass I would like to create a resource in the database one time, which is then used for all of the tests in the class.

After I create the resource in setUpClass, I would like to perform assertions on it right then and there. However, I'm not sure how to call assertions in setUpClass, given that all of the assertion functions are instance methods, not class methods.

import unittest

class TestFoo(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.foo = cls.make_foo(name='bar')
        # How would I assert that cls.foo['name'] == 'bar'?
        # The following does not work, as the assertEquals function is not a class method
        # cls.assertEquals(cls.foo['name'], 'bar')

    @classmethod
    def make_foo(cls, name):
        # Calls a POST API to create a resource in the database
        return {'name': name}

    def test_foo_0(self):
        # Do something with cls.foo
        pass

    def test_foo_1(self):
        # do something else with cls.foo
        pass
       

The only alternative I can think of is to raise an exception in setUpClass:

    @classmethod
    def setUpClass(cls):
        cls.foo = cls.make_foo(name='bar')
        if cls.foo['name'] != 'bar':
            raise Exception("Failed to create resource, cannot do the tests")

Of course, I do not want to call the assertions from each test, as this will just duplicate the code.


Edit: I don't think this workaround is good, because the failure message will point to the self.assertFalse(self.flag) line, instead of the if cls.foo['name'] ~= 'bar' line. In addition, if you created multiple resources, this would need multiple flags to disambiguate.

    flag=False
    
    @classmethod
    def setUpClass(cls):
        cls.foo = cls.make_foo(name='bar')
        if cls.foo['name'] != 'bar':
            cls.flag=True

    def setUp(self):
        self.assertFalse(self.flag)

Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • Does this answer your question? [How to fail a python unittest in setUpClass?](https://stackoverflow.com/questions/14768135/how-to-fail-a-python-unittest-in-setupclass) – quamrana Apr 11 '21 at 17:17
  • @quamrana No, the linked question is about how to fail a test from setUpClass. My question is how to call assertion functions from setUpClass. While a similar technique could be used (capturing a flag in the cls method and then asserting the flag in setUp), it is not ideal because the log message will just tell you that the flag asserted incorrectly, instead of the actual value you would like to assert. – Matthew Moisen Apr 11 '21 at 17:22
  • what's wrong with creating a mixin that you give to your other classes to use – gold_cy Apr 11 '21 at 19:36

0 Answers0