def get_test_labels(cls, tests): """Get a list of app labels and possibly tests for the db app optimizer This should be called after `loadTestsFromNames` has been called. """ test_apps = set(app.name for app in apps.get_app_configs() if app.name not in settings.APPS_TO_EXCLUDE_FROM_TESTS and not app.name.startswith('django.')) if not cls.user_specified_test_names: return [AppConfig.create(app).label for app in test_apps] def iter_names(test): # a.b.c -> a.b.c, a.b, a if isinstance(test.context, type): name = test.context.__module__ elif isinstance(test.context, types.ModuleType): name = test.context.__name__ else: raise RuntimeError("unknown test type: {!r}".format(test)) parts = name.split(".") num_parts = len(parts) for i in range(num_parts): yield ".".join(parts[:num_parts - i]) labels = set() for test in tests: for name in iter_names(test): if name in test_apps: labels.add((AppConfig.create(name).label, test.context)) break return list(labels)
def ready(self): from .models import MeetingInteraction, PhoneInteraction from .signals.handlers import set_attendees_string m2m_changed.connect( set_attendees_string, sender=PhoneInteraction.attendees.through) m2m_changed.connect( set_attendees_string, sender=MeetingInteraction.attendees.through) AppConfig.ready(self)
def ready(self): from .signals import document_consumption_finished from .signals.handlers import ( set_correspondent, set_tags, run_external_script) document_consumption_finished.connect(set_tags) document_consumption_finished.connect(set_correspondent) document_consumption_finished.connect(run_external_script) AppConfig.ready(self)
def ready(self): if self.ready_run: return self.ready_run = True try: functionList = inspect.getmembers(analytics_automated.validators, inspect.isfunction) validatorList = [seq[0] for seq in functionList] validator_types = AppConfig.get_model(self, "ValidatorTypes") existing_entries = validator_types.objects.all().values_list('name') existing_types = [seq[0] for seq in existing_entries] for this_type in existing_types: print("Existing validator: "+str(this_type)) if this_type not in validatorList: print("Removing removed validator: "+this_type) validator_types.objects.filter(name=this_type).delete() for validator in validatorList: if validator not in existing_types and \ not validator.startswith("_"): print("Registering New Validator Type: "+validator) validator_types.objects.create(name=validator) except: print("First time eh?")
def test_import_error(self): "Test for #12658 - Tests with ImportError's shouldn't fail silently" from django.apps import AppConfig from django.test.simple import get_tests app_config = AppConfig.create('test_runner_invalid_app') app_config.import_models({}) with self.assertRaises(ImportError): get_tests(app_config)
def test_get_tests(self): "Check that the get_tests helper function can find tests in a directory" from django.apps import AppConfig from django.test.simple import get_tests app_config = AppConfig.create('test_runner.valid_app') app_config.import_models({}) tests = get_tests(app_config) self.assertIsInstance(tests, types.ModuleType)
def test_overriding_view_is_possible_without_overriding_app(self): # If test fails, it's helpful to know if it's caused by order of # execution customer_app_config = AppConfig.create('oscar.apps.customer') customer_app_config.ready() self.assertEqual(customer_app_config.summary_view.__module__, 'tests._site.apps.customer.views') self.assertEqual(apps.get_app_config('customer').summary_view.__module__, 'tests._site.apps.customer.views')
def app_labels(apps_list): """ Returns a list of app labels of the given apps_list, now properly handles new Django 1.7+ application registry. https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.label """ if AppConfig is None: return [app.split('.')[-1] for app in apps_list] return [AppConfig.create(app).label for app in apps_list]
def post_migrate_tags(sender: AppConfig, **kwargs): Tag = sender.get_model("Tag") for data in TAGS: if not Tag.objects.filter(color=data['color']).exists(): Tag.objects.create(**data)
from django.apps import AppConfig class {{ cookiecutter.project_slug.title().replace('_', '') }}AppConfig(AppConfig): name = '{{ cookiecutter.project_slug }}' def ready(self): # noinspection PyUnresolvedReferences from {{ cookiecutter.project_slug }} import celery # noqa
def __init__(self, app_name, app_module): AppConfig.__init__(self, app_name, app_module) local_settings.APP_PATH = self.path
def ready(self): import hotel.signals AppConfig.ready(self)
def get_first_party_app_labels() -> set[str] | None: if not settings.is_overridden("FIRST_PARTY_APPS"): return None return {AppConfig.create(name).label for name in settings.FIRST_PARTY_APPS}
def ready(self): AppConfig.ready(self)
def test_no_dunder_path_or_dunder_file(self): """If there is no __path__ or __file__, raise ImproperlyConfigured.""" with self.assertRaises(ImproperlyConfigured): AppConfig('label', Stub())
def test_multiple_dunder_path_no_dunder_file(self): """If the __path__ attr is length>1 and there is no __file__, raise.""" with self.assertRaises(ImproperlyConfigured): AppConfig('label', Stub(__path__=['a', 'b']))
def setUp(self): super(CredentialsConfigTests, self).setUp() self.app_config = AppConfig.create('credentials.apps.credentials')
def test_empty_dunder_path_fallback_to_dunder_file(self): """If the __path__ attr is empty, use __file__ if set.""" ac = AppConfig('label', Stub(__path__=[], __file__='b/__init__.py')) self.assertEqual(ac.path, 'b')
def test_default_config_exists(): """ A really trivial "test case": just checking that the app can be instantiated. """ app = AppConfig.create("morphodict.apps.MorphodictConfig") assert "morphodict" in app.name
def post_migrate_modules(sender: AppConfig, **kwargs): if sender.name + "_module" in connection.introspection.table_names(): Module = sender.get_model('Module') for kw in data: if not Module.objects.filter(name=kw["name"]).exists(): Module.objects.create(**kw)
def ready(self): from user.receivers import SignalReceiver SignalReceiver.connect() AppConfig.ready(self)
def _ready(self): return _APPCFG.ready(self)
def ready(self): import djreservation.signals AppConfig.ready(self)
def test_multiple_dunder_path_fallback_to_dunder_file(self): """If the __path__ attr is length>1, use __file__ if set.""" ac = AppConfig('label', Stub(__path__=['a', 'b'], __file__='c/__init__.py')) self.assertEqual(ac.path, 'c')
def ready(self): AppConfig.ready(self) from book_store import signals
def test_empty_dunder_path_no_dunder_file(self): """If the __path__ attr is empty and there is no __file__, raise.""" with self.assertRaises(ImproperlyConfigured): AppConfig('label', Stub(__path__=[]))
urlpatterns += redirect_urlpatterns() def remove_prefix(appname, prefix="omero_"): if appname.startswith(prefix): return appname[len(prefix):] return appname for app in settings.ADDITIONAL_APPS: if django.VERSION > (1, 7): from django.apps import AppConfig if isinstance(app, AppConfig): app_config = app else: app_config = AppConfig.create(app) label = app_config.label else: logger.warn( ("Django %s does not support AppConfig. Some OMERO.web plugins " "may not work correctly.") % django.get_version()) label = remove_prefix(app) # Depending on how we added the app to INSTALLED_APPS in settings.py, # include the urls the same way if 'omeroweb.%s' % app in settings.INSTALLED_APPS: urlmodule = 'omeroweb.%s.urls' % app else: urlmodule = '%s.urls' % app try: __import__(urlmodule) except ImportError:
from django.apps import AppConfig class Wagtail{{ cookiecutter.project_name_camel }}AppConfig(AppConfig): label = "wagtail_{{ cookiecutter.project_name_snake }}" name = "wagtail_{{ cookiecutter.project_name_snake }}" verbose_name = "Wagtail {{ cookiecutter.project_name }}"
def ready(self): from documents.signals import document_consumer_declaration if settings.PAPERLESS_TIKA_ENABLED: document_consumer_declaration.connect(tika_consumer_declaration) AppConfig.ready(self)
def ready(self): AppConfig.ready(self) init_session() g.version = str(uuid.uuid4()).replace('-', '')
def _ready(self): from . import signals return _APPCFG.ready(self)
def add_post(request): postInfo = AppConfig.get_model(Posts, required_ready=True) form = postInfo(request.POST) print("requestpost", request.POST) form.save()
def setup(verbosity, test_labels): import django from django.apps import apps, AppConfig from django.conf import settings from django.test import TransactionTestCase, TestCase print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the ALWAYS_INSTALLED_APPS. with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning) apps.populate_models() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: match = lambda label: ( module_label == label or # exact match module_label.startswith(label + '.') # ancestor match ) module_found_in_labels = any(match(l) for l in test_labels_set) if module_found_in_labels: if verbosity >= 2: print("Importing application %s" % module_name) # HACK. if module_label not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(module_label) app_config = AppConfig.create(module_label) app_config.import_models(apps.all_models[app_config.label]) apps.app_configs[app_config.label] = app_config apps.get_models.cache_clear() return state
def setup(verbosity, test_labels): state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'denyzen.tests.urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. #settings._explicit_settings.add('MIDDLEWARE_CLASSES') settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'django.contrib.contenttypes.tests.migrations', } # Load all the ALWAYS_INSTALLED_APPS. django.setup() if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the test model apps. test_modules = get_test_modules() print(test_modules) test_labels_set = set() for label in test_labels: test_labels_set.add(label) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) app_config = AppConfig.create(module_name) apps.app_configs[app_config.label] = app_config app_config.import_models(apps.all_models[app_config.label]) apps.clear_cache() apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): from django.apps import apps, AppConfig from django.conf import settings from django.test import TransactionTestCase, TestCase print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR), ) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( 'ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', RemovedInDjango18Warning) warnings.filterwarnings( 'ignore', 'Model class django.contrib.comments.models.* Django 1.9.', RemovedInDjango19Warning) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) installed_app_names = set(get_installed()) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) # HACK. settings.INSTALLED_APPS.append(module_label) app_config = AppConfig.create(module_label) apps.app_configs[app_config.label] = app_config app_config.import_models(apps.all_models[app_config.label]) apps.clear_cache() return state
def ready(self): AppConfig.ready(self) bot = GobbleBot() import_bot_handlers()
def ready(self): from documents.signals import document_consumer_declaration from .signals import ConsumerDeclaration document_consumer_declaration.connect(ConsumerDeclaration.handle) AppConfig.ready(self)
username_field = lambda: getattr(get_user_model(), 'USERNAME_FIELD', 'username') try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User get_user_model = lambda: User try: from django.utils.encoding import smart_text except ImportError: from django.utils.encoding import smart_unicode as smart_text try: from django.contrib.contenttypes import fields as generic except ImportError: from django.contrib.contenttypes import generic try: from django.apps import AppConfig user_model_class = lambda: AppConfig.get_model(*user_model_label.split('.')) except ImportError: from django.db import models user_model_class = lambda: models.get_model(*user_model_label.split('.')) class AppConfig(object): name = None def get_model(self, model_name): return models.get_model(self.name.split('.')[-1], model_name, only_installed=False)
def test_repr(self): ac = AppConfig('label', Stub(__path__=['a'])) self.assertEqual(repr(ac), '<AppConfig: label>')
def _strip(self, entry): app_config = AppConfig.create(entry) return app_config.label
def test_dunder_path(self): """If single element in __path__, use it (in preference to __file__).""" ac = AppConfig('label', Stub(__path__=['a'], __file__='b/__init__.py')) self.assertEqual(ac.path, 'a')
def test_no_dunder_path_fallback_to_dunder_file(self): """If there is no __path__ attr, use __file__.""" ac = AppConfig('label', Stub(__file__='b/__init__.py')) self.assertEqual(ac.path, 'b')
def _create_app_config(self, app_module): from django.apps import apps, AppConfig from django.conf import settings app = AppConfig(app_module.__name__, app_module) apps.populate(list(settings.INSTALLED_APPS) + [app]) return app