当我们在使用pytest框架执行测试用例时发现,单独执行每个测试用例时都能通过,但多个执行时只有第一个通过后面的报: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=8497): Max retries exceeded with url: /session/431f5c10cc45
ef9536226f1e6f453861/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020AE7FDBD00>: Failed to establish a new
connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。'))错误
问题:
在执行第二个 test方法时,其实还是使用的第一个test中实例出来的driver,而此时第一个test中的driver已经被设置为None了
解决方法:
每次执行test方法时都使用同一个 driver 对象即可。
class TestLogin:
driver = None
@classmethod
def setup_class(cls):
cls.driver = webdriver.Chrome()
cls.driver.maximize_window()
cls.driver.implicitly_wait(10)
def setup_method(self):
self.driver.get("http://127.0.0.1/")
def teardown_method(self):
# 这里可以根据需要决定是否在每个测试方法后进行清理操作
# 比如清除 cookies 等
# self.driver.delete_all_cookies()
上面代码分析:driver
被定义为类变量,通过 @classmethod
装饰的 setup_class
方法进行初始化。这样,在各个测试方法中都可以通过 self.driver
来访问同一个 driver
对象。
方法二:
如果希望更加严格地控制 driver
对象的创建和使用,可以考虑使用单例模式来确保始终只有一个 driver
实例存在
class SingletonDriver:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = webdriver.Chrome()
cls._instance.maximize_window()
cls._instance.implicitly_wait(10)
return cls._instance
class TestLogin:
def setup_class(self):
self.driver = SingletonDriver()
def setup_method(self):
self.driver.get("http://127.0.0.1/")
def teardown_method(self):
# 这里可以根据需要决定是否在每个测试方法后进行清理操作
# 比如清除 cookies 等
# self.driver.delete_all_cookies()
这里定义了一个 SingletonDriver
类来实现单例模式,确保在整个测试过程中只有一个 driver
实例被创建。
通过以上方法,可以确保在每次执行测试方法时都使用同一个 driver
对象,减少资源消耗和提高测试效率。同时,需要注意在测试结束后正确地关闭 driver
对象以释放资源。