def get_element_attribute(self, element, attr, css=False, expected_value=None): """ Get the value of an attribute or css attribute from an element. :param element: CSS Selector or XPATH used to locate the element :type element: str :param attr: The attribute to lookup :type attr: str :param css: Whether or not this is a CSS atrribute :type css: bool :param expected_value: :return: The value of the attribute """ elem = self.get_element(element) if css: value = elem.value_of_css_property(attr) if self.is_color(value): value = Color.from_string(value) if expected_value: if self.is_color(expected_value): expected_value = Color.from_string(expected_value) return value, expected_value else: value = elem.get_attribute(attr) return value
def __init__(self, url, btnElem: selenium.webdriver.remote.webelement.WebElement): self.url = url # Url for screenshot cap. self.text = None # The content of the button text. self.color = None # The color of the button. self.textColor = None # The color of the text. self.type = None # The type of button. self.redirect = None # Is the button a redirect to another page? self.html = None # Raw HTML of button. self.size = None # Size. self.scrn = None # A screenshot of the button. # If we got a button, add it! if btnElem: # Lets not forget the element. self.elem = btnElem # Now lets fill out the apprBtn extras from button. if self.elem: self.text = self.elem.text or self.elem.get_attribute("value") self.type = self.elem.tag_name self.html = self.elem.get_attribute("outerHTML") if self.elem.size: self.size = self.elem.size if self.elem.get_attribute("href"): self.redirect = self.elem.get_attribute("href") if self.elem.value_of_css_property("background-color"): self.color = Color.from_string( self.elem.value_of_css_property("background-color")).hex if self.elem.value_of_css_property("color"): self.textColor = Color.from_string( self.elem.value_of_css_property("color")).hex
def test_empty_password_submitted(self): self.driver.find_element(By.CLASS_NAME, "my-tui").click() time.sleep(2) self.driver.find_element(By.CLASS_NAME, "my-tui").click() time.sleep(2) self.driver.switch_to.window(self.driver.window_handles[1]) email = self.driver.find_element(By.ID, "email") password = self.driver.find_element(By.ID, "pass") email.clear() email.send_keys("*****@*****.**") password.clear() rgb = email.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print(hex) rgb = password.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print(hex) self.driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click() time.sleep(2) print("\n Password alert and input color:") passAlert = self.driver.find_element( By.CSS_SELECTOR, 'form-message[content = "Wpisz hasło."]') print("Password alert is displayed: ", passAlert.is_displayed()) rgb = password.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print("Color of input changed to: ", hex)
def create_lobby(self, name="frederick", color=None): driver = InterfaceTest.driver self.modal_appear_wait("name") name_entry = driver.find_element_by_id("user-nickname") name_entry.send_keys(name) color_master = driver.find_element_by_id("color-picker") color_blocks = color_master.find_elements_by_class_name("ColorBlotch") if color is None: color_block = random.choice(color_blocks) color_block.click() else: desired_color = Color.from_string(color) found = False for color_block in color_blocks: if Color.from_string(color_block.value_of_css_property("background-color")) == desired_color: color_block.click() found = True break if not found: raise Exception("unable to find desired color: " + color) self.modal_complete() username_button = driver.find_element_by_id("change-username") self.assertIn(name, username_button.text) create_button = driver.find_element_by_id("create-lobby") create_button.click() self.modal_appear_wait("Lobby") self.modal_complete() return InterfaceTest.wait.until(ec.visibility_of_element_located((by.ID, "canvas")))
def _assert_intra_move(self): now = datetime.now() self.driver.get(self.live_server_url + reverse('moneybook:index')) rows = self.driver.find_elements(By.XPATH, '//*[@id="transactions"]/table/tbody/tr') self.assertEqual(len(rows), 3) tds = rows[1].find_elements(By.TAG_NAME, 'td') self.assertEqual(tds[0].text, str(now.year) + "/" + str.zfill(str(now.month), 2) + "/" + '02') self.assertEqual(tds[1].text, 'ないぶいどう') self.assertEqual(tds[2].text, '200') self.assertEqual(tds[3].text, 'Kyash') self.assertEqual(tds[4].text, '内部移動') self.assertEqual(Color.from_string(rows[1].value_of_css_property('background-color')), Color.from_string('rgba(0, 0, 0, 0)')) # direction確認 tds[5].find_element(By.TAG_NAME, 'a').click() self.assertEqual(self.driver.find_element(By.XPATH, '//form/table[1]/tbody/tr[4]/td[1]/input[1]').is_selected(), True) self.driver.get(self.live_server_url + reverse('moneybook:index')) rows = self.driver.find_elements(By.XPATH, '//*[@id="transactions"]/table/tbody/tr') tds = rows[2].find_elements(By.TAG_NAME, 'td') self.assertEqual(tds[0].text, str(now.year) + "/" + str.zfill(str(now.month), 2) + "/" + '02') self.assertEqual(tds[1].text, 'ないぶいどう') self.assertEqual(tds[2].text, '200') self.assertEqual(tds[3].text, '現金') self.assertEqual(tds[4].text, '内部移動') self.assertEqual(Color.from_string(rows[2].value_of_css_property('background-color')), Color.from_string('rgba(0, 0, 0, 0)')) # direction確認 tds[5].find_element(By.TAG_NAME, 'a').click() self.assertEqual(self.driver.find_element(By.XPATH, '//form/table[1]/tbody/tr[4]/td[1]/input[2]').is_selected(), True)
def test_consistency(self): # testing other fields and consistency # place monthly to mid range self.home.drag_something( self.home.find_by_xpath(self.home.full_slider_track), self.home.find_by_xpath(self.home.monthpay_slide), 50) # assert for dispaly of gren track assert self.home.find_by_xpath( self.home.slider_left_selection_green).is_displayed() # get if it is affordable or not if self.home.is_affordable(): max_amount = self.home.find_by_xpath(self.home.max_amount) rgb = max_amount.value_of_css_property("color") color_hex = Color.from_string(rgb).hex assert color_hex == "#8dc63f" assert not self.home.find_by_xpath( self.home.alt_message).is_displayed() assert self.home.find_by_xpath( self.home.success_pig).is_displayed() assert not self.home.find_by_xpath( self.home.fail_pig).is_displayed() else: max_amount = self.home.find_by_xpath(self.home.max_amount) rgb = max_amount.value_of_css_property("color") color_hex = Color.from_string(rgb).hex assert color_hex == "#ed681f" assert self.home.find_by_xpath( self.home.alt_message).is_displayed() assert not self.home.find_by_xpath( self.home.success_pig).is_displayed() assert self.home.find_by_xpath(self.home.fail_pig).is_displayed()
def test_hsl_to_rgba(self): hsl = "hsl(120, 100%, 25%)" rgba = "rgba(0, 128, 0, 1)" assert Color.from_string(hsl).rgba == rgba hsl = "hsl(100, 0%, 50%)" rgba = "rgba(128, 128, 128, 1)" assert Color.from_string(hsl).rgba == rgba
def test_hsla_to_rgba(self): hsla = "hsla(120, 100%, 25%, 1)" rgba = "rgba(0, 128, 0, 1)" assert Color.from_string(hsla).rgba == rgba hsla = "hsla(100, 0%, 50%, 0.5)" rgba = "rgba(128, 128, 128, 0.5)" assert Color.from_string(hsla).rgba == rgba
def test_hex_to_rgba(self): hex_ = "#01Ff03" rgba = "rgba(1, 255, 3, 1)" assert Color.from_string(hex_).rgba == rgba hex_ = "#00ff33" rgba = "rgba(0, 255, 51, 1)" assert Color.from_string(hex_).rgba == rgba
def wait_for_background_color(self, selector, color_string): color = Color.from_string(color_string) correct_color = lambda driver: Color.from_string( driver.find_element_by_css_selector(selector). value_of_css_property("background-color")) == color msg = "The color of '%s' should be %s" % (selector, color_string) Wait(self.sel).until(correct_color, msg) self.screenshot()
def get_view_color_values(self): grid = Color.from_string(self.web_driver.find_element_by_name("view_grid").value_of_css_property('color')).hex tile = Color.from_string(self.web_driver.find_element_by_name("view_tile").value_of_css_property('color')).hex list = Color.from_string(self.web_driver.find_element_by_name("view_list").value_of_css_property('color')).hex self.web_session.logger.debug("grid: {} tile: {} list: {}".format(grid, tile, list)) return grid, tile, list
def __init__(self, color, background_color, opacity, font, border, background_image): self.__color = Color.from_string(color) self.__background_color = Color.from_string(background_color) self.__opacity = opacity self.__font = font self.__border = border self.__background_image = background_image
def test_should_pick_up_style_of_an_element(driver, pages): pages.load("javascriptPage.html") element = driver.find_element(by=By.ID, value="green-parent") backgroundColour = Color.from_string(element.value_of_css_property("background-color")) assert Color.from_string("rgba(0, 128, 0, 1)") == backgroundColour element = driver.find_element(by=By.ID, value="red-item") backgroundColour = Color.from_string(element.value_of_css_property("background-color")) assert Color.from_string("rgba(255, 0, 0, 1)") == backgroundColour
def testShouldPickUpStyleOfAnElement(driver, pages): pages.load("javascriptPage.html") element = driver.find_element(by=By.ID, value="green-parent") backgroundColour = Color.from_string(element.value_of_css_property("background-color")) assert Color.from_string("rgba(0, 128, 0, 1)") == backgroundColour element = driver.find_element(by=By.ID, value="red-item") backgroundColour = Color.from_string(element.value_of_css_property("background-color")) assert Color.from_string("rgba(255, 0, 0, 1)") == backgroundColour
def test_app(self): elm1 = self.wd.find_element_by_id('1') elm2 = self.wd.find_element_by_id('2') elm3 = self.wd.find_element_by_id('3') self.assertEqual(Color.from_string('red').rgba, elm1.value_of_css_property('background-color')) self.assertEqual(Color.from_string('green').rgba, elm2.value_of_css_property('background-color')) self.assertEqual(Color.from_string('blue').rgba, elm3.value_of_css_property('background-color'))
def wait_for_background_color(self, selector, color_string): color = Color.from_string(color_string) correct_color = ( lambda driver: Color.from_string( driver.find_element_by_css_selector(selector).value_of_css_property("background-color") ) == color ) msg = "The color of '%s' should be %s" % (selector, color_string) Wait(self.sel).until(correct_color, msg) self.screenshot()
def _assert_add(self, item, method, category): now = datetime.now() self._login() self.driver.get(self.live_server_url + reverse('moneybook:index')) self.assertEqual( len( self.driver.find_elements( By.XPATH, '//*[@id="transactions"]/table/tbody/tr')), 1) # 1件追加 self.driver.find_element(By.ID, 'a_day').send_keys('3') self.driver.find_element(By.ID, 'a_item').send_keys(item) self.driver.find_element(By.ID, 'a_price').send_keys('1000') labels = self.driver.find_elements( By.XPATH, '//*[@id="filter-fixed"]/form/table/tbody/tr[4]/td/label') for label in labels: if label.text == method: label.click() break labels = self.driver.find_elements( By.XPATH, '//*[@id="filter-fixed"]/form/table/tbody/tr[5]/td/table/tbody/tr/td/label' ) for label in labels: if label.text == category: label.click() break self.driver.find_element( By.XPATH, '//*[@id="filter-fixed"]/form/input[@value="追加"]').click() time.sleep(2) rows = self.driver.find_elements( By.XPATH, '//*[@id="transactions"]/table/tbody/tr') self.assertEqual(len(rows), 2) tds = rows[1].find_elements(By.TAG_NAME, 'td') self.assertEqual( tds[0].text, str(now.year) + "/" + str.zfill(str(now.month), 2) + "/" + '03') self.assertEqual(tds[1].text, item) self.assertEqual(tds[2].text, '1,000') self.assertEqual(tds[3].text, method) self.assertEqual(tds[4].text, category) # 未チェック確認 self.assertEqual( Color.from_string( rows[1].value_of_css_property('background-color')), Color.from_string('rgba(0, 0, 0, 0)')) # 入力欄が戻っていることを確認 self._assert_initialized_add_mini(now.year, now.month)
def is_color(str_): """ Whether or not the string represents a color. :param str_: :return: """ try: Color.from_string(str_) return True except ValueError: return False
def assertion(local_driver): regular_price = local_driver.find_element_by_css_selector( "s.regular-price") regular_price_color = Color.from_string( regular_price.value_of_css_property('color')) assert regular_price_color.red == regular_price_color.blue == regular_price_color.green campaign_price = local_driver.find_element_by_css_selector( ".campaign-price") campaign_price_color = Color.from_string( campaign_price.value_of_css_property('color')) assert campaign_price_color.green == campaign_price_color.blue == 0 assert campaign_price.get_attribute("tagName") == 'STRONG' assert int_from_string(campaign_price.value_of_css_property('font-size')) \ > int_from_string(regular_price.value_of_css_property('font-size'))
def test_compare_product_info(app): link = app.product.get_product_link_from_main_page() product_from_main_page = app.product.get_product_from_main_page() product_from_product_page = app.product.get_product_from_product_page(link) # а) на главной странице и на странице товара совпадает текст названия товара assert product_from_main_page.name == product_from_product_page.name # б) на главной странице и на странице товара совпадают цены (обычная и акционная) assert product_from_main_page.regular_price_text == product_from_product_page.regular_price_text assert product_from_main_page.campaign_price_text == product_from_product_page.campaign_price_text # в) обычная цена зачёркнутая и серая (можно считать, что "серый" цвет это такой, у которого в # RGBa представлении одинаковые значения для каналов R, G и B) regular_price_red_main_page = Color.from_string( product_from_main_page.regular_price_color).red regular_price_green_main_page = Color.from_string( product_from_main_page.regular_price_color).green regular_price_blue_main_page = Color.from_string( product_from_main_page.regular_price_color).blue assert ((product_from_main_page.regular_price_style == "line-through") and (regular_price_red_main_page == regular_price_green_main_page == regular_price_blue_main_page)) regular_price_red_product_page = Color.from_string( product_from_product_page.regular_price_color).red regular_price_green_product_page = Color.from_string( product_from_product_page.regular_price_color).green regular_price_blue_product_page = Color.from_string( product_from_product_page.regular_price_color).blue assert ((product_from_product_page.regular_price_style == "line-through") and (regular_price_red_product_page == regular_price_green_product_page == regular_price_blue_product_page)) # г) акционная жирная и красная (можно считать, что "красный" цвет это такой, у которого # в RGBa представлении каналы G и B имеют нулевые значения) campaign_price_green_main_page = Color.from_string( product_from_main_page.campaign_price_color).green campaign_price_blue_main_page = Color.from_string( product_from_main_page.campaign_price_color).blue assert ( (int(product_from_main_page.campaign_price_style) > 600) and (campaign_price_green_main_page == campaign_price_blue_main_page == 0)) campaign_price_green_product_page = Color.from_string( product_from_product_page.campaign_price_color).green campaign_price_blue_product_page = Color.from_string( product_from_product_page.campaign_price_color).blue assert ((int(product_from_product_page.campaign_price_style) > 600) and (campaign_price_green_product_page == campaign_price_blue_product_page == 0)) # д) акционная цена крупнее, чем обычная (это тоже надо проверить на каждой странице независимо) assert product_from_main_page.campaign_price_height > product_from_main_page.regular_price_height assert product_from_product_page.campaign_price_height > product_from_product_page.regular_price_height
def get_view_color_values(self): grid = Color.from_string( self.web_driver.find_element_by_name( "view_grid").value_of_css_property('color')).hex tile = Color.from_string( self.web_driver.find_element_by_name( "view_tile").value_of_css_property('color')).hex list = Color.from_string( self.web_driver.find_element_by_name( "view_list").value_of_css_property('color')).hex self.web_session.logger.debug("grid: {} tile: {} list: {}".format( grid, tile, list)) return grid, tile, list
def get_default_value(htmlfile, xpath, name, css=True): cwd = os.path.dirname(os.path.realpath(__file__)) driver = None while True: try: driver = selenium.webdriver.Firefox() #driver = selenium.webdriver.PhantomJS() break except: time.sleep(1) driver.get('file://' + cwd + '/' + htmlfile) #driver.set_window_size(800, 600) #driver.maximize_window(); element = driver.find_element_by_xpath(patch_xpath(xpath)) if css: value = element.value_of_css_property(name) else: value = element.get_attribute(name) if not value: value = '' if '-moz-' in value: value = value.replace('-moz-', '') if 'color' in name: try: value = Color.from_string(value).hex except: pass driver.quit() time.sleep(1) return value
def test__favorite_job_favorite_icon_is_filled__should_pass(self): driver = self.driver time.sleep(1) favorite_btn = driver.find_element_by_link_text('Favorite Jobs') favorite_btn.click() time.sleep(DELAY_SHORT) # --------------- KEEP THIS SECTION FOR PAGINATION START-------- # i = 0; # page_count = driver.find_elements_by_class_name('page-item ').__len__() # for i in range(i, page_count-2): # if i <= page_count-3: # if page_count = # page = driver.find_element_by_css_selector('.page-item.active').text # time.sleep(1) # self.assertEqual(page, str(i+1)) # else: # time.sleep(1) # --------------- KEEP THIS SECTION FOR PAGINATION END-------- time.sleep(1) job_list = driver.find_elements_by_class_name('job-list') for job in job_list: try: fill_color = job.find_element_by_class_name( 'feather-heart').value_of_css_property('fill') fill_color_hex = Color.from_string(fill_color).hex self.assertEqual(fill_color_hex, LOVE_ICON_FILL) time.sleep(1) except: self.fail()
def test_manual_add_tmp(self): now = datetime.now() # 前処理 self._login() self.driver.get(self.live_server_url + reverse('moneybook:add')) # テスト self.driver.find_element(By.ID, 'a_day').send_keys('5') self.driver.find_element(By.ID, 'a_item').send_keys('マニュアルテスト') self.driver.find_element(By.ID, 'a_price').send_keys('500') self.driver.find_element(By.XPATH, '//form[4]/table/tbody/tr[7]/td/label[2]').click() self.driver.find_element(By.XPATH, '//form[4]/input[@type="button"]').click() self.driver.get(self.live_server_url + reverse('moneybook:index')) rows = self.driver.find_elements(By.XPATH, '//*[@id="transactions"]/table/tbody/tr') self.assertEqual(len(rows), 2) tds = rows[1].find_elements(By.TAG_NAME, 'td') self.assertEqual(tds[0].text, str(now.year) + "/" + str.zfill(str(now.month), 2) + "/" + '05') self.assertEqual(tds[1].text, 'マニュアルテスト') self.assertEqual(tds[2].text, '500') self.assertEqual(tds[3].text, '銀行') self.assertEqual(tds[4].text, '立替') self.assertEqual(Color.from_string(rows[1].value_of_css_property('background-color')), Color.from_string('rgba(0, 0, 0, 0)')) # direction確認 tds[5].find_element(By.TAG_NAME, 'a').click() self.assertEqual(self.driver.find_element(By.XPATH, '//form/table[1]/tbody/tr[4]/td[1]/input[2]').is_selected(), False)
def test_colors(): driver = webdriver.Chrome() driver.implicitly_wait(7) email = "*****@*****.**" pw = "Passw0rd!" driver.get("https://v2.whil.blue") driver.find_element_by_name("email").send_keys(email) driver.find_element_by_name("password").send_keys(pw, Keys.ENTER) sleep(4) driver.find_element_by_partial_link_text('Exit').click() sleep(3) el = driver.find_element_by_xpath( "//a[./img and ./div[text()='Health']]").click() # action = webdriver.common.action_chains.ActionChains(driver) # action.move_to_element_with_offset(el, 0, 0) # action.click() # action.perform() driver.find_element_by_xpath("//span[text()= 'EXPLORE COLLECTIONS']") # driver.find_element_by_css_selector("html/body/div[1]/div/div/main/div/div[3]/div/div[2]/div/div/a[1]/img").click() driver.find_element_by_css_selector("img[alt='Icon Health']").click() rgb1 = driver.find_element_by_xpath( '//div[contains(@class, "goalsHeader"]').value_of_css_property( "background-color") hex1 = Color.from_string(rgb1).hex driver.back() sleep(2) driver.find_element_by_css_selector("img[alt='Icon Health']").click() rgb2 = driver.find_element_by_xpath( '//div[@class="src-containers-goals-___styles__goalsHeader___1VP2m"]' ).value_of_css_property("background-color") hex2 = Color.from_string(rgb2).hex driver.back() sleep(2) driver.find_element_by_xpath("//div[text()='Relationships']").click() rgb3 = driver.find_element_by_xpath( '//div[@class="src-containers-goals-___styles__goalsHeader___1VP2m"]' ).value_of_css_property("background-color") hex3 = Color.from_string(rgb3).hex assert hex1 == "#30a064" assert hex2 == "#475d6f" assert hex3 == "#ffab20"
def get_color_message_error(self): try: WebDriverWait(self._driver, 1).until( expected_conditions.text_to_be_present_in_element( (By.XPATH, self._message_error), "User not found")) except TimeoutException: print("Закончилось время ожидания элемента 'User not found'") rgb = self._driver.find_elements_by_xpath(self._message_error)[0].value_of_css_property("color") return Color.from_string(rgb).hex
def test_explore_stock_color(self): _explore_css = 'div.span4:nth-child(1) > ul:nth-child(1) > li:nth-child(1) > a:nth-child(1)' _expected_result ='#0066cc' actual_color = self.driver.find_element_by_css_selector(_explore_css).value_of_css_property('color') actual_result = Color.from_string(actual_color).hex assert actual_result == _expected_result, "CURRENT: {0}, EXPECTED: {1}".format(actual_result, _expected_result)
def test_tags_selection(self): self.profile_page.open_tags_modal() bg_color = self.profile_page.select_golang_tag() actual = Color.from_string(bg_color).hex expected = '#9cbdb6' self.assertEqual( expected, actual, f'Selected tag background color {actual} doesn\'t match {expected}' )
def test_empty_form_submitted(self): self.driver.find_element(By.CLASS_NAME, "my-tui").click() time.sleep(2) self.driver.switch_to.window(self.driver.window_handles[1]) email = self.driver.find_element(By.ID, "email") password = self.driver.find_element(By.ID, "pass") email.clear() password.clear() rgb = email.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print("E-mail input color is: ", hex) rgb = password.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print("Password input color is: ", hex) self.driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click() time.sleep(2) form_message = self.driver.find_element_by_css_selector("form-message") print("Alerts are displayed: ", form_message.is_displayed()) print("\n Email alert and input color:") emailAlert = self.driver.find_element( By.CSS_SELECTOR, 'form-message[content = "Wpisz poprawny adres e-mail."]') print("Email alert is displayed: ", emailAlert.is_displayed()) # driver.getCssValue(email, 'background-color') rgb = email.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print("Color of email input changed to: ", hex) print("\n Password alert and input color:") passAlert = self.driver.find_element( By.CSS_SELECTOR, 'form-message[content = "Wpisz hasło."]') print("Password alert is displayed: ", passAlert.is_displayed()) rgb = password.value_of_css_property('background-color') hex = Color.from_string(rgb).hex print("Color of password input changed to: ", hex)
def test_check_random_failed_button_font_color(self, browser, login, logout): """Check font color if click random 'Failed' button""" self.open_run_test_page_for_1st_test(browser) run_test_page = RunTestPage(browser) n = run_test_page.click_random_failed_btn() print("n=", n) random_failed = RunTestPageLocators.TC_N_FAILED_BTNS print("Random failed = ", random_failed) black_font = Color.from_string( run_test_page.find_elements(random_failed) [n].value_of_css_property("color")).hex print("Black font = ", black_font) run_test_page.move_mouse_on_element(random_failed, 0) new_color = Color.from_string( run_test_page.find_elements(random_failed) [n].value_of_css_property("color")).hex assert new_color == '#fdfdfd' # black_font == '#212529' and run_test_page.back_to_suite_btn_click()
def get_text_features(ele, win_size, img_ele): """ calculate element font size and position percentage in the window :param ele: selenium.webdriver.remote.webelement.WebElement :param win_size: {'height':, 'width':} :return: font_size, position_x, position_y by percentage, """ try: x, y = ele.location['x'], ele.location['y'] # TODO: use location_once_scrolled? except: x, y = -1, -1 win_h, win_w = win_size['height'], win_size['width'] try: font_str = ele.value_of_css_property('font-size') except: font_str = -1 # print(font_str) # print(type(font_str)) font_size = int(config.REGEX_CACHE['num'].findall(font_str)[0]) # calculate color contrast text_c = Color.from_string(ele.value_of_css_property('color')) back_c = Color.from_string(ele.value_of_css_property('background-color')) contrast = calc_color_contrast(rgb_unpack(text_c), rgb_unpack(back_c), float(text_c.alpha)) # calculate luminance r, g, b = rgb_unpack(text_c) luminance = calc_luminance((r, g, b)) # calculate img distance if img_ele is None: dx, dy, dxy = -1, -1, -1 else: try: dx, dy, dxy = elements_dist(ele, img_ele) except StaleElementReferenceException: dx, dy, dxy = -1, -1, -1 return font_size, float(x) / win_w, float(y) / win_h, contrast, luminance, dx, dy, dxy, r, g, b
def test_click_passed_btn_is_active_for_1st_step(self, browser, login, logout): """Check that 'Passed' button is active and focus after click""" self.open_run_test_page_for_1st_test(browser) run_test_page = RunTestPage(browser) passed_btn = RunTestPageLocators.TC_N_STEP_PASSED_BTN background_color = Color.from_string( run_test_page.find_elements(passed_btn)[0].value_of_css_property( "background-color")).hex print("BACKGROUND COLOR =", background_color) color = Color.from_string( run_test_page.find_elements(passed_btn)[0].value_of_css_property( "color")).hex run_test_page.failed_btn_1_step_click() run_test_page.passed_btn_1_step_click() print("BACKGROUND COLOR =", background_color) # background_color == 'rgba(250, 253, 250, 1)' and assert 'focus active' in run_test_page.visible_element_get_class(passed_btn, 0) and \ color == '#212529', \ " 'focus active' should be in class and button color = green" run_test_page.back_to_suite_btn_click()
def test_element_color(self): display = Display(visible=0, size=(800, 800)) display.start() options = webdriver.ChromeOptions() self.driver =webdriver.Chrome() self.driver.get('http://localhost:8000/pagina1/') elem = self.driver.find_element_by_tag_name('h1') rgb = elem.value_of_css_property('color') hex = Color.from_string(rgb).hex self.assertTrue(hex) self.driver.close()
def upcoming_workshop_btn_test(self): workshops_title = self.driver.find_elements( *WorkShopPageLocator.WORKSHOP_TITLE_ELEMENT) color_to_match = '#1bb4b9' for i in range(len(workshops_title)): rgb = workshops_title[i].value_of_css_property('background') hex_value = Color.from_string(rgb[:17]).hex if color_to_match == hex_value: print(f'Colors for element is same as {color_to_match}') else: print('Color are not the same') return True
def color_element_from_url(browser): # browser = webdriver.Chrome(ChromeDriverManager().install()) # browser.get(url) # Find elements which contain 'color' in style attribute candi_elems = browser.find_elements_by_xpath( "//*[contains(@style, 'color') and \ not (contains(@style, 'background'))]" ) result = [] index = 1 for ce in candi_elems: # If there is no text, continue to next element if ce.text == "": continue # single_r format : [index, text element, text color, background element, background color] single_r = [] single_r.append(index) # Find parent element of candidate element which indicates background p_of_ce = ce.find_element_by_xpath("..") style_of_ce = ce.get_attribute("style") # Get background color from the parent element p_back = p_of_ce.value_of_css_property("background-color") for soc in style_of_ce.split(";"): if "color" in soc: cstr = soc.split(":")[1].strip() ccol = Color.from_string( cstr) # Convert text color to Color class single_r.append(ce) single_r.append(ccol) break p_back = Color.from_string( p_back) # Convert background color to Color class single_r.append(p_of_ce) single_r.append(p_back) index += 1 result.append(single_r) return result
def state_of_cloud(context,search_cloud,state): from .clouds import find_cloud cloud = find_cloud(context,search_cloud.lower()) if not cloud: assert False, "Cloud %s is not added" % cloud if state not in ['enabled','disabled']: raise Exception('Unknown type of state') button_state = cloud.find_element_by_class_name('icon').value_of_css_property('background-color') color = Color.from_string(button_state).hex actual_state = get_color_from_state(state) if color != actual_state: assert False, "Cloud should be %s, but it is not" % state
def getDefaultValue(filepath, xpath, name, css=True): driver = webdriver.Firefox() # driver = webdriver.PhantomJS() driver.maximize_window() driver.get('file://' + filepath) element = driver.find_element_by_xpath(xpath) if css: value = element.value_of_css_property(name) else: value = element.get_attribute(name) if not value: value = '' if '-moz-' in value: value = value.replace('-moz-', '') if 'color' in name: value = Color.from_string(value).hex driver.quit() return value
def test_home(self): help_css = 'div.span4.offset1.footer-links-logos > div.hidden-phone > div.row-fluid.footer-links > div.span4 > ul > li:nth-child(3) > a' most_popular_q__css = '#rn_PageContent > div > h2' expected_result = "MOST POPULAR QUESTIONS" expected_url = "https://google.custhelp.com/app/home" self.driver.find_element_by_css_selector(help_css).click() actual_result = self.driver.find_element_by_css_selector(most_popular_q__css).text assert actual_result == expected_result, actual_result current_url = self.driver.current_url self._wait_for_element(most_popular_q__css) assert current_url == expected_url, current_url popular_questions_css = '#rn_ProductCategoryList_main_3 > h2:nth-child(1) > div > a' actual_color = self.driver.find_element_by_css_selector(popular_questions_css).value_of_css_property('color') expected_color = '#c87100' actual_color_result = Color.from_string(actual_color).hex assert actual_color_result == expected_color, actual_color_result
def test_isolated_component(): assert Color.from_string("#ffffff") == Color(255, 255, 255)
def test_hash(self): hash1 = hash(Color.from_string("#f00")) hash2 = hash(Color.from_string("rgb(255, 0, 0)")) assert hash1 == hash2
def test_equals(self): assert Color.from_string("#f00") == Color.from_string("rgb(255, 0, 0)") assert Color.from_string("rgba(30, 30, 30, 0.2)") != Color.from_string("rgba(30, 30, 30, 1)")
def test_named_color(self): assert Color.from_string("green").rgba == "rgba(0, 128, 0, 1)" assert Color.from_string("gray").rgba == "rgba(128, 128, 128, 1)" assert Color.from_string("aqua").hex == "#00ffff"
def test_rgb_to_rgb(): rgb = "rgb(1, 2, 3)" assert Color.from_string(rgb).rgb == rgb
def get_filter_color(self, coding='hex'): color = self._selenium_root.value_of_css_property('background-color') return getattr(Color.from_string(color), coding).upper()
def test_rgb_pct_to_rgba(self): rgb = "rgb(10%, 20%, 30%)" assert Color.from_string(rgb).rgba == "rgba(25, 51, 76, 1)"
def test_hex_to_rgb(self): hex_ = "#01Ff03" rgb = "rgb(1, 255, 3)" assert Color.from_string(hex_).rgb == rgb
def test_hex_to_hex(self): hex_ = "#ff00a0" assert Color.from_string(hex_).hex == hex_
def test_rgba_pct_to_rgba(self): rgba = "rgba(10%, 20%, 30%, 0.5)" assert Color.from_string(rgba).rgba == "rgba(25, 51, 76, 0.5)"
def test_rgba_to_rgba(self): rgba = "rgba(1, 2, 3, 0.5)" assert Color.from_string(rgba).rgba == rgba
def test_rgb_allows_whitespace(self): rgb = "rgb(\t1, 2 , 3)" assert Color.from_string(rgb).rgb == "rgb(1, 2, 3)"
def testShouldAllowInheritedStylesToBeUsed(driver, pages): pages.load("javascriptPage.html") element = driver.find_element(by=By.ID, value="green-item") backgroundColour = Color.from_string(element.value_of_css_property("background-color")) assert backgroundColour == Color.from_string("transparent")
def test_rgb_to_rgba(self): rgb = "rgb(1, 2, 3)" assert Color.from_string(rgb).rgba == "rgba(1, 2, 3, 1)"
def test_hex3_to_rgba(self): assert Color.from_string("#0f3").rgba == "rgba(0, 255, 51, 1)"
def test_named_color(): assert Color.from_string("green").rgba == "rgba(0, 128, 0, 1)" assert Color.from_string("gray").rgba == "rgba(128, 128, 128, 1)" assert Color.from_string("aqua").hex == "#00ffff" assert Color.from_string("transparent").rgba == "rgba(0, 0, 0, 0)"
def test_rgb_to_hex(self): assert Color.from_string("rgb(1, 255, 3)").hex == "#01ff03"
def test_string_representations(self): hex_ = "#01Ff03" assert str(Color.from_string(hex_)) == "Color: rgba(1, 255, 3, 1)" assert repr(Color.from_string(hex_)) == "Color(red=1, green=255, blue=3, alpha=1)"