如何测试具有transaction.atomic(using = myDb)的Django视图?

时间:2017-05-02 18:47:16

标签: django testing transactions

我正在尝试测试包含交易的django视图;特别是,我指定transaction.atomic(using=myDb)要使用哪个数据库。但是,当我运行测试时,我得到django.db.utils.ConnectionDoesNotExist: The connection myDb doesn't exist

考虑到我没有在测试中击中myDb,有没有办法测试视图?谢谢你的帮助!

Trackeback:

    Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 176, in ensure_defaults
    conn = self.databases[alias]
KeyError: 'myDb'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Z:\web-django-2\web-django\src\revisorsite\track\tests.py", line 92, in test_redirect_on_edit
    response = Add.as_view()(request)
  File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python34\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "Z:\web-django-2\web-django\src\revisorsite\login\decorators.py", line 8, in wrap
    return function(request, *args, **kwargs)
  File "C:\Python34\lib\site-packages\django\utils\decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "Z:\web-django-2\web-django\src\revisorsite\track\views.py", line 47, in post
    transaction.set_autocommit(False, using='myDb')
  File "C:\Python34\lib\site-packages\django\db\transaction.py", line 35, in set_autocommit
    return get_connection(using).set_autocommit(autocommit)
  File "C:\Python34\lib\site-packages\django\db\transaction.py", line 21, in get_connection
    return connections[using]
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 208, in __getitem__
    self.ensure_defaults(alias)
  File "C:\Python34\lib\site-packages\django\db\utils.py", line 178, in ensure_defaults
    raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
django.db.utils.ConnectionDoesNotExist: The connection myDb doesn't exist

1 个答案:

答案 0 :(得分:1)

想出来,伙计们。诀窍是指定与变量一起使用的数据库。 DATABASES键返回一个不同的列表,具体取决于代码是作为测试运行还是正常运行。

from django.conf import settings
if 'myDb' in settings.DATABASES:
    db = 'myDb'
else:
    db = 'default'
with transaction.atomic(using=db):
    ...