使用FastTenantTestCase创建租户报错,求解决方法
Django Tenants测试异常解决方案:Can't create tenant outside the public schema
问题场景
使用Django 3.2.16 + django-tenants 3.3.4版本,通过FastTenantTestCase编写测试用例时触发以下异常:
Exception: Can't create tenant outside the public schema. Current schema is fast_test.
测试代码
from django_tenants.test.cases import FastTenantTestCase class TestWorkflowDocumentCategories(FastTenantTestCase): """测试工作流文档分类""" def setUp(self) -> None: self.client = TenantClient(self.tenant) self.url = reverse('sample-url-list') self.existing_document_categories = {'xyz'} self.factory = SampleFactory() def test_document_categories_list(self) -> None: response = self.client.get(self.url, {}, **self.header) self.assertEqual(response.status_code, status.HTTP_200_OK)
错误栈信息
Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django_tenants/test/cases.py", line 134, in setup_test_tenant_and_domain cls.tenant.save(verbosity=cls.get_verbosity()) File "/usr/local/lib/python3.9/site-packages/django_tenants/models.py", line 100, in save raise Exception("Can't create tenant outside the public schema. " Exception: Can't create tenant outside the public schema. Current schema is fast_test.
解决方案
1. 强制在setUpClass阶段切换到public schema
重写setUpClass方法,在创建测试租户前手动切换到public schema,确保租户创建上下文正确:
from django_tenants.test.cases import FastTenantTestCase from django_tenants.utils import schema_context, get_public_schema_name class TestWorkflowDocumentCategories(FastTenantTestCase): """测试工作流文档分类""" @classmethod def setUpClass(cls): # 强制切换到public schema执行租户创建逻辑 with schema_context(get_public_schema_name()): super().setUpClass() # 切换回测试租户的schema,保证后续测试环境正确 with schema_context(cls.tenant.schema_name): pass def setUp(self) -> None: self.client = TenantClient(self.tenant) self.url = reverse('sample-url-list') self.existing_document_categories = {'xyz'} self.factory = SampleFactory() def test_document_categories_list(self) -> None: response = self.client.get(self.url, {}, **self.header) self.assertEqual(response.status_code, status.HTTP_200_OK)
2. 全局重置测试schema上下文
如果项目中有自定义测试基类,可在基类中添加前置处理,确保所有测试类执行前都重置到public schema:
from django.test import TestCase from django_tenants.utils import schema_context, get_public_schema_name class BaseTenantTestCase(TestCase): @classmethod def setUpClass(cls): with schema_context(get_public_schema_name()): super().setUpClass()
然后让测试类按顺序继承基类和FastTenantTestCase:
class TestWorkflowDocumentCategories(BaseTenantTestCase, FastTenantTestCase): # 原有测试代码...
3. 检查配置正确性
确认settings.py中PUBLIC_SCHEMA_NAME配置为默认值(或你自定义的public schema名称),避免配置错误导致识别失败:
# settings.py PUBLIC_SCHEMA_NAME = 'public'
内容的提问来源于stack exchange,提问作者Mech.py
相关产品推荐
相关产品推荐

