def should_see_content_for(driver: WebDriver, industry_name: str): industry_name = clean_name(industry_name) logging.debug("Looking for: {}".format(industry_name)) industry_breadcrumb = find_element( driver, INDUSTRY_BREADCRUMB, element_name="Industry breadcrumb", wait_for_it=False, ) current_industry = industry_breadcrumb.text with assertion_msg( "Expected to see breadcrumb for '%s' industry but got '%s' instead" " on %s", industry_name, current_industry, driver.current_url, ): assert industry_name == current_industry source = driver.page_source with assertion_msg( "Expected to find term '%s' in the source of the page %s", industry_name, driver.current_url, ): from html import escape assert escape(industry_name) in source
def generic_check_gtm_events(context: Context): required_columns = ["action", "element", "event", "type", "value"] context.table.require_columns(required_columns) expected_gtm_events = table_to_list_of_dicts(context.table) for event in expected_gtm_events: if event["type"] == "Empty string": event["type"] = "" if event["value"] == "Empty string": event["value"] = "" if event["type"] == "Not present": event.pop("type") if event["value"] == "Not present": event.pop("value") logging.debug(f"Expected GTM events: {expected_gtm_events}") registered_gtm_events = get_gtm_data_layer_events(context.driver) missing_events = [ event for event in expected_gtm_events if event not in registered_gtm_events ] with assertion_msg( f"Could not find following GTM events:\n{missing_events}\n" f"among following GTM events:\n{registered_gtm_events}\n" f"registered on: {context.driver.current_url}\n" f"Diff:\n{diff(expected_gtm_events, registered_gtm_events)}"): assert not missing_events with assertion_msg( f"Expected to find {len(expected_gtm_events)} registered GTM event(s) but " f"found {len(registered_gtm_events)} instead: " f"{registered_gtm_events}"): assert len(expected_gtm_events) == len(registered_gtm_events)
def should_see_filtered_results(driver: WebDriver, expected_filters: List[str]): def to_filter_format(name): return name.upper().replace(" ", "_").replace("-", "_") formatted_expected_filters = list(map(to_filter_format, expected_filters)) show_filters(driver) sector_filters = find_elements(driver, SECTOR_FILTERS) checked_sector_filters = [ sector_filter.get_attribute("value") for sector_filter in sector_filters if sector_filter.get_attribute("checked") ] number_expected_filters = len(formatted_expected_filters) number_checked_filters = len(checked_sector_filters) with assertion_msg( f"Expected to see {number_expected_filters} sector filter(s) to be checked but " f"saw {number_checked_filters}"): assert number_checked_filters == number_expected_filters diff = list(set(formatted_expected_filters) - set(checked_sector_filters)) with assertion_msg( f"Couldn't find '{diff}' among checked filters: {checked_sector_filters}" ): assert not diff
def check_if_populated(driver: WebDriver, expected_form_details: dict): for key, expected_value in expected_form_details.items(): existing_field_selector = PREPOPULATED_FORM_FIELDS.get(key, None) if not existing_field_selector: continue existing_field = find_element(driver, existing_field_selector, element_name=key) existing_field_value = existing_field.get_attribute("value") if expected_value: error = ( f"Expected '{key}' value to be '{expected_value}' but got " f"'{existing_field_value}'") if existing_field_value.lower() == expected_value.lower(): with assertion_msg(error): assert existing_field_value.lower( ) == expected_value.lower() logging.debug( f"'{key}' field was prepopulated with expected value: " f"'{expected_value}'") else: with assertion_msg(error): assert existing_field_value.lower( ) in expected_value.lower() logging.debug( f"Prepopulated '{key}' field is part of expected value: " f"'{expected_value}'")
def should_see_it_on(driver: WebDriver, page: ModuleType): take_screenshot(driver, NAME + page.NAME) selector = find_selector_by_name(page.SELECTORS, "language selector") language_selector = find_element(driver, selector, element_name="language selector") with assertion_msg(f"Language selector is not visible on {driver.current_url}"): assert language_selector.is_displayed() logging.debug(f"Language selector is visible on {driver.current_url}")
def has_pagination(driver: WebDriver, min_page_num: int): scroll_to(driver, find_element(driver, PAGINATION)) take_screenshot(driver, NAME) selectors = find_elements(driver, PAGES) with assertion_msg( f"Expected to see more that {min_page_num} search results page but got just {len(selectors)}" ): assert len(selectors) > min_page_num
def should_see_page_number(driver: WebDriver, page_num: int): scroll_to(driver, find_element(driver, ACTIVE_PAGE)) take_screenshot(driver, NAME) selector = find_element(driver, ACTIVE_PAGE) with assertion_msg( f"Expected to see {page_num} but got {int(selector.text)}"): assert int(selector.text) == page_num
def check_if_populated(driver: WebDriver, shared_url: str): status_update_message = find_element(driver, MESSAGE_BOX) with assertion_msg( "Expected to see article URL '%s' in LinkedIn's status update " "textbox, but couldn't find it in : %s", shared_url, status_update_message.text, ): assert shared_url in status_update_message.text
def check_if_populated(driver: WebDriver, shared_url: str): found_shared_url = extract_shared_url(driver.current_url) with assertion_msg( "Expected to find link to Article '%s' in the Facebook share page " "URL, but got '%s' instead", shared_url, found_shared_url, ): assert shared_url == found_shared_url
def should_see_content_for(driver: WebDriver, region_name: str): source = driver.page_source region_name = clean_name(region_name) logging.debug("Looking for: {}".format(region_name)) with assertion_msg( "Expected to find term '%s' in the source of the page %s", region_name, driver.current_url, ): assert region_name.lower() in source.lower()
def check_if_link_opens_email_client(driver: WebDriver): share_button_selector = SHARE_BUTTONS["email"] share_button = find_element(driver, share_button_selector) href = share_button.get_attribute("href") with assertion_msg( "Expected the 'share via email' link to open in Email Client, but " "got a invalid link: %s", href, ): assert href.startswith("mailto:")
def navigate_through_links_with_keyboard(driver: WebDriver, page: ModuleType): selector = find_selector_by_name(page.SELECTORS, "language selector") language_selector = find_element(driver, selector, element_name="language selector") options = language_selector.find_elements_by_tag_name("option") for _ in options: language_selector.send_keys(Keys.DOWN) for _ in options: language_selector.send_keys(Keys.UP) with assertion_msg(f"Language selector is not visible on {driver.current_url}"): assert language_selector.is_displayed()
def check_if_link_opens_new_tab(driver: WebDriver, social_media: str): share_button_selector = SHARE_BUTTONS[social_media.lower()] share_button = find_element(driver, share_button_selector) target = share_button.get_attribute("target") with assertion_msg( "Expected link to '%s' share page to open in new tab, but instead " "found a link with target attribute set to '%s'", social_media, target, ): assert target == "_blank"
def check_page_language_is(driver: WebDriver, expected_language: str): expected_language_code = LANGUAGE_INDICATOR_VALUES[expected_language] language_selector = find_element(driver, LANGUAGE_SELECTOR) options = language_selector.find_elements_by_tag_name("option") selected = [option for option in options if option.is_selected()][0] with assertion_msg( "Expected to see page in '%s' but got '%s'", expected_language_code, selected.get_attribute("value"), ): assert selected.get_attribute("value") == expected_language_code
def check_if_populated(driver: WebDriver, shared_url: str): found_shared_url = extract_shared_url(driver) with assertion_msg( "Expected to find link to Article '%s' in the LinkedIn share page " "URL, but got '%s' instead", shared_url, found_shared_url, ): assert shared_url == found_shared_url logging.debug( f"Link to share page on LinkedIn contains expected {shared_url}")
def erp_should_receive_email_with_link_to_restore_saved_progress( context: Context, actor_alias: str): avoid_browser_stack_idle_timeout_exception(context.driver) actor = get_actor(context, actor_alias) link = get_verification_link(actor.email, subject=EMAIL_ERP_PROGRESS_SAVED_MSG_SUBJECT) with assertion_msg( f"Could not find an email with link to restore saved progress"): assert link update_actor(context, actor_alias, saved_progress_link=link)
def check_share_via_email_link_details(driver: WebDriver, expected_subject: str, expected_body: str): share_button_selector = SHARE_BUTTONS["email"] share_button = find_element(driver, share_button_selector) href = share_button.get_attribute("href") parsed_url = urlparse.urlparse(href) query_parameters = urlparse.parse_qs(parsed_url.query) subject = query_parameters["subject"][0] body = query_parameters["body"][0] with assertion_msg( "Expected 'share via email' link to contain message body '%s' but " "got '%s' instead", expected_body, body, ): assert body == expected_body with assertion_msg( "Expected 'share via email' link's message subject to contain " "Article title '%s' but got '%s' instead", expected_subject, subject, ): assert expected_subject in subject
def fas_buyer_should_be_signed_up_for_email_updates(context: Context, actor_alias: str): actor = get_actor(context, actor_alias) response = DIRECTORY_TEST_API_CLIENT.get( f"testapi/buyer/{actor.email}/", authenticator=BASIC_AUTHENTICATOR, ) with assertion_msg( f"Expected 200 OK but got {response.status_code} from {response.url}" ): assert response.status_code == 200 assert response.json()["email"] == actor.email assert response.json()["name"] == actor.alias assert response.json()["company_name"] == "AUTOMATED TESTS" logging.debug(f"{actor_alias} successfully signed up for email updates. " f"Here's Buyer's data: {response.json()}")
def generic_should_be_on_one_of_the_pages(context: Context, actor_alias: str, expected_pages: str): expected_pages = [page.strip() for page in expected_pages.split(",")] urls = [get_page_object(name).URL for name in expected_pages] logging.debug(f"Will check {context.driver.current_url} against {urls}") results = defaultdict() for page_name in expected_pages: try: should_be_on_page(context, actor_alias, page_name) results[page_name] = True break except AssertionError: results[page_name] = False with assertion_msg( f"{actor_alias} expected to land on one of the following pages: {urls}, " f"instead we got to: {context.driver.current_url}"): assert any(list(results.values()))
def autocomplete_industry(driver: WebDriver, *, value): if isinstance(value, bool) and not value: logging.debug(f"Won't use autocomplete") return if isinstance(value, bool): logging.debug(f"Will select random industry to type") options = extract_by_css( driver.page_source, "#id_imported-products-usage-imported_good_sector-select option::text", first=False, ) logging.debug(f"Available country options: {options}") value = random.choice(options) logging.debug(f"Will select '{value}' from Industry Autocomplete list") # enter text value into the input field with autocomplete input_selector = Selector( By.ID, "id_imported-products-usage-imported_good_sector", is_visible=True ) input = find_element( driver, input_selector, element_name="industry input", wait_for_it=True ) input.click() input.send_keys(value) logging.debug(f"Get list of options from autocomplete listbox") autocomplete_list = find_element( driver, Selector( By.ID, "id_imported-products-usage-imported_good_sector__listbox", is_visible=False, ), wait_for_it=True, ) autocomplete_list_options = autocomplete_list.find_elements(By.TAG_NAME, "li") with assertion_msg(f"Expected to find at least 1 region suggestion but got 0"): assert autocomplete_list_options logging.debug(f"Selecting random element from the autocomplete listbox") option = random.choice(autocomplete_list_options) option.click()
def promo_video_check_watch_time(context: Context, actor_alias: str, expected_watch_time: int): page = get_last_visited_page(context, actor_alias) has_action(page, "get_video_watch_time") watch_time = page.get_video_watch_time(context.driver) with assertion_msg( "%s expected to watch at least first '%d' seconds of the video but" " got '%d'", actor_alias, expected_watch_time, watch_time, ): assert watch_time >= expected_watch_time logging.debug( "%s was able to watch see at least first '%d' seconds of the" " promotional video", actor_alias, expected_watch_time, )
def click_on_result_of_type(driver: WebDriver, type_of: str): results = find_elements(driver, SEARCH_RESULTS) results_of_matching_type = [ result for result in results if result.find_element_by_css_selector( "span.type").text.lower() == type_of.lower() ] with assertion_msg( f"Expected to see at least 1 search result of type '{type_of}' but found none" ): assert results_of_matching_type logging.debug( f"Found {len(results_of_matching_type)} results of type '{type_of}'") result = random.choice(results_of_matching_type) result_link = result.find_element_by_css_selector("a") logging.debug( f"Will click on {result_link.text} -> {result_link.get_property('href')}" ) result_link.click()
def should_see_marketplaces(driver: WebDriver, country: str): expected_countries = [country, "Global"] markets_selector = Selector(By.CSS_SELECTOR, "div.market-item-inner") marketplace_countries = { marketplace.find_element_by_tag_name("a").text: marketplace.find_element_by_css_selector( "div.market-item-inner p.market-operating-countries").text for marketplace in find_elements(driver, markets_selector) } error = f"Found marketplace without a list of countries it operates in" assert marketplace_countries, error for marketplace, countries in marketplace_countries.items(): with assertion_msg( f"{marketplace} does not operate in '{country}' or Globally!" f"but in '{countries}' instead"): assert any(country in countries for country in expected_countries) logging.debug( f"{marketplace} operates in '{country}' or Globally! -> {countries}" )
def autocomplete_uk_region(driver: WebDriver, *, value): if isinstance(value, bool) and not value: logging.debug(f"Won't use autocomplete") return if isinstance(value, bool): logging.debug(f"Will select random region to type") options = extract_by_css( driver.page_source, "select[id$=regions] option::text", first=False ) logging.debug(f"Available country options: {options}") value = random.choice(options) logging.debug(f"Will select '{value}' from Region Autocomplete list") # enter text value into the input field with autocomplete input_selector = Selector( By.CSS_SELECTOR, "[id$=_regions_autocomplete]", is_visible=True ) input = find_element( driver, input_selector, element_name="region input", wait_for_it=True ) input.click() input.send_keys(value) logging.debug(f"Get list of options from autocomplete listbox") autocomplete_list = find_element( driver, Selector( By.CSS_SELECTOR, "[id$=regions_autocomplete__listbox]", is_visible=False ), wait_for_it=True, ) autocomplete_list_options = autocomplete_list.find_elements(By.TAG_NAME, "li") with assertion_msg(f"Expected to find at least 1 region suggestion but got 0"): assert autocomplete_list_options logging.debug(f"Selecting random element from the autocomplete listbox") option = random.choice(autocomplete_list_options) option.click()
def generic_check_gtm_datalayer_properties(context: Context, table: Table): row_names = [ "businessUnit", "loginStatus", "siteLanguage", "siteSection", "siteSubsection", "userId", ] table.require_columns(row_names) raw_properties = { name: row.get(name) for name in row_names for row in table } expected_properties = replace_string_representations(raw_properties) found_properties = get_gtm_data_layer_properties(context.driver) with assertion_msg( f"Expected to see following GTM data layer properties:\n" f"'{expected_properties}'\n but got:\n'{found_properties}'\non: " f"{context.driver.current_url}\ndiff:\n" f"{diff(expected_properties, found_properties)}"): assert expected_properties == found_properties
def should_see_link_to(driver: WebDriver, section: str, item_name: str): item_selector = SELECTORS[section.lower()][item_name.lower()] menu_item = find_element(driver, item_selector, element_name=item_name) with assertion_msg("It looks like '%s' in '%s' section is not visible", item_name, section): assert menu_item.is_displayed()