首页 > 解决方案 > Python unittesting - How to assert inside of setUpClass?

问题描述

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)

标签: python

解决方案


推荐阅读