在Python中模拟数据类时如何使用spec [英] How to use spec when mocking data classes in Python

查看:148
本文介绍了在Python中模拟数据类时如何使用spec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用backport包将namedtuple类移植到Python 3.6中的数据类中.但是,我注意到在模拟数据类时,不能再使用"spec"关键字了.我认为这是因为数据类代码是自动生成的.

I'm trying to port our namedtuple classes into dataclass in Python 3.6 using the backport package. However, I noticed when mocking dataclass classes, you cannot use the "spec" keyword anymore. I assume it's because the dataclass code is auto generated.

from dataclasses import dataclass
import mock

@dataclass
class A:
    aaa: str
    bbb: int


m = mock.Mock(spec=A)

m.aaa

这是我得到的错误:

AttributeError: Mock object has no attribute 'aaa'

有没有办法自动设置从原始对象到模拟对象的所有属性?我有很多具有大量数据的数据类.如果我尝试一个接一个地手动设置值,那将非常繁琐.

Any idea if there's any way to automatically set all the attributes from original object to the mock object? I have lots of data classes with a lot of data. It's going to be really tedious if I try to manually set the values one by one.

推荐答案

我最终使用了该通用帮助函数来实现常规类的规范:

I ended up using this generic helper function to achieve what spec does with regular classes:

import mock
from dataclasses import fields


def create_dataclass_mock(obj):
    return mock.Mock(spec=[field.name for field in fields(obj)])

这篇关于在Python中模拟数据类时如何使用spec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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