You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium测试的setUp方法中创建有效的Django测试用户?

问题原因与解决方案

核心问题

你遇到的问题根源在于:

  • LiveServerTestCase会自动创建独立的测试数据库,你在setUp中创建的用户仅存在于这个临时数据库中。
  • 但测试代码硬编码了http://127.0.0.1:8000/login,这个地址指向的是手动启动的开发服务器,而开发服务器连接的是主项目数据库,测试用例创建的用户根本不在这个库中,自然无法登录。

无需预先创建用户的正确实现方式

只需调整两个关键环节,就能让测试用例自动创建用户并完成登录验证:

1. 使用测试服务器的动态URL

LiveServerTestCase提供了live_server_url属性,它指向自动启动的测试服务器地址,用这个属性拼接登录路径,确保Selenium访问的是连接测试数据库的服务器。

2. 替换固定等待为显式等待

sleep(3)是不可靠的硬等待,改用Selenium的显式等待,直到元素加载完成再进行断言,能大幅提升测试稳定性。

修改后的完整测试代码

from django.contrib.auth.models import User
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class TestLoginFormFirefox(LiveServerTestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        # 在测试数据库中创建用户
        self.good_user = User.objects.create_user(username="unittest", password="this_is_unit")

    def tearDown(self):
        self.driver.quit()  # 用quit()彻底关闭浏览器,比close()更彻底

    def test_index_login_success(self):
        """验证用户登录成功后导航栏显示个人资料链接"""
        # 使用测试服务器的动态URL
        self.driver.get(f"{self.live_server_url}/login")
        
        # 填写登录表单
        username_field = self.driver.find_element(by=By.ID, value='id_username')
        password_field = self.driver.find_element(by=By.ID, value='id_password')
        username_field.send_keys('unittest')
        password_field.send_keys("this_is_unit")
        
        # 提交表单
        login_button = self.driver.find_element(by=By.CLASS_NAME, value="btn-primary")
        login_button.click()  # 用click()更符合实际操作,替代send_keys(Keys.RETURN)
        
        # 显式等待个人资料链接加载完成,最长等待10秒
        profile_link = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.ID, 'id_profile_link'))
        )
        
        # 断言链接文本正确
        assert profile_link.text == 'unittest'

额外注意事项

  • 运行测试时不要手动启动开发服务器,LiveServerTestCase会自动启动一个临时测试服务器,测试结束后自动关闭。
  • 如果测试需要其他依赖数据,同样可以在setUp或setUpTestData中创建,这些数据都会被隔离在测试数据库中,不会影响主项目数据。

内容的提问来源于stack exchange,提问作者nerdenator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:01:07