Example #1
0
    def decorator(func):
        """The real decorator."""

        if ALOE_INSTALLED:
            aloe_step(step_sentence)(func)
        if BEHAVE_INSTALLED:
            use_step_matcher('re')
            behave_step(step_sentence)(func)

        return func
Example #2
0
    def build_step_func(self):
        decorator = DECORATORS_BY_TYPES[self.type_]
        use_step_matcher('re')

        @decorator(self.sentence)
        def behave_step(context, *args, **kwargs):
            self.context = context
            # args not used. Your regex must use named groups "(?P<name>...)"
            return self.step(**kwargs)

        return behave_step
Example #3
0
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

"""
"""

import os
import sys
from behave import use_step_matcher, given, when, then

if sys.version_info < (3, 0):
    from urllib2 import urlopen
else:
    from urllib.request import urlopen

use_step_matcher("re")


@given(u'data is available')
def step_impl_data_available(context):
    if not os.path.exists('/tmp/SVM02_npp_d20150311_t1122204_e1123446_b17451_c20150311113206961730_cspp_dev.h5'):
        response = urlopen('https://zenodo.org/record/16355/files/'
                           'SVM02_npp_d20150311_t1122204_e1123446_b17451_c20150311113206961730_cspp_dev.h5')
        with open('/tmp/SVM02_npp_d20150311_t1122204_e1123446_b17451_c20150311113206961730_cspp_dev.h5',
                  mode="w") as fp:
            fp.write(response.read())
    if not os.path.exists('/tmp/GMTCO_npp_d20150311_t1122204_e1123446_b17451_c20150311113205873710_cspp_dev.h5'):
        response = urlopen('https://zenodo.org/record/16355/files/'
                           'GMTCO_npp_d20150311_t1122204_e1123446_b17451_c20150311113205873710_cspp_dev.h5')
        with open('/tmp/GMTCO_npp_d20150311_t1122204_e1123446_b17451_c20150311113205873710_cspp_dev.h5',
                  mode="w") as fp:
Example #4
0
    dialog = get_dialog(context, dialog_title)
    dialog_shadow = expand_shadow_root(context, dialog)
    input_element = None
    timeout = time() + int(seconds)
    while time() < timeout:
        input_element = get_input_element_from_form(context, dialog_shadow, field_name)
        if input_element.is_displayed():
            return True
        sleep(1)
    assert input_element, "Could not find field %s after %s seconds" % field_name
    assert False, "Field %s did not become visible after %s seconds" \
                  % (field_name, seconds)


#@step(u'I click the "{button_name}" button in the "{dialog_title}" dialog')
use_step_matcher("re")
@step(u'I click the "(?P<button_name>[A-Za-z0-9_\. ]+)" button in the "(?P<dialog_title>[A-Za-z ]+)" dialog')
def click_button_in_dialog(context, button_name, dialog_title):
    dialog = get_dialog(context, dialog_title)
    assert dialog, "Could not find dialog with title %s" % dialog_title
    dialog_shadow = expand_shadow_root(context, dialog)
    button = get_button_from_form(context, dialog_shadow, button_name, tag_name='paper-button:not([hidden]), paper-item:not([hidden])')
    clicketi_click(context, button)


use_step_matcher("parse")
@step(u'I click the toggle button with id "{btn_id}" in the "{dialog}" dialog')
def click_toggle_button_in_dialog(context, btn_id, dialog):
    open_dialog = get_dialog(context, dialog)
    assert open_dialog, "Could not find dialog with title %s" % dialog
    dialog_shadow = expand_shadow_root(context, open_dialog)
Example #5
0
# limitations under the License.
import behave
import simplejson as json
import staticconf.testing
from clusterman_metrics import APP_METRICS
from clusterman_metrics import SYSTEM_METRICS
from moto import mock_autoscaling
from moto import mock_ec2
from moto import mock_sqs

from clusterman.aws.client import autoscaling
from clusterman.aws.client import ec2
from clusterman.config import CREDENTIALS_NAMESPACE
from clusterman.monitoring_lib import yelp_meteorite

behave.use_step_matcher('re')
BEHAVE_DEBUG_ON_ERROR = False


@behave.fixture
def patch_meteorite(context):
    if yelp_meteorite:
        with yelp_meteorite.testcase():
            yield
    else:
        yield


@behave.fixture
def setup_configurations(context):
    boto_config = {
before_feature(context, feature), after_feature(context, feature)
    These run before and after each feature file is exercised.
    The feature passed in is an instance of Feature.
before_tag(context, tag), after_tag(context, tag)
"""
import json
import platform
import os
import re
import requests
import uuid
from behave import use_step_matcher
from features.support import Config

# -- SETUP: Use cfparse as default matcher
use_step_matcher('cfparse')
with_JIRA = False


def before_all(context):
    global with_JIRA
    # Set Config File to Data variable and check if we are running locally or in Jenkins
    try:
        # We set the data for the Autoamtion using the ENV variable passed Thru jenkins.
        context.data = Config.Config(str(os.environ['ENV'])).save_to_var()
        # We turn the API on.
        with_JIRA = True
        # If this fails we set it to a hardcoded Value, that can be changed according to your needs.
    except KeyError:
        context.data = Config.Config('DEV').save_to_var()
    if with_JIRA:
Example #7
0
from behave import given, when, then, use_step_matcher

try:
    from unittest.mock import patch
except ImportError:
    from mock import patch


use_step_matcher("re")


@given("a dataset is available")  # noqa: F811
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    from satpy import Scene
    from xarray import DataArray
    scn = Scene()
    scn["MyDataset"] = DataArray([[1, 2], [3, 4]], dims=['y', 'x'])
    context.scene = scn


@when("the show command is called")  # noqa: F811
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    with patch('trollimage.xrimage.XRImage.show') as mock_show:
        context.scene.show("MyDataset")
        mock_show.assert_called_once_with()
Example #8
0
import json
import behave
from behave import when, given

from liveblog_helpers import liveblog_request
from liveblog_fixtures import upload_fixtures


# ============================================================================
behave.use_step_matcher('re')
METHODS_RE = '(?P<method>GET|POST|PUT|PATCH|DELETE)'


@when(METHODS_RE + ' (?P<uri>.*) with headers')
def step_impl_request_with_headers(context, method, uri):
    headers = json.loads(context.text)
    liveblog_request(context, method, uri, headers=headers)


@when(METHODS_RE + ' (?P<uri>.*)')
def step_impl_request(context, method, uri):
    liveblog_request(context, method, uri)


# ============================================================================
behave.use_step_matcher('parse')


@given('{number:n} fixtures')
def step_imp_fixtures(context, number):
    upload_fixtures(context, number)
Example #9
0
from behave import step

from iotqatools.helpers_utils import *
from iotqatools.cb_v2_utils import CB
from iotqatools.mongo_utils import Mongo

from tools.properties_config import Properties  # methods in properties class
from tools.NGSI_v2 import NGSI

# constants
CONTEXT_BROKER_ENV = u'context_broker_env'
MONGO_ENV = u'mongo_env'

properties_class = Properties()

behave.use_step_matcher("re")
__logger__ = logging.getLogger("steps")

# ------------------ create_entities ------------------------------------------------


@step(u'a definition of headers')
def definition_of_headers(context):
    """
    configuration of  different header (service, service path, Content-Type, Accept, etc)
    :param context: It’s a clever place where you and behave can store information to share around. It runs at three levels, automatically managed by behave.
    """
    __logger__.info("Reading CB properties from properties.json file...")
    props = properties_class.read_properties()[CONTEXT_BROKER_ENV]
    context.cb = CB(protocol=props["CB_PROTOCOL"],
                    host=props["CB_HOST"],
"""
SetUp environment for BDD tests
"""
from behave import use_step_matcher

# Select default step matcher, possible variants are: ['re', 'parse', 'cfparse']
# NOTE: PyCharm understands only 're'
#   issue: https://youtrack.jetbrains.com/issue/PY-14532
use_step_matcher('re')
Example #11
0
    add_form = get_add_form(context, title) if form_type == 'add' else \
        get_edit_form(context, title)
    add_form_shadow = expand_shadow_root(context, add_form)
    form_input = None
    timeout = time() + int(seconds)
    while time() < timeout:
        form_input = get_input_element_from_form(context, add_form_shadow,
                                                 field_name)
        if form_input and form_input.is_displayed():
            return True
        sleep(1)
    assert form_input, "Could not find field %s after %s seconds" % (
        field_name, seconds)


use_step_matcher("re")


@step(
    u'I set the "(?P<script_input>[A-Za-z ]+)" script "(?P<script>[A-Za-z0-9 \-/,._#!<>+:=\{\}@%\*\"\n~\\\\\[\]]+)"'
)
def set_script_to_field(context, script_input, script):
    form = get_add_form(context, 'machine')
    form_shadow = expand_shadow_root(context, form)
    form_input = get_input_element_from_form(context, form_shadow,
                                             script_input.lower())
    n = 70
    script.replace('\"', '"')
    chunks = [script[i:i + n] for i in xrange(0, len(script), n)]
    for chunk in chunks:
        if '\\n' in chunk:
Example #12
0
def call(context, url):
    """Send message to microservice."""
    request = {
        'message': {
            'query_graph': context.query_graph,
            'results': getattr(context, 'results', []),
        },
        'options': getattr(context, 'options', {})
    }
    if 'knowledge_graph' in context:
        request['message']['knowledge_graph'] = context.knowledge_graph
    context.response = requests.post(url, json=request)
    context.response_json = context.response.json()


use_step_matcher('re')

# This is much too generic a pattern matching template which
# will override any other @given in the steps.py file which starts with the English article 'a'
# so we comment it out!
#
#@given('a (?P<key>.*)')
#def append_to_list(context, key):
#   """Append element to list in context.
#
#    Create the list if it does not exist.
#    """
#    key = key.replace(' ', '_') + 's'
#    value = getattr(context, key, [])
#    value.append(json.loads(context.text))
#    setattr(context, key, value)
Example #13
0
    add_form = get_add_form(context, title) if form_type == 'add' else \
        get_edit_form(context, title)
    add_form_shadow = expand_shadow_root(context, add_form)
    form_input = None
    timeout = time() + int(seconds)
    while time() < timeout:
        form_input = get_input_element_from_form(context, add_form_shadow, field_name)
        if form_input.is_displayed():
            return True
        sleep(1)
    assert form_input, "Could not find field %s after %s seconds" % field_name
    assert False, "Field %s did not become visible after %s seconds" \
                  % (field_name, seconds)


use_step_matcher("re")
@step(u'I set the value "(?P<value>[A-Za-z0-9 \-/,._#!<>+:=\{\}@%\*\"\n~\\\\]+)" to field "(?P<name>[A-Za-z ]+)" in the "(?P<title>[A-Za-z]+)" (?P<form_type>[A-Za-z]+) form')
def set_value_to_field(context, value, name, title, form_type):
    if context.mist_config.get(value):
        value = context.mist_config.get(value)
    elif "random" in value:
        value_key = value
        value = value.replace("random", str(randrange(1000)))
        context.mist_config[value_key] = value
    form = get_add_form(context, title) if form_type == 'add' else \
        get_edit_form(context, title)
    form_shadow = expand_shadow_root(context, form)
    form_input = get_input_element_from_form(context, form_shadow, name.lower())
    assert form_input, "Could not set value to field %s" % name
    clear_input_and_send_keys(form_input, value)
from behave import use_step_matcher, step

from acceptance.page_model.change_user_page import ChangeUserPage

use_step_matcher('re')


@step('I click on SAVE button again')
def step_impl(context):
    page = ChangeUserPage(context)
    page.save_button.click()
Example #15
0
        assert premis_event is not None
        # <premis:eventDetail>program=gpg (GPG); version=1.4.16; python-gnupg;
        # version=0.4.0</premis:eventDetail>
        premis_event_detail = premis_event.find(
            'mets:xmlData/premis:event/premis:eventDetail',
            context.am_user.mets.mets_nsmap).text
        assert 'GPG' in premis_event_detail
        assert 'version=' in premis_event_detail
        premis_event_od_note = premis_event.find(
            'mets:xmlData/premis:event/premis:eventOutcomeInformation/'
            'premis:eventOutcomeDetail/premis:eventOutcomeDetailNote',
            context.am_user.mets.mets_nsmap).text.strip()
        assert 'Status="encryption ok"' in premis_event_od_note


use_step_matcher('re')


@then(
    'the (?P<aip_description>.*)pointer file contains a mets:transformFile element'
    ' for the encryption event')
def step_impl(context, aip_description):
    """Makes the following assertions about the first (and presumably only)
    <mets:file> element in the AIP's pointer file:
    1. the xlink:href attribute's value of <mets:FLocat> is a path with
       extension .gpg
    2. the decompression-type <mets:transformFile> has TRANSFORMORDER 2
    3. there is a new <mets:transformFile> element for the decryption event
       needed to get at this AIP.
    4. <premis:compositionLevel> incremented
    5. <premis:inhibitors> added
Example #16
0
from behave import given, then, when, use_step_matcher


use_step_matcher("re")

@given('we have behave "(?P<name>\w+)"')  # noqa
def step_impl(context, name):  # noqa
    print(name)


@when('we implement test number "(?P<numeral>\d+)"')  # noqa
def step_impl(context, numeral):  # noqa
    try:
        numeral = int(numeral)
        print(numeral)
    except ValueError:
        context.failed = True


@when('we implement test number "(?P<word>\w+)"')  # noqa
def step_impl(context, word):  # noqa
    print(word)
    assert type(word) is str


use_step_matcher("parse")


@when('we run test number "{value:d}"')  # noqa
def step_impl(context, value):  # noqa
    print(value)
import behave
import logging
from behave import step

from iotqatools.mongo_utils import Mongo

from tools.properties_config import Properties
from tools.NGSI_v2 import NGSI

# constants
MONGO_ENV = u'mongo_env'

properties_class = Properties()

behave.use_step_matcher("re")
__logger__ = logging.getLogger("steps")


# ------------------ create subscriptions ------------------------------------------------

@step(u'properties to subscriptions')
def properties_to_subscriptions(context):
    """
    properties to subscription (previous step to create or update subcription request)
    :param context: It’s a clever place where you and behave can store information to share around. It runs at three levels, automatically managed by behave.
    """
    __logger__.info("Define the properties used in the subcription request")
    context.cb.properties_to_subcription(context)

Example #18
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
Example #19
0
# -*- coding: utf--8 -*-
# -- SETUP: Use cfparse as default matcher
from behave import use_step_matcher
use_step_matcher("cfparse")