import time import itertools from pytest_bdd import given from pytest_bdd import parsers, when, then from tests.gui.conftest import WAIT_BACKEND, SELENIUM_IMPLICIT_WAIT, WAIT_FRONTEND from tests.gui.utils.generic import repeat_failed, implicit_wait, redirect_display __author__ = "Bartosz Walkowicz" __copyright__ = "Copyright (C) 2017 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" @when(parsers.parse('user of {browser_id} sees that provider popup for provider ' 'named "{provider}" has appeared on world map')) @then(parsers.parse('user of {browser_id} sees that provider popup for provider ' 'named "{provider}" has appeared on world map')) @repeat_failed(timeout=WAIT_FRONTEND) def assert_provider_popup_has_appeared_on_map(selenium, browser_id, provider, oz_page): driver = selenium[browser_id] err_msg = 'Popup displayed for provider named "{}" ' \ 'instead of "{}"' prov = oz_page(driver)['world map'].get_provider_with_displayed_popup() assert provider == prov.name, err_msg.format(prov.name, provider) @when(parsers.re(r'user of (?P<browser_id>.+?) clicks on the ' r'"(?P<btn>Go to your files|copy hostname)" button in ' r'"(?P<provider>.+?)" provider\'s popup displayed on world map'))
yield b b.quit() # Given steps @given('the DuckDuckGo home page is displayed') def ddg_home(browser): browser.get(DUCKDUCKGO_HOME) # When steps @when(parsers.parse('the user searches for "{text}"')) @when(parsers.parse('the user searches for the phrase:\n"""{text}"""')) def search_phrase(browser, text): search_input = browser.find_element_by_name('q') search_input.send_keys(text + Keys.RETURN) # Then steps @then(parsers.parse('one of the results contains "{phrase}"')) def results_have_one(browser, phrase): xpath = "//div[@id='links']//*[contains(text(), '%s')]" % phrase results = browser.find_elements_by_xpath(xpath) assert len(results) > 0
@given("an api to an empty MediaWiki") def empty_mediawiki(mediawiki): mediawiki.clear() @given("an empty wiki-scripts database") def empty_wsdb(db): # TODO: the db is currently function-scoped, so clearing is useless # db.clear() pass @when("I synchronize the wiki-scripts database") def sync_page_tables(mediawiki, db): db.sync_with_api(mediawiki.api, with_content=True) @when(parsers.parse("I create page \"{title}\"")) def create_page(mediawiki, title): # all pages are created as empty mediawiki.api.create(title, "", title) @when(parsers.re("I move page \"(?P<src_title>.+?)\" to \"(?P<dest_title>.+?)\"(?P<noredirect> without leaving a redirect)?")) def move_page(mediawiki, src_title, dest_title, noredirect): noredirect = False if noredirect is None else True mediawiki.api.move(src_title, dest_title, "moved due to BDD tests", noredirect=noredirect) def _get_content_api(api, title): result = api.call_api(action="query", titles=title, prop="revisions", rvprop="content|timestamp") page = list(result["pages"].values())[0] text = page["revisions"][0]["*"] timestamp = page["revisions"][0]["timestamp"] return text, timestamp, page["pageid"]
@when('we create a new document') def when_new_doc(template_dict): template_dict.clear() @when('it has timeBase <time_base>') def when_time_base(time_base, template_dict): template_dict['time_base'] = time_base @when('it has sequenceIdentifier <sequence_identifier>') def when_seq_id(sequence_identifier, template_dict): template_dict['sequence_identifier'] = sequence_identifier @when(parsers.parse('it has predefined sequenceNumber {sequence_number}')) def when_sequence_number(sequence_number, template_dict): template_dict['sequence_number'] = sequence_number @when('it has doc1 body begin time <doc1_begin>') def when_doc1_body_begin(doc1_begin, template_dict): template_dict['body_begin'] = doc1_begin @when('it has doc1 body end time <doc1_end>') def when_doc1_body_end(doc1_end, template_dict): template_dict['body_end'] = doc1_end @when('it has doc1 body duration <doc1_dur>')
from pytest_bdd import scenarios, given, when, then, parsers import pytest scenarios("features/writing_input.feature") @given("a Pwscf object") def empty_pwscf(): from pylada.espresso import Pwscf return Pwscf() @given(parsers.parse("mandatory attribute pwscf.system.ecutwfc is set to {value:f} {units:S}")) def set_ecutwfc(empty_pwscf, value, units): import quantities empty_pwscf.system.ecutwfc = value * getattr(quantities, units) @given(parsers.parse("pwscf.{namelist:w}.{attribute:w} is set to {value:f}")) def set_an_attribute0(empty_pwscf, namelist, attribute, value): # equivalent to pwscf.namelist.attribute = value # with namelist and attribute replaced by their values setattr(getattr(empty_pwscf, namelist), attribute, value) @when(parsers.parse("writing to {filename:S} without specifying a structure")) def writing_no_structure(empty_pwscf, tmpdir, filename): empty_pwscf.write(tmpdir.join(filename)) @then(parsers.parse("the file {filename:S} appears and can be read"))
__copyright__ = "Copyright (C) 2017 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" from itertools import izip import pytest from pytest_bdd import given, when, then, parsers from tests.gui.conftest import WAIT_BACKEND, SELENIUM_IMPLICIT_WAIT, WAIT_FRONTEND from tests.gui.utils.generic import (repeat_failed, implicit_wait, parse_seq, upload_file_path, transform) @when(parsers.parse('user of {browser_id} uses spaces select to change ' 'data space to "{space_name}"')) @then(parsers.parse('user of {browser_id} uses spaces select to change ' 'data space to "{space_name}"')) @repeat_failed(timeout=WAIT_BACKEND) def change_space_view_in_data_tab_in_op(selenium, browser_id, space_name, op_page): driver = selenium[browser_id] selector = op_page(driver).data.sidebar.space_selector selector.expand() selector.spaces[space_name].click() @when(parsers.re(r'user of (?P<browser_id>.*?) clicks the button ' r'from top menu bar with tooltip ' r'"(?P<tooltip>Create directory|Create file|Share element|' r'Edit metadata|Rename element|Change element permissions|'
return {} @given('A Hello World Flask-Wired Application') def hello_world_flask_wired_app(): from flask_wired import FlaskWired app = FlaskWired("hello_world") @app.route('/hello') def hello_world(): return "Hello, World!!!" return app @when(parsers.parse('Accessing {endpoint}')) def http_get_endpoint(scenario_context, hello_world_flask_wired_app, endpoint): client = hello_world_flask_wired_app.test_client() response = client.get(endpoint) scenario_context['response'] = response @then(parsers.parse('I get a {expected_status:d} Response')) def assert_response_status(scenario_context, expected_status): assert scenario_context['response'].status_code == expected_status @then(parsers.parse('response body is {body}')) def assert_response_body(scenario_context, body): assert str(scenario_context['response'].data, 'utf-8') == body
@pytest.mark.xfail @scenario("Keyboard.feature", "Russian comma") @pytest.mark.p2 @pytest.allure.severity(pytest.allure.severity_level.MINOR) @pytest.allure.feature("Keyboard input", "Data handling") def test_comma_separation(browser): pass @given("I am russian matematician") def russian_matematician(browser): browser.open_page(constants.PAGE_URL) pass @when(parsers.parse("I type {expr}")) def type_simple_expression(browser, communicator, expr): browser.type_text(constants.INPUT_ELEMENT, expr) @then(parsers.parse("I count it")) def count_it(browser): browser.click(constants.RESULT_ELEMENT) @then(parsers.parse("see {result} on screen")) def check_result(browser, result): result = float(result) browser.check_equality(constants.INPUT_ELEMENT, result)
import time from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from function import (wait_on_element, is_element_present, wait_on_element_disappear, attribute_value_exist) from pytest_bdd import (given, scenario, then, when, parsers) @scenario( 'features/NAS-T962.feature', 'Verify Active Directory works after failover with new system dataset') def test_setting_up_active_directory_with_the_new_system_dataset(driver): """Verify Active Directory works after failover with new system dataset.""" @given(parsers.parse('the browser is open navigate to "{nas_url}"')) def the_browser_is_open_navigate_to_nas_url(driver, nas_url): """the browser is open navigate to "{nas_url}".""" if nas_url not in driver.current_url: driver.get(f"http://{nas_url}/ui/sessions/signin") time.sleep(3) @when(parsers.parse('If login page appear enter "{user}" and "{password}"')) def if_login_page_appear_enter_root_and_password(driver, user, password): """If login page appear enter "{user}" and "{password}".""" if not is_element_present(driver, '//mat-list-item[@ix-auto="option__Dashboard"]'): assert wait_on_element(driver, 1, 10, '//input[@data-placeholder="Username"]') driver.find_element_by_xpath(
import uuid from pytest_bdd import when, parsers from selene.api import s, browser, have @when(parsers.parse('I create account with random email')) def create_account_with_email(): email = generate_email() s('#email_create').set(email) s('#SubmitCreate').click() @when( parsers.parse( 'I fill required information {first_name}, {last_name}, {password}, {firstname}, {lastname},' '{address1}, {city}, {state}, {postcode}, {mobile}')) def fill_in_required_account_info(first_name, last_name, password, firstname, lastname, address1, city, state, postcode, mobile): s('#customer_firstname').set(first_name) s('#customer_lastname').set(last_name) s('#passwd').set(password) s('#passwd').set(password) s('#firstname').set(firstname) s('#lastname').set(lastname) s('#address1').set(address1) s('#city').set(city) s('#uniform-id_state').click() browser.all('option').element_by(have.text(state)).click() s('#postcode').set(postcode) s('#phone_mobile').set(mobile)
from ui_tests.caseworker.pages.users_page import UsersPage from ui_tests.caseworker.pages.roles_pages import RolesPages import tests_common.tools.helpers as utils scenarios("../features/roles.feature", strict_gherkin=False) @when("I go to manage roles") def go_to_manage_roles(driver): user_page = UsersPage(driver) user_page.click_on_manage_roles() @when( parsers.parse( 'I add a new role called "{role_name}" with permission to "{permissions}" and set status to "{status}"' )) def add_a_role(driver, role_name, permissions, status, context): roles_page = RolesPages(driver) roles_page.click_add_a_role_button() if role_name == " ": context.role_name = role_name else: context.role_name = f"{role_name} {utils.get_formatted_date_time_y_m_d_h_s()}"[: 25] roles_page.enter_role_name(context.role_name) roles_page.select_permissions(permissions) roles_page.select_statuses(status) Shared(driver).click_submit()
CONVERTERS = dict(criteria=str, occurrence=int) scenarios('../features/table_filter.feature', example_converters=CONVERTERS) # Given Steps @given("the task table is displayed") def go_to_task_page(driver): driver.get(TASK_TABLE_URL) # When Steps @when('i enter the task name as search <criteria>') @when('i enter the assignee name as search <criteria>') @when('i enter the task status as search <criteria>') @when('i enter an unavailable search <criteria>') @when(parsers.parse('i enter an unavailable search {criteria}')) def enter_task_name_as_search_criteria(driver, criteria): page = TaskFilter(driver) page.enter_search_criteria(search_criteria=criteria + Keys.RETURN) # Then Steps @then( 'the table should contains only the task matching the search <criteria> name' ) @then( parsers.parse( 'the table should contains only the task matching the search {criteria} name' )) def check_table_row_contains_selected_task(driver, criteria): search_result = None
tmp_memory[browser_id][items_type][item_name] = item time.sleep(1) times -= 1 def _not_in_sidebar_list(driver, items_names, items_type, items=None): items = items if items else _get_items_from_sidebar_list(driver, items_type) for item_name in parse_seq(items_names): item = items.get(item_name) if item: return False return True @when(parsers.parse('user of {browser_id} selects "{item_name}" ' 'from {item_type} sidebar list')) @then(parsers.parse('user of {browser_id} selects "{item_name}" ' 'from {item_type} sidebar list')) def select_item_from_sidebar_list(selenium, browser_id, item_name, item_type, tmp_memory): driver = selenium[browser_id] _select_items_from_sidebar_list(driver, browser_id, tmp_memory, item_name, item_type) @when(parsers.parse('user of {browser_id} clicks on settings icon displayed ' 'for "{item_name}" item on the {item_type} sidebar list')) @then(parsers.parse('user of {browser_id} clicks on settings icon displayed ' 'for "{item_name}" item on the {item_type} sidebar list')) def click_settings_icon_for_item(selenium, browser_id, item_name, item_type): driver = selenium[browser_id]
""" __author__ = "Jakub Kudzia" __copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" from tests.utils.acceptance_utils import list_parser from tests.utils.utils import set_dns from tests.utils.user_utils import create_user, delete_user, get_id from tests.utils.space_utils import delete_space from environment import docker from pytest_bdd import given, parsers @given(parsers.parse("users {users} register with passwords {passwords}")) def register_users(users, passwords, context, onedata_environment, request): set_dns(onedata_environment) users = list_parser(users) passwords = list_parser(passwords) onepanel = onedata_environment['onepanel_nodes'][0].split('@')[1] if not hasattr(context, "users"): context.users = {} for user_name, password in zip(users, passwords): user = create_user(user_name, password, onepanel) user.set_oz_domain(onedata_environment) context.users[user_name] = user def fin():
matcher = partial(matcher, match(arg, *args[i + 1:])) break return matcher() @then( parsers. re("allure report has result for (?:\")(?P<scenario_name>[\\w|\\s|,]*)(?:\") scenario" )) def match_scenario(allure_report, context, scenario_name): matcher = partial(match, has_test_case, scenario_name) assert_that(allure_report, matcher()) context['scenario'] = matcher @then(parsers.parse("this {item:w} has {status:w} status")) def item_status(allure_report, context, item, status): context_matcher = context[item] matcher = partial(context_matcher, with_status, status) assert_that(allure_report, matcher()) @then( parsers.re("this (?P<item>\\w+) " "has parameter (?:\")(?P<param_name>[\\w|\\s]*)(?:\") " "with value (?:\")(?P<param_value>[\\w|\\s]*)(?:\")")) def item_parameter(allure_report, context, item, param_name, param_value): context_matcher = context[item] matcher = partial(context_matcher, has_parameter, param_name, param_value) assert_that(allure_report, matcher())
@scenario(u'Steps in .py file have unicode') def test_steps_in_py_file_have_unicode(): pass pattern = r"(?P<content>'\w+')" @pytest.fixture def string(): """String fixture.""" return {'content': ''} @given(parsers.parse(u"у мене є рядок який містить '{content}'")) def there_is_a_string_with_content(content, string): """Create string with unicode content.""" string['content'] = content @given("there is an other string with content 'якийсь контент'") def there_is_an_other_string_with_content(string): """Create other string with unicode content.""" string['content'] = u"с каким-то контентом" @then("I should see that the other string equals to content 'якийсь контент'") def assert_that_the_other_string_equals_to_content(string): """Assert that the other string equals to content.""" assert string['content'] == u"с каким-то контентом"
pass @given("I have a first <first> contact") def have_a_first_contact(contactbook, first): contactbook.add(first, "000") return first @given("I have a second <second> contact") def have_a_second_contact(contactbook, second): contactbook.add(second, "000") return second @then("the output contains <listed_contacts> contacts") def outputcontains(listed_contacts, capsys): expected_list = "".join([f"{c} 000\n" for c in listed_contacts.split(",")]) out, _ = capsys.readouterr() assert out == expected_list @given("I have a contact book", target_fixture="contactbook") def contactbook(): return contacts.Application() @given(parsers.parse("I have a \"{contactname}\" contact")) def have_a_contact(contactbook, contactname): contactbook.add(contactname, "000") @when(parsers.parse("I run the \"{command}\" command")) def runcommand(contactbook, command): contactbook.run(command)
"""Steps for features of Onezone login page. """ __author__ = "Jakub Liput" __copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" from pytest_bdd import given, when, then, parsers from tests.gui.utils.generic import parse_seq @then(parsers.parse('user of {browser_id} should see login button ' 'for {provider_name}')) def login_provider_buttons(selenium, browser_id, provider_name): driver = selenium[browser_id] assert driver.find_element_by_css_selector( '.login-box a.login-icon-box.{name}'.format(name=provider_name) ), 'login for provider {} not found'.format(provider_name) def _click_login_provider_button(driver, provider_name): driver.find_element_by_css_selector( '.login-box a.login-icon-box.{:s}'.format(provider_name) ).click() @given(parsers.re('users? of (?P<browser_id_list>.*) clicked on the ' '"(?P<provider_name>.*)" login button')) def g_click_login_provider_button(selenium, browser_id_list, provider_name): for browser_id in parse_seq(browser_id_list): driver = selenium[browser_id]
'clickable') driver.find_element_by_xpath( '//mat-list-item[@ix-auto="option__Shares"]').click() assert wait_on_element(driver, 5, '//div[contains(.,"Shares")]') assert wait_on_element( driver, 7, '//mat-card[contains(.,"Windows (SMB) Shares")]//button[contains(.,"Add")]', 'clickable') driver.find_element_by_xpath( '//mat-card[contains(.,"Windows (SMB) Shares")]//button[contains(.,"Add")]' ).click() @then( parsers.parse( 'Set Path to the LDAP dataset "{path}", Input "{smbname}" as name, Click to enable, Input "{description}" as description, and Click Summit' )) def set_path_to_the_ldap_dataset_mnttankwheel_dataset_input_wheelsmbshare_as_name_click_to_enable_input_test_wheel_smb_share_as_description_and_click_summit( driver, path, smbname, description): """Set Path to the LDAP dataset {path}, Input {smbname} as name, Click to enable, Input {description} as description, and Click Summit.""" assert wait_on_element(driver, 5, '//h3[contains(text(),"Add SMB")]') global smb_path smb_path = path assert wait_on_element(driver, 5, '//input[@ix-auto="input__path"]', 'inputable') driver.find_element_by_xpath('//input[@ix-auto="input__path"]').clear() driver.find_element_by_xpath('//input[@ix-auto="input__path"]').send_keys( path) assert wait_on_element(driver, 5, '//input[@ix-auto="input__Name"]', 'inputable') driver.find_element_by_xpath('//input[@ix-auto="input__Name"]').clear()
r'(?P<path>.+?) concatenated with received (?P<item>.*)')) @then(parsers.re(r'user of (?P<browser_id>.*?) changes webapp path to ' r'(?P<path>.+?) concatenated with received (?P<item>.*)')) def change_app_path_with_recv_item(selenium, browser_id, path, tmp_memory, item): driver = selenium[browser_id] base_url = parse_url(driver.current_url).group('base_url') item = tmp_memory[browser_id]['mailbox'][item.lower()] url = '{base_url}{path}/{item}'.format(base_url=base_url, path=path, item=item) driver.get(url) @when(parsers.parse('user of {browser_id} copies url ' 'from browser\'s location bar')) @then(parsers.parse('user of {browser_id} copies url ' 'from browser\'s location bar')) def copy_site_url(selenium, browser_id, displays, clipboard): driver = selenium[browser_id] clipboard.copy(driver.current_url, display=displays[browser_id]) @when(parsers.parse('user of {browser_id} opens copied URL ' 'in browser\'s location bar')) @then(parsers.parse('user of {browser_id} opens copied URL ' 'in browser\'s location bar')) def open_site_url(selenium, browser_id, displays, clipboard): driver = selenium[browser_id] driver.get(clipboard.paste(display=displays[browser_id]))
import logging _logger = logging.getLogger(__name__) scenarios('discovery.feature') @given('a client listens for discovery events') @sync async def discovery_events_subscribed(event_bus_connection): result = await event_bus_connection.send(method='subscribe', params={'category': 'discovery'}) assert result is True @when(parsers.parse('a {device_type} {name} {action} the network')) def device_appears_or_leaves(test_context, name, action): assert action in ('appears on', 'leaves') if action == 'appears on': descriptor = create_fake_device(name) test_context.add_device_to_network(name, descriptor, notify=True) else: test_context.remove_device_to_network(name, notify=True) @when('the client unsubscribes for discovery events') @sync async def unsubscribe_discovery_events(event_bus_connection): result = await event_bus_connection.send(method='unsubscribe', params={'category': 'discovery'}) assert result is True
given, then, when, ) try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin #################### # basic @when(parse('I wait for {timeout:d} seconds')) def wait_for_timeout(browser, timeout): import time time.sleep(timeout) @when(parse('I show the element with id "{id}"')) def show_element_by_id(browser, id): assert browser.find_by_id(id) browser.execute_script('document.getElementById("%s").style.display="inline";' % id) @when(parse('I hide the element with id "{id}"')) def hide_element_by_id(browser, id): assert browser.find_by_id(id) browser.execute_script('document.getElementById("%s").style.display="none";' % id)
DocumentGradingPage(driver).confirm_upload_document("no") @when("I see ECJU helpline details") def ecju_helpline(driver): assert DocumentGradingPage(driver).get_ecju_help() @when("I select a valid missing document reason") def select_missing_document_reason(driver): DocumentGradingPage(driver).select_valid_missing_document_reason() functions.click_submit(driver) @when( parsers.parse( 'I see "{expected_count:d}" documents ready to be included in the response' )) def verify_upload_document_count(driver, expected_count): items = RespondToEcjuQueryPage(driver).get_uploaded_document_items() assert len(items) == expected_count @when(parsers.parse('I delete document "{item_index:d}" from the response')) def delete_uploaded_document_and_submit(driver, item_index): document = RespondToEcjuQueryPage( driver).get_uploaded_documents_delete_links()[item_index - 1] driver.execute_script("arguments[0].scrollIntoView();", document) driver.execute_script("arguments[0].click();", document) functions.click_submit(driver)
__author__ = "Jakub Kudzia" __copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" from tests.utils.space_utils import unsupport_space from tests.utils.acceptance_utils import list_parser from tests.utils.space_utils import (create_space, support_space, request_support, invite_to_space, join_space, remove_user, delete_space, assign_privileges) from pytest_bdd import parsers, then, when @when(parsers.parse('{user} creates spaces {spaces}')) def spaces_creation(user, spaces, onedata_environment, context): spaces = list_parser(spaces) user = context.get_user(user) for space in spaces: space_id = create_space(user, space) user.spaces.update({space: space_id}) user.created_spaces.update({space: space_id}) @when(parsers.parse('{user} gets token to support spaces {spaces}')) def request_spaces_support(user, spaces, onedata_environment, context): spaces = list_parser(spaces) user = context.get_user(user) for space in spaces: token = request_support(user, space)
def you_see_the_dashboard_click_network_on_the_side_menu(driver): """you see the dashboard click Network on the side menu.""" assert wait_on_element(driver, 10, '//span[contains(.,"Dashboard")]') assert wait_on_element(driver, 10, '//mat-list-item[@ix-auto="option__Network"]', 'clickable') driver.find_element_by_xpath('//mat-list-item[@ix-auto="option__Network"]').click() @when('the Network page will open, click Global Configuration Settings') def the_network_page_will_open_click_global_configuration_settings(driver): """the Network page will open, click Global Configuration Settings.""" assert wait_on_element(driver, 10, '//h1[contains(.,"Network")]') assert wait_on_element(driver, 10, '//button[contains(.,"Settings")]', 'clickable') driver.find_element_by_xpath('//button[contains(.,"Settings")]').click() @then(parsers.parse('the global config page will open and input Nameservers "{nameserver1}", "{nameserver2}" and "{nameserver3}"')) def the_global_config_page_will_open_and_input_nameservers(driver, nameserver1, nameserver2, nameserver3): """the global config page will open and input Nameservers "{nameserver1}", "{nameserver2}" and "{nameserver3}".""" assert wait_on_element(driver, 10, '//h3[contains(.,"Global Configuration")]') assert wait_on_element(driver, 7, '//ix-input[contains(.,"Nameserver 3")]//input', 'inputable') driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 1")]//input').clear() driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 1")]//input').send_keys(nameserver1) driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 2")]//input').clear() driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 2")]//input').send_keys(nameserver2) driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 3")]//input').clear() driver.find_element_by_xpath('//ix-input[contains(.,"Nameserver 3")]//input').send_keys(nameserver3) @then(parsers.parse('input gateway "{gateway}" and an hostname and click SAVE')) def input_gateway_and_a_hostname_and_click_save(driver, nas_hostname, gateway): """input gateway "{gateway}" and an hostname and click SAVE."""
chdir_using_breadcrumbs from pytest_bdd import when, then, parsers from selenium.webdriver.support.ui import WebDriverWait as Wait from selenium.webdriver.support.expected_conditions import staleness_of def _get_share_from_shares_list(driver, name): return driver.find_elements_by_css_selector('ul.shares-list ' '.secondary-sidebar-item ' '.item-label[title="{name}"]' ''.format(name=name)) @when(parsers.parse('user of {browser_id} sees that share named ' '"{name}" has appeared in the shared list')) @then(parsers.parse('user of {browser_id} sees that share named ' '"{name}" has appeared in the shared list')) def is_present_on_share_list(selenium, browser_id, name): driver = selenium[browser_id] assert len(_get_share_from_shares_list(driver, name)) == 1, \ 'there is no {} on shares list'.format(name) @when(parsers.parse('user of {browser_id} sees that share named ' '"{name}" has disappeared from the shares list')) @then(parsers.parse('user of {browser_id} sees that share named ' '"{name}" has disappeared from the shares list')) def is_not_present_in_share_list(selenium, browser_id, name): driver = selenium[browser_id] assert len(_get_share_from_shares_list(driver, name)) == 0, \
from pytest_bdd import scenarios, given, when, then, parsers import pytest scenarios("features/writing_input.feature") @given("a Pwscf object") def empty_pwscf(): from pylada.espresso import Pwscf return Pwscf() @given( parsers.parse( "mandatory attribute pwscf.system.ecutwfc is set to {value:f} {units:S}" )) def set_ecutwfc(empty_pwscf, value, units): import quantities empty_pwscf.system.ecutwfc = value * getattr(quantities, units) @given(parsers.parse("pwscf.{namelist:w}.{attribute:w} is set to {value:f}")) def set_an_attribute0(empty_pwscf, namelist, attribute, value): # equivalent to pwscf.namelist.attribute = value # with namelist and attribute replaced by their values setattr(getattr(empty_pwscf, namelist), attribute, value) @when(parsers.parse("writing to {filename:S} without specifying a structure")) def writing_no_structure(empty_pwscf, tmpdir, filename): empty_pwscf.write(tmpdir.join(filename))
browser.fill('password', 'test_result') browser.find_by_xpath('//input[@type="submit"]')[0].click() @given('Jack has a username test_result & password test_result') def background(browser): User.objects.create_user(username='******', password='******') connect(browser) @given('Jack submitted lesson 1 having 2 questions') def _background(): mommy.make(Lesson, name='Lesson 1') @given(parsers.parse('{wrong:d} answers are wrong and {correct:d} answers are correct')) def submit_answers(wrong, correct): Result.objects.create( user_id=1, lesson_id=1, correct=correct, wrong=wrong ) @then('Jack should receive a list with his score (0%)') def jack_should_receive_the_message_score_0(browser): browser.visit('%s/results/%s' % (DOMAIN, 1)) scores = browser.find_by_xpath('//tbody/tr').text assert 'Lesson 1' in scores
@given("A Flask-Wired Application with config") def flask_wired_app(config): from flask_wired import create_app app = create_app(config) return app @given("A Flask-Wired Application with config multiple") def flask_wired_app_config_multiple(config_multiple): from flask_wired import create_app app = create_app(config_multiple) return app @when(parsers.parse('Accessing {endpoint}')) def http_get_endpoint(scenario_context, flask_wired_app, endpoint): client = flask_wired_app.test_client() response = client.get(endpoint) scenario_context['response'] = response @then(parsers.parse('I get a {expected_status:d} Response for {endpoint}')) def assert_response_status(scenario_context, endpoint, expected_status): assert scenario_context['response'][ endpoint].status_code == expected_status @then(parsers.parse('{endpoint} response body is {body}')) def assert_response_body(scenario_context, endpoint, body): assert str(scenario_context['response'][endpoint].data, 'utf-8') == body
driver = selenium[browser_id] _click_on_tab_in_main_menu_sidebar(driver, main_menu_tab) @when(parsers.re('users? of (?P<browser_id_list>.*) clicks on the ' '"(?P<main_menu_tab>.*)" tab in main menu sidebar')) @then(parsers.re('users? of (?P<browser_id_list>.*) clicks on the ' '"(?P<main_menu_tab>.*)" tab in main menu sidebar')) def wt_click_on_the_given_main_menu_tab(selenium, browser_id_list, main_menu_tab): for browser_id in parse_seq(browser_id_list): driver = selenium[browser_id] _click_on_tab_in_main_menu_sidebar(driver, main_menu_tab) @when(parsers.parse('user of {browser_id} refreshes Oneprovider site')) @then(parsers.parse('user of {browser_id} refreshes Oneprovider site')) def op_refresh_op_site_by_rm_hashtag(selenium, browser_id): driver = selenium[browser_id] op_url = parse_url(driver.current_url).group('base_url') driver.get(op_url) def _check_for_presence_of_item_in_table(driver, name, caption): table_elems = driver.find_elements_by_css_selector('table thead, ' 'table tbody') for thead, tbody in zip(table_elems[::2], table_elems[1::2]): th = thead.find_element_by_css_selector('th .item-label') if th.text.lower() == caption.lower(): items = tbody.find_elements_by_css_selector('.permissions-' 'table-row '
from pytest_bdd.parsers import parse from pytest_bdd import ( then, when, ) @then(parse('the title should contain the text "{text}"')) def the_title_should_contain_the_text(browser, text, splinter_selenium_implicit_wait): browser.wait_for_condition(lambda browser: text in browser.title, timeout=splinter_selenium_implicit_wait) @then( parse( 'I should see at least {count:d} elements with the css selector "{css}"' )) def should_see_at_least_count_elements_with_css(browser, css, count): element_count = len(browser.find_by_css(css)) assert element_count >= count, u'Element has at least that many counts' @then(parse('I should see {count:d} elements with the css selector "{css}"')) def should_see_count_elements_with_css(browser, css, count): element_count = len(browser.find_by_css(css)) assert element_count == count, u'Found %d (expected %d)' % (element_count, count) @then(
'args.feature', 'Executed with steps matching step definitons with arguments', ) def test_steps(): pass @given('I have a foo fixture with value "foo"') def foo(): return 'foo' @given('there is a list') def results(): return [] @when(parsers.parse('I append {n:d} to the list')) def append_to_list(results, n): results.append(n) @then('foo should have value "foo"') def foo_is_foo(foo): assert foo == 'foo' @then('the list should be [1, 2, 3]') def check_results(results): assert results == [1, 2, 3]
return self.response def post(self, *args, **kwargs): """ Submit a POST request to the server. """ self.response = self.test_client.post(*args, **kwargs) return self.response @pytest.fixture(name="test_session") def test_session(client): """ Set up a TestSession to hold state between steps. """ return TestSession(client) @given(parse('a user "{user_name}" exists')) def user_exists(session, user_name): user = create_user(session, user_name, TEST_PASSWORD) session.commit() return user @given(parse('I am logged in as "{user_name}"')) def login_user(session, test_session, user_name): user = get_user(session, user_name) test_session.login(user) return test_session
item = _get_tool_icon(driver, item_name, item_type, tool_type, items) if item: item.click() def _is_tool_icon_displayed(driver, item_name, item_type, tool_type): item = _get_tool_icon(driver, item_name, item_type, tool_type, css_path='.file-tool-{}'.format(tool_type)) if item: return 'visible-on-parent-hover-25p' in item.get_attribute('class') else: return False @when(parsers.parse('user of {browser_id} should not see {tool_type} ' 'icon for {item_type} named "{item_name}"')) @then(parsers.parse('user of {browser_id} should not see {tool_type} ' 'icon for {item_type} named "{item_name}"')) def is_tool_icon_hidden(selenium, browser_id, tool_type, item_name, item_type): driver = selenium[browser_id] Wait(driver, WAIT_FRONTEND).until_not( lambda _: _is_tool_icon_displayed(driver, item_name, item_type, tool_type), message='checking if {tool_type} icon for {item_type} named ' '"{item_name}" is hidden'.format(tool_type=tool_type, item_type=item_type, item_name=item_name) ) @when(parsers.parse('user of {browser_id} sees {tool_type} icon for '
pytest.skip('Inventory has been already used for a scenario') else: inventory_usage[inventory] = True @given('A complete inventory') def inventory_check(inventory): return inventory @given('an installed platform') def complete_installation(inventory): pass @when(parsers.parse("I launch ansible with the '{playbook}' playbook")) def ansible_playbook_step(request, playbook): ansible_process = run_ansible_playbook(playbook) request.ansible_process = ansible_process return ansible_process @when(parsers.parse("I redeploy '{tag}'")) def redeploy_tag(request, tag): ansible_process = run_ansible_playbook("deploy.yml", skip_tags='always', tags=tag) assert ansible_process.returncode == 0 return ansible_process
Lines """)[1:-1] ), ]) def test_multiline(request, tmpdir, feature_text, expected_text): file_name = tmpdir.join('test.feature') with file_name.open('w') as fd: fd.write(feature_text) @scenario(file_name.strpath, 'Multiline step using sub indentation') def test_multiline(request): assert get_fixture_value(request, 'i_have_text') == expected_text test_multiline(request) @given(parsers.parse('I have a step with:\n{text}')) def i_have_text(text): return text @then('the text should be parsed with correct indentation') def text_should_be_correct(i_have_text, text, expected_text): assert i_have_text == text == expected_text def test_multiline_wrong_indent(request): """Multiline step using sub indentation wrong indent.""" @scenario( 'multiline.feature', 'Multiline step using sub indentation wrong indent', )
assert req.meta['__id'] @then('the counter for the response is <n_requests>') def the_counter_for_the_response_is_n_requests(n_requests, mixin_instance): rid = mixin_instance._get_response_id( mixin_instance.response_for_pagination_mixin) assert mixin_instance._request_registry[rid]['counter'] == n_requests @then('the identifier is present in the request') def the_identifier_is_present_in_the_request(req): assert req.meta['__id'] @then(parsers.parse('the counter for the response is {number:d}')) def the_counter_for_the_response_is_number(mixin_instance, number): assert mixin_instance._request_registry[RESPONSE_ID]['counter'] == number @then('getting response returns the same response') def get_the_same_response_after_calling_get_response(mixin_instance): result = mixin_instance._get_response(None, None) assert result.meta['tag'] @then('getting response without response object raises exception') def calling_get_response_without_response_object_raises_exception( mixin_instance): with pytest.raises(ValueError): mixin_instance._get_response([], {})
@scenario_when('Argument in when, step 2') def test_argument_in_when_step_2(): pass def test_multiple_given(request): """Using the same given fixture raises an error.""" @scenario_args('Using the same given fixture raises an error') def test(): pass with pytest.raises(exceptions.GivenAlreadyUsed): test(request) @given(parsers.parse('I have {euro:d} Euro')) def i_have(euro, values): assert euro == values.pop(0) @when(parsers.parse('I pay {euro:d} Euro')) def i_pay(euro, values, request): assert euro == values.pop(0) @then(parsers.parse('I should have {euro:d} Euro')) def i_should_have(euro, values): assert euro == values.pop(0) @given(parsers.parse('I have an argument {arg:Number}', extra_types=dict(Number=int)))
from app.c_haines.severity_index import ( generate_severity_data, open_gdal, make_model_run_base_url, make_model_run_filename, make_model_run_download_urls, re_project_and_classify_geojson) from app.weather_models import ModelEnum from app.c_haines.c_haines_index import calculate_c_haines_index, CHainesGenerator from app.tests import get_complete_filename @scenario( 'test_c_haines.feature', 'Calculate c-haines') def test_extract_origin_and_pixel_information(): """ BDD Scenario. """ @then(parsers.parse('With {t_850} {t_700} and {dp_850}, I expect {c_haines}'), converters={'t_850': float, 't_700': float, 'dp_850': float, 'c_haines': float}) def with_temperature_and_dewpoint_values(t_850, t_700, dp_850, c_haines): """ Open the dataset. """ calculated = calculate_c_haines_index(t_700, t_850, dp_850) assert calculated == c_haines @scenario( 'test_c_haines.feature', 'Calculate severity') def test_calculate_mask_and_severity(): """ BDD Scenario. """ @given(parsers.parse('c_haines_data: {c_haines_data}'),
"""Steps for USER ALIAS panel features of Onezone page. """ from pytest_bdd import when, then, parsers from tests.gui.conftest import WAIT_BACKEND from tests.gui.utils.generic import repeat_failed __author__ = "Bartek Walkowicz" __copyright__ = "Copyright (C) 2017 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" @when(parsers.parse('user of {browser_id} records his current alias ' 'displayed in "USER ALIAS" Onezone panel')) @then(parsers.parse('user of {browser_id} records his current alias ' 'displayed in "USER ALIAS" Onezone panel')) @repeat_failed(timeout=WAIT_BACKEND) def record_oz_usr_alias(selenium, browser_id, tmp_memory, oz_page): driver = selenium[browser_id] usr_alias = oz_page(driver)['user alias'].alias tmp_memory[browser_id]['user_alias'] = usr_alias @when(parsers.parse('user of {browser_id} activates edit box by clicking on ' 'the user alias in expanded "USER ALIAS" Onezone panel')) @then(parsers.parse('user of {browser_id} activates edit box by clicking on ' 'the user alias in expanded "USER ALIAS" Onezone panel')) @repeat_failed(timeout=WAIT_BACKEND) def click_user_alias_edit(selenium, browser_id, tmp_memory, oz_page):
if view_link_table_cell: assert "View" in view_link_table_cell.text @then("I see an inactive party on page") def i_see_inactive_party(driver, context): destinations = [context.third_party] destinations_table_text = CasePage(driver).get_deleted_entities_text() for destination in destinations: assert destination["name"] in destinations_table_text @then( parsers.parse( 'the "{party_type}" name is "{name}", address is "{address}", country is "{country}"' )) def filter_by_application_type(driver, party_type, name, address, country): destinations = driver.find_element_by_id("table-destinations") party_index = {"End user": 1, "Consignee": 2} index = party_index.get(party_type, 1) party = destinations.find_element_by_xpath(f".//tbody/tr[{index}]") party_type_text = party.find_element_by_xpath(".//th").text party_name = party.find_element_by_xpath(".//td[2]").text party_address = party.find_element_by_xpath(".//td[3]").text assert party_type_text == party_type assert party_name == name assert party_address == f"{address}, {country}"
scenarios('features/validation/sequence_identical_timing_model.feature') # We cannot use a sequence fixture here like in other sequence tests because # the sequence is created later from the first document and assigning a fixture # after its creation function is not possible. So we store the documents in an # array and create the sequence in the final thens @given('a test sequence') def doc_list(template_dict): doc_list = [] return doc_list @when(parsers.parse('it has sequenceNumber {sequence_number}')) def when_sequence_number(sequence_number, template_dict): template_dict['sequence_number'] = sequence_number @when('it has timeBase <time_base1>') def when_time_base1(time_base1, template_dict): template_dict['time_base'] = time_base1 @when('it has clockMode <clock_mode1>') def when_clock_mode1(clock_mode1, template_dict): template_dict['clock_mode'] = clock_mode1 @when('it has frameRate <frame_rate1>')
"""Obtaining bad data from the probes.""" @scenario('../features/device/probe.feature', 'Obtaining good and bad data from the probes') def test_obtaining_good_and_bad_data(): """Obtaining good and bad data from the probes.""" @given('I have a mock probe') def mock_probe(mocker): """I have a probe.""" mocker.patch("chickenstrumentation.probe.Reader.read_probes") return Reader @given(parsers.parse('I obtain the reading:\n{reading}')) def data_output(mock_probe, reading): """I obtain the temperature reading.""" mock_probe.read_probes.return_value = reading data_output = mock_probe.get_data() mock_probe.read_probes.assert_called_once_with() return data_output @then(parsers.parse('I obtain the following data:\n{string_data}')) def data_does_not_have_pattern(data_output, string_data): """I obtain the following data.""" data = ast.literal_eval(string_data) assert data == data_output
"""Steps for features of Oneprovider metadata. """ from tests.gui.conftest import WAIT_FRONTEND from tests.gui.utils.generic import parse_seq, repeat_failed from pytest_bdd import when, then, parsers __author__ = "Michał Ćwiertnia, Bartosz Walkowicz" __copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH" __license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" @when(parsers.parse('user of {browser_id} sees that metadata panel for ' '"{item_name}" in files list is displayed')) @then(parsers.parse('user of {browser_id} sees that metadata panel for ' '"{item_name}" in files list is displayed')) @when(parsers.parse('user of {browser_id} sees that metadata panel for ' '"{item_name}" in files list has appeared')) @then(parsers.parse('user of {browser_id} sees that metadata panel for ' '"{item_name}" in files list has appeared')) @repeat_failed(timeout=WAIT_FRONTEND) def assert_files_metadata_panel_displayed(browser_id, item_name, tmp_memory): browser = tmp_memory[browser_id]['file_browser'] browser.get_metadata_for(item_name) @when(parsers.parse('user of {browser_id} sees that metadata panel for ' '"{item_name}" in files list is not displayed')) @then(parsers.parse('user of {browser_id} sees that metadata panel for '
CONVERTERS = { "email": str, "password": str, "nickname": str, "age": int, "language": str, "info": str, "message": str, "code": int, } scenarios("../features/user/user.feature", example_converters=CONVERTERS) @given( parsers.parse( "유저는 <email>, <password>, <nickname>, <age>, <language> 를 입력한다")) def user(email, password, nickname, age, language): user = { "email": email, "password": password, "nickname": nickname, "age": age, "language": language, } yield user @when(parsers.parse("유저가 위 정보 중 <info> 를 빼고 보낸다.")) def remove_property(flask_client, user, info): del user[info]
assert browser.find_by_xpath('//table[@id="result_list"]//tr//*[text()="{0}"]'.format(case.id)) @then('I should see a CI project in the list') def i_should_see_a_ci_project_in_the_list(browser, ci_project): """I should see a CI project in the list.""" assert browser.find_by_xpath('//table[@id="result_list"]//tr//*[text()="{0}"]'.format(ci_project.name)) @then('I should see a migration in the list') def i_should_see_a_migration_in_the_list(browser, migration): """I should see a migration in the list.""" assert browser.find_by_xpath('//table[@id="result_list"]//tr//*[text()="{0}"]'.format(migration.uid)) @then(parsers.parse('I should see a "{message_type}" message')) def i_should_see_a_message(browser, message_type): """I should see a message.""" assert browser.find_by_xpath('//ul[contains(@class, "messagelist")]/li[contains(@class, "{0}")]'.format( message_type)) @then(parsers.parse('the instance should be created')) def instance_should_be_created(browser, instance__name): """Instance should be created.""" assert Instance.objects.get(name=instance__name) @then(parsers.parse('the case should be created')) def case_should_be_created(browser, case__id): """Case should be created."""
import time from function import ( wait_on_element, is_element_present, ) from pytest_bdd import (given, scenario, then, when, parsers) @scenario('features/NAS-T956.feature', 'Edit User Try Change Password with mismatched passwords') def test_edit_user_try_change_password_with_mismatched_passwords(driver): """Edit User Try Change Password with mismatched passwords.""" pass @given(parsers.parse('The browser is open navigate to "{nas_url}"')) def the_browser_is_open_navigate_to_nas_url(driver, nas_url): """The browser is open navigate to "{nas_user}".""" if nas_url not in driver.current_url: driver.get(f"http://{nas_url}/ui/sessions/signin") time.sleep(1) @when(parsers.parse('If login page appear enter "{user}" and "{password}"')) def if_login_page_appear_enter_root_and_password(driver, user, password): """If login page appear enter "{user}" and "{password}".""" if not is_element_present(driver, '//mat-list-item[@ix-auto="option__Dashboard"]'): assert wait_on_element(driver, 5, '//input[@data-placeholder="Username"]') driver.find_element_by_xpath(
@scenario('build_brief.feature', 'Select how long your brief will be open') def test_how_long(): pass @scenario('build_brief.feature', 'Select who can respond') def test_who_can_respond(): pass @scenario('build_brief.feature', 'Review and publish your requirements') def test_publish_brief(): pass @given(parsers.parse('I have created a brief')) def verify_brief(brief_title, browser): visit_page('/buyers', browser) if browser.is_text_present(brief_title): browser.click_link_by_text(brief_title) wait_for_page('Write your brief', browser) else: create_brief(brief_title, browser) @when(parsers.parse('I enter {input_text} into {input_names} on the {page_text} page')) def enter_text(input_text, input_names, page_text, browser): wait_for_page(page_text, browser) for text, input in zip(input_text.split(','), input_names.split(',')): browser.fill(input, text) save_and_continue(browser)
if scenario.name == 'I want to validate the hash service response immediately': DATA['start_time'] = time.time() elif scenario.name == 'I want to create a hash with alphanumeric password': DATA['hash_numbers'] = 0 DATA['create_hash'] = False elif scenario.name == 'I want to validate the hash service response immediately' or \ scenario.name == 'I want to validate the fields in the stats response': DATA['min_time'] = MINIMUM_TIME DATA['max_time'] = MAXIMUM_TIME def pytest_bdd_after_scenario(request, feature, scenario): print('') @when(parsers.parse('the response status code is "{code}"')) def when_validate_status_code(get_data, code): try: condition = get_data['create_hash'] if condition: get_data['hash_numbers'] = get_data['hash_numbers'] + 1 get_data['create_hash'] = False assert get_data['request'].status_code == int(code) except Exception: assert get_data['request'].status_code == int(code) @then(parsers.parse('the response status code is "{code}"')) def then_validate_status_code(get_data, code): try: condition = get_data['create_hash']
from pytest_bdd.parsers import parse from pytest_bdd import ( then, when, ) @then(parse('the title should contain the text "{text}"')) def the_title_should_contain_the_text(browser, text, splinter_selenium_implicit_wait): browser.wait_for_condition( lambda browser: text in browser.title, timeout=splinter_selenium_implicit_wait) @then(parse('I should see at least {count:d} elements with the css selector "{css}"')) def should_see_at_least_count_elements_with_css(browser, css, count): element_count = len(browser.find_by_css(css)) assert element_count >= count, u'Element has at least that many counts' @then(parse('I should see {count:d} elements with the css selector "{css}"')) def should_see_count_elements_with_css(browser, css, count): element_count = len(browser.find_by_css(css)) assert element_count == count, u'Found %d (expected %d)' % (element_count, count) @then(parse('I should see exactly one element with the css selector "{css}" containing the text "{text}"')) def should_see_element_with_css_and_text(browser, css, text): elements = browser.find_by_css(css) assert len(elements) == 1 element_text = elements.first.text
from boofuzz import BitField scenarios("bit_field_original_value.feature") @given("A BitField") def request_one_block(context): context.uut = BitField(100, width=8) @given("A 4 byte BitField with value 100") def bitfield_ascii_100(context): context.uut = BitField(100, width=32) @given(parsers.parse("A 4 byte BitField with value {value:d} and format ascii") ) def bitfield_4_bytes(context, value): context.uut = BitField(value, width=32, output_format="ascii") @given("Mutated once") def mutate_once(context): context.uut.mutate() @given("Mutated twice") def mutate_twice(context): context.uut.mutate() context.uut.mutate()
__license__ = "This software is released under the MIT license cited in " \ "LICENSE.txt" @when(parsers.re('user of (?P<browser_id>.*?) sends copied (?P<item_type>.*?) ' 'to users? of (?P<browser_list>.*)')) @then(parsers.re('user of (?P<browser_id>.*?) sends copied (?P<item_type>.*?) ' 'to users? of (?P<browser_list>.*)')) def send_copied_item_to_other_users(browser_id, item_type, browser_list, tmp_memory, displays, clipboard): item = clipboard.paste(display=displays[browser_id]) for browser in parse_seq(browser_list): tmp_memory[browser]['mailbox'][item_type.lower()] = item @when(parsers.parse('user of {browser_id} sees that copied token ' 'matches displayed one')) @then(parsers.parse('user of {browser_id} sees that copied token ' 'matches displayed one')) def assert_copied_token_match_displayed_one(browser_id, tmp_memory, displays, clipboard): displayed_token = tmp_memory[browser_id]['token'] copied_token = clipboard.paste(display=displays[browser_id]) err_msg = 'Displayed token: {} does not match copied one: ' \ '{}'.format(displayed_token, copied_token) assert copied_token == displayed_token, err_msg @when(parsers.parse('user of {browser_id} sees that copied token ' 'does not match displayed one')) @then(parsers.parse('user of {browser_id} sees that copied token ' 'does not match displayed one'))
from pytest_bdd import then, parsers @then(parsers.parse("report has link type of {type_name} with url:\n{url}")) def check_link(type_name, url, allure_report): links = _get_links(allure_report) desired_link = {"type": type_name, "url": url, "name": url} assert desired_link in links @then( parsers.parse( "report has link type of {type_name} with \"{link_name}\" name and url:\n{url}" )) def check_link_with_custom_name(type_name, link_name, url, allure_report): links = _get_links(allure_report) desired_link = {"type": type_name, "url": url, "name": link_name} assert desired_link in links def _get_links(allure_report): return allure_report.test_cases[0]["links"]
'German': 'de', 'Spanish': 'es', 'French': 'fr', 'Norwegian Bokmål': 'nb', 'Dutch': 'nl', 'Polish': 'pl', 'Portuguese': 'pt', 'Russian': 'ru', 'Swedish': 'sv', 'Telugu': 'te', 'Turkish': 'tr', 'Simplified Chinese': 'zh-hans', } @when(parsers.parse('I change the hostname to {hostname:w}')) def change_hostname_to(browser, hostname): system.set_hostname(browser, hostname) @when(parsers.parse('I change the domain name to {domain:w}')) def change_domain_name_to(browser, domain): system.set_domain_name(browser, domain) @when('I change the language to <language>') def change_language(browser, language): system.set_language(browser, language_codes[language]) @then(parsers.parse('the hostname should be {hostname:w}'))
# coding=utf-8 """High Availability (tn-bhyve01) feature tests.""" import time from function import wait_on_element, is_element_present, wait_on_element_disappear from pytest_bdd import (given, scenario, then, when, parsers) @scenario('features/NAS-T961.feature', 'Creating new pool and set it as System Dataset') def test_creating_new_pool_and_set_it_as_system_dataset(driver): """Creating new pool and set it as System Dataset.""" pass @given(parsers.parse('the browser is open, navigate to "{nas_url}"')) def the_browser_is_open_navigate_to_nas_url(driver, nas_url): """the browser is open, navigate to "{nas_url}".""" global host host = nas_url if nas_url not in driver.current_url: driver.get(f"http://{nas_url}/ui/sessions/signin") assert wait_on_element(driver, 0.5, 5, '//input[@data-placeholder="Username"]') time.sleep(1) @when(parsers.parse('the login page appears, enter "{user}" and "{password}"')) def the_login_page_appear_enter_root_and_password(driver, user, password): """the login page appears, enter "{user}" and "{password}".""" global root_password
# # This file is part of Plinth-tester. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from pytest_bdd import parsers, then from support import site @then(parsers.parse('the {site_name:w} site should be available')) def site_should_be_available(browser, site_name): assert site.is_available(browser, site_name) @then(parsers.parse('the {site_name:w} site should not be available')) def site_should_not_be_available(browser, site_name): assert not site.is_available(browser, site_name)
from pytest_bdd import given, when from pytest_bdd import parsers @given( parsers.parse( "feature file {name} with content:\n\"\"\"\n{feature}\n\"\"\"")) def feature_definition(feature, testdir, name="example"): testdir.makefile(".feature".format(name=name), **dict([(name, feature)])) pass @given("dummy steps in conftest.py") def dummy_steps(request, testdir): dummy_steps_path = request.config.rootdir.join("test", "dummy_steps.py") with open(dummy_steps_path, encoding="utf-8") as f: content = f.read() testdir.makeconftest(content) @given(parsers.parse('test file with "{scenario}" scenario in {feature}')) def test_file_with_scenario(testdir, scenario, feature): testdir.makepyfile(current_test=""" from pytest_bdd import scenario @scenario("{feature}.feature", "{scenario}") def test_it(): pass """.format(scenario=scenario, feature=feature))
scenario( 'not_found.feature', 'NOT FOUND' ) assert six.text_type(exc_info.value).startswith( 'Scenario "NOT FOUND" in feature "[Empty]" in {feature_path}' .format(feature_path=request.fspath.join('..', 'not_found.feature'))) @given('comments should be at the start of words') def comments(): """Comments.""" pass @then(parsers.parse('this is not {acomment}')) def a_comment(acomment): """A comment.""" assert re.search('a.*comment', acomment) def test_scenario_comments(request): """Test comments inside scenario.""" @scenario( 'comments.feature', 'Comments' ) def test(): pass @scenario(
(PlanningWeatherStation(station_code=334, fuel_type_id=2, planning_area_id=2), fuel_type_2, planning_area_2, fire_centre) ) monkeypatch.setattr(ClientSession, 'get', default_mock_client_get) monkeypatch.setattr(app.hfi.hfi_calc, 'get_fire_weather_stations', mock_get_fire_weather_stations) # Create API client and get the response. client = TestClient(app.main.app) headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer token'} return dict(response=client.get('/api/hfi-calc/fire-centres/', headers=headers)) @then(parsers.parse('there are at least {num_fire_centres} fire centres'), converters={'num_fire_centres': int}) def assert_number_of_fire_centres(response, num_fire_centres): """ Assert that we receive the minimum expected number of fire centres """ assert len(response['response'].json()['fire_centres']) >= num_fire_centres @then('each fire centre has at least 1 planning area') def assert_min_num_planning_areas_in_fire_centre(response): """ Assert that each fire centre returned has at least 1 planning area assigned to it """ for fire_centre in response['response'].json()['fire_centres']: assert len(fire_centre['planning_areas']) >= 1 @then('each planning area has at least 1 weather station') def assert_min_num_stations_in_planning_area(response):