我试图在测试中有 2 个具有相同会话的浏览器窗口。请注意,由于 selenium 的限制,每个浏览器都有不同的 firefox 配置文件。
测试(您可以尝试,只要您有测试/测试人员用户)是:
import time
from django.test import LiveServerTestCase
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
class ScriptTestCase(LiveServerTestCase):
def do_admin_login(self, username, password, browser):
browser.get('%s%s' % (self.live_server_url, '/admin/'))
username_input = browser.find_element_by_name("username")
username_input.send_keys(username)
password_input = browser.find_element_by_name("password")
password_input.send_keys(password)
browser.find_element_by_xpath('//input[@value="Log in"]').click()
def test_double_window_inactivity(self):
browser0 = WebDriver()
self.do_admin_login('test', 'test', browser0)
cookie = browser0.get_cookie('sessionid')
cookies = {'name': 'sessionid', 'value': cookie['value']}
browser1 = WebDriver()
browser1.add_cookie(cookies)
print 1, browser0.get_cookie('sessionid')['value']
print 2, browser1.get_cookie('sessionid')['value']
browser1.get('%s%s' % (self.live_server_url, '/admin/'))
print 3, browser0.get_cookie('sessionid')['value']
print 4, browser1.get_cookie('sessionid')['value']
输出是:
1 08ba4efecf00d2b98aacd174ed20e144
2 08ba4efecf00d2b98aacd174ed20e144
3 08ba4efecf00d2b98aacd174ed20e144
4 cb49379190cb37735697c5c82ab300fc
如您所见,在 browser1 打开 /admin/ 后,它的 sessionid 被意外覆盖。
如何解决这个问题?我试图让 browser1 与 browser0 具有相同的会话。
修复代码,感谢 Hedde ---
def test_double_window_inactivity(self):
self.browser.execute_script('window.open("/admin/", "other")')
for win in self.browser.window_handles:
self.browser.switch_to_window(win)
self.assertWarningHidden()
time.sleep(5+1) # Added one second to compensate for fadeIn
for win in self.browser.window_handles:
self.browser.switch_to_window(win)
self.assertWarningShown()
time.sleep(5+1) # Added one second to compensate for lag
for win in self.browser.window_handles:
self.browser.switch_to_window(win)
self.assertWarningNotInPage()