AlphaFoxtrot
AlphaFoxtrot

Reputation: 684

Calling functions from another file with Python/Selenium

I'm having trouble running a selenium test and trying to call a function from another file in the same directory. I've looked through many topics on importing modules but I'm having no luck. When I run test.py, it will stop at wait_until_id_is_clickable with the NoSuchElementException being raised which is in base.py. This function is successful if I put it in test.py.

test.py

import unittest
import base
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action.chains import ActionChains


class Selenium_Test(unittest.TestCase):


    def setUp(self):
        self.browser = webdriver.Firefox()

    def test_community_diversity(self):
        browser = self.browser
        browser.get("https://python.org")
        self.assertEqual(browser.title, "Welcome to Python.org")
        base.wait_until_id_is_clickable("community") #Function in base.py

        elem = browser.find_element_by_id("community")

        hover = ActionChains(browser).move_to_element(elem)
        hover.perform()
        browser.implicitly_wait(1)

        elem2 = elem.find_element_by_link_text("Diversity")
        self.assertEqual(elem2.is_displayed(), True)

    def tearDown(self):
        self.browser.close()

if __name__=="__main__":
    unittest.main()

base.py

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()

def wait_until_id_is_clickable(element,time=10):
    wait = WebDriverWait(browser, time)
    try:
        wait.until(EC.element_to_be_clickable((By.ID,element)))
    except:
        raise NoSuchElementException("Could not find element in time.")

I am using nosetests to run my tests. Any help is appreciated!

Upvotes: 1

Views: 4317

Answers (1)

Louis
Louis

Reputation: 151391

In base.py you create an extraneous browser instance. Remove this line:

browser = webdriver.Firefox()

and pass the browser you have created in test.py to wait_until_id_is_clickable. Modify the definition to:

def wait_until_id_is_clickable(browser, element, time=10):

and call it with:

base.wait_until_id_is_clickable(browser, "community")

Upvotes: 2

Related Questions