def register_type(self, name, parse_function=(lambda x: x), enumeration=None, is_constant=False): register_type(**{name: parse_function}) if is_constant: self.constant_types[name] = enumeration else: self.types[name] = enumeration
def register_system_types(): """ Will register all B system types. These keeps them from being synthesized. """ register_type(STRING=parse_string) register_type(INT=parse_nat) register_type(BOOL=parse_bool) register_type(NAT=parse_nat) register_type(NAT1=parse_nat1)
# ------------------------------------------------------------------------ from behave import register_type from parse_type import TypeBuilder 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() # -- SAME: # parse_optional_word_a = TypeBuilder.with_zero_or_one(parse_word_a) parse_optional_word_a = TypeBuilder.with_optional(parse_word_a) 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.
REPO_TMPL = "/etc/yum.repos.d/{!s}.repo" HEADINGS_REPO = ["Package", "Tag", "Value"] PKG_TAGS_REPEATING = ["BuildRequires", "Requires", "Recommends", "Suggests", "Supplements", "Enhances", "Obsoletes", "Provides", "Conflicts", "%pretrans", "%pre", "%post", "%preun", "%postun", "%posttrans", "Requires(pretrans)", "Requires(pre)", "Requires(post)", "Requires(preun)"] PKG_TAGS = ["Summary", "Version", "Release", "License", "Arch"] + PKG_TAGS_REPEATING JINJA_ENV = jinja2.Environment(undefined=jinja2.StrictUndefined) @parse.with_pattern(r"enable|disable") def parse_enable_disable(text): if text == "enable": return True if text == "disable": return False assert False register_type(enable_disable=parse_enable_disable) @parse.with_pattern(r"enabled |disabled |") def parse_enabled_status(text): if text == "enabled ": return True if text == "disabled " or text == "": return False assert False register_type(enabled_status=parse_enabled_status) @parse.with_pattern(r"local |http |https |ftp |") def parse_repo_type(text): if text == "http ": return "http"
# @mark.user_defined_types # ---------------------------------------------------------------------------- # USER-DEFINED TYPES: # ---------------------------------------------------------------------------- from behave import register_type 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). 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):
from __future__ import absolute_import from __future__ import unicode_literals from behave import register_type from behave import then from behave import when import parse import command_utils @parse.with_pattern(r"stdout|stderr") def parse_stdout_stderr(text): return text register_type(stdout_stderr=parse_stdout_stderr) @when('I run "{command}"') def step_i_run_command(ctx, command): """ Run a ``{command}`` as subprocess, collect its output and returncode. """ ctx.cmd_result = command_utils.run(ctx, command) @when('I successfully run "{command}"') def step_i_successfully_run_command(ctx, command): step_i_run_command(ctx, command) step_the_command_should_pass(ctx) @then("the command should pass") def step_the_command_should_pass(ctx): ctx.assertion.assertEqual(ctx.cmd_result.returncode, 0)
from behave import given, when, then, register_type, use_step_matcher from test.common.helper import create_project import parse @parse.with_pattern(r"[a-zA-Z0-9_\s]+") def parse_string(text): return text register_type(str_value=parse_string) use_step_matcher("cfparse") @then('the response field "{field}" should be "{value:str_value?}"') def step_impl(context, field, value): if value is None: value = '' assert context.response[field] == value @then('The response should have the error message: "{error_message}"') def step_impl(context, error_message): assert context.response['errorMessages'][0] == error_message @then('The response should have an error message') def step_impl(context): assert 'errorMessages' in context.response
_ = openshift.apply_yaml_file(os.path.join( os.getcwd(), "test/acceptance/resources/backend_crd.yaml"), namespace=ns) else: _ = openshift.apply_yaml_file(os.path.join( os.getcwd(), "test/acceptance/resources/", backend_service + ".operator.manifest.yaml"), namespace=ns) @parse.with_pattern(r'.*') def parse_nullable_string(text): return text register_type(NullableString=parse_nullable_string) # STEP @step( u'Secret contains "{secret_key}" key with value "{secret_value:NullableString}"' ) def check_secret_key_value(context, secret_key, secret_value): sb = list(context.bindings.values())[0] openshift = Openshift() secret = polling2.poll(lambda: sb.get_secret_name(), step=100, timeout=1000, ignore_exceptions=(ValueError, ), check_success=lambda v: v is not None) json_path = f'{{.data.{secret_key}}}'
} # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import register_type 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 }) 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}"')
from behave import given, when, then, register_type import parse # FIXME regex patterns aren't working as expected # \w+ matches only one word, and \w doesn't match one word @parse.with_pattern(r"\w+") def parse_word(text): return str(text) @parse.with_pattern(r'\w+') def parse_string(text): return str(text) register_type(some_word = parse_word) register_type(some_string = parse_string) @given('that Liberator is running') def step_impl(context): pass @given('{:some_word} homepage is at http://192.168.66.6:{port:d}') def step_impl(context, word, port): context.browser.get('http://192.168.66.6:8000') assert "Liberator" in context.browser.title @given('no access privileges are implemented') def step_impl(context): pass @given('I load the page for new article submission')
import os import tempfile import shutil import sys from parse_type import TypeBuilder from behave import register_type parse_bool = TypeBuilder.make_enum({"False": False, "True": True}) register_type(Bool=parse_bool) def before_scenario(context, scenario): context.tmpdir = tempfile.mkdtemp() sys.path.append(context.tmpdir + '/output') os.chdir(context.tmpdir) def after_scenario(context, scenario): sys.path.remove(context.tmpdir + '/output') os.chdir('/') shutil.rmtree(context.tmpdir)
'Medication orders': 'MedicationOrder?patient={patientId}', 'Medication statements': 'MedicationStatement?patient={patientId}', 'Medication dispensations': 'MedicationDispense?patient={patientId}', 'Medication administrations': 'MedicationAdministration?patient={patientId}', 'Allergies and intolerances': 'AllergyIntolerance?patient={patientId}', 'Vital signs': 'Observation?category=vital-signs&patient={patientId}', 'Procedures': 'Procedure?patient={patientId}', 'Immunizations': 'Immunization?patient={patientId}', 'Patient documents': 'DocumentReference?patient={patientId}', } @parse.with_pattern(r'|'.join(MU_CCDS_MAPPINGS)) def parse_mu_ccds_mapping(mu_ccds): return MU_CCDS_MAPPINGS[mu_ccds] register_type(MU_CCDS=parse_mu_ccds_mapping) @given('I have a valid conformance statement') def step_impl(context): assert context.conformance is not None, \ ERROR_MISSING_CONFORMANCE_STATEMENT @given('this server supports {mu_ccds_query:MU_CCDS}') def step_impl(context, mu_ccds_query): # If there is no conformance statement, assume this resource is supported if context.conformance is None: return # The resourceType is the first block before a "/" or a "?"
import parse from behave import register_type TYPE_TO_PARSE_TYPE_MAP = { "int": "d", "float": "f", } class Word(str): pass @parse.with_pattern(r"(.*)") def parse_str(value: str) -> str: return value @parse.with_pattern(r"\w+") def parse_word(value: str) -> Word: return Word(value) register_type(str=parse_str, Word=parse_word)
@parse.with_pattern(r".+") def parse_side(text): if text.startswith("the "): text = text[4:] return text @parse.with_pattern(r"(?:\w+/)*\w+(?:\.\w+)?") def parse_path(text): return text @parse.with_pattern(r"[1-9][0-9]*") def parse_count(text): return int(text) register_type(Side = parse_side, Path = parse_path, Count = parse_count) def before_scenario(context, scenario): if ("local" in scenario.tags) or ("local" in scenario.feature.tags): # Setup a temporary directory for the scenario to run in. context.original_path = getcwd() context.sandbox = TempDirectory() chdir(context.sandbox.path) context.dealer = None else: context.sandbox = defaultdict(TempDirectory) context.bot_config = {} context.dealer = {} context.server = None context.server_thread = None
# common-sense parsers for regexes from behave import register_type import parse @parse.with_pattern(r'[-+]?\d+') def parse_integer(text): return int(text) @parse.with_pattern(r'[Tt]rue|[Ff]alse') def parse_boolean(text): if text.lower() == 'true': return True return False register_type(Boolean=parse_boolean) register_type(Integer=parse_integer)
@behave.step('I require client certificate verification with certificate "{client_cert}" and key "{client_key}"') def step_impl(context, client_cert, client_key): if "client_ssl" not in context.dnf: context.dnf["client_ssl"] = dict() context.dnf["client_ssl"]["certificate"] = os.path.join(context.dnf.fixturesdir, client_cert) context.dnf["client_ssl"]["key"] = os.path.join(context.dnf.fixturesdir, client_key) @parse.with_pattern(r"http|https") def parse_repo_type(text): if text in ("http", "https"): return text assert False behave.register_type(repo_type=parse_repo_type) @behave.step("I use the {rtype:repo_type} repository based on \"{repo}\"") def step_impl(context, rtype, repo): assert hasattr(context, 'httpd'), 'Httpd fixture not set. Use @fixture.httpd tag.' if rtype == "http": host, port = context.httpd.new_http_server(context.dnf.repos_location) else: cacert = os.path.join(context.dnf.fixturesdir, 'certificates/testcerts/ca/cert.pem') cert = os.path.join(context.dnf.fixturesdir, 'certificates/testcerts/server/cert.pem') key = os.path.join(context.dnf.fixturesdir, 'certificates/testcerts/server/key.pem') client_ssl = context.dnf._get(context, "client_ssl") if client_ssl:
import parse import pytz import requests import time import yaml from behave import register_type, step, then from datetime import datetime, timedelta @parse.with_pattern(r'https?://(?:\w|\.|:|/)+') def parse_url(text): return text register_type(url=parse_url) # there is no way we can find out if the node has already # started as a leader without checking the DCS. We cannot # just rely on the database availability, since there is # a short gap between the time PostgreSQL becomes available # and Patroni assuming the leader role. @step('{name:w} is a leader after {time_limit:d} seconds') @then('{name:w} is a leader after {time_limit:d} seconds') def is_a_leader(context, name, time_limit): max_time = time.time() + int(time_limit) while (context.dcs_ctl.query("leader") != name): time.sleep(1) assert time.time() < max_time, "{0} is not a leader in dcs after {1} seconds".format(name, time_limit)
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 register_type 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) 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)
# -*- coding: UTF-8 -*- import logging logging.basicConfig(format='%(message)s') # ---------------------------------------------------------------------------- # USER-DEFINED TYPES: # ---------------------------------------------------------------------------- from behave import register_type import json def parse_ids(ids): # logging.warning(type(ids)) # logging.warning(ids) strippedIds = ids.strip('\'"') strIds = json.loads(strippedIds) strIds = list(map(lambda x: int(x), strIds)) return strIds # -- REGISTER: User-defined type converter (parse_type). register_type(IdList=parse_ids)
import time import yaml from behave import register_type, step, then from dateutil import tz from datetime import datetime, timedelta tzutc = tz.tzutc() @parse.with_pattern(r'https?://(?:\w|\.|:|/)+') def parse_url(text): return text register_type(url=parse_url) # there is no way we can find out if the node has already # started as a leader without checking the DCS. We cannot # just rely on the database availability, since there is # a short gap between the time PostgreSQL becomes available # and Patroni assuming the leader role. @step('{name:w} is a leader after {time_limit:d} seconds') @then('{name:w} is a leader after {time_limit:d} seconds') def is_a_leader(context, name, time_limit): time_limit *= context.timeout_multiplier max_time = time.time() + int(time_limit) while (context.dcs_ctl.query("leader") != name): time.sleep(1) assert time.time() < max_time, "{0} is not a leader in dcs after {1} seconds".format(name, time_limit)
# ----------------------------------------------------------------------------- # TEST DOMAIN, FIXTURES, STEP UTILS: # ----------------------------------------------------------------------------- class ModelElement(object): def __init__(self, name, tags=None): self.name = name self.tags = tags or [] # ----------------------------------------------------------------------------- # TYPE CONVERTERS: # ----------------------------------------------------------------------------- def convert_tag_expression(text): parts = text.strip().split() return TagExpression(parts) register_type(TagExpression=convert_tag_expression) def convert_yesno(text): text = text.strip().lower() assert text in convert_yesno.choices return text in convert_yesno.true_choices convert_yesno.choices = ("yes", "no", "true", "false") convert_yesno.true_choices = ("yes", "true") # ----------------------------------------------------------------------------- # STEP DEFINITIONS: # ----------------------------------------------------------------------------- @given('the tag expression "{tag_expression:TagExpression}"') def step_given_the_tag_expression(context, tag_expression): """
# ---------------------------------------------------------------------------- class Meeting(object): def __init__(self): self.persons = set() # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import register_type from parse_type import TypeBuilder company_persons = [ "Alice", "Bob", "Charly", "Dodo" ] parse_person = TypeBuilder.make_choice(company_persons) 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") register_type(PersonAndMore=parse_persons) # -- NEEDED-UNTIL: parse_type.cfparse.Parser is used by behave. # parse_persons2 = TypeBuilder.with_many(parse_person) # type_dict = {"Person+": parse_persons2} # register_type(**type_dict) # @mark.steps # ---------------------------------------------------------------------------- # STEPS:
# @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import register_type 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() register_type(a_=parse_word_a) # -- NEEDED-UNTIL: parse_type.cfparse.Parser is used by behave. # from parse_type import TypeBuilder # parse_opt_word_a = TypeBuilder.with_optional(parse_word_a) # type_dict = {"a_?": parse_opt_word_a} # register_type(**type_dict) # @mark.steps # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to, is_in
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 register_type from parse_type import TypeBuilder parse_vegetable = TypeBuilder.make_choice(["cucumbers", "lettuce"]) register_type(Vegetable=parse_vegetable) parse_fruit = TypeBuilder.make_choice(["apples", "pears"]) 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 = [ ]
# USER-DEFINED TYPES: # ---------------------------------------------------------------------------- from behave import register_type 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 float(text) # -- REGISTER: User-defined type converter (parse_type). register_type(Number=parse_number) # ---------------------------------------------------------------------------- # STEPS: # ---------------------------------------------------------------------------- from behave import given, when, then from hamcrest import assert_that, equal_to from atm import ATM @given('I have a Platinum account and am withdrawing cash from an ATM') def step_impl(context): context.atm = ATM() @when('I have "{x:Number}" on my account and want to withdraw "{y:Number}"')
The default driver is 'phantomjs'. This assigns the new driver to the global _driver and returns it. """ global _driver driver_name = context.config.userdata.get('browser', 'phantomjs') cls = DRIVER_MAP[driver_name] _driver = cls() return _driver def before_all(context): context.driver = create_driver(context) context.base_url = context.config.userdata.get( 'base-url', 'http://localhost:3000/') def after_all(context): _driver.quit() def before_tag(context, tag): if tag == 'clear-agenda': page = AgendaPage(context) page.visit() for p in page.proposals(): p.bookmarked = False # Register the Int type converter behave.register_type(Int=int)
from __future__ import unicode_literals import sys from behave import register_type from behave import then from behave import when import parse import command_utils @parse.with_pattern(r"stdout|stderr") def parse_stdout_stderr(text): return text register_type(stdout_stderr=parse_stdout_stderr) @when('I run "{command}"') def step_i_run_command(ctx, command): """ Run a ``{command}`` as subprocess, collect its output and returncode. """ ctx.cmd_result = command_utils.run(ctx, command) @when('I successfully run "{command}"') def step_i_successfully_run_command(ctx, command): step_i_run_command(ctx, command) step_the_command_should_pass(ctx) @then("the command should pass") def step_the_command_should_pass(ctx):
| red | | green | | blue | """ # @mark.user_defined_types # ------------------------------------------------------------------------ # USER-DEFINED TYPES: # ------------------------------------------------------------------------ from behave import register_type from parse_type import TypeBuilder def slurp_space(text): return text slurp_space.pattern = r"\s*" register_type(slurp_space=slurp_space) parse_color = TypeBuilder.make_choice([ "red", "green", "blue", "yellow" ]) register_type(Color=parse_color) # -- MANY-TYPE: Persons := list<Person> with list-separator = "and" # parse_colors = TypeBuilder.with_many0(parse_color, listsep="and") parse_colors0A= TypeBuilder.with_zero_or_more(parse_color, listsep="and") register_type(OptionalColorAndMore=parse_colors0A) # -- NEEDED-UNTIL: parse_type.cfparse.Parser is used by behave. # parse_colors0C = TypeBuilder.with_zero_or_more(parse_color) # type_dict = {"Color*": parse_colors0C} # register_type(**type_dict)
PKG_TAGS = ["Summary", "Version", "Release", "License", "Arch" ] + PKG_TAGS_REPEATING JINJA_ENV = jinja2.Environment(undefined=jinja2.StrictUndefined) @parse.with_pattern(r"enable|disable") def parse_enable_disable(text): if text == "enable": return True if text == "disable": return False assert False register_type(enable_disable=parse_enable_disable) @parse.with_pattern(r"enabled |disabled |") def parse_enabled_status(text): if text == "enabled ": return True if text == "disabled " or text == "": return False assert False register_type(enabled_status=parse_enabled_status) @parse.with_pattern(r"local |http |https |ftp |")
REPO_TMPL = "/etc/yum.repos.d/{!s}.repo" HEADINGS_REPO = ["Package", "Tag", "Value"] PKG_TAGS_REPEATING = ["BuildRequires", "Requires", "Obsoletes", "Provides", "Conflicts"] PKG_TAGS = ["Summary", "Version", "Release", "License"] + PKG_TAGS_REPEATING JINJA_ENV = jinja2.Environment(undefined=jinja2.StrictUndefined) @parse.with_pattern(r"enable|disable") def parse_enable_disable(text): if text == "enable": return True if text == "disable": return False assert False register_type(enable_disable=parse_enable_disable) @when('I remove all repositories') def step_i_remove_all_repositories(ctx): """ Remove all ``*.repo`` files in ``/etc/yum.repos.d/``. """ for f in glob.glob("/etc/yum.repos.d/*.repo"): os.remove(f) @given('repository "{repository}" with packages') def given_repository_with_packages(ctx, repository): """ Builds dummy noarch packages, creates repo and *.repo* file. .. note::
from behave import given, when, then, register_type from features.support import custom_type_parser from packit_app.table_elements import User, UserGarmentSetting, Garment from packit_app.table_fields import UserID, UserGarmentSettingsID, GarmentID, \ Username, GarmentName users = [] register_type(Gender=custom_type_parser.parse_gender) register_type(Username=custom_type_parser.parse_username) register_type(GarmentName=custom_type_parser.parse_garment_name) register_type(Quantity=custom_type_parser.parse_quantity) @given(u'user {username:Username} has an entry for {garment_name:GarmentName}') def check_user_clothing_entry_exists(context, username, garment_name): context.garment = Garment(context.gender_id, garment_name) context.username = username context.user_id = UserID( context.user_table.get_matching_element( User(username, context.gender_id))[UserID.column_name]) context.garment_id = GarmentID( context.garment_table.add_element(context.garment)) user_garment_setting_id = context.user_garment_settings_table.add_element( UserGarmentSetting(context.user_id, context.garment_id)) context.user_garment_setting_id = UserGarmentSettingsID( user_garment_setting_id) result = context.user_garment_settings_table.get_matching_elements( context.user_garment_setting_id)
REPO_TMPL = "/etc/yum.repos.d/{!s}.repo" HEADINGS_REPO = ["Package", "Tag", "Value"] PKG_TAGS_REPEATING = ["BuildRequires", "Requires", "Obsoletes", "Provides", "Conflicts"] PKG_TAGS = ["Summary", "Version", "Release", "License", "Arch"] + PKG_TAGS_REPEATING JINJA_ENV = jinja2.Environment(undefined=jinja2.StrictUndefined) @parse.with_pattern(r"enable|disable") def parse_enable_disable(text): if text == "enable": return True if text == "disable": return False assert False register_type(enable_disable=parse_enable_disable) @parse.with_pattern(r"local |http |https |ftp |") def parse_repo_type(text): if text == "http ": return "http" elif text == "https ": return "https" elif text == "ftp ": return "ftp" elif text == 'local ' or text == '': return "file" assert False register_type(repo_type=parse_repo_type)
from config import DEFAULT_REQUEST_TIMEOUT JSON_TYPE = 'application/json' def parse_boolean(text): if text.lower() == 'true': return True elif text.lower() == 'false': return False raise ValueError('Expect True or False, got {}'.format(text)) register_type(boolean=parse_boolean) def options_request(context, url): context.response = context.http_client.options( url, headers=context.headers) def get_request(context, url): # todo : lots data = context.params or None kwargs = { 'params': data, 'headers': context.headers, 'allow_redirects': False, 'timeout': DEFAULT_REQUEST_TIMEOUT # todo: load from context }
import parse from behave import step, register_type, use_step_matcher from behave.runner import Context from pyassert import assert_that use_step_matcher("parse") @parse.with_pattern(r'\d+') def parse_integer(text: int): return int(text) register_type(Integer=parse_integer) @step("APIサーバにリクエストする") def step_impl(context: Context) -> None: """ :type context: behave.runner.Context """ # ステータスコードのステップを実行したいので、一旦無視する pass # status_codeがstrでないという警告が出るので無効化する # noinspection PyBDDParameters @step("ステータスコードが {status_code:Integer} である") def step_impl(context: Context, status_code: int) -> None: """ :type context: behave.runner.Context
# -- VARIANT 1: @when(u'I click on ${environment_variable:w}') def step_impl(context, environment_variable): env_value = os.environ.get(environment_variable, None) if env_value is None: raise LookupError("Environment variable '%s' is undefined" % environment_variable) print("USE ENVIRONMENT-VAR: %s = %s (variant 1)" % (environment_variable, env_value)) # -- VARIANT 2: Use type converter from behave import register_type import parse @parse.with_pattern(r"\$\w+") # -- ONLY FOR: $WORD def parse_environment_var(text): assert text.startswith("$") env_name = text[1:] env_value = os.environ.get(env_name, None) return (env_name, env_value) register_type(EnvironmentVar=parse_environment_var) @when(u'I use the environment variable {environment_variable:EnvironmentVar}') def step_impl(context, environment_variable): env_name, env_value = environment_variable if env_value is None: raise LookupError("Environment variable '%s' is undefined" % env_name) print("USE ENVIRONMENT-VAR: %s = %s (variant 2)" \ % (env_name, env_value))
PKG_TAGS = ["Summary", "Version", "Release", "License", "Arch" ] + PKG_TAGS_REPEATING JINJA_ENV = jinja2.Environment(undefined=jinja2.StrictUndefined) @parse.with_pattern(r"enable|disable") def parse_enable_disable(text): if text == "enable": return True if text == "disable": return False assert False register_type(enable_disable=parse_enable_disable) @parse.with_pattern(r"local |http |ftp |") def parse_repo_type(text): if text == "http ": return "http" elif text == "ftp ": return "ftp" elif text == 'local ' or text == '': return "file" assert False register_type(repo_type=parse_repo_type)
from behave import given, when, then, step, register_type from parse_type import TypeBuilder import sfctss from sfctss.scheduler.examples import GreedyShortestDeadlineFirstScheduler, LoadUnawareRoundRobinScheduler, RejectScheduler SCHEDULER_GREEDY_ORACLE = "GreedyOracle" SCHEDULER_GREEDY_LOCAL = "GreedyLocal" SCHEDULER_STATIC = "Static" SCHEDULER_REJECT = "Reject" schedulers = [ SCHEDULER_GREEDY_ORACLE, SCHEDULER_GREEDY_LOCAL, SCHEDULER_STATIC, SCHEDULER_REJECT ] parse_scheduler = TypeBuilder.make_choice(schedulers) register_type(Scheduler=parse_scheduler) DO = 'do' DO_NOT = 'do not' do_do_not = [DO, DO_NOT] parse_do_do_not = TypeBuilder.make_choice(do_do_not) register_type(DoDoNot=parse_do_do_not) default_config = { 'sff_bw_capacity': 1000, 'sfi_rate': 15, 'cpu_policy': 'one-at-a-time', 'individual_class_per_egress': False, 'latency_between_sites': 1000, 'latency_within_sites': 10, 'number_of_sf_types': 5,
if env_value is None: raise LookupError("Environment variable '%s' is undefined" % environment_variable) print("USE ENVIRONMENT-VAR: %s = %s (variant 1)" % (environment_variable, env_value)) # -- VARIANT 2: Use type converter from behave import register_type import parse @parse.with_pattern(r"\$\w+") # -- ONLY FOR: $WORD def parse_environment_var(text): assert text.startswith("$") env_name = text[1:] env_value = os.environ.get(env_name, None) return (env_name, env_value) register_type(EnvironmentVar=parse_environment_var) @when(u'I use the environment variable {environment_variable:EnvironmentVar}') def step_impl(context, environment_variable): env_name, env_value = environment_variable if env_value is None: raise LookupError("Environment variable '%s' is undefined" % env_name) print("USE ENVIRONMENT-VAR: %s = %s (variant 2)" \ % (env_name, env_value))
@step(u'{i} = Intersection({t:g}, {obj})') def step_impl(context, i, t, obj): _obj = getattr(context, obj) _i = Intersection(t, _obj) setattr(context, i, _i) @given(u'{i} = Intersection(√2, {ray})') def step_impl(context, i, ray): _obj = getattr(context, ray) _i = Intersection(math.sqrt(2), _obj) setattr(context, i, _i) list_of_strings = TypeBuilder.make_list(str) register_type(ListOfStrings=list_of_strings) @step(u'{xs} = intersections_shorthand({args:ListOfStrings})') def step_impl(context, xs, args): '''This is just the wacky syntax some tests use to construct Intersections''' list_of_intersection = [] for i in args: t, shape = i.split(":") try: t = float(t) except ValueError: # Hacky, can I fix this by defining my own type t = parse_interesting_trig_values(t) shape = getattr(context, shape) list_of_intersection.append(Intersection(t, shape)) _xs = Intersections(*list_of_intersection)
from behave import register_type, step, then from datetime import datetime, timedelta @parse.with_pattern(r'https?://(?:\w|\.|:|/)+') def parse_url(text): return text @parse.with_pattern(r'(?:\w+=(?:\w|\.|:|-|\+|\s)+,?)+') def parse_data(text): return text register_type(url=parse_url, data=parse_data) # there is no way we can find out if the node has already # started as a leader without checking the DCS. We cannot # just rely on the database availability, since there is # a short gap between the time PostgreSQL becomes available # and Patroni assuming the leader role. @step('{name:w} is a leader after {time_limit:d} seconds') @then('{name:w} is a leader after {time_limit:d} seconds') def is_a_leader(context, name, time_limit): max_time = time.time() + int(time_limit) while (context.dcs_ctl.query("leader") != name): time.sleep(1) assert time.time() < max_time, "{0} is not a leader in dcs after {1} seconds".format(name, time_limit)
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 register_type from parse_type import TypeBuilder parse_vegetable = TypeBuilder.make_choice(["cucumbers", "lettuce"]) register_type(Vegetable=parse_vegetable) parse_fruit = TypeBuilder.make_choice(["apples", "pears"]) 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 = []
from behave import register_type from parse import with_pattern from parse_type import TypeBuilder from ray_tracer.tuples import is_point, is_vector parse_interesting_trig_values = TypeBuilder.make_enum({ "0": 0, "√2/2": math.sqrt(2) / 2, "1": 1, "√2": math.sqrt(2), "-√2/2": -math.sqrt(2) / 2, "-1": -1, "-3": -3 # This is stoopid - try to define my own parser below }) register_type(InterestingTrigValue=parse_interesting_trig_values) # @with_pattern(r'\g+') # def _parse_float(text): # return float(text) # parse_reals = TypeBuilder.make_variant([parse_interesting_trig_values, _parse_float]) # register_type(InterestingRealNumbers=parse_reals) parse_point_or_vector = TypeBuilder.make_enum({ "point": is_point, "vector": is_vector, }) register_type(ElementIn3D=parse_point_or_vector) # Copyright 2020 Bloomberg Finance L.P.
from datetime import datetime import hashlib import json import random import time import urllib from urllib.request import Request, urlopen import parse @parse.with_pattern(r".*") def parse_string(text): return text register_type(MaybeString=parse_string) @given("mock server recording request paths") def setup_mockserver(context): context.url = "http://127.0.0.1:" + str(context.path_server_port) context.acl = algod.AlgodClient("algod_token", context.url) context.icl = indexer.IndexerClient("indexer_token", context.url) @given('mock http responses in "{jsonfiles}" loaded from "{directory}"') def mock_response(context, jsonfiles, directory): context.url = "http://127.0.0.1:" + str(context.response_server_port) context.acl = algod.AlgodClient("algod_token", context.url) context.icl = indexer.IndexerClient("indexer_token", context.url)
from decimal import Decimal from test_wallet_leveller.constants import ( SOURCE_DEFAULT_ACCOUNT, DESTINATION_DEFAULT_ACCOUNT ) from test_wallet_leveller.test_wallet_signals import ( check_async ) @parse.with_pattern(r"\d*\.?\d*") def parse_decimal(text): return Decimal(text) register_type(Decimal=parse_decimal) def wallet_from_name(context, wallet_name): if wallet_name == 'source': wallet = context.source elif wallet_name == 'destination': wallet = context.destination else: raise ValueError('Unknown wallet {}'.format(wallet_name)) return wallet def _transaction_confirmed(context, transaction_id): return context.destination.find_transaction(transaction_id) and context.source.find_transaction(transaction_id) def _wrap_with_confirmation(context, test_function): def wrapped(cb_transaction_id, cb_message_data, cb_associated_data):
def step_impl(context, expr, n, m): expected = table_to_matrix(context.table) setattr(context, "expected", expected) context.execute_steps(f"then {expr} == expected") assert expected.shape == (n, m) @then(u'{expr} is the following matrix') def step_impl(context, expr): expected = table_to_matrix(context.table) setattr(context, "expected", expected) context.execute_steps(f"then {expr} == expected") parse_is_or_is_not = TypeBuilder.make_enum({"is": True, "is not": False}) register_type(IsOrIsNot=parse_is_or_is_not) @then(u'{name} {x:IsOrIsNot} invertible') def step_impl(context, name, x): _name = getattr(context, name) if x: assert _name.det() != 0 else: assert _name.det() == 0 @given(u'C = A * B') def step_impl(context): _A = getattr(context, "A") _B = getattr(context, "B")
from behave import register_type, given, when from parse_type import TypeBuilder from ray_tracer.material import Material, lighting from ray_tracer.tuples import Point @given(u'{m} = Material()') def step_impl(context, m): _m = Material() setattr(context, m, _m) parse_bool = TypeBuilder.make_enum({"True": True, "False": False}) register_type(BoolType=parse_bool) @when(u'{result} = lighting({material}, {object_}, {light}, Point({x:g},{y:g},{z:g}), {eyev}, {normalv}, {in_shadow:BoolType})') def step_impl(context, result, material, object_, light, x, y, z, eyev, normalv, in_shadow): _position = Point(x, y, z) setattr(context, "position", _position) context.execute_steps(f"when {result} = lighting({material}, {object_}, {light}, position, {eyev}, {normalv}, {in_shadow})") @when(u'{result} = lighting({material}, {object_}, {light}, {position}, {eyev}, {normalv}, {in_shadow:BoolType})') def step_impl(context, result, material, object_, light, position, eyev, normalv, in_shadow): _material = getattr(context, material) _object = getattr(context, object_) _light = getattr(context, light) _position = getattr(context, position)
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) def parse_list(text): """ Convert str into a List, seperated by ',' :param text: Parsed text, called by :py:meth:`parse.Parser.parse()`. :return: List instance (List), created from parsed text """ return text.split(",") def parse_dic(text): """ Convert str into a Dictionary, seperated by ',' :param text: Parsed text, called by :py:meth:`parse.Parser.parse()`. :return: Dictionary instance (Dictionary), created from parsed text """ return eval(text) # -- REGISTER: User-defined type converter (parse_type). register_type(Number=parse_number) register_type(List=parse_list) register_type(Dic=parse_dic)
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 register_type 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}) 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}"')
""" Captures the ordinal indicator of a number. Use this type by annotating your variable with the ``ordinal_indicator``. **Usage** :: @then('the user chooses the {option:d}{ordinal:ordinal_indicator}') def test_method(context, option, ordinal): pass """ return text.strip() register_type(ordinal_indicator=ordinal_indicator_option) @parse.with_pattern(r"|".join( list(map(lambda x: x.replace("_", " ").title(), Keys.__dict__)))) def parse_pressable_key(text): """ Enables the use of browser Keys in sentences. The value of the property is converted to a human readable version for consumption, and then exrapolated for use in the statement Use this type by annotating your variable with the ``pressable_key``. **Usage** :: @then('the user presses {key:pressable_key}')
inside installroot) with the default values overriden with what is in the context table. """ check_context_table(context, ["key", "value"]) write_repo_config(context, repo, repo_config(repo, dict(context.table))) @parse.with_pattern(r"http|https|ftp") def parse_repo_type(text): if text in ("http", "https", "ftp"): return text assert False behave.register_type(repo_type=parse_repo_type) @behave.step( "I make packages from repository \"{repo}\" accessible via {rtype:repo_type}" ) def make_repo_packages_accessible(context, repo, rtype): """ Starts a new HTTP/FTP server at the repository's location and saves its port to context. """ repo_info = get_repo_info(context, repo) server_dir = repo_info.path host, port = start_server_based_on_type(context, server_dir, rtype) context.dnf.ports[repo] = port
from behave import register_type from .utils import parse_py from azove import leaf register_type(Py=parse_py) @given(u'nibbles: {src_nibbles:Py}') # noqa def step_impl(context, src_nibbles): context.src_nibbles = src_nibbles @when(u'append a terminator') # noqa def step_impl(context): context.src_nibbles.append(trie.NIBBLE_TERMINATOR) @when(u'packed to binary') # noqa def step_impl(context): context.dst_binary = trie.pack_nibbles(context.src_nibbles) @then(u'in the binary, the first nibbles should be {first_nibble:Py}') # noqa def step_impl(context, first_nibble): assert ord(context.dst_binary[0]) & 0xF0 == first_nibble << 4 context.prefix_nibbles_count = 1 @then(u'the second nibbles should be {second_nibble:Py}') # noqa def step_impl(context, second_nibble):
# # parse_positive_integer(text) # Converts `text` from `unicode` to `str` (python 2) # @with_pattern(r'[1-9]\d*') def parse_positive_integer(text): assert type(text) is unicode v = int(text) assert v > 0 return v register_type(PositiveInteger = parse_positive_integer) # # parse_string(text) # Converts `text` from `unicode` to `str` (python 2) # if is_python_2: def parse_string(text): assert type(text) is unicode return str(text) else: def parse_string(text): assert (type(text) is str)
"version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.6" } }, "nbformat": 4, "nbformat_minor": 2 } """ behave.register_type(CSV=util.parse_csv) def _check_service_up(context: behave.runner.Context, url: str, string: str): """Check that a service is running and responding appropriately. Args: context: Test context. url: Url that is to be read. string: The string to be checked. """ response = requests.get(url, timeout=1.0) response.raise_for_status() data = response.text
from behave import register_type import parse @parse.with_pattern(r"(accepted|confirmed|cancelled|dismissed)") def prompt_action_type(text): """ Captures the alert type. Use this type by annotating your variable with the ``prompt_action``. **Usage** :: @then('the prompt is {action:prompt_action}') def test_method(context, action): pass """ return text.strip() register_type(prompt_action=prompt_action_type)