freezegun icon indicating copy to clipboard operation
freezegun copied to clipboard

Nested class decorators

Open mscansian opened this issue 5 years ago • 1 comments

Hello guys, I'm trying to implement the following logic on my test cases:

@freeze_time("2020-01-02")
class SomeBasicTest(TestCase):
    ... do some testing here ...

@freeze_time("2020-01-31")
class EdgeCaseTest(SomeBasicTest):
    ... run the same basic test on a specific date
        and some additional tests for this edge case ..

The issue that I'm facing is not with lib itselft but the evaluation order of the decorators, since 2020-01-02 is the last one to be evaluated, this is the date that is frozen inside EdgeCaseTest. Is there any way around this issue without having to create a thrid-class with the shared functionality without a frozen time?

mscansian avatar Feb 05 '20 18:02 mscansian

Instead of using the class decorator, you can replicate what it does in your own setUpClass and tearDownClass, reading from a class variable (untested):

class SomeBasicTest(TestCase):
    frozen_time = "2020-01-02"
    
    @classmethod
    def setUpClass(cls):
        cls.freeze_time = freeze_time(cls.frozen_time)
        cls.freeze_time.start()
        super().setUpClass()
    
    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        cls.freeze_time.stop()


class EdgeCaseTest(SomeBasicTest):
    frozen_time = "2020-01-31"

adamchainz avatar May 01 '20 09:05 adamchainz