0

我尝试在测试中模拟我的 Mongo 数据库。我找到了我关注的文章,但不幸的是我的测试写入真正的 mongo 数据库而不是模拟。我有创建database.py文件PyMongo

from flask_pymongo import PyMongo

mongo = PyMongo()

我在文件中导入mongo变量__init__.py以使用应用程序进行初始化:

import app.database as mongo_database


def create_app(env=None):
    app = Flask(__name__)
    ...
    app.config.from_object(config())
    mongo_database.mongo.init_app(app)

我使用自定义 Mongo 类来查找数据并插入到 mongo,这是我的控制器的示例:

@bp.route('/some-route', methods=['get'])
@jwt_required
def fetch_data():
    ...
    cached_data = MongoCache.getInstance().get_data(lender_id, "lenders")
    if cached_data:
        return cached_data
    ...
    MongoCache.getInstance().insert_data(lender_id, data, 'lenders')
    return data

这是我的MongoCache课:

import app.database


@Singleton
class MongoCache:
    def __init__(self):
        self.db = app.database.mongo.db

    ...

    def get_data(self, params, collection):
        ...
        result = self.db[collection].find_one(params)
        ...
        return result

    def insert_data(self, params, response, collection):
        ...
        try:
            self.db[collection].insert_one(data)
        except Exception as e:
            logger.exception(str(e))
            raise Exception(e)

但是当我添加修补 PyMongo 客户端时,它对我不起作用: tests.py

from mongomock import MongoClient

class PyMongoMock(MongoClient):
    def init_app(self, app):
        return super().__init__()

class MyTest(unittest.TestCase):

        def setUp(self):
        if os.environ.get('FLASK_ENV') != 'testing':
            raise Exception('Cannot run tests in non-test environment (FLASK_ENV must be set to "testing")')
        app = create_app()
        self.test_client = app.test_client()
        self._ctx = app.app_context()
        self._ctx.push()

        database_uri = self.test_client.application.config['SQLALCHEMY_DATABASE_URI']
        ...

    def test_actovia_lender_lookup(self):
        with patch('third_party_api', return_value={}) as patched_api:
            with patch("app.database", "mongo", PyMongoMock()):
                resp = self.test_client.get('/my-custom-url', headers={
                    'Authorization': 'Bearer %s' % jwt['access_token']
                })

                self.assertEqual(resp.status_code, 200)
                patched_api.assert_called_with('1')

有没有人有任何建议我做错了什么,我该如何解决?

4

0 回答 0