Test django with mongomock for django auth models - python

I'm trying to perform unit tests on Django with db mocking by mongomock.
My connection to the DB is made using settings.py:
DATABASES = {
'dbname': {
'ENGINE': 'djongo',
'NAME': 'db1',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': DB_HOST,
'port': DB_PORT,
'username': DB_USERNAME,
'password': DB_PASSWORD,
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1'
}
},
'default': {
'ENGINE': 'djongo',
'NAME': 'users',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': DB_HOST,
'port': DB_PORT,
'username': DB_USERNAME,
'password': DB_PASSWORD,
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1'
}
}
}
and the test looks like this:
from django.contrib.auth.models import User
class BaseApiTest():
def test_access_login(self):
User.objects.create_user(
username='admin',
password='admin'
)
....
self.assertEqual(AccessAttempt.objects.count(), 1)
Here there is an internal connection of Django to the DB. (when its trying to access django.contrib.auth.models.User)
Any ideas?
The goal is to run the tests without a DB instance.
In other words, how can I overwrite the Django connection (self.databases) to the DB using a mongomock connection...

Related

Serving separate database per user django

i am creating database according this now: Saperate PostgreSQL db for each client, with automated migrations on creating client on single Django app and on same server
Now I want to serve the db per user. We can return db from db routers only if they exists in the DATABASES varriable in the settings file.
Does anybody know how to serve db which are created on server but not added in settings.py, which will be according to the logged in user.
There will be a main db for user, in which their relations with their db name is saved.
Settings.py
DATABASE_ROUTERS = ['app.router_middleware.DataBaseRouter']
DATABASES = {'default':
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'abc',
'USER': 'xyz',
'PASSWORD': '*****',
'HOST': 'localhost',
'PORT': '5432',
}
}
import django
django.setup()
from Client.views import ALL_DB
DATABASES.update(ALL_DB)
Client.views
ALL_DB = { x.db_name: {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': x.db_name,
'USER': 'xyz',
'PASSWORD': '****',
'HOST': 'localhost',
'PORT': '5432',
} for x in Client.objects.all()}
router_middleware.py
db_name = 'default'
class RouterMiddleware(CoreSessionMiddleware):
def process_request(self, request):
if request.user.is_authenticated() :
user = request.user
if ClientEmployee.objects.filter(user=user).exists():
client_employee = ClientEmployee.objects.get(user=user)
db_name = client_employee.client.db_name
class DataBaseRouter(object):
def db_for_read(self, model, **hints):
return db_name
def db_for_write(self, model, **hints):
return db_name

MySql configuration for Django

I am getting error when try to run
python manage.py migrate
django.db.utils.OperationalError: (1045, "Access denied for user 'someuser'#'localhost' (using password: NO)")
This is my database setting inside setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/config/mysql.cnf',
},
}
}
config/mysql.cnf
[client] database = dbname user =
root password = passwt host = localhost
default-character-set = utf8
The MySql configs can be provided in settings.py file, as like below
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
}
} }
If need to configure with external file, below may be helpful
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, 'mysql.cnf'),
}
} }
The mysql.cnf file should be in project dir

postgresql django not sending password

I am getting the error OperationalError: fe_sendauth: no password supplied on my production server but I cannot see why...
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'dbuser',
'PASSWORD': PROD_DB_PASSWORD,
'HOST': 'localhost',
'PORT': '5432',
}
}
pg_hba.conf:
host dbname dbuser localhost md5
If I do psql -d dbname -U dbuser -h localhost and then enter the password at the prompt I can see that it works so IDK why django is not sending the password and IDK where to look from here.
I suspect you're not passing the password correctly. Here's how you debug. After the DATABASES line in settings.py, can you try printing out the dict.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'dbuser',
'PASSWORD': PROD_DB_PASSWORD,
'HOST': 'localhost',
'PORT': '5432',
}
}
print DATABASES
Then manage.py runserver as you would.
See if the password is properly passed. Apologies my rep's not enough to comment yet.
For future readers also check the spelling and later cases. All database keys must be in UPPER CASE e.g ENGINE, NAME, USER, PASSWORD, HOST and PORT.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.getenv("DB_NAME", "db_name"),
"USER": os.getenv("DB_USERNAME", "db_user"),
"PASSWORD": os.getenv("DB_PASSWORD", "db#password"),
"HOST": os.getenv("DB_HOST", "localhost"),
"PORT": os.getenv("DB_PORT", "5432")
}
}

Want to implement multiple database in django project

I want to use multiple sqlite3 database for my app. I want to write some of the data(which is user log) to one database and rest of the stuff to another db. After that I want to read from both the database.
Thanks
DATABASE_ROUTERS = ['manager.router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = { 'db_b':'db_b'}
DATABASES = {
'default': {
'ENGINE': 'backend_of_your_choice',
'NAME': 'default',
'USER': 'xxx',
'PASSWORD': 'xxx',
'HOST': '127.0.0.1',
'PORT': '',
},
'db_b': {
'ENGINE': 'backend_of_your_choice',
'NAME': 'db_b',
'USER': 'xxx',
'PASSWORD': 'xxx',
'HOST': '127.0.0.1',
'PORT': '',
},}
Then in your model MetaClass define the following for all the models which you want to use db_b:
class Meta:
app_label = 'db_b'

How to configure Django database using Heroku?

I'm using Heroku with Django.
The database is configured in settings.py this way, using the dj-database-url module:
DATABASES = {'default': dj_database_url.config()}
How can I do to add additional parameters, for example ATOMIC_REQUESTS? In a "normal" case I would do like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
'ATOMIC_REQUESTS': True,
}
}
DATABASES is just a dictionary: you can add the relevant settings after the initial configuration.
DATABASES = {'default': dj_database_url.config()}
DATABASES['default']['ATOMIC_REQUESTS'] = True

Categories

Resources