Как повторно использовать определение шагов одной реализации файла объекта в другой в pytest_ bdd? - PullRequest
2 голосов
/ 31 января 2020

У меня ниже структура папок

folder root
    features
         file1.feature
         file2.feature
    source
         file1.py
         file2.py

Реализация file1.feature находится в file1.py и file2.feature находится в file2.py . Я пытался повторно использовать шаг в file1.feature в file2.feature. Я попытался импортировать метод непосредственно в file2.py, как показано ниже

from source.file2 import method1

Однако это привело к приведенной ниже ошибке:

    def _find_step_function(request, step, scenario, encoding):
        """Match the step defined by the regular expression pattern.

        :param request: PyTest request object.
        :param step: Step.
        :param scenario: Scenario.

        :return: Function of the step.
        :rtype: function
        """
        name = step.name
        try:
            # Simple case where no parser is used for the step
            return request.getfixturevalue(get_step_fixture_name(name, step.type, encoding))
        except pytest_fixtures.FixtureLookupError:
            try:
                # Could not find a fixture with the same name, let's see if there is a parser involved
                name = find_argumented_step_fixture_name(name, step.type, request._fixturemanager, request)
                if name:
                    return request.getfixturevalue(name)
                raise
            except pytest_fixtures.FixtureLookupError:
                raise exceptions.StepDefinitionNotFoundError(
                    u"""Step definition is not found: {step}."""
                    """ Line {step.line_number} in scenario "{scenario.name}" in the feature "{feature.filename}""".format(
                        step=step,
                        scenario=scenario,
>                       feature=scenario.feature,
                    )
                )    pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "User is logged-in". Line 6 in scenario "Scenario 1" in the feature "../Features/file1.feature

Есть ли способ эффективно использовать шаги одного файл функции в другом файле pytest_ bdd

Ниже приведены файлы функций file1

Feature: Action 1

  Scenario: Creating a new Action 1
    Given User is logged-in
    And User is in Home page
    When User clicks on New in the Dashboard
    And User selects Action 1
    Then Action 1 is created

и file2

Feature: Action 2

  Scenario: Creating a new Action 2
    Given User is logged-in
    And User is in Home page
    When User clicks on New in the Dashboard
    And User selects Action 2
    Then Action 2 is created

Ниже приведен файл определения шага для file1.py

from pytest_bdd import scenario, given, when, then

@scenario('../Features/file1.feature','Creating a new Action 1')
def test_login_page():
    pass


@given("User is logged-in")
def logging_in():
//some actions
    pass


@given("User is in Home page")
def homepage():
//some actions
        pass

@when("clicks on New in the Dashboard")
def new():
//some actions
    pass

@when("User selects Action 1")
def act1():
//some actions
        pass


@then("Action1 is created")
def logged_in():
//some actions
    pass 

Я пытаюсь найти способы реализовать пошаговое определение file2.feature в file2.py, не повторяя пошаговые определения, которые уже определены в file1.py. Я попытался импортировать методы напрямую, как показано ниже, но это привело к вставке ошибки.

import logging_in, homepage

1 Ответ

3 голосов
/ 03 февраля 2020

Опция 1:

Вы можете создавать общие шаги в conftest.py

@given("User is logged-in")
def logging_in():
    print('logging_in')


@given("User is in Home page")
def homepage():
    print('homepage')

и добавлять файл общих функций common_steps.feature

Scenario: All steps are declared in the conftest
    Given User is logged-in
    Given User is in Home page

И добавить еще один @scenario к тесту

@scenario('common_steps.feature', 'All steps are declared in the conftest')
@scenario('file1.feature', 'Creating a new Action 1')
def test_login_page():
    pass


@when("User clicks on New in the Dashboard")
def new():
    print('new')


@when("User selects Action 1")
def act1():
    print('act1')


@then("Action 1 is created")
def logged_in():
    print('logged_in')

Опция 2:

Использовать Background в common_steps.feature

Feature: Common steps

Background:
    Given User is logged-in
    And User is in Home page

Scenario: Creating a new Action 1
    When User clicks on New in the Dashboard
    And User selects Action 1
    Then Action 1 is created

Scenario: Creating a new Action 2
    When User clicks on New in the Dashboard
    And User selects Action 2
    Then Action 2 is created

И тест

@scenario('common_steps.feature', 'Creating a new Action 1')
def test_login_page():
    pass


@given("User is logged-in")
def logging_in():
    print('logging_in')


@given("User is in Home page")
def homepage():
    print('homepage')


@when("User clicks on New in the Dashboard")
def new():
    print('new1')


@when("User selects Action 1")
def act1():
    print('act1')


@then("Action 1 is created")
def logged_in():
    print('logged_in')

Вариант 3:

Определить pytest.fixture в test_common.py

@pytest.fixture
def common_logging_in():
    print('common logging_in')


@pytest.fixture
def common_homepage():
    print('common homepage')

И отправить его в качестве значения для шагов теста

@scenario('file1.feature', 'Creating a new Action 1')
def test_login_page():
    pass


@given("User is logged-in")
def logging_in(common_logging_in):
    pass


@given("User is in Home page")
def homepage(common_homepage):
    pass


@when("User clicks on New in the Dashboard")
def new():
    print('new1')


@when("User selects Action 1")
def act1():
    print('act1')


@then("Action 1 is created")
def logged_in():
    print('logged_in')

Ответ основан на идеях из Pytest- BDD Документация

...