Best Python code snippet using behave
hunts.py
Source: hunts.py
...28 hunt.admin_id = 1 # fresh db for each scenario29 db.session.add(hunt)30 db.session.commit()31 context.hunt = hunt32step_matcher('parse')33@when(u'waiting for the page to load')34def wait_for_page_change(context):35 def ready_state_complete(d):36 return d.execute_script('return document.readyState') == 'complete'37 # Wait a few seconds for js accordions and things to settle38 time.sleep(5)39 try:40 WebDriverWait(context.browser, 30)\41 .until(ready_state_complete)42 except TimeoutException:43 d.execute_script('window.stop();')44 except WebDriverException:45 pass46@given('I am logged in')47def logged_in(context):48 context.browser.get(context.root)49 email_field = context.browser.find_element_by_name('username')50 email_field.send_keys(context.admin.email)51 password_field = context.browser.find_element_by_name('password')52 password_field.send_keys(context.admin.password)53 context.browser.find_element_by_css_selector('button[type=submit]').click()54 wait_for_page_change(context)55@given('I am on the "{pagepath}" page')56def visit_page(context, pagepath):57 context.browser.get('{}/{}'.format(context.root, pagepath))58step_matcher('re')59@when("clicking the hunt's name")60def click_hunt_name(context):61 click_the_button(context, context.hunt.name)62@when(u'clicking the "(?P<value>[^"]+)" button')63def click_the_button(context, value):64 paths = [65 '//input[normalize-space(@value)="%s"]',66 '//a[contains(normalize-space(text()),"%s")]',67 '//a[contains(normalize-space(string(.)),"%s")]',68 '//button[normalize-space(text())="%s"]',69 '//button[contains(normalize-space(string(.)),"%s")]',70 '//button/span[contains(normalize-space(string(.)),"%s")]'71 ]72 failures = []73 for xpath in paths:74 try:75 context.browser.find_element_by_xpath(xpath % value).click()76 except Exception, e:77 failures.append(e)78 else:79 failures = []80 break81 assert not failures, 'Failed to find the button labeled "{}": {}'.format(82 value, failures)83step_matcher('parse')84@when('clicking the "{name}" radio button with value "{value}"')85def click_radio(context, name, value):86 context.browser.find_element_by_css_selector(87 'input[name={}][value={}]'.format(name, value)).click()88@when('filling out the "{fieldname}" field')89def fill_out_field(context, fieldname):90 field = context.browser.find_element_by_name(fieldname)91 value = uuid.uuid4().hex92 setattr(context, fieldname, value)93 field.send_keys(value)94@when('entering {num:d} participant emails')95def participant_emails(context, num):96 field = context.browser.find_element_by_css_selector('input[type=email]')97 for _ in xrange(num):98 context.emails = getattr(context, 'emails', [])99 context.emails.append(email())100 field.send_keys(context.emails[-1])101 context.browser.find_element_by_css_selector(102 "#add-participant").click()103@when('entering {num:d} item names')104def item_names(context, num):105 field = context.browser.find_element_by_css_selector(106 'input#items-template')107 for _ in xrange(num):108 context.items = getattr(context, 'items', [])109 context.items.append(uuid.uuid4().hex)110 field.send_keys(context.items[-1])111 context.browser.find_element_by_css_selector("#add-item").click()112fake_data = {113 'participant': email,114 'item': randomtext115}116step_matcher('re')117@when('adding (?:a|an) (?P<form_item>[^"]+)')118def add_form_item(context, form_item):119 context.added = getattr(context, 'added', {})120 data = fake_data[form_item]()121 context.added[form_item] = getattr(context.added, form_item, [])122 context.added[form_item].append(data)123 form = context.browser.find_element_by_css_selector(124 '#more-{}s'.format(form_item)).send_keys(data)125 btn = context.browser.find_element_by_css_selector(126 '#more-{}s-btn'.format(form_item)).click()127step_matcher('parse')128@when('revisiting the "{path}" page')129def revisit_path(context, path):130 visit_page(context, path)131def click_selector(context, selector):132 context.browser.find_element_by_css_selector(selector).click()133def send_keys(context, selector, data):134 context.browser.find_element_by_css_selector(selector).send_keys(data)135@when('changing the {msgtype} message')136def change_message(context, msgtype):137 click_selector(context, '.panel.{}'.format(msgtype))138 context.added = getattr(context, 'added', {})139 context.added[msgtype] = uuid.uuid4().hex140 send_keys(context, '#update-{}'.format(msgtype), context.added[msgtype])141 click_selector(context, 'html') # blur triggers update...
test_allure_library.py
Source: test_allure_library.py
...46 assert_that(allure_report, severity_matcher())47def should_has_step(context, step):48 allure_report, item_matcher = context49 step_matcher = partial(item_matcher, has_step, step)50 assert_that(allure_report, step_matcher())51 return allure_report, step_matcher52def should_not_has_step(context, step):53 allure_report, item_matcher = context54 step_matcher = partial(item_matcher, not_, has_step, step)55 assert_that(allure_report, step_matcher())56def should_has_attachment(context, attach_type=None, name=None):57 allure_report, item_matcher = context58 matcher = partial(item_matcher, has_attachment, attach_type, name)59 assert_that(allure_report, matcher())60def should_has_description(context, description):61 allure_report, test_case_matcher = context62 description_matcher = partial(test_case_matcher, has_description, description)63 assert_that(allure_report, description_matcher())64def should_has_before_fixture(context, fixture):65 allure_report, test_case_matcher = context66 fixture_matcher = partial(test_case_matcher, has_container, allure_report, has_before, fixture)67 assert_that(allure_report, fixture_matcher())68 return allure_report, fixture_matcher69def should_has_after_fixture(context, fixture):...
utils.py
Source: utils.py
...10 password = factory.PostGenerationMethodCall('set_password', 'user_test')11#################################12# Regex steps #13# ###############################14step_matcher('re')15#16#17# GIVEN18#19#20@given(r'I am on the (?P<page>[-\:\w]+)(?: page)?')21def impl(context, page):22 visit(context, reverse(page))23#24#25# WHEN26#27#28@when(r'I (?:click(?: on)?|follow) "(?P<text>.+)" for "(?P<parent>.+)"')29def click_in(context, text, parent):30 element = context.browser31 element = element.find_by_xpath("//li[contains(.,'" + parent + "')]|//tr[contains(.,'" + parent + "')]")32 link = element.first.find_by_xpath(".//a[contains(.,'" + text + "')]")33 link.click()34@when(r'I (?:click(?: on)?|follow) "(?P<text>.+)"')35def click(context, text):36 element = context.browser37 link = element.find_link_by_partial_text(text)38 if link:39 link.click()40 return41 other_elements = element.find_by_value(text).click()42 if other_elements:43 other_elements.click()44@when(r'I find "(?P<css>.+)" and (?:click(?: on)?|follow)(?: it)?')45def click_css(context, css):46 browser = context.browser47 browser.find_by_css(css).first.click()48@when(r'I hover(?: on)? "(?P<text>.+)"')49def hover(context, text):50 element = context.browser.find_by_xpath(".//strong[contains(.,'" + text + "')]")51 element.mouse_over()52@when(r'I have (?:a |the )?cookie "(?P<cookie>.+)" with the value of "(?P<value>.+)"')53def add_cookie(context, cookie, value):54 context.browser.cookies.add({'visited': 'true'})55@when(r'I pause for "(?P<seconds>.+)"(?: second(?:s)?)?')56def pause(context, seconds):57 time.sleep(float(seconds))58#59#60# THEN61#62#63@then(r'I should (?:see|be on) the (?P<page>\w+)(?: page)?')64def impl(context, page):65 assert page.lower() in context.browser.find_by_tag('h2').first.text.lower()66#################################67# Parse steps #68# ###############################69step_matcher('parse')70#71#72# Prerequisites73#74#75@given(u'a {type} user')76def create_user(context, user_type):77 context.email = 'test{}@fakeemailaddressdomain.com'.format(str(random.randint(0, 20000)))78 kwargs = {'email': context.email, 'is_active': True}79 if user_type == 'staff':80 kwargs.update({'is_staff': True, 'is_superuser': True})81 elif user_type == 'fake':82 kwargs['is_active'] = False83 UserFactory.create(**kwargs)...
magic.py
Source: magic.py
...39 else:40 target = None41 make(caster, cast_spell(spell_name=spell,42 target=target))43step_matcher('re')44@given('(?P<caster_name>[A-Za-z]+) has no spirit left')45def impl(context, caster_name):46 caster = get_character(context, caster_name)47 caster.spirit = 048step_matcher('parse')49@when('{caster_name} uses {item_name} for {domain_name} domain')50def step_impl(context, caster_name, item_name, domain_name):51 caster = get_character(context, caster_name)52 item = get_item(context, item_name)53 make(caster, gain_domain_(item=item,54 domain=domain_name))55@then('{caster_name} should have more {domain_name} spells')56def step_impl(context, caster_name, domain_name):...
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Cucumber Tutorial.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.
Headless browsers are gaining popularity as a viable option for testing web applications. As we all know, web browsers are an integral part of automation testing using Selenium Webdriver. While performing Selenium automation testing, Selenium launches the corresponding browser defined in the script during the test run and then executes test steps. However, issues like the slow rendering of web pages can be a potential issue that can delay the test execution speed. As a solution, headless browser testing was introduced to speed up test execution time.
Selenium is one of the most prominent automation frameworks for functional testing and web app testing. Automation testers who use Selenium can run tests across different browser and platform combinations by leveraging an online Selenium Grid, you can learn more about what Is Selenium? Though Selenium is the go-to framework for test automation, Cypress – a relatively late entrant in the test automation game has been catching up at a breakneck pace.
WordPress is like a lighthouse, that lightens up 30% of the internet. Pivotal reason behind it’s huge success is the level of customization that it offers along with huge amount of community support in the form of plugins, themes, extensions, etc. .
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!