Я пытаюсь написать тест, используя Cucumber (Behave). Оператор «данный» должен иметь возможность принимать необязательный параметр, он предназначен для проверки содержимого строки.
Пример синтаксиса функции для обоих сценариев:
Given Verify text "this is a test string"
When String validation is "success"
Then Store form contents.
Given Verify text "this is a test string" exclude "test,trial,hello"
When String validation is "success"
Then Store form contents.
Шаг, который я пытался реализовать, был:
# Verify text "this is a test string" exclude "test,trial,hello"
@given('Verify text "{text_to_clean}" {?: exclude "{excluded}')
def step_verify_text(context, text_to_clean, excluded):
context.verified = verify_string(text_to_clean, excluded)
Как мне это сделать? Я пытался использовать необязательный символ ?
, но не могу понять. Что мне нужно сделать, чтобы использовать необязательные параметры?
Я использую Mac на macOS Catalina.
Примечание: feature
имя файла и имя файла внутри steps
папки должны совпадать.
например: если feature
имя файла question_regex.feature
, то имя файла внутри steps
папки должно быть question_regex.py
функции/question_regex.feature
Feature: regex question
Scenario: first question regex
Given Verify text "this is a string"
Then parameter "excluded" is ""
Scenario: second question regex
Given Verify text "this is a test string" exclude "test,trial,hello"
Then parameter "excluded" is "test,trial,hello"
особенности/шаги/question_regex.py
from behave import use_step_matcher, given, when, then
use_step_matcher("re")
@given('Verify text "(?P<text_to_clean>.*?)"((?: exclude )"(?P<excluded>.*?)")?')
def step_verify_text(context, text_to_clean, excluded):
context.myvar = excluded
@then('parameter "(?P<name>.*?)" is "(?P<result>.*?)"')
def step_verify_text(context, name, result):
return getattr(context, name, None) == result
особенности/шаги/question_cfparse.feature
Feature: cfparse question
Scenario: first question cfparse
Given Verify text 2 "this is a test string"
Then normal parameter "excluded" is ""
Scenario: second question cfparse
Given Verify text 2 "this is a test string" exclude "test,trial,hello"
Then normal parameter "excluded" is "test,trial,hello"
Scenario: second question cfparse
Given Verify text 3 "this is a test string" exclude "hi,hello,I"
Then normal parameter "excluded" is "hi,hello,I"
особенности/шаги/question_cfparse.py
from behave import given, when, then, use_step_matcher, register_type
import parse
use_step_matcher("cfparse")
@parse.with_pattern(r'(?: exclude )"(.*?)"')
def parse_word_optional(text):
print(text)
return text.strip()
@parse.with_pattern(r'(?: exclude )')
def parse_exclude(text):
return text.strip()
@parse.with_pattern(r'"(.*?)"')
def parse_word_between_quote(text):
return text.strip()
register_type(my1_=parse_exclude)
register_type(quote_word=parse_word_between_quote)
register_type(my_=parse_word_optional)
@given('Verify text 2 "{text_to_clean}"{ignore1:my1_?}{excluded:quote_word?}')
def step_verify_text(context, text_to_clean, ignore1, excluded):
context.excluded = excluded
@given('Verify text 3 "{text_to_clean}"{excluded:my_?}')
def step_verify_text(context, text_to_clean, excluded):
context.excluded = excluded
@then('normal parameter "{name}" is {result:quote_word*}')
def step_verify_text(context, name, result):
return getattr(context, name, None) == result
Примечание: парсер cfparse
не является хорошим вариантом, если у вас есть несколько необязательных parameters
, которые идут один за другим.
cfparse работает, хотя при исключении я могу ввести что угодно: данный текст проверки 2 «это тестовая строка» изолирует «тест, пробная версия, привет»
Регулярное выражение @GemmaMorriss является более гибким и хорошо работает, если у вас есть некоторые проблемы.
Регулярное выражение для необязательной части: (?: exclude "(?P<excluded>[^"]*?)")?
Верните пошаговый сопоставитель обратно к значению по умолчанию 'parse'
, если не используете парсер регулярных выражений для всех шагов.
use_step_matcher('re')
@given('Verify text "(?P<text_to_clean>[^"]*?)"(?: exclude "(?P<excluded>[^"]*?)")?')
def step_verify_text(context, text_to_clean, excluded):
context.verified = verify_string(text_to_clean, excluded)
use_step_matcher('parse')
Вы рассмотрели/попробовали украсить функцию реализации шага дважды:
@given('Verify text "{text_to_clean}"')
@given('Verify text "{text_to_clean}" exclude "{excluded}"')
def step_verify_text(context, text_to_clean, excluded=None):
context.verified = verify_string(text_to_clean, excluded)
У меня был некоторый успех с этим подходом в других подобных ситуациях.
Я бы хотел, чтобы это сработало, но я не думаю, что это сработает
@SabrinaLeggett У меня это работает с behave
версией 1.2.6.
Я скопировал и вставил ваше предложение, чтобы запустить его и извлечь из него уроки, но я получаю: вы можете реализовать определения шагов для неопределенных шагов с помощью этих фрагментов: @given(u'Verify text "this is a test string"') def step_impl(context ): поднять NotImplementedError(u'STEP: данный текст проверки "это тестовая строка"')