如何在Pytest中模拟SQLAlchemy模型的创建方法

问题描述

我有一个API,可以在db中创建新的排期,生成ID,然后插入db。我现在需要嘲笑这个。它是现有代码,所以我不想更改它。

     # create_flight.py (Existing code)

     from app.models.flight import Flight
     flight=Flight()
     flight.create_flight(json_data)  # need to mock this,# this generates and commits in db and sets the flight object 
     response= { 'flight_id' : flight.flight_id } 

我尝试使用pytest

   #conftest.py
   @pytest.fixture
   def mock_response(monkeypatch):
       def mock_create_flight(*args):
           class flight:
                 flight_id=str(uuid.uuid4())
            test=flight()
            return test
        monkeypatch.setattr('app.models.flight.Flight.create_flight',mock_create_flight)

它正确地修补了它,但我希望 flight 应该设置 flight_id 属性,以便响应字典发送模拟的航班ID,而不是发送到db。我肯定在这里做错了。不知道在哪里。感谢您的关注

解决方法

我通过在<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>中导入sqlalchemy模型Flight来解决这个问题,这是我的解决方案

conftest

然后,它以原始代码返回模拟的from app.models.flight import Flight import uuid @pytest.fixture(scope='session') def get_flight_id(): yield str(uuid.uuid4()) @pytest.fixture(scope="session") def mock_response(monkeypatch,get_flight_id): def mock_create_flight(*args): flight = Flight() flight.flight_id = get_flight_id flight.version_id = 1 return flight monkeypatch.setattr('app.models.flight.Flight.create_flight',mock_create_flight) 对象