假设你有一个特定的dict,你想对它进行断言,但是你想在该dict的一个给定属性中有几个特定的值,你怎么做呢
# This is in a separate shared constants file, used by a whole lot of tests
expected_geoip = {
"country": "Finland",
# "city" should allow for either "Helsinki" or "Espoo", but nothing else
"city": ""
}
# class, etc... not relevant
def test_something(self):
result = something.query("something")
geoip = result[0]["data"]["geoip"]
# geoip["city"] can be either "Helsinki" or "Espoo", at random(!) (true story...)
self.assertEquals(expected_geoip, geoip)
显然,我可以直接检查如下内容:self.assertTrue(geoip["city"] in ["Helsinki", "Espoo"]
但问题是,我必须更新大量的旧测试。有了这样的东西就容易多了:
expected_geoip = {
"country": "Finland",
"city": mock.list("Helsinki", "Espoo")
}
但就我从http://www.voidspace.org.uk/python/mock/helpers.html#any的模拟文档中可以看出,只有一个mock.ANY
,太宽泛了
如果我可以直接向共享的expected_geoip
dict添加一些修改,那将是最佳选择,因为所有测试都以相同的方式引用它
背后的故事是,我们的办公室不断改变两个相邻城市之间的实际位置-至少根据Maxmind GeoIP的回应:)
您可以使用合适的^{} method 使
expected_geoip
成为自定义类的实例。每当将一个对象与另一个具有==
的对象进行比较时,就会调用__eq__
方法现在
assertEquals(expected_geoip, geoip)
将按您想要的方式工作,您不必对现有的单元测试进行任何更改相关问题 更多 >
编程相关推荐