Django 4.2后台管理页面登录测试失败问题排查求助
问题原因及解决方案
核心问题:密码未哈希存储
Django用户系统不会直接存储明文密码,authenticate方法仅验证经过哈希处理的密码。你的fixture文件中直接写入明文密码"123admin",导致:
- 第二个测试中
authenticate返回None,密码匹配失败 - 第一个Selenium测试登录失败,页面停留在登录页,因此找不到"Site administration"文本
修复步骤
1. 生成正确哈希后的密码
在Django shell中生成密码哈希值:
python manage.py shell
执行以下代码获取哈希字符串:
from django.contrib.auth.hashers import make_password print(make_password("123admin"))
将输出的哈希字符串替换db_admin_fixture.json里的password字段值。
2. 修正test_admin_login测试逻辑
authenticate函数无需传入request参数(Django 4.2中该参数为可选,传None或省略均可)- 简化断言逻辑,直接验证用户状态:
@pytest.mark.django_db def test_admin_login(): user = authenticate(username='admin@email.com', password='123admin') assert user is not None assert user.is_active assert user.is_staff
3. 调整fixture作用域(可选)
当前db_fixture_setup的scope="session"会让数据在所有测试间共享,若其他测试修改用户数据可能影响结果。可改为函数级作用域避免数据污染:
@pytest.fixture(scope="function") def db_fixture_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command("loaddata","db_admin_fixture.json")
4. Selenium测试添加等待优化(可选)
登录后添加显式等待,避免页面未加载完成就执行断言:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC @pytest.mark.selenium def test_dashboard_admin_login(live_server, db_fixture_setup, chrome_browser_instance): browser = chrome_browser_instance browser.get(f"{live_server.url}/admin/login/?next=/admin/") user_name = browser.find_element(By.ID, "id_username") user_pwd = browser.find_element(By.ID, "id_password") submit = browser.find_element(By.XPATH,'//input[@value="Log in"]') user_name.send_keys("admin@email.com") user_pwd.send_keys("123admin") submit.click() # 等待页面加载完成,直到目标标题出现 WebDriverWait(browser, 10).until( EC.text_to_be_present_in_element((By.TAG_NAME, "h1"), "Site administration") ) assert "Site administration" in browser.page_source
验证修复
重新运行测试即可:
pytest test_admin_page.py -v
内容的提问来源于stack exchange,提问作者manuersuper
相关产品推荐
相关产品推荐

