Self hosted FLOSS fitness/workout, nutrition and weight tracker
Improvements to db detection while bootstrapping
Roland Geider6d2a3c43a04c
diff --git a/wger/core/tests/test_cli.py b/wger/core/tests/test_cli.pyindex f39ab783e..915aea6ef 100644--- a/wger/core/tests/test_cli.py+++ b/wger/core/tests/test_cli.py@@ -18,12 +18,21 @@ import tempfilefrom unittest import mock# Django-from django.test import SimpleTestCase+from django.contrib.auth.models import User+from django.db import OperationalError+from django.test import (+ SimpleTestCase,+ TestCase,+)# Third Party-from invoke import Config+from invoke import (+ Config,+ Context,+)# wger+from wger import tasksfrom wger.tasks import WgerConfig@@ -42,3 +51,75 @@ class WgerConfigTestCase(SimpleTestCase):self.assertTrue(Config().run.echo)self.assertFalse(WgerConfig().run.echo)+++class BootstrapTestCase(TestCase):+ """+ Test that bootstrapping never touches the data of an existing installation+ """++ fixtures = (+ 'gym',+ 'gym_config',+ 'groups',+ 'languages',+ )++ def setUp(self):+ self.context = Context()++ @mock.patch('wger.tasks.load_admin_fixture')+ @mock.patch('wger.tasks.load_fixtures')+ @mock.patch('wger.tasks.migrate_db')+ @mock.patch('wger.tasks.setup_django_environment')+ def test_existing_installation_is_left_alone(self, setup, migrate, fixtures, admin_fixture):+ User.objects.create_user('admin', password='secret')++ tasks.bootstrap(self.context, process_static=False)++ migrate.assert_not_called()+ fixtures.assert_not_called()+ admin_fixture.assert_not_called()+ self.assertTrue(User.objects.get(username='admin').check_password('secret'))++ @mock.patch('wger.tasks.load_admin_fixture')+ @mock.patch('wger.tasks.load_fixtures')+ @mock.patch('wger.tasks.migrate_db')+ @mock.patch('wger.tasks.setup_django_environment')+ def test_unreachable_database_is_an_error(self, setup, migrate, fixtures, admin):+ User.objects.create_user('admin', password='secret')++ with mock.patch(+ 'django.db.connection.ensure_connection',+ side_effect=OperationalError('connection refused'),+ ):+ with self.assertRaises(OperationalError):+ tasks.bootstrap(self.context, process_static=False)++ migrate.assert_not_called()+ fixtures.assert_not_called()+ admin.assert_not_called()+ self.assertTrue(User.objects.get(username='admin').check_password('secret'))++ @mock.patch('wger.tasks.load_admin_fixture')+ @mock.patch('wger.tasks.load_fixtures')+ @mock.patch('wger.tasks.migrate_db')+ @mock.patch('wger.tasks.setup_django_environment')+ def test_empty_database_is_initialised(self, setup, migrate, fixtures, admin_fixture):+ tasks.bootstrap(self.context, process_static=False)++ migrate.assert_called_once()+ fixtures.assert_called_once()+ admin_fixture.assert_called_once()++ def test_ensure_admin_user_creates_missing_admin(self):+ tasks.ensure_admin_user()++ self.assertTrue(User.objects.get(username='admin').check_password('adminadmin'))++ def test_ensure_admin_user_keeps_existing_password(self):+ User.objects.create_user('admin', password='secret')++ tasks.ensure_admin_user()++ self.assertTrue(User.objects.get(username='admin').check_password('secret'))diff --git a/wger/tasks.py b/wger/tasks.pyindex 550043c2c..10894b022 100644--- a/wger/tasks.py+++ b/wger/tasks.py@@ -85,7 +85,7 @@ def bootstrap(context, settings_path=None, process_static=True):print('*** Database is empty or incomplete, setting it up now')migrate_db(context, settings_path=settings_path)load_fixtures(context, settings_path=settings_path)- create_or_reset_admin(context, settings_path=settings_path)+ ensure_admin_user()# Download JS and CSS librariesif process_static:@@ -105,16 +105,12 @@ def create_or_reset_admin(context, settings_path: str = None):# Djangofrom django.contrib.auth.models import User- try:- User.objects.get(username='admin')+ if User.objects.filter(username='admin').exists():print("*** Password for user admin was reset to 'adminadmin'")- except User.DoesNotExist:+ else:print('*** Created default admin user')- current_dir = os.path.dirname(os.path.abspath(__file__))- path = os.path.join(current_dir, 'core', 'fixtures/')-- call_command('loaddata', path + 'users.json')+ load_admin_fixture()@task(help={'settings-path': 'Path to settings file. Leave empty for default (settings.main)'})@@ -222,23 +218,59 @@ def setup_django_environment(settings_path: str = None):def database_initialised():"""- Detect whether the database exists and was completely set up+ Detect whether the database was completely set up++ The admin user is created as the last step of the setup, so a database+ without any users is either empty or the result of an interrupted setup."""# can't be imported in global scope as they already require# the settings module during import# Djangofrom django.contrib.auth.models import User- from django.core.exceptions import ImproperlyConfigured- from django.db import DatabaseError+ from django.db import (+ DatabaseError,+ connection,+ )++ # A database that can't be reached is an error, not an empty database.+ connection.ensure_connection()try:return User.objects.exists()- except DatabaseError:+ except DatabaseError as e:+ # The tables were not created yet+ print(f'*** Could not query the user table: {str(e).strip()}')return False- except ImproperlyConfigured as e:- print(style.ERROR('Your settings file seems broken: '), e)- sys.exit(0)+++def ensure_admin_user():+ """+ Create the default admin user if it does not exist++ Unlike create_or_reset_admin, an existing admin user is left untouched.+ """++ # can't be imported in global scope as it already requires+ # the settings module during import+ # Django+ from django.contrib.auth.models import User++ if User.objects.filter(username='admin').exists():+ return++ print('*** Created default admin user')+ load_admin_fixture()+++def load_admin_fixture():+ """+ Load the fixture with the default admin user (password 'adminadmin')+ """+ current_dir = os.path.dirname(os.path.abspath(__file__))+ path = os.path.join(current_dir, 'core', 'fixtures/')++ call_command('loaddata', path + 'users.json')class WgerConfig(Config):