def driver_booking(request, session_booking): driver = WebDriverManager.get_instance().driver driver.implicitly_wait(10) platform = WebDriverManager.get_instance().device.platform if platform == "Android": result = driver.execute_script( "mobile: shell", {'command': "dumpsys window windows | grep -E 'mCurrentFocus'"}) locale = driver.execute_script( "mobile: shell", {'command': "getprop persist.sys.locale"}) app_package = result.split("/")[0].split(" ")[-1] set_settings("Android", "package", app_package) set_settings("Android", "locale", locale.split("-")[0]) else: locale = subprocess.run([ "ideviceinfo -u {} -q com.apple.international -k Locale".format( WebDriverManager.get_instance().device.udid) ], shell=True, stdout=PIPE, stderr=PIPE).stdout set_settings("Android", "locale", locale.decode().split("_")[0]) set_settings("System", "platform", platform) yield driver WebDriverManager.destroy()
def get_screenshot(filename): try: WebDriverManager.get_instance().driver.get_screenshot_as_file(filename) return True except Exception: logging.warning("Error while making screenshot!") return False
def emulate_location_moscow(driver): if get_settings("System", "platform") == "Android": pass else: if not WebDriverManager.get_instance().device.emulator: system("idevicelocation -u {} 55.7968802 37.537294".format(WebDriverManager.get_instance().device.udid)) else: WebDriverManager.get_instance().driver.set_location(55.7968802, 37.537294, 0)
def find_category_in_list_ios(self, steps, category_name): driver = WebDriverManager.get_instance().driver cat = steps.try_get(category_name) old_page_elements = [ x.text for x in driver.find_elements_by_xpath( "//*[@type='XCUIElementTypeStaticText']") ] new_page_elements = [] timeout = time() + 60 while not (cat and cat.get_attribute("visible") == 'true') and old_page_elements != new_page_elements: old_page_elements = new_page_elements steps.scroll_down(small=True) cat = steps.try_get(category_name) new_page_elements = [ x.text for x in driver.find_elements_by_xpath( "//*[@type='XCUIElementTypeStaticText']") ] if time() > timeout: break sleep(1) steps.try_get(category_name).click() try: WebDriverWait(driver, 20).until( EC.visibility_of_element_located( (By.ID, Locator.SHOW_ON_MAP.get()))) except TimeoutException as nse: steps.try_get(category_name).click() WebDriverWait(driver, 20).until( EC.visibility_of_element_located( (By.ID, Locator.SHOW_ON_MAP.get())))
def find_button(self, text): driver = WebDriverManager.get_instance().driver try: return driver.find_element_by_xpath( "//*[@text='{}' or @text='{}' or @text='{}']/parent::*".format(text, text.upper(), text.lower())) except NoSuchElementException: return None
def driver(self, request): unlock(request.config.getoption("--device-id")) driver = WebDriverManager.get_instance().driver driver.implicitly_wait(30) platform = WebDriverManager.get_instance().device.platform set_settings("System", "platform", platform) result = driver.execute_script("mobile: shell", {'command': "dumpsys window windows | grep -E 'mCurrentFocus'"}) locale = driver.execute_script("mobile: shell", {'command': "getprop persist.sys.locale"}) app_package = result.split("/")[0].split(" ")[-1] set_settings("Android", "package", app_package) set_settings("Android", "locale", locale.split("-")[0]) yield driver try: WebDriverManager.destroy() except (InvalidSessionIdException, WebDriverException): logging.info("Session deleted by timeout")
def find_category_in_list_android(self, steps, category_name): driver = WebDriverManager.get_instance().driver cat = steps.try_get_by_text(text=category_name) old_page_elements = [ x.text for x in driver.find_elements_by_xpath( "//*[@class='android.widget.TextView']") ] new_page_elements = [] timeout = time() + 60 while not cat and old_page_elements != new_page_elements: old_page_elements = new_page_elements steps.scroll_down(small=True) cat = steps.try_get_by_text(text=category_name) new_page_elements = [ x.text for x in driver.find_elements_by_xpath( "//*[@class='android.widget.TextView']") ] if time() > timeout: break steps.try_get_by_text(text=category_name).click() try: in_progress = driver.find_element_by_id( Locator.SEARCH_PROGRESS.get()) WebDriverWait(driver, 120).until(EC.staleness_of(in_progress)) except NoSuchElementException as nse: pass
def collect_categories_android(self, steps): all_categories = set() for _ in range(3): categories = WebDriverManager.get_instance( ).driver.find_elements_by_xpath( "//*[@class='android.support.v7.widget.RecyclerView']/*") all_categories.update([x.text for x in categories]) steps.scroll_down() return all_categories
def collect_categories_ios(self, steps): all_categories = set() for _ in range(2): categories = WebDriverManager.get_instance( ).driver.find_elements_by_xpath( "//*[@type='XCUIElementTypeTable']//*[@type='XCUIElementTypeStaticText']" ) all_categories.update([x.text for x in categories]) steps.scroll_down() return all_categories
def driver(request, session): logging.info("[session] starting driver") if not request.config.getoption("--simulator"): unlock(request.config.getoption("--device-id")) driver = WebDriverManager.get_instance().driver driver.implicitly_wait(10) platform = WebDriverManager.get_instance().device.platform if platform == "Android": result = driver.execute_script("mobile: shell", { 'command': "dumpsys window windows | grep -E 'mObscuringWindow|mHoldScreenWindow|mCurrentFocus' | grep -E 'mapswithme'"}) locale = driver.execute_script("mobile: shell", {'command': "getprop persist.sys.locale"}) if locale == "\n": locale = "en-US" app_package = result.split("/")[0].split(" ")[-1] set_settings("Android", "package", app_package) set_settings("Android", "locale", locale.split("-")[0]) else: if WebDriverManager.get_instance().device.emulator: locale = b'ru_RU' else: locale = subprocess.run(["ideviceinfo -u {} -q com.apple.international -k Locale" .format(WebDriverManager.get_instance().device.udid)], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout set_settings("Android", "locale", locale.decode().split("_")[0]) # ideviceinstaller -U <UUID> -l | grep maps.me set_settings("Tests", "routing_time", request.config.getoption("--time")) set_settings("System", "platform", platform) yield driver WebDriverManager.destroy()
def return_back_to_mapsme(steps): yield driver = WebDriverManager.get_instance().driver try: if get_settings("System", "platform") == "Android": driver.execute_script("mobile: shell", { 'command': "am start {}/com.mapswithme.maps.SplashActivity".format(get_settings("Android", "package"))}) steps.close_first_time_frame() else: driver.execute_script("mobile: activateApp", {"bundleId": 'com.my.maps-beta-enterprise'}) steps.close_first_time_frame() except: pass
def wrapper(*args, **kwargs): if context_type == "native": driver = WebDriverManager.get_instance().driver if driver.context != "NATIVE_APP": driver.switch_to.context("NATIVE_APP") else: driver = WebDriverManager.get_instance().driver if driver.context == "NATIVE_APP": try: WebDriverWait(driver, 20).until(EC2.web_view_context_enabled()) contexts = driver.contexts cons = [ x.split("_")[-1] for x in contexts if x != "NATIVE_APP" and "chrome" not in x ] if len(cons) > 0: driver.switch_to.context("WEBVIEW_{}".format( cons[-1])) except TimeoutException: pass return func(*args, **kwargs)
def pytest_runtest_makereport(item, call): outcome = yield rep = outcome.get_result() setattr(item, "rep_" + rep.when, rep) pytest_html = item.config.pluginmanager.getplugin('html') extra = getattr(rep, 'extra', []) if rep.when == 'call' or rep.when == 'setup': xfail = hasattr(rep, 'wasxfail') if (rep.skipped and xfail) or (rep.failed and not xfail): path = dirname(realpath(__file__)).split('mapsme')[0] filename = join(path, item.name + ".png") screencap = WebDriverManager.get_instance( ).driver.get_screenshot_as_base64() image_64_decode = base64.b64decode(screencap) try: log = "<br>".join( [rep.longrepr.reprcrash.message] + rep.longrepr.reprtraceback.reprentries[0].lines) except: logging.info("LOG ERROR") log = "error" with open(filename, 'wb') as ff: ff.write(image_64_decode) test_r = None try: with open("testresult.txt", "r") as f: test_r = f.read() params = { "test_result": test_r, "log": "Error:<br> {}".format(log), "file": screencap, "timestamp": datetime.now(), "is_fail": True, "before": True } resp = requests.post("{}/testlog".format( get_settings("ReportServer", "host")), data=params) except FileNotFoundError: logging.info("TESTRESULT.TXT is NOT FOUND") extra.append(pytest_html.extras.image(item.name + ".png")) rep.extra = extra
def activate_app_if_crashed(steps): """Костыльная обработка крешей todo проверено только на ios""" logging.info("Check if app was crashed") if get_settings("System", "platform") == "IOS": try: cur_app = WebDriverManager.get_instance( ).driver.find_element_by_xpath( "//*[@type='XCUIElementTypeApplication']").text logging.info("current focus: {}".format(cur_app)) if "maps.me" not in cur_app: logging.info("executing mobile:activateApp for {}".format( get_settings("Android", "package"))) WebDriverManager.get_instance().driver.execute_script( "mobile:activateApp", {"bundleId": get_settings("Android", "package")}) except Exception as e: logging.info("executing mobile:activateApp for {}".format( get_settings("Android", "package"))) WebDriverManager.get_instance().driver.execute_script( "mobile:activateApp", {"bundleId": get_settings("Android", "package")}) else: cur_focus = WebDriverManager.get_instance().driver.execute_script( "mobile: shell", { 'command': "dumpsys window windows | grep -E 'mObscuringWindow|mHoldScreenWindow|mCurrentFocus'" }) if not get_settings( "Android", "package") in cur_focus or "Application Error" in cur_focus: if "LauncherActivity" in cur_focus or "mCurrentFocus=null" in cur_focus: pass else: WebDriverManager.get_instance().driver.execute_script( "mobile: shell", { 'command': "am start {}/com.mapswithme.maps.SplashActivity". format(get_settings("Android", "package")) }) steps.close_first_time_frame()
def execute_deeplink(self, deeplink): driver = WebDriverManager.get_instance().driver logging.info("Terminating Safari") driver.execute_script("mobile: terminateApp", {"bundleId": "com.apple.mobilesafari"}) logging.info("Terminating mapsme") driver.execute_script("mobile: terminateApp", {"bundleId": get_settings("Android", "package")}) sleep(3) logging.info("Executing deeplink: {}".format(deeplink)) driver.execute_script("mobile: launchApp", { "bundleId": "com.apple.mobilesafari", "arguments": ["-U", deeplink] }) driver.find_element_by_id(LocalizedButtons.OPEN.get()).click()
def assert_route_points(self, count, p2p=True, *points): metro = self.try_get(Locator.ROUTING_METRO.get()) if metro: self.try_get(LocalizedButtons.MANAGE_ROUTE.get()).click() for point in points: assert self.try_get(point) else: if WebDriverManager.get_instance().device.platform_version >= "13": els = self.driver.find_elements_by_xpath( "//*[@type='XCUIElementTypeCollectionView']/*[@type='XCUIElementTypeCell']" ) assert len( els ) >= count * 4 + 3 # (count + 2) + count*2 + (count + 1) else: assert self.try_get(Locator.ROUTE_METRO.get()) route_stop = "ic_route_manager_stop_{}" alphabet = string.ascii_lowercase for i in range(count): assert self.try_get(route_stop.format(alphabet[i]))
def test_swipe_map_randomly(self, testitem, check_diff, download_maps, um24c, memory_script, steps): time_in_minutes = get_settings('Tests', 'routing_time') timeout = time.time() + 60 * int(time_in_minutes) driver = WebDriverManager.get_instance().driver driver.implicitly_wait(0.5) actions = TouchAction(driver) win_size = driver.get_window_size() min_x = 100 max_x = win_size["width"] - 100 min_y = 100 max_y = win_size["height"] - 100 while time.time() <= timeout: random_x_1 = random.randint(min_x, max_x) random_y_1 = random.randint(min_y, max_y) random_x_2 = random.randint(min_x, max_x) random_y_2 = random.randint(min_y, max_y) actions.press(None, random_x_1, random_y_1).wait(500).move_to( None, random_x_2, random_y_2).release().perform() logging.info("Swipe from ({},{}) to ({},{})".format( random_x_1, random_y_1, random_x_2, random_y_2)) download_map = steps.try_get(Locator.DOWNLOAD_MAP_BUTTON.get()) if download_map: position = steps.try_get(Locator.GET_POSITION_LIGHT.get()) if not position: actions.tap(x=200, y=200).perform() time.sleep(1) steps.try_get(Locator.GET_POSITION_LIGHT.get()).click() time.sleep(1) anchor = steps.try_get(Locator.PP_ANCHOR.get()) if anchor: steps.scroll_up(from_el=anchor)
def __init__(self): self.driver = WebDriverManager.get_instance().driver
def uninstall_taxi(self): execute_adb_command("adb -s {} shell pm uninstall {}".format( WebDriverManager.get_instance().device.device_id, get_settings("Tests", "partner_taxi")))
def wait_route_start(self): timeout = 180 if WebDriverManager.get_instance().device.platform_version <= "7.0": timeout = 300 WebDriverWait(WebDriverManager.get_instance().driver, timeout).until( EC.visibility_of_element_located((By.ID, Locator.TIME.get())))
def get(): if WebDriverManager.get_instance().device.platform == "Android": return AndroidRoutingSteps() else: return IosRoutingSteps()
def assert_title_contains(self, title, limit=5): results = WebDriverManager.get_instance().driver.find_elements_by_id( Locator.TITLE.get())[:limit] for res in results: assert title.lower() in res.text.lower( ), "Search result should contain {}".format(title)
def get(): if WebDriverManager.get_instance().device.platform == "Android": return AndroidBookmarkSteps() else: return IosBookmarkSteps()
def browser_steps(self, booking, hotel=None): driver = WebDriverManager.get_instance().driver driver.implicitly_wait(30) form = BookingWebSearchForm() sleep(10) url = driver.current_url url = url + "&test=1" driver.get(url) sleep(10) try: driver.find_element_by_xpath("//div[@id='sr-header-group-action-icon']").click() except: pass chosen_date = form.checkin_input().get_attribute("value") logging.info("Current chosen check-in date: {}".format(chosen_date)) chosen = datetime.strptime(chosen_date, "%Y-%m-%d") if (chosen - datetime.now()).days < 30: form.checkin_date().click() WebDriverWait(driver, 10) \ .until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class,'pikaday-checkin')]"))) form.datepicker_next_arrow().click() form.datepicker_ci_last_day().click() chosen_date = form.checkin_input().get_attribute("value") logging.info("Current chosen check-in date: {}".format(chosen_date)) if hotel: try: driver.find_element_by_xpath("//button[@class='input_clear_button']").click() form.direction().send_keys(hotel) sleep(1) except (ElementNotVisibleException, NoSuchElementException): pass try: form.submit_search().click() except (ElementClickInterceptedException, WebDriverException): try: driver.find_element_by_xpath("//*[@class='alertify-log-close-button']").click() except NoSuchElementException: pass form.submit_search().click() logging.info("Clicking search") form.wait_search_overlay() form.go_to_first_result() logging.info("Choosing first search result") try: WebDriverWait(driver, 20).until(EC.visibility_of_element_located( (By.XPATH, "//a[contains(@href, '#availabilityBlock')]"))) except TimeoutException: return False form.go_to_variants().click() sleep(3) try: form.free_cancellation().click() logging.info("Clicking free cancellation filter") except: pass form.first_book_variant().click() logging.info("Selecting first book variant in list") form.book().click() logging.info("Clicking Reserve") form.wait_search_overlay() form.book().click() logging.info("Clicking Book") sleep(5) try: form.fill_cc_data( "4441336954914542") # todo: generate valid card numbers (mapsmefr/utils/card_number_generator) except: pass form.save_old_bookings() try: form.book().click() except: pass result = form.wait_booked_stamp() if result: prog = re.compile(r"[0-9.]+") result = prog.search(form.price().text.replace(" ", "").replace(",", "")) booking.price = float(result[0]) booking.reservation_id = form.reservation_id() return result
def get(): if WebDriverManager.get_instance().device.platform == "Android": return AndroidDownloaderSteps() else: return IosDownloaderSteps()
def _get(self): if WebDriverManager.get_instance().device.platform == "Android": return AndroidSearchFilter() else: return IosSearchFilter()
def find_button_by_id(self, locator): try: return WebDriverManager.get_instance().driver.find_element_by_id(locator) except NoSuchElementException: return None
def download(self): if get_settings("System", "platform") == "Android": return self.find_button_by_id(Locator.DOWNLOAD_ICON.get()) else: return WebDriverManager.get_instance().driver.find_element_by_xpath( "//*[./following-sibling::*[@name='{}']]".format(LocalizedButtons.DOWNLOAD_FROM_PP_BUTTON.get()))
def click_search(self, steps): steps.try_get(Locator.SEARCH_BUTTON.get()).click() sleep(2) WebDriverManager.get_instance().driver.hide_keyboard()
def switch_to_native(b_steps): if get_settings("System", "platform") == "IOS": WebDriverManager.get_instance().driver.execute_script("mobile: terminateApp", {"bundleId": 'com.apple.mobilesafari'}) yield b_steps.switch_to_native()