如何在 Django 中测试非托管数据库?

问题描述

我正在开发一个使用非托管模型连接到外部数据库的 Django API。我想在我的单元测试中在这个数据库中创建一些对象,这样我就可以测试几个端点,但我不能,因为这个数据库是完全不受管理的,根本没有迁移。我曾尝试使用 schema_editor 创建表,但它不起作用,因为架构不存在。我试图运行原始 SQL 来创建架构,但它不起作用。我尝试了许多不同事物的许多变体,老实说,我不知道哪些值得在这里详细描述。在我当前的设置中,我有一个自定义测试运行器,看起来有点像这样:

from django.db import connections
from django.test.runner import DiscoverRunner


class TestRunner(DiscoverRunner):

    def setup_databases(self,*args,**kwargs):
        super().setup_test_environment(*args,**kwargs)
        with connections["unmanaged_db"].cursor() as cursor:
            cursor.execute(
                """
                CREATE SCHEMA myschema;
                CREATE TABLE myschema.mytable (
                    ...
                );
                """
            )

当我运行测试并尝试使用工厂在数据库中创建一些对象时,我得到:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 1247,in _fixture_teardown
    if self._should_check_constraints(connections[db_name]):
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 1255,in _should_check_constraints
    not connection.needs_rollback and connection.is_usable()
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py",line 291,in is_usable
    with self.connection.cursor() as cursor:
AttributeError: 'NoneType' object has no attribute 'cursor'

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 284,in _setup_and_call
    self._post_teardown()
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 1006,in _post_teardown
    self._fixture_teardown()
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 1250,in _fixture_teardown
    self._rollback_atomics(self.atomics)
  File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py",line 1173,in _rollback_atomics
    transaction.set_rollback(True,using=db_name)
  File "/usr/local/lib/python3.7/site-packages/django/db/transaction.py",line 92,in set_rollback
    return get_connection(using).set_rollback(rollback)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py",line 436,in set_rollback
    "The rollback flag doesn't work outside of an 'atomic' block.")
django.db.transaction.TransactionManagementError: The rollback flag doesn't work outside of an 'atomic' block.

有什么办法可以修复这个设置吗?或者是否有一种完全不同(更好)的方式来实现这一目标?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)