我在单元测试下的一个方法中有以下声明.
db_employees = self.db._session.query(Employee).filter(Employee.dept == new_employee.dept).all()
我希望db_employees获得模拟员工列表.我尝试使用以下方法实现此目的
m = MagickMock() m.return_value.filter().all().return_value = employees
员工是员工对象的列表.但这没效果.当我尝试打印任何属性的值时,它具有模拟值.这是代码的样子:
class Database(object): def __init__(self, user=None, passwd=None, db="sqlite:////tmp/emp.db"): try: engine = create_engine(db) except Exception: raise ValueError("Database '%s' does not exist." % db) def on_connect(conn, record): conn.execute('pragma foreign_keys=ON') if 'sqlite://' in db: event.listen(engine, 'connect', on_connect) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) self._session = DBSession() class TestEmployee(MyEmployee): def setUp(self): self.db = emp.database.Database(db=options.connection) self.db._session._autoflush() @mock.patch.object(session.Session, 'add') @mock.patch.object(session.Session, 'query') def test_update(self, mock_query, mock_add): employees = [{'id': 1, 'name': 'Pradeep', 'department': 'IT', 'manager': 'John'}] mock_add.side_effect = self.add_side_effect mock_query.return_value = self.query_results() self.update_employees(employees) def add_side_effect(self, instance, _warn=True): // Code to mock add // Values will be stored in a dict which will be used to // check with expected value. def query_results(self): m = MagicMock() if self.count == 0: m.return_value.filter.return_value.all.return_value = [employee] elif: m.return_value.filter.return_value.all.return_value = [department] return m
我有query_results作为测试调用查询两次的方法.首先是员工表,然后是部门表.
如何模拟此链接函数调用?
m = MagickMock() m.session.query().filter().all.return_value = employees
https://docs.python.org/3/library/unittest.mock.html