Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running functions in a python script in order

I am creating a test suite written in python using selenium webdriver. However, when I run my test, I get the error that: 'PythonOrgSearch' object has no attribute 'driver'

I am pretty sure this is because the tests are not running in order, so the driver is closed before the tests are completed. I had previously also gotten the error: "Tried to run command without establishing a connection", which I thought also indicated that the tests were not running in order so the driver hadn't started? I am not sure this is accurate though, just my best guess. My code looks like:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.action_chains import ActionChains
from urllib.request import urlopen
from html.parser import HTMLParser


gecko = os.path.normpath(os.path.join(os.path.dirname(__file__), 'geckodriver'))
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path=gecko+'.exe')


class PythonOrgSearch(unittest.TestCase):

#sets up driver to run tests
    def setUp(self):
        self.driver = driver
        self.driver.start()

    def test_opens(self):
        driver.get("url.com")
        driver.find_element_by_id('username').send_keys('user')
        driver.find_element_by_id('password').send_keys('pass')
        driver.find_elements_by_css_selector("button[type='submit']")[0].click()
        time.sleep(2);
        self.assertIn("title", driver.title)

    def ztearDown(self):
        self.driver.close()

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

EDIT: I added driver=self.driver at the start of each function

like image 863
Cassie H. Avatar asked Oct 20 '25 20:10

Cassie H.


2 Answers

It looks like you never initialized the self.driver variable. Do you have an __init__ method inside the PythonOrgSearch class declaring one?

like image 190
Costa Nostra Avatar answered Oct 22 '25 10:10

Costa Nostra


Okay, I sort of solved the problem using a workaround. Although the functions didn't run in order, they did run in the same order every time, so I put driver.quit() at the end of the function that ran last. I also (as put in the edit) adding driver=self.driver to the top of each function. As other posters have responded, it would have been better practice to put an init method in the class.

This resolution is likely not the best practice, but it does work. For people with similar issues, other responses in this thread do give some insight into the issue, I just did not find one that fixed my issue.

like image 28
Cassie H. Avatar answered Oct 22 '25 09:10

Cassie H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!