Django多租户Selenium测试报错:relation does not exist
解决Django多租户+Selenium测试中User表不存在的问题
问题根源
你已加载租户的fixture,但测试环境中并未为demo租户对应的schema执行数据库迁移,导致该schema下缺少auth_user等基础表,创建User时触发"relation does not exist"错误。
具体解决步骤
1. 在测试类中添加租户迁移逻辑
修改test.py,在加载fixture后为目标租户执行迁移,确保schema下的表全部创建:
from django.core.management import call_command from tenant_schemas.utils import schema_context class VisitCreationTestCase(StaticLiveServerTestCase): fixtures = ['save.json'] @classmethod def setUpClass(cls): super().setUpClass() # 为demo租户执行数据库迁移 tenant = Client.objects.first() with schema_context(tenant.schema_name): call_command('migrate', '--noinput') def check_connect(self, driver): driver.get(self.live_server_url.split("localhost")[0] + Domain.objects.first().domain + self.live_server_url.split("localhost")[1]) title = driver.title username = driver.find_element(by=By.NAME, value="login") password = driver.find_element(by=By.NAME, value="password") submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button[type='submit']") connection.set_tenant(Client.objects.first()) # 修正密码设置方式:Django需加密存储密码 user = User.objects.create(username="demo") user.set_password("testmdpusee") user.save() username.send_keys("demo") password.send_keys("testmdpusee") submit_button.click() driver.implicitly_wait(1) driver.find_element(by=By.XPATH, value="//p[contains(text(),'Aucun dossier ou fichier')]") def setUp(self) -> None: service = ChromeService(executable_path=ChromeDriverManager().install()) self.driver = webdriver.Chrome(service=service) self.check_connect(self.driver)
2. 关键修正说明
- 租户迁移:通过
schema_context切换到目标租户的schema,调用migrate命令完成表创建,这是解决"relation does not exist"的核心。 - 密码处理:原代码直接赋值
password会存储明文,导致登录验证失败,必须用set_password方法加密后保存。
额外注意事项
- 若使用
django-tenants(原django-tenant-schemas分支),确保迁移命令与版本匹配。 setUpClass在所有测试方法执行前仅运行一次,避免重复执行迁移浪费资源。- Django测试框架会自动清理测试数据库,无需手动删除租户schema。
内容的提问来源于stack exchange,提问作者Pollo9
相关产品推荐
相关产品推荐

