Skip to content

Commit

Permalink
fix crash if settings.DATABASES['NAME'] is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
timgraham committed Dec 5, 2024
1 parent 36c5718 commit 34dba7b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
7 changes: 4 additions & 3 deletions django_mongodb/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import contextlib

from django.core.exceptions import ImproperlyConfigured
from django.db.backends.base.base import BaseDatabaseWrapper
from pymongo.collection import Collection
from pymongo.mongo_client import MongoClient
Expand Down Expand Up @@ -151,13 +152,13 @@ def __getattr__(self, attr):
raise AttributeError(attr)

def init_connection_state(self):
db_name = self.settings_dict["NAME"]
if db_name:
self.database = self.connection[db_name]
self.database = self.connection[self.settings_dict["NAME"]]
super().init_connection_state()

def get_connection_params(self):
settings_dict = self.settings_dict
if not settings_dict["NAME"]:
raise ImproperlyConfigured('settings.DATABASES is missing the "NAME" value.')
return {
"host": settings_dict["HOST"] or None,
"port": int(settings_dict["PORT"] or 27017),
Expand Down
Empty file added tests/backend_/__init__.py
Empty file.
14 changes: 14 additions & 0 deletions tests/backend_/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.test import SimpleTestCase

from django_mongodb.base import DatabaseWrapper


class DatabaseWrapperTests(SimpleTestCase):
def test_database_name_empty(self):
settings = connection.settings_dict.copy()
settings["NAME"] = ""
msg = 'settings.DATABASES is missing the "NAME" value.'
with self.assertRaisesMessage(ImproperlyConfigured, msg):
DatabaseWrapper(settings).get_connection_params()

0 comments on commit 34dba7b

Please sign in to comment.