Naga P Naga P -3 years ago 106
Python Question

Python Selenium - I'm trying to use pytest framework , running into errors

from selenium import webdriver
from selenium.webdriver.common.by import By

from commonPages.LoginPage import LoginPage
from util.InitialSetUp import InitSetup

i = InitSetup()
chrome_options = i.close_popup()
driver = webdriver.Chrome(chrome_options=chrome_options)

log = LoginPage(driver)
log.nav_login_page()

class Test_Home_Page:
def test_logo_exists(self):
logo = driver.find_element(By.CLASS_NAME, 'logo')
assert logo

def test_user_profile_section_exists(self):
user_profile_section = driver.find_element(By.CLASS_NAME, 'user-name')
assert user_profile_section

def test_user_profile_link_click_opens_dropdown(self):
user_profile_link = driver.find_element(By.CLASS_NAME, 'user-dropdown-button')
user_profile_link.click()

user_profile_menu_item = driver.find_element(By.CLASS_NAME, 'user-profile-menu-item')
assert user_profile_menu_item

driver.close()


When run the above program, the program fails when function #2 starts :
def test_user_profile_section_exists(self):


It throws an error:

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x03AB28D0>
response = {'sessionId': '57da643e085012ed03d18a284c063c24', 'status': 7, 'value': {'message': 'no such element: Unable to locate...r info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64)'}}


It executes perfectly, when there is only one function in the program.

Answer Source

You are getting this error because that class element really doesn't exists or not visible. Again driver.find_element(By.CLASS_NAME, 'user-name') is not Boolean type, so you cannot use assert on that directly.

You can use below approach for tests validation for all tests.

def test_user_profile_section_exists(self):
    try:
        driver.find_element(By.CLASS_NAME, 'user-name')
    except NoSuchElementException:
        assert False

    assert True
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download