Python mock是否允许列表中的特定值?

2024-10-06 15:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你有一个特定的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_geoipdict添加一些修改,那将是最佳选择,因为所有测试都以相同的方式引用它

背后的故事是,我们的办公室不断改变两个相邻城市之间的实际位置-至少根据Maxmind GeoIP的回应:)


Tags: orinselfcityresultmockcountrydict
1条回答
网友
1楼 · 发布于 2024-10-06 15:19:00

您可以使用合适的^{} method使expected_geoip成为自定义类的实例。每当将一个对象与另一个具有==的对象进行比较时,就会调用__eq__方法

class ExpectedGeoIP:
    def __eq__(self, other):
        if not isinstance(other, dict):
            return False

        if other["country"] != "Finland":
            return False

        return other['city'] in {"Helsinki", "Espoo"}

expected_geoip = ExpectedGeoIP()

现在assertEquals(expected_geoip, geoip)将按您想要的方式工作,您不必对现有的单元测试进行任何更改

相关问题 更多 >