简体   繁体   中英

class method in Python unit test case

I am trying to mock up a function in the setUpClass() method, and then restore the function in the tearDownClass() method.

class MyClass(unittest.TestCase):

    @classmethod
    def setUpClass(cls):

        cls.save_func = module.func
        module.func = lambda: True

    @classmethod
    def tearDownClass(cls):

        module.func = cls.save_func

After the tearDownClass() method, I expected a call to module.func() would call the actual function. But it doesn't.

I did some debugging by printing the functions. I got the below outputs from the tearDownClass() method.

cls.save_func: <unbound method MyClass.save_func>
module.func:  <unbound method MyClass.save_func>

I was trying different things and I changed the methods from class methods to setup methods:

     def setUp(cls):

        cls.save_func = module.func
        module.func = lambda: True


    def tearDown(cls):

        module.func = cls.save_func

To my surprise, everything seems to be working. module.func is restored back, and when I print it, it gives me the function address.

module.func <function func at 0x89f9a74>

Can you please explain the behaviour?

Because setUp isn't a "static" classmethod , it requires an instance of the class.

Reference: unittest basic example

It's working differently without the @classmethod decorator because, in the revised code, "cls" is no longer the class: it's the instance. We normally designate the instance as "self", but "self" and "cls" aren't reserved words in Python--they're merely conventions. You can put anything you want in their places, though doing so will cause confusion (as is evident in the original code).

As for the I think the inconsistency between the outputs of the two versions of the code, I can't reproduce the behavior with the methods of an ordinary custom class, so it must have something to do with the unittest package. However, I'm willing to bet it's due to the difference between class methods and instance methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM