Howto to write a step implementation that supports multiple words

断了今生、忘了曾经 提交于 2021-02-10 16:22:08

问题


Example Gherkin

# Gherkin snip
When waiting for 30 seconds
# or
When waiting for 5 s

I want to implement above steps in one step definition. I tried the following step implementation.

from behave import *
use_step_matcher("re")

@when(u"waiting for (?P<time>\d+) (s|seconds)")
def step_impl(context, time):    
  pass

When running this results in this error:

TypeError: step_impl() got multiple values for keyword argument 'time'

Behave extracts it as a parameter.

What's a good practice for doing this?


回答1:


You can you write two step definitions, one for each case. This will reduce your problem a bit. These two steps would then delegate to a helper method that does the actual call.

When the next requirement shows up and you want to combine three things in the same step, it gets easier to catch the arguments in one step and delegate it to the same helper method that you already have.

This would most likely be my approach as I would find this easier to understand and maintain.

You don't want to write clever code. Clever code is very complicated for your future you to understand and change. Dead simple code is always better.




回答2:


I got a similar issue and after many attempts I have found that adding a dummy parameter _unused solves the issue:

@when(u"waiting for (?P<time>\d+) (s|seconds)")
def step_impl(context, _unused, time):    
  pass

My similar issue was about negative lookahead assertion regex:

@when(r'buy')
@when(r'buy (?P<home_owner>((?!.* car).)+) home')
@when(r'buy (?P<car_owner>((?!.* home).)+) car')
@when(r'buy (?P<home_owner>.+) home and (?P<car_owner>.+) car')
def buy(context, home_owner="default", car_owner="default"):
    pass

I have fixed it by splitting my single function and adding parameter _unused:

@when(r'buy')
@when(r'buy (?P<home_owner>.+) home and (?P<car_owner>.+) car')
def buy1(context, home_owner="default", car_owner="default"):
    pass

@when(r'buy (?P<home_owner>((?!.* car).)+) home')
@when(r'buy (?P<car_owner>((?!.* home).)+) car')
def buy2(context, _unused, home_owner="default", car_owner="default"):
    buy1(context, home_owner, car_owner)


来源:https://stackoverflow.com/questions/47751317/howto-to-write-a-step-implementation-that-supports-multiple-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!