Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Django tests - patch object in all tests

I need to create some kind of MockMixin for my tests. It should include mocks for everything that calls external sources. For example, each time I save model in admin panel I call some remote URLs. It would be good, to have that mocked and use like that:

class ExampleTestCase(MockedTestCase):
    # tests

So each time I save model in admin, for example in functional tests, this mock is applied instead of calling remote URLs.

Is that actually possible? I'm able to do that for 1 particular test, that is not a problem. But it'd be more useful to have some global mock because I use it a lot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the mock documentation:

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set.

This basically means that you can create a base test class with @patch decorator applied on it that would mock your external calls while every test method inside would be executed.

Also, you can use start() and stop() patcher's methods in setUp() and tearDown() methods respectively:

class BaseTestCase(TestCase):
    def setUp(self):
        self.patcher = patch('mymodule.foo')
        self.mock_foo = self.patcher.start()

    def tearDown(self):
        self.patcher.stop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...