创建 pymongo.MongoClient 而不是 mongomock.MongoClient

问题描述 投票:0回答:1

当我尝试运行测试时,它尝试与 MongoDB 创建真正的连接,而不是使用 mongomock。

当我从我的 init.py 中删除“from .main import HashClient”时,这种情况就会停止发生。

我的项目是:

哈希_控制器/

|

|----> init.py

|----> hash_controller.py

|----> test_hash_controller.py

我的init.py是:

`from .main import HashClient`

我的 hash_controller 是:


    import hashlib
    import json
    import os
    import time


    def get_connection():
        _db_user = os.environ["HASH_DB_USER"]
        _db_password = os.environ["HASH_DB_PASS"]
        _db_host = os.environ["HASH_DB_HOST"]
        _db_port = os.environ["HASH_DB_PORT"]
        _db_name = os.environ["HASH_DB_NAME"]
        _db_collection = os.environ["HASH_DB_COLLECTION"]

        # _client = MongoClient(f"mongodb://{_db_user}:{_db_password}@{_db_host}:{_db_port}/")
        from pymongo import MongoClient
        _client = MongoClient(f"mongodb://{_db_host}:{_db_port}/")
        _database = _client[_db_name]
        _collection = _database[_db_collection]
        return _collection


    class HashClient:

        @staticmethod
        def exist(customer_uuid: str, type: str, obj):
            HashClient._check_customer_and_type(customer_uuid, type)
            HashClient._check_obj(obj)
            id = HashClient._get_hash(customer_uuid, type, obj)
            collection = get_connection()
            item = collection.find_one(id)
            if item is None:
                return False
            else:
                return True

我的测试是:

    import os
    import mongomock

    os.environ["HASH_DB_USER"]=""
    os.environ["HASH_DB_PASS"]=""
    os.environ["HASH_DB_HOST"]="localhost"
    os.environ["HASH_DB_PORT"]="27017"
    os.environ["HASH_DB_NAME"]="test"
    os.environ["HASH_DB_COLLECTION"]="test"

    with mongomock.patch(servers=(('localhost', 27017),)):
        import pymongo
        client = pymongo.MongoClient("localhost")
        from .main import HashClient


    def test_exist_false():
        hash = HashClient._get_hash("123", "user", {"user": "222"})
        client["test"]["test"].insert_one({"_id": hash})
        response = HashClient.exist("123", "user", {"user": "123"})
        assert response == False
        client.test.test.delete_many({})

我尝试移动函数内的所有导入,以便它们在运行测试时不会被执行,但任何方法都有帮助。 这个想法是通过从 init.py

导入来运行测试
python mongodb testing pymongo mongomock
1个回答
0
投票

在最后一个测试函数

def test_exist_false()
中,调用了在
client
块中创建的模拟mongo
whit
来保存数据。
client["test"]["test"].insert_one({"_id": hash})

这是被嘲笑的客户端,没问题。但
HashClient.exist()
不使用它,它甚至无法访问模拟的
client

为什么

HashClient.exist()
无法访问模拟的
client

因为它在自身内部创建了自己的集合。问题是在
exist()
函数中创建的集合没有被模拟,它是真正的集合。

最好将文件

hash_controller.py
拆分为两个文件。一个
get_collection
的文件和另一个
HashClient
的文件。
HashClient
可以通过
__init__()
set_collection()
等方法设置集合

因此可以在测试中为

HashClient
设置模拟集合。

© www.soinside.com 2019 - 2024. All rights reserved.