请求对象中的键错误,即使存在键(pytest-bdd)



我在tests/features/Admin.feature 中有以下功能

Feature: Admin
Scenario Outline: register a new user
Given I'm logged in as an admin at "<host_name>" with email "<admin_email>" and password "<admin_password>"
When I call the register method for host "<host_name>" with email "<user_email>" and password "<user_password>" and firstName "<first_name>" and last name "<last_name>"
Then the user will be able to log in to "<host_name>"
| host_name      | admin_email          | admin_password | user_email                           | user_password | first_name | last_name |
| localhost:3000 | admin_user@gmail.com | somepassword   | nowaythisusernameistaken18@gmail.com | somepassword  | john       | jjjjjjj   |

并且正在通过以下方式进行测试:

import pytest
from pytest_bdd import scenario, given, when, then, parsers
from admin import Admin
from user import User
@scenario('../features/Admin.feature',
'register a new user')
def test_admin():
pass
@pytest.fixture
@given('I'm logged in as an admin at "<host_name>" with email "<admin_email>" and password "<admin_password>"')
def admin_login(host_name, admin_email, admin_password):
admin = Admin(admin_email, admin_password)
admin.login(host_name)
assert admin.status_code == 200
return admin
@pytest.fixture
@when('I call the register method for host "<host_name>" with email "<user_email>" and password "<user_password>" and firstName "<first_name>" and last name "<last_name>"')
def register_user(admin_login, host_name, user_email, user_password, first_name, last_name):
user_id = admin_login.register_user(host_name, user_email, user_password, first_name, last_name)
print('the user id is: ' + user_id)
assert admin_login.status_code == 200
user = User(user_email, user_password, _id=user_id)
print(user)
return user
@then('the user will be able to log in to "<host_name>"')
def user_login(host_name):
user.login(host_name)
assert user.status_code == 200
return user

不知怎么的,admin.register_user方法似乎被调用了两次。我不知道有什么其他方法可以解释这个关键错误。第二次,由于用户应该已经注册,我希望得到一个错误,说用户已经注册。这就是我得到的,尽管我只想注册一次。以下是进行注册的代码:

import requests
import json
from user import User
def get_login_url(host):
return f'http://{host}/api/auth/login'
def get_register_url(host):
return f'http://{host}/api/auth/register'
class Admin:
def __init__(self, email, password):
self.email = email
self.password = password
self.bearer_token = None
self.status_code = None  # used to check status codes
def register_user(self, host, email, password, first_name, last_name):
# make sure bearer is present
if not len(self.bearer_token) > 0:
raise Exception('Must log in before registering users.')
# send registration request
registration_headers = {"Authorization": f'BEARER {self.bearer_token}', 'content-type': 'application/json', 'cookie': 'auth.strategy=local', 'auth._token.local': "false"}
registration_credentials = f'"email": "{email}", "password": "{password}", "firstName": "{first_name}", "lastName": "{last_name}"'
registration_payload = "{" + registration_credentials + "}"
registration_request = requests.post(get_register_url(host), data=registration_payload, headers=registration_headers)
user_id = json.loads(registration_request.text)['user']['_id']
print(json.loads(registration_request.text).keys())
return user_id

因此,当我运行pytest时,我会收到一条错误消息,其中一部分内容是:

self = <admin.Admin object at 0x10ad47d90>, host = 'localhost:3000'
email = 'nowaythisusernameistaken20@gmail.com', password = 'somepassword'
first_name = 'john', last_name = 'jjjjjjj'
def register_user(self, host, email, password, first_name, last_name):
# make sure bearer is present
if not len(self.bearer_token) > 0:
raise Exception('Must log in before registering users.')
# send registration request
registration_headers = {"Authorization": f'BEARER {self.bearer_token}', 'content-type': 'application/json', 'cookie': 'auth.strategy=local', 'auth._token.local': "false"}
registration_credentials = f'"email": "{email}", "password": "{password}", "firstName": "{first_name}", "lastName": "{last_name}"'
registration_payload = "{" + registration_credentials + "}"
registration_request = requests.post(get_register_url(host), data=registration_payload, headers=registration_headers)
>       user_id = json.loads(registration_request.text)['user']['_id']
E       KeyError: 'user'
admin.py:27: KeyError
----------------------------- Captured stdout call -----------------------------
dict_keys(['success', 'status', 'user'])
the user id is: 5fbfa5c6f45373b57d7dad0f
<user.User object at 0x10a3442d0>
=========================== short test summary info ============================
FAILED tests/step_defs/test_admin.py::test_admin[localhost:3000-admin_user@gmail.com-somepassword-nowaythisusernameistaken18@gmail.com-somepassword-john-jjjjjjj]
============================== 1 failed in 1.69s ===============================

如果响应中没有用户密钥,stdout如何捕获用户id

我认为问题来自于在给定步骤和时间步骤中使用@pytest.fixture,因为这两个步骤将分别从pytest和pytest-bdd在场景上下文中独立执行以创建fixture。

解决方案:从admin_loginregister_user步骤中删除@pytest.fixture注释。

如果你想让一个fixture与pytest-bdd步骤相关联,你可以通过以下两种方式来实现:

  1. 创建一个fixture并"使用";它在BDD步骤中:pytest-BDD重用夹具
  2. 对于给定的步骤,您还可以在@giving:pytest-bdd中添加target_fixture="<fixture-name>",在给定的中创建fixture

最新更新