这里是我在使用selenium进行端到端测试时使用的代码片段(我在selenium django测试中完全是新手);
from django.contrib.auth.models import User
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.chrome.webdriver import WebDriver
class MyTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
super(DashboardTest, cls).setUpClass()
cls.selenium = WebDriver()
cls.user = User.objects.create_superuser(username=...,
password=...,
email=...)
time.sleep(1)
cls._login()
@classmethod
def _login(cls):
cls.selenium.get(
'%s%s' % (cls.live_server_url, '/admin/login/?next=/'))
...
def test_login(self):
self.selenium.implicitly_wait(10)
self.assertIn(self.username,
self.selenium.find_element_by_class_name("fixtop").text)
def test_go_to_dashboard(self):
query_json, saved_entry = self._create_entry()
self.selenium.get(
'%s%s' % (
self.live_server_url, '/dashboard/%d/' % saved_entry.id))
# assert on displayed values
def self._create_entry():
# create an entry using form and returns it
def test_create(self):
self.maxDiff = None
query_json, saved_entry = self._create_entry()
... assert on displayed values我注意到在每次测试之间,登录都是不持久的。因此,我可以在_login中使用setUp,但使测试更慢。
那么如何在测试之间保持持久的登录呢?测试这些测试的最佳实践是什么(djnago selenium测试)?
发布于 2016-04-18 08:28:38
kevinharvey给我指明了解决方案!最后,找到了一种减少测试时间和跟踪所有测试的方法:
我将以test..开头的所有方法重命名为_test_..,并添加了一个调用每个_test_方法的main方法:
def test_main(self):
for attr in dir(self):
# call each test and avoid recursive call
if attr.startswith('_test_') and attr != self.test_main.__name__:
with self.subTest("subtest %s " % attr):
self.selenium.get(self.live_server_url)
getattr(self, attr)()这样,我就可以单独测试(调试)每个方法:)
发布于 2016-04-14 16:47:56
通过浏览器与Selenium的测试是缓慢的,周期。然而,它们是非常有价值的,因为它们是您在自动化真正的用户体验方面的最佳选择。
您不应该尝试用Selenium编写真正的单元测试。相反,使用它来编写一个或两个大型功能测试。尝试从开始到结束捕获整个用户交互。然后构造您的测试套件,以便您可以单独运行快速、非Selenium单元测试,并且只需要偶尔运行缓慢的功能测试。
您的代码看起来很好,但是在这个场景中,您需要将test_go_to_dashboard和test_create组合成一个方法。
https://stackoverflow.com/questions/36593784
复制相似问题