我有一个函数应该将对象属性设置为 PIL Image 实例:
from PIL import Image
class SimpleExample:
def __init__(self):
self.img = self.load_image()
def load_image():
self.img = Image.open(image)
为了测试 load_image() 的正确执行,我想使用 unittest.TestCase.assertIsInstance(),但是结果实例的内省(introspection)给出了不同的类。名称取决于加载的图像的文件类型。我在 unittest 中找不到与 assertIsInstanceFromModule() 类似的任何内容,因此这似乎是最能反射(reflect)我真正想要测试的内容的断言助手。
我想出了几个解决方案,但对其中任何一个都不满意:
使用循环 生成所有可能类名的列表,遍历列表,测试每个成员是否相等,然后为适当的列表成员断言 IsInstance。这很尴尬,没有 pythonic,我当然不会为此感到自豪。但是它确实有效,并且它使用了我认为最有意义的断言。
simplified_names = ['JpegImageFile', 'PngImageFile']
for i, name in enumerate(simplified_names):
if SimpleExample.img.__class__.__name__ == name:
TestCase.assertIsInstance(SimpleExample.img, simplified_names[i])
使用不同的断言助手 生成所有可能类名的列表,并断言生成的对象的类名在该列表中。它有效,简单,但我不喜欢我在这里断言的内容。
simplified_names = ['JpegImageFile', 'PngImageFile']
TestCase.assertIn(SimpleExample.img.__class__.__name__, simplified_names)
有没有人对如何针对多个可能的类名进行断言有任何其他想法? 我应该从不同的方向接近测试并使用不同的断言吗? 这是我第一次涉足单元测试。我是否应该返回使用 print 测试我的代码?
~~~~~ 显而易见的答案是......
针对父类进行测试。或者,我本可以注意到每次看到以下错误时都会向我提供更好的选择:
TypeError: isinstance() arg 2 must be a type or tuple of types
强调“或元组”。
感谢 Martijn Pieters 的所有帮助。
最佳答案
使用父类;您不关心这是众多子类中的哪一个,只要它是一个图像文件即可。
assertIsInstace()
的第二个参数必须是类本身,而不是类名:
from PIL import ImageFile
self.assertIsInstance(SimpleExample.img, ImageFile.ImageFile)
或者您可以更进一步并断言它是一个 PIL.Image.Image
实例,而不关心它是来自特定文件还是以其他方式生成:
from PIL import Image
self.assertIsInstance(SimpleExample.img, Image.Image)
如果您确实需要针对多个类进行测试,isinstance()
(以及通过扩展,assertIsInstance()
)也接受一个类元组作为第二个参数:
>>> foo = 'bar'
>>> isinstance(foo, (str, int, float))
True
关于python - 针对多个类名的 assertIsInstance(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27509398/