def setUp(self):
settings.INSTALLED_APPS = [
'zerodowntime',
'tests.safe_migrations',
]
self.reinitialize_django_apps()
python类INSTALLED_APPS的实例源码
def add_django_app(self, app_module):
settings.INSTALLED_APPS.append(app_module)
self.reinitialize_django_apps()
def reinitialize_django_apps(self):
apps.app_configs = OrderedDict()
# set ready to false so that populate will work
apps.ready = False
# re-initialize them all; is there a way to add just one without reloading them all?
apps.populate(settings.INSTALLED_APPS)
def test_registry(self):
"""Verify registration and autodiscovery work correctly.
Please note that this implicitly tests that autodiscovery works
by virtue of the fact that the dashboards listed in
``settings.INSTALLED_APPS`` are loaded from the start.
"""
# Registration
self.assertEqual(2, len(base.Horizon._registry))
horizon.register(MyDash)
self.assertEqual(3, len(base.Horizon._registry))
with self.assertRaises(ValueError):
horizon.register(MyPanel)
with self.assertRaises(ValueError):
horizon.register("MyPanel")
# Retrieval
my_dash_instance_by_name = horizon.get_dashboard("mydash")
self.assertIsInstance(my_dash_instance_by_name, MyDash)
my_dash_instance_by_class = horizon.get_dashboard(MyDash)
self.assertEqual(my_dash_instance_by_name, my_dash_instance_by_class)
with self.assertRaises(base.NotRegistered):
horizon.get_dashboard("fake")
self.assertQuerysetEqual(horizon.get_dashboards(),
['<Dashboard: cats>',
'<Dashboard: dogs>',
'<Dashboard: mydash>'])
# Removal
self.assertEqual(3, len(base.Horizon._registry))
horizon.unregister(MyDash)
self.assertEqual(2, len(base.Horizon._registry))
with self.assertRaises(base.NotRegistered):
horizon.get_dashboard(MyDash)
def clean(self):
if not (self.cleaned_data.get('thumbnail_option') or ((self.cleaned_data.get('width') or 0) + (self.cleaned_data.get('height') or 0))):
if 'cmsplugin_filer_image' in settings.INSTALLED_APPS:
raise ValidationError(_('Thumbnail option or resize parameters must be choosen.'))
else:
raise ValidationError(_('Resize parameters must be choosen.'))
return self.cleaned_data
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get('DJANGO_SETTINGS_MODULE'):
# If `subcommand` is missing due to misconfigured settings, the
# following line will retrigger an ImproperlyConfigured exception
# (get_commands() swallows the original one) so the user is
# informed about it.
settings.INSTALLED_APPS
else:
sys.stderr.write("No Django settings specified.\n")
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def model_unpickle(model_id, attrs, factory):
"""
Used to unpickle Model subclasses with deferred fields.
"""
if isinstance(model_id, tuple):
if not apps.ready:
apps.populate(settings.INSTALLED_APPS)
model = apps.get_model(*model_id)
else:
# Backwards compat - the model was cached directly in earlier versions.
model = model_id
cls = factory(model, attrs)
return cls.__new__(cls)
def _pre_setup(self):
"""Performs any pre-test setup. This includes:
* If the class has an 'available_apps' attribute, restricting the app
registry to these applications, then firing post_migrate -- it must
run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, installing these fixtures.
"""
super(TransactionTestCase, self)._pre_setup()
if self.available_apps is not None:
apps.set_available_apps(self.available_apps)
setting_changed.send(sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=self.available_apps,
enter=True)
for db_name in self._databases_names(include_mirrors=False):
emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name)
try:
self._fixture_setup()
except Exception:
if self.available_apps is not None:
apps.unset_available_apps()
setting_changed.send(sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=settings.INSTALLED_APPS,
enter=False)
raise
def _post_teardown(self):
"""Performs any post-test things. This includes:
* Flushing the contents of the database, to leave a clean slate. If
the class has an 'available_apps' attribute, post_migrate isn't fired.
* Force-closing the connection, so the next test gets a clean cursor.
"""
try:
self._fixture_teardown()
super(TransactionTestCase, self)._post_teardown()
if self._should_reload_connections():
# Some DB cursors include SQL statements as part of cursor
# creation. If you have a test that does a rollback, the effect
# of these statements is lost, which can affect the operation of
# tests (e.g., losing a timezone setting causing objects to be
# created with the wrong time). To make sure this doesn't
# happen, get a clean connection at the start of every test.
for conn in connections.all():
conn.close()
finally:
if self.available_apps is not None:
apps.unset_available_apps()
setting_changed.send(sender=settings._wrapped.__class__,
setting='INSTALLED_APPS',
value=settings.INSTALLED_APPS,
enter=False)
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get('DJANGO_SETTINGS_MODULE'):
# If `subcommand` is missing due to misconfigured settings, the
# following line will retrigger an ImproperlyConfigured exception
# (get_commands() swallows the original one) so the user is
# informed about it.
settings.INSTALLED_APPS
else:
sys.stderr.write("No Django settings specified.\n")
sys.stderr.write(
"Unknown command: %r\nType '%s help' for usage.\n"
% (subcommand, self.prog_name)
)
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def test_verify_installed_apps(self):
from django.conf import settings
self.assertIn('modeltrans', settings.INSTALLED_APPS)
self.assertNotIn('modeltranslation', settings.INSTALLED_APPS)
def test_verify_installed_apps(self):
from django.conf import settings
self.assertNotIn('modeltrans', settings.INSTALLED_APPS)
self.assertIn('modeltranslation', settings.INSTALLED_APPS)
def _get_social_auth_providers(request):
if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
return []
from allauth.socialaccount import providers
return [{'name': provider.name, 'url': provider.get_login_url(request)}
for provider in providers.registry.get_list()]
def get_current_site(self):
if self.request:
site = get_current_site(self.request)
elif ('django.contrib.sites' in settings.INSTALLED_APPS and
settings.SITE_ID):
from django.contrib.sites.models import Site
site = Site.objects.get_current()
else:
site = None
return site
def load(self):
from django.conf import settings
for app in settings.INSTALLED_APPS:
try:
m = app + '.activities'
import_module(m)
except ImportError:
pass
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get('DJANGO_SETTINGS_MODULE'):
# If `subcommand` is missing due to misconfigured settings, the
# following line will retrigger an ImproperlyConfigured exception
# (get_commands() swallows the original one) so the user is
# informed about it.
settings.INSTALLED_APPS
else:
sys.stderr.write("No Django settings specified.\n")
sys.stderr.write(
"Unknown command: %r\nType '%s help' for usage.\n"
% (subcommand, self.prog_name)
)
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
def is_installed(appname):
return appname in settings.INSTALLED_APPS #or apps.is_installed(appname)
def __init__(self):
super(NotificationMethod, self).__init__()
if settings.EMAIL_BACKEND:
self.server_configured = True
if 'djembe' in settings.INSTALLED_APPS:
self.options['certificate'] = forms.CharField(required=False,
widget=forms.Textarea(attrs={'cols': 60, 'rows': 15}),
help_text=_('Encryption certificate in PEM format.'))
def ready(self):
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
if hasattr(settings, 'RAVEN_CONFIG'):
# Celery signal registration
from raven import Client as RavenClient
from raven.contrib.celery import register_signal as raven_register_signal
from raven.contrib.celery import register_logger_signal as raven_register_logger_signal
raven_client = RavenClient(dsn=settings.RAVEN_CONFIG['DSN'])
raven_register_logger_signal(raven_client)
raven_register_signal(raven_client)
def load():
# Dynamically grab package name
package_name = os.path.dirname(__file__)
# For each registered app, import all of the available roles
for app in settings.INSTALLED_APPS:
# Make sure the app is not self
if app is not package_name:
try:
import_module('.roles', app)
except ImportError:
pass
# Registers a Role with the global Bootstrapper if it is not already registered.
# Returns the True if Role is added, None if it already exists