Django测试 - 所有测试中的patch对象 [英] Django tests - patch object in all tests

查看:352
本文介绍了Django测试 - 所有测试中的patch对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的测试创建一些 MockMixin 。它应该包括所有称为外部来源的所有模拟器。
例如,每次在管理面板中保存模型时,我会调用一些远程URL。这样做会很好,就像这样嘲笑和使用:

  class ExampleTestCase(MockedTestCase):
#tests所以每次在管理员中保存模型时,例如在功能测试中,应用这个模拟,而不是应用调用远程URL。



真的有可能吗?我可以做一个特别的测试,这不是一个问题。但是,由于我使用它很多,所以有一些全球模拟会更有用。

解决方案

根据 mock 文档


补丁可以用作TestCase类装饰器。它由
工作,在类中装饰每个测试方法。当您的测试方法共享一个常见的修补程序集时,这将减少样本
代码。


这基本上意味着您可以创建一个基础测试类与 @patch 装饰器应用于将会篡改外部调用,而每个测试方法将执行。



另外,您也可以使用 start() stop() 修补程序的方法在 setUp() tearDown()方法分别:

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

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


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.

解决方案

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()

这篇关于Django测试 - 所有测试中的patch对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆