比较两个容器以确定其内容物的身份
我有一个返回一组对象的方法,并且我正在为此方法编写单元测试。是否有一种通用的、整洁的和惯用的方法来比较它们的同一性(而不是平等)?还是我需要自己写一个合适的实现?
一个例子(为了简单起见):
class Foo(object):
def has_some_property(self):
...
class Container(object):
def __init__(self):
self.foo_set = set()
def add_foo(self, foo):
self.foo_set.add(foo)
def foo_objects_that_have_property(self):
return set([foo for foo in self.foo_set if foo.has_some_property()])
import unittest
class TestCase(unittest.TestCase):
def testFoo(self):
c = Container()
x, y, z = Foo(), Foo(), Foo()
...
self.assertContentIdentity(c.foo_objects_that_have_property(), set([x, y]))
重要的是,在这里测试相等性是行不通的,因为改变 foo_objects_that_have_property()
返回的对象可能会导致不一致的结果,具体取决于这些对象的使用方式即使它们在测试时“相等”,在 Container
中也会有所不同。
I have a method that returns a set of objects, and I'm writing a unit test for this method. Is there a generic, tidy and idiomatic way of comparing these for identity (rather than equality)? Or do I need to write a suitable implementation myself?
An example (somewhat contrived to keep it simple):
class Foo(object):
def has_some_property(self):
...
class Container(object):
def __init__(self):
self.foo_set = set()
def add_foo(self, foo):
self.foo_set.add(foo)
def foo_objects_that_have_property(self):
return set([foo for foo in self.foo_set if foo.has_some_property()])
import unittest
class TestCase(unittest.TestCase):
def testFoo(self):
c = Container()
x, y, z = Foo(), Foo(), Foo()
...
self.assertContentIdentity(c.foo_objects_that_have_property(), set([x, y]))
Importantly, testing here for equality won't do, since mutating the objects returned by foo_objects_that_have_property()
may lead to inconsistent results depending on how those objects are used differently in Container
even if they are "equal" at the time of the test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能想到的最好的办法是:
然而,这是专门用于集合的,不能处理嵌套容器。
The best I can come up with is:
However, this is specialised for sets and can't deal with nested containers.
一个简单但不是最有效的方法:
A simple, albeit not the most efficient, way to do it:
然后你需要编写自己的函数,例如
Then you need to write your own function, like