Reputation: 557
I am trying to test a django view that includes a transaction; in particular, I specify which db I want to use by transaction.atomic(using=myDb)
. However, when I run my test I get django.db.utils.ConnectionDoesNotExist: The connection myDb doesn't exist
.
Is there any way to test the view given that I'm not hitting myDb in the test? Thanks for your help!
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
Upvotes: 1
Views: 2777
Reputation: 11
Below solution is working fine for me
from unittest.mock import MagicMock, patch
patch('django.db.transaction.atomic', return_value = MagicMock())
Upvotes: 1
Reputation: 557
Figured it out, guys. The trick is to specify the db being used with a variable. The DATABASES key returns a different list depending on whether the code is running as a test or normally.
from django.conf import settings
if 'myDb' in settings.DATABASES:
db = 'myDb'
else:
db = 'default'
with transaction.atomic(using=db):
...
Upvotes: 3