0

我在 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 ===============================

如果响应中不存在用户密钥,标准输出如何捕获用户 ID?

4

1 回答 1

0

我会假设问题来自@pytest.fixture在给定步骤和 when 步骤中的使用,因为这两个步骤都将从 pytest 独立执行以创建一个fixture,并在场景上下文中从 pytest-bdd 执行。

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

如果您希望将夹具与 pytest-bdd 步骤相关联,可以通过以下两种方式进行:

  1. 创建一个夹具并在 BDD 步骤中“使用”它:pytest-bdd 重用夹具
  2. 对于给定的步骤,您还可以target_fixture="<fixture-name>"在 @given: pytest-bdd create fixture in given中添加一个
于 2021-03-03T15:49:34.827 回答