pytest monkeypatch无法修补mongodb集合

时间:2020-06-27 01:25:04

标签: python mongodb unit-testing pytest mongomock

我正在尝试使用pytest对以下功能进行单元测试。

@login_sys.route("/users/register", methods=["POST"])
def register():
    users = mongo.db.users # TRYING TO PATCH THIS
    print("--->{}".format(type(users)))
    email = request.get_json()["email"]
    response = users.find_one({"email": email})
    if response:
        result = jsonify({"result": "email already registered"})
        return result

    first_name = request.get_json()["first_name"]
    last_name = request.get_json()["last_name"]

    password = bcrypt.generate_password_hash(request.get_json()["password"]).decode(
        "utf-8"
    )
    created = datetime.utcnow()

    user_id = users.insert(
        {
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "password": password,
            "created": created,
        }
    )

    new_user = users.find_one({"_id": user_id})

    result = {"email": new_user["email"] + " registered"}

    return jsonify({"result": result})

以下是我写的测试

@pytest.fixture(scope="module")
def client():
    app.config['TESTING'] = True
    app.register_blueprint(login_sys)
    with app.test_client() as client:
        return client

def test_register(client, monkeypatch):
    print(type(client))
    mimetype = 'application/json'
    headers = {
        'Content-Type': mimetype,
        'Accept': mimetype
    }
    userInfo = {
            "first_name": "admin",
            "last_name": "admin",
            "email": "admin@gmail.com",
            "password": "admin",
        }
    def mock_db():
        return mongomock.MongoClient().db.collection
    print(type(mongomock.MongoClient().db.collection)) 
    #class'mongomock.collection.Collection'>
    monkeypatch.setattr(mongo.db, 'users', mock_db)
    rv = client.post("/users/register", data=json.dumps(userInfo), headers=headers)
    dprint(rv.data)
    assert True

我正尝试用我用mongomock mongo.db.users制造的假冒伪造品代替mongomock.MongoClient().db.collection。但是,当我运行此测试时,它显示了如下所示的属性错误:

E AttributeError:“函数”对象没有属性“ find_one”

我不确定为什么模拟_db()返回类型function而不是类型<class'mongomock.collection.Collection'>

让我知道是否有人有任何建议。

谢谢。

0 个答案:

没有答案