Python 将模拟对象添加到sqlalchemy集合会引发异常

Python 将模拟对象添加到sqlalchemy集合会引发异常,python,unit-testing,sqlalchemy,mocking,python-mock,Python,Unit Testing,Sqlalchemy,Mocking,Python Mock,我正在为具有一对多关系的SQLAlchemy模型类编写单元测试,但无法将模拟对象添加到集合中 测试类别: class PCLRun(Base): __tablename__ = 'pcl_runs' id = Column(Integer, primary_key=True) ... files = relationship("PCLOutputFile", backref='pcl_run') class PCLOutputFile(Base): __

我正在为具有一对多关系的SQLAlchemy模型类编写单元测试,但无法将模拟对象添加到集合中

测试类别:

class PCLRun(Base):
    __tablename__ = 'pcl_runs'
    id = Column(Integer, primary_key=True)
    ...
    files = relationship("PCLOutputFile", backref='pcl_run')

class PCLOutputFile(Base):
    __tablename__ = 'pcl_output_files'
    id = Column(Integer, primary_key=True)
    ...
    pcl_run_id = Column(Integer, ForeignKey('pcl_runs.id'))
测试代码:

class PCLRunTests(unittest.TestCase):
    def test_foo(self):
        file_mock = mock.Mock()
        pcl_run = PCLRun()
        pcl_run.files.append(file_mock)
        ...
追加模拟对象会引发异常:

TypeError: 'Mock' object has no attribute '__getitem__'
有没有办法通过向包含关系的类中添加mock来单元测试该类,同时保持集合的行为类似于一个简单的列表


我使用的是mock 1.0.1和sqlalchemy 0.8.2。

我认为问题在于
PCLRun
实例需要
PCLOutputFile
类的一个实例作为
append
方法的参数。您的
Mock
实例没有相同的属性,因此它在尝试
\uuu getitem\uuu
方法时会引发错误

您可以尝试利用Python使用duck类型创建一个
Mock
对象,该对象包含
PCLOutputFile
文件的所有属性,但这可能会很困难,这取决于查询所需列值之外的继承元数据的数量

或者,您可以定义设置/拆卸方法/装置,这些方法/装置将在测试表中创建
PCLOutputFile
类的真实实例。鼻测试模块为这种类型的测试模式提供了一种新的测试模式