我正在尝试使用 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
我正在尝试mongo.db.users
用我用 mongomock 制作的假的替换mongomock.MongoClient().db.collection
。但是,当我运行此测试时,它显示如下所示的属性错误:
E AttributeError: 'function' 对象没有属性 'find_one'
我不确定为什么 mock_db() 返回类型function
而不是类型<class'mongomock.collection.Collection'>
让我知道是否有人有任何建议。
谢谢你。