# ---------------------------------------------------------------------------- class Meeting(object): def __init__(self): self.persons = set() # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder company_persons = ["Alice", "Bob", "Charly", "Dodo"] parse_person = TypeBuilder.make_choice(company_persons) matchers.register_type(Person=parse_person) # -- MANY-TYPE: Persons := list<Person> with list-separator = "and" # parse_persons = TypeBuilder.with_one_or_more(parse_person, listsep="and") parse_persons = TypeBuilder.with_many(parse_person, listsep="and") matchers.register_type(PersonAndMore=parse_persons) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then # -- MANY-VARIANT 1: Use Cardinality field in parse expression (comma-separated) @when('I meet {persons:Person+}')
value = context.active_outline['spam'] expected = value + ' Cans' assert context.saved_table[0]['department'] == expected, '%r != %r' % ( context.saved_table[0]['department'], expected) @given('the tag "{tag}" is set') def step(context, tag): assert tag in context.tags, '%r NOT present in %r!' % (tag, context.tags) if tag == 'spam': assert context.is_spammy @given('the tag "{tag}" is not set') def step(context, tag): assert tag not in context.tags, '%r IS present in %r!' % (tag, context.tags) @given('a string {argument} an argument') def step(context, argument): context.argument = argument from behave.matchers import register_type register_type(custom=lambda s: s.upper()) @given('a string {argument:custom} a custom type') def step(context, argument): context.argument = argument @then('we get "{argument}" parsed') def step(context, argument): assert context.argument == argument
TODO: matcher that ignores empty lines and whitespace and has contains comparison """ from __future__ import print_function from behave import given, when, then, step, matchers import command_shell import command_util import os import shutil from hamcrest import assert_that, equal_to, is_not, contains_string # ----------------------------------------------------------------------------- # INIT: # ----------------------------------------------------------------------------- matchers.register_type(int=int) DEBUG = True # ----------------------------------------------------------------------------- # STEPS: # ----------------------------------------------------------------------------- @given(u'a new working directory') def step_a_new_working_directory(context): """ Creates a new, empty working directory """ command_util.ensure_context_attribute_exists(context, "workdir", None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True)
# USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse import TypeBuilder, with_pattern @with_pattern(r"a\s+") def parse_word_a(text): """Type converter for "a " (followed by one/more spaces).""" return text.strip() # -- SAME: # parse_optional_word_a = TypeBuilder.with_zero_or_one(parse_word_a) parse_optional_word_a = TypeBuilder.with_optional(parse_word_a) matchers.register_type(optional_a_=parse_optional_word_a) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to, is_in # -- OPTIONAL-PART: {:optional_a_} # By using data type with cardinality zero or one (0..1, optional). @when('attacked by {:optional_a_}{opponent}') def step_attacked_by(context, a_, opponent): context.ninja_fight.opponent = opponent # -- VERIFY: Optional part feature.
# ---------------------------------------------------------------------------- class Meeting(object): def __init__(self): self.persons = set() # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder company_persons = [ "Alice", "Bob", "Charly", "Dodo" ] parse_person = TypeBuilder.make_choice(company_persons) matchers.register_type(Person=parse_person) # -- MANY-TYPE: Persons := list<Person> with list-separator = "and" # parse_persons = TypeBuilder.with_one_or_more(parse_person, listsep="and") parse_persons = TypeBuilder.with_many(parse_person, listsep="and") matchers.register_type(PersonAndMore=parse_persons) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then # -- MANY-VARIANT 1: Use Cardinality field in parse expression (comma-separated) @when('I meet {persons:Person+}')
# @mark.user_defined_types # ---------------------------------------------------------------------------- # USER-DEFINED TYPES: # ---------------------------------------------------------------------------- from behave import matchers def parse_number(text): """ Convert parsed text into a number. :param text: Parsed text, called by :py:meth:`parse.Parser.parse()`. :return: Number instance (integer), created from parsed text. """ return int(text) # -- REGISTER: User-defined type converter (parse_type). matchers.register_type(Number=parse_number) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to from calculator import Calculator @given('I have a calculator') def step_impl(context): context.calculator = Calculator() @when('I add "{x:Number}" and "{y:Number}"') def step_impl(context, x, y):
def register_type(): from behave import matchers import numpy matchers.register_type(Integer=lambda x: int(eval(x))) matchers.register_type(Float=lambda x: float(eval(x))) matchers.register_type( Eval=lambda x: eval(x, globals(), numpy.__dict__.copy())) matchers.register_type(Bool=lambda x: bool(eval(x))) matchers.register_type(Matrix=Matrix) matchers.register_type(QMatrix=QMat)
''' helper function for dsl manipulation ''' from behave.matchers import register_type from support import * import time def parse_optional(text): return text.strip() # https://pypi.python.org/pypi/parse#custom-type-conversions parse_optional.pattern = r'\s?\w*\s?' register_type(optional=parse_optional) def parse_domain(domain): rv = {} if domain[-1:] == ':': domain = domain[:-1] for term in domain.split(' and '): key, value = term.split(None, 1) if key[-1:] == ':': key = key[:-1] try: value = literal_eval(value) except Exception: # Interpret the value as a string pass rv[key.lstrip()] = value if 'oid' in rv:
Given I go to a shop to buy ingredients for a meal And I buy apples And I buy beef """ # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder # -- CHOICE: Constrain to a list of supported items (as string). offered_shop_items = [ "apples", "beef", "potatoes", "pork" ] parse_shop_item = TypeBuilder.make_choice(offered_shop_items) matchers.register_type(ShopItem=parse_shop_item) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then @given(u"I go to a shop to buy ingredients for a meal") def step_given_I_go_to_a_shop(context): context.shopping_cart = [ ] @when(u"I buy {shop_item:ShopItem}") def step_when_I_buy(context, shop_item): assert shop_item in offered_shop_items context.shopping_cart.append(shop_item)
from behave import * from behave.matchers import register_type from steamer.stats import get_stats from tests.integration.steam_simulator import SteamSimulator from behave.matchers import register_type register_type(username=lambda s: s) register_type(string=lambda s: s) @given(r'{username:username} as user') def impl(context, username): context.username = username @when(u'he asks for the {game:string} status') def impl(context, game): context.game = game context.stats = get_stats(context.username, context.game) @then(u'the {key:string} is {value:string}') def impl(context, key, value): assert context.stats[key] == value, 'The %s should be %s and it is %s' % (key, value, context.stats[key])
def register_type(): from behave import matchers import numpy matchers.register_type(Integer=lambda x: int(eval(x))) matchers.register_type(Float=lambda x: float(eval(x))) matchers.register_type(Eval=lambda x: eval(x, globals(), numpy.__dict__.copy())) matchers.register_type(Bool=lambda x: bool(eval(x))) matchers.register_type(Matrix=Matrix) matchers.register_type(QMatrix=QMat)
from behave import * from behave.matchers import register_type from steamer.stats import get_stats from tests.integration.steam_simulator import SteamSimulator from behave.matchers import register_type register_type(username=lambda s: s) register_type(string=lambda s: s) @given(r'{username:username} as user') def impl(context, username): context.username = username @when(u'he asks for the {game:string} status') def impl(context, game): context.game = game context.stats = get_stats(context.username, context.game) @then(u'the {key:string} is {value:string}') def impl(context, key, value): assert context.stats[key] == value, 'The %s should be %s and it is %s' % ( key, value, context.stats[key])
answer_oracle = { "Do you love me?": True, "Do you hate me?": False, "Do you kiss me?": True, } # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder # -- ENUM: Returns True (for "yes" and "jubilee"), False (for "no") parse_yesno = TypeBuilder.make_enum({"yes": True, "no": False, "jubilee": True }) matchers.register_type(YesNo=parse_yesno) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import when, then from hamcrest import assert_that, equal_to @when(u'Romeo asks Julia: "{question}"') def step_when_romeo_asks_julia(context, question): context.question = question @then(u'the answer is "{answer:YesNo}"') def step_then_the_answer_is(context, answer): assert_that(answer, equal_to(answer_oracle.get(context.question, None)))
def timestamp_converter(input): return str(int(time.mktime(input.timetuple()))) converters = { 'timestamp': timestamp_converter } def parse_boolean(input): return bool(input.strip()) parse_boolean.pattern = r'\s?\w*\s?' register_type(optional=parse_boolean) @given(u'I authorize as {name} with password {password}') def authorize(context, name, password): name, password = (json.loads(name), json.loads(password)) request = requests.post("%s/auth" % (context.root), json={'name': name, 'password': password}) context.access_token = request.json()['access_token'] @given(u'I define that {variable} is {value}') def define_variable(context, variable, value): context.s[variable] = json.loads(value)
price_per_unit = self.vegetable_price_list[vegetable] return price_per_unit*amount def calculate_price_for(self, shop_item, amount): price_per_unit = self.common_price_list[shop_item] return price_per_unit*amount # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder parse_vegetable = TypeBuilder.make_choice(["cucumbers", "lettuce"]) matchers.register_type(Vegetable=parse_vegetable) parse_fruit = TypeBuilder.make_choice(["apples", "pears"]) matchers.register_type(Fruit=parse_fruit) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then @given(u"I go to a shop") def step_given_I_go_to_a_shop(context): context.shop = Shop() context.shopping_cart = [ ]
# @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers import parse @parse.with_pattern(r"a\s+") def parse_word_a(text): """Type converter for "a " (followed by one/more spaces).""" return text.strip() matchers.register_type(a_=parse_word_a) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to, is_in # -- OPTIONAL-PART: {:a_?} # By using cardinality field in parse expressions. @when('attacked by {:a_?}{opponent}') def step_attacked_by(context, a_, opponent): context.ninja_fight.opponent = opponent # -- VERIFY: Optional part feature.
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import time import subprocess import socket from hamcrest import assert_that, is_, is_not from behave.matchers import register_type from utils import parse_nullable_string, is_entry_created, remove_entry parse_nullable_string.pattern = r'.*' register_type(NullableString=parse_nullable_string) @step( 'The second "{process}" is turned off inside "{container_name}" container') def step_impl(context, process, container_name): if process != "agent" and process != "server": raise Exception("Invalid process '%s'. Choose 'agent' or 'server'." % process) workload_id = "" if context.workload_b in context.tags: workload_id = context.workload_b elif context.workload_c in context.tags: workload_id = context.workload_c os.system( "/mnt/c-spiffe/integration_test/helpers/bash-spire-scripts/ssh-stop-process.sh %s %s"
''' import time from functools import wraps from behave.matchers import register_type from oerpscenario.support import * import logging _logger = logging.getLogger(__name__) def parse_optional(text): return text.strip() # https://pypi.python.org/pypi/parse#custom-type-conversions parse_optional.pattern = r'\s?\w*\s?' register_type(optional=parse_optional) def parse_domain(domain): rv = {} if domain[-1:] == ':': domain = domain[:-1] for term in domain.split(' and '): key, value = term.split(None, 1) if key[-1:] == ':': key = key[:-1] try: value = literal_eval(value) except Exception: # Interpret the value as a string pass
@given('the tag "{tag}" is set') def step(context, tag): assert tag in context.tags, '%r NOT present in %r!' % (tag, context.tags) if tag == 'spam': assert context.is_spammy @given('the tag "{tag}" is not set') def step(context, tag): assert tag not in context.tags, '%r IS present in %r!' % (tag, context.tags) @given('a string {argument} an argument') def step(context, argument): context.argument = argument from behave.matchers import register_type register_type(custom=lambda s: s.upper()) @given('a string {argument:custom} a custom type') def step(context, argument): context.argument = argument @then('we get "{argument}" parsed') def step(context, argument): assert context.argument == argument
When attacked by Chuck Norris """ # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers import parse @parse.with_pattern(r"a\s+") def parse_word_a(text): """Type converter for "a " (followed by one/more spaces).""" return text.strip() matchers.register_type(a_=parse_word_a) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to, is_in # -- OPTIONAL-PART: {:a_?} # By using cardinality field in parse expressions. @when('attacked by {:a_?}{opponent}') def step_attacked_by(context, a_, opponent): context.ninja_fight.opponent = opponent # -- VERIFY: Optional part feature. assert_that(a_, is_in(["a", None]))
# USER-DEFINED TYPES: # ---------------------------------------------------------------------------- from behave import matchers def parse_number(text): """ Convert parsed text into a number. :param text: Parsed text, called by :py:meth:`parse.Parser.parse()`. :return: Number instance (integer), created from parsed text. """ return int(text) # -- REGISTER: User-defined type converter (parse_type). matchers.register_type(Number=parse_number) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to from calculator import Calculator @given('I have a calculator') def step_impl(context): context.calculator = Calculator()
return price_per_unit * amount def calculate_price_for(self, shop_item, amount): price_per_unit = self.common_price_list[shop_item] return price_per_unit * amount # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder parse_vegetable = TypeBuilder.make_choice(["cucumbers", "lettuce"]) matchers.register_type(Vegetable=parse_vegetable) parse_fruit = TypeBuilder.make_choice(["apples", "pears"]) matchers.register_type(Fruit=parse_fruit) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then @given(u"I go to a shop") def step_given_I_go_to_a_shop(context): context.shop = Shop() context.shopping_cart = []
""" # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse_type import TypeBuilder def slurp_space(text): return text slurp_space.pattern = r"\s*" matchers.register_type(slurp_space=slurp_space) parse_color = TypeBuilder.make_choice(["red", "green", "blue", "yellow"]) matchers.register_type(Color=parse_color) # -- MANY-TYPE: Persons := list<Person> with list-separator = "and" # parse_colors = TypeBuilder.with_many0(parse_color, listsep="and") parse_colors0 = TypeBuilder.with_zero_or_more(parse_color, listsep="and") matchers.register_type(OptionalColorAndMore=parse_colors0) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then
TODO: matcher that ignores empty lines and whitespace and has contains comparison """ from __future__ import print_function from behave import given, when, then, step, matchers from behave4cmd0 import command_shell, command_util, pathutil, textutil from behave4cmd0.pathutil import posixpath_normpath import os import shutil from hamcrest import assert_that, equal_to, is_not, contains_string # ----------------------------------------------------------------------------- # INIT: # ----------------------------------------------------------------------------- matchers.register_type(int=int) DEBUG = True # ----------------------------------------------------------------------------- # STEPS: WORKING DIR # ----------------------------------------------------------------------------- @given(u'a new working directory') def step_a_new_working_directory(context): """ Creates a new, empty working directory """ command_util.ensure_context_attribute_exists(context, "workdir", None) command_util.ensure_workdir_exists(context) shutil.rmtree(context.workdir, ignore_errors=True)
# @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import matchers from parse import TypeBuilder, with_pattern @with_pattern(r"a\s+") def parse_word_a(text): """Type converter for "a " (followed by one/more spaces).""" return text.strip() # -- SAME: # parse_optional_word_a = TypeBuilder.with_zero_or_one(parse_word_a) parse_optional_word_a = TypeBuilder.with_optional(parse_word_a) matchers.register_type(optional_a_=parse_optional_word_a) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to, is_in # -- OPTIONAL-PART: {:optional_a_} # By using data type with cardinality zero or one (0..1, optional). @when('attacked by {:optional_a_}{opponent}') def step_attacked_by(context, a_, opponent): context.ninja_fight.opponent = opponent # -- VERIFY: Optional part feature.