python中的Selenium webdriver:跨测试用例重用相同的web浏览器

2024-05-13 04:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

Python新手来了。 我试图在我的测试用例中重复使用同一个浏览器。 但是,我不知道如何传递全局变量来实现这一点。

目前, 我有一个main.py,看起来像这样 #!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)

在setup/文件夹中有一个testcaseA.py文件,如下所示:

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与testcaseA.py基本相同

当我运行main.py时,我得到一个错误: ft1.1:回溯(最近一次呼叫最后一次): 文件“C:\ test\setup\testcaseA.py”,第10行,在安装程序中 self.driver=驱动程序#获取全局驱动程序变量 名称错误:未定义全局名称“DRIVER”

有什么建议吗?

谢谢!


Tags: pathfrompyimportselfosdriverselenium
2条回答

您有一个异常,因为testcaseA.py不知道什么是驱动程序。你必须以某种方式导入它。不能直接从main.py导入它,因为这将导致循环依赖。最好的解决方案是在单独的模块中创建驱动程序。

如果您是从Python中的测试开始您的旅程,请查看nosetests库。你不会后悔的!

您可以尝试创建另一个模块(我通常使用pkg.\uu init\uu来实现这类功能),并在其中放置一个返回selenium驱动程序的函数。当然,如果已经存在,则返回缓存的。例如,在mypkg/uu init_uuu.py中

from selenium import webdriver

DRIVER = None

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

从测试中调用:

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

    def setUp(self):
        self.driver = mypkg.getOrCreateWebdriver()

相关问题 更多 >