Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium webdriver in python: Re-using same web browser across testcases

Python newb here. I'm trying to re-use same browser throughout my testcases. However, I cannot figure out how to pass global variable to make this work.

Currently, I have a main.py that looks like this #!C:/Python27/python.exe

import unittest
import unittest, time, re, HTMLTestRunner, cgi
import os, sys, inspect

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

global DRIVER
DRIVER  = webdriver.Firefox()

# Make all subfolders available for importing
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
    sys.path.insert(0, cmd_folder)

# Import test cases
from setup.testcaseA import *
from setup.testcaseB import *

# serialize the testcases (grouping testcases)
suite = unittest.TestSuite() # setup new test suite
suite.addTest(unittest.makeSuite(testcaseA))
suite.addTest(unittest.makeSuite(testcaseB))

runner = HTMLTestRunner.HTMLTestRunner()
print "Content-Type: text/html\n" # header is required for displaying the website
runner.run(suite)

And I have testcaseA.py file in setup/ folder that looks like this:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re, cgi

class testcaseA(unittest.TestCase):

    def setUp(self):
        #get global driver variable <- DOESNT WORK!
        self.driver = DRIVER            

    def testcaseA(self):
        driver = self.driver
        #Bunch of tests

    def tearDown(self):
        #self.driver.quit() <- Commented out, because I want to continue re-using the browser

testcaseB.py is basically identical to testcaseA.py

When I run main.py, I get an error: ft1.1: Traceback (most recent call last): File "C:\test\setup\testcaseA.py", line 10, in setUp self.driver = DRIVER #get global driver variable NameError: global name 'DRIVER' is not defined

Any suggestions?

Thanks!

like image 975
m0dE Avatar asked Dec 12 '22 02:12

m0dE


1 Answers

You could try creating another module (I usually use pkg.__init__ for such things) and in there put a function that returns the selenium driver. Return the cached one if already exists, of course. Eg. in mypkg/__init__.py

from selenium import webdriver

DRIVER = None

def getOrCreateWebdriver():
    global DRIVER
    DRIVER = DRIVER or webdriver.Firefox()
    return DRIVER

And call from your tests with:

import mypkg
...
class testcaseA(unittest.TestCase):

    def setUp(self):
        self.driver = mypkg.getOrCreateWebdriver()
like image 188
Brad M Avatar answered Dec 22 '22 03:12

Brad M