微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何模拟django.db.connection.schema_name

如何解决如何模拟django.db.connection.schema_name

我正在尝试测试多租户django应用。我正在尝试模拟与公共租户的连接:

NULL

但是,当我在测试过程中调试此程序以检查.data方法中schema_name的值时,我得到了:

mtcars %>% count(cyll)

所以至少我知道我正在修补正确的位置。问题在于class ViewsTest(ViewTestUtilsMixin,TenantTestCase): def setUp(self): self.factory = RequestFactory() def test_some_public_only_view(self) # generate a request instance so we can call our view directly request = self.factory.get('/') with patch('tenant.views.connection.schema_name',return_value=get_public_schema_name()): response = some_public_only_view(request) self.assertEqual(response.status_code,200) 不是方法,因此它不使用返回值。

那么我该如何嘲笑some_public_only_view?正在测试的视图正在 tenant / views.py

中以这种方式使用它
<Magicmock name='schema_name' id='140578910478880'>

我也尝试过:

schema_name

这给了我:schema_name

解决方法

您可以通过以下方式使用PropertyMock模拟对象属性:

@patch('tenant.views.connection.schema_name',new_callable=PropertyMock(return_value="abc"))
def test_some_public_only_view(self,mock_schema):
...

此处为文档https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock

无论如何,您的方法没有错,事实上,我也测试了您的代码:

with patch.object('tenant.views.connection','schema_name',get_public_schema_name()):

我没有得到任何错误。

我在没有设置正确的数据库后端的情况下首次尝试时遇到了错误AttributeError: tenant.views.connection does not have the attribute 'schema_name',该错误应该来自tenant_schemas库,其中之一:postgresql_psycopg2','mysql','sqlite3' or 'oracle',我已经使用了tenant_schemas.postgresql_psycopg2

如果这是原因(数据库设置配置错误),如果您尝试运行测试而不修补schema_name,则应该出现此错误

AttributeError: 'DatabaseWrapper' object has no attribute 'schema_name'

如此处所述:https://github.com/bernardopires/django-tenant-schemas/issues/328

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。