在Python中,什么是在单元测试期间禁用某些代码的好模式? [英] In Python, what's a good pattern for disabling certain code during unit tests?

查看:81
本文介绍了在Python中,什么是在单元测试期间禁用某些代码的好模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我想禁用尽可能少的代码,并且我希望它是明确的:我不希望被测试的代码确定它是否是测试,我希望测试告诉该代码嘿,顺便说一句,我正在运行一个单元测试,请您不要打电话给solr,而是可以在这个位置粘贴您要发送给solr的内容,以便我检查。我有我的想法,但我不喜欢其中的任何一个,我希望有一种很好的pythonic方法来做到这一点。

In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can you please not make your call to solr, instead can you please stick what you would send to solr in this spot so I can check it". I have my ideas but I don't like any of them, I am hoping that there's a good pythonic way to do this.

推荐答案

在单元测试中使用Michael Foord的模拟
可以做到这一点:

Use Michael Foord's Mock in your unit test do this:

from mock import Mock

class Person(object):
    def __init__(self, name):
        super(Person, self).__init__()
        self.name = name

    def say(self, str):
        print "%s says \"%s\"" % (self.name, str)


...

#In your unit test....
#create the class as normal
person = Person("Bob")
#now mock all of person's methods/attributes
person = Mock(spec=person)
#talkto is some function you are testing
talkTo(person)
#make sure the Person class's say method was called
self.assertTrue(person.say.called, "Person wasn't asked to talk")

#make sure the person said "Hello"
args = ("Hello")
keywargs = {}
self.assertEquals(person.say.call_args, (args, keywargs), "Person did not say hello")

这篇关于在Python中,什么是在单元测试期间禁用某些代码的好模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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