Exemple #1
0
def autocomplete_country(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 country to type")
        options = extract_by_css(
            driver.page_source, "select[id^=id] option::text", first=False
        )
        logging.debug(f"Available country options: {options}")
        value = random.choice(options)

    logging.debug(f"Will select '{value}' from country autocomplete list")

    # enter text value into the input field with autocomplete
    input_selector = Selector(
        By.CSS_SELECTOR, "input.autocomplete__input", is_visible=True
    )
    input = find_element(
        driver, input_selector, element_name="country input", wait_for_it=False
    )
    input.click()
    input.send_keys(value)

    logging.debug(f"Get list of options from autocomplete listbox")
    autocomplete_list = find_elements(
        driver, Selector(By.CSS_SELECTOR, "ul[role=listbox] li", is_visible=True)
    )
    input.send_keys(Keys.DOWN)
    random.choice(autocomplete_list).send_keys(Keys.SPACE)
Exemple #2
0
def get_all_market_slugs(
    *, auth: tuple = (BASICAUTH_USER, BASICAUTH_PASS)) -> list:
    start_page = f"{URLs.SOO_SEARCH_RESULTS.absolute}?category_id=&country_id=&commit="
    response = get_and_assert(url=start_page,
                              status_code=HTTP_200_OK,
                              auth=auth)
    content = response.content.decode("UTF-8")
    hrefs = extract_attributes_by_css(content,
                                      "a.market-header-link",
                                      attrs=["href"],
                                      text=False)

    last_page_number = int(
        extract_by_css(content,
                       "nav.pagination > ol > li:last-of-type > a::text"))
    if last_page_number > 1:
        for page_number in range(2, last_page_number + 1):
            url = f"{start_page}&page={page_number}"
            response = get_and_assert(url=url,
                                      status_code=HTTP_200_OK,
                                      auth=auth)
            content = response.content.decode("UTF-8")
            hrefs += extract_attributes_by_css(content,
                                               "a.market-header-link",
                                               attrs=["href"],
                                               text=False)
    # flatten the results and return only the market's slug value e.g. tthigo
    # results format is:
    # [{'href': '/selling-online-overseas/markets/details/tthigo/'}, ...]
    slugs = [href["href"].split("/")[-2] for href in hrefs]
    return slugs
Exemple #3
0
def extract_logo_url(response: Response):
    """Extract URL of the Company's logo picture from the Directory
    edit profile page content.

    :param response: response with the contents of edit profile page
    :param fas: Use FAS specific CSS selector if True, else use FAB selector
    :return: a URL to the company's logo image
    """
    css_selector = "#logo-container img::attr(src)"
    logo_url = extract_by_css(response.content.decode("UTF-8"), css_selector)
    with assertion_msg("Could not find Company's logo URL in the response"):
        assert logo_url
    return logo_url
Exemple #4
0
def extract_form_action(response: Response) -> str:
    """Extract the form action (endpoint).

    Comes in handy when dealing with e.g. Django forms.

    :param response: requests response
    :return: for action endpoint
    """
    with assertion_msg("Can't extract form action from an empty response!"):
        assert response.content
    css_selector = "#content form::attr(action)"
    action = extract_by_css(response.content.decode("UTF-8"), css_selector)
    logging.debug("Found confirm email form action value=%s", action)
    return action
Exemple #5
0
def get_number_of_search_result_pages(response: Response) -> int:
    """Will extract the last search result page number from provided response.

    The CSS selector will return string like: `page 1 of 2`.
    Then we extract the numbers from it and return the last one.
    In case of lack of thereof a 0 is returned.

    :param response: FAS Search Result response
    :return: a number of FAS Search Result pages or 0 if couldn't find
             information about number of pages
    """
    last_page_css_selector = "#paginator ol li.active-blue-text ~ li a::text"
    last_page = extract_by_css(response.content.decode("UTF-8"),
                               last_page_css_selector).strip()
    last_page = int(last_page) if last_page.isdigit() else 0
    logging.debug(f"Number of search result pages: {last_page}")
    return last_page
Exemple #6
0
def extract_csrf_middleware_token(response: Response) -> str:
    """Extract CSRF middleware token from the response content.

    Comes in handy when dealing with e.g. Django forms.

    :param response: requests response
    :type  response: requests.models.Response
    :return: CSRF middleware token extracted from the response content
    :rtype: str
    """
    with assertion_msg("Can't extract CSRF token as response has no content"):
        assert response.content
    css_selector = "input[type=hidden][name=csrfmiddlewaretoken]::attr(value)"
    token = extract_by_css(response.content.decode("UTF-8"), css_selector)
    with assertion_msg(f"Couldn't find csrfmiddlewaretoken on {response.url}"):
        assert token
    logging.debug("Found CSRF token: %s", token)
    return token
Exemple #7
0
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()
Exemple #8
0
def should_be_able_to_print(driver: WebDriver):
    print_link_selector = Selector(By.PARTIAL_LINK_TEXT, "print a copy now")
    print_link = find_element(driver, print_link_selector)
    onclick = print_link.get_attribute("onclick")
    error = f"Expected 'window.print()' got '{onclick}' on {driver.current_url}"
    assert onclick == "window.print()", error

    print_only_selector = "div.print-only *::text"
    raw_to_print = extract_by_css(driver.page_source,
                                  print_only_selector,
                                  first=False)
    clean_to_print = [
        text for text in raw_to_print
        if "\n" not in text and "Change" not in text and "answer" not in text
    ]
    to_print = "\n".join(clean_to_print)
    error = (
        f"Could not find expected values in content to print: {to_print} on "
        f"{driver.current_url}")
    assert "Feedback form details" in to_print, error
Exemple #9
0
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()