Example #1
0
def register_to_payment(order_class, **kwargs):
    """
    A function for registering unaware order class to ``getpaid``. This will
    generate a ``Payment`` model class that will store payments with
    ForeignKey to original order class

    This also will build a model class for every enabled backend.
    """
    global Payment
    global Order

    class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
        objects = PaymentManager()

        class Meta:
            ordering = ('-created_on', )
            verbose_name = _("Payment")
            verbose_name_plural = _("Payments")

    Order = order_class

    # Now build models for backends

    backend_models_modules = import_backend_modules('models')
    for backend_name, models_module in backend_models_modules.items():
        for model in models_module.build_models(Payment):
            apps.register_model(backend_name, model)
    return Payment
Example #2
0
    def test_files_content(self):
        self.assertTableNotExists("migrations_unicodemodel")
        apps.register_model('migrations', UnicodeModel)
        with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}):
            call_command("makemigrations", "migrations", verbosity=0)

        init_file = os.path.join(self.migration_dir, "__init__.py")

        # Check for existing __init__.py file in migrations folder
        self.assertTrue(os.path.exists(init_file))

        with open(init_file, 'r') as fp:
            content = force_text(fp.read())
            self.assertEqual(content, '')

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")

        # Check for existing 0001_initial.py file in migration folder
        self.assertTrue(os.path.exists(initial_file))

        with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
            content = fp.read()
            self.assertIn('# -*- coding: utf-8 -*-', content)
            self.assertIn('migrations.CreateModel', content)

            if six.PY3:
                self.assertIn('úñí©óðé µóðéø', content)  # Meta.verbose_name
                self.assertIn('úñí©óðé µóðéøß', content)  # Meta.verbose_name_plural
                self.assertIn('ÚÑÍ¢ÓÐÉ', content)  # title.verbose_name
                self.assertIn('“Ðjáñgó”', content)  # title.default
            else:
                self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8', content)  # Meta.verbose_name
                self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf', content)  # Meta.verbose_name_plural
                self.assertIn('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9', content)  # title.verbose_name
                self.assertIn('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d', content)  # title.default
Example #3
0
def register_to_payment(order_class, **kwargs):
    """
    A function for registering unaware order class to ``getpaid``. This will
    generate a ``Payment`` model class that will store payments with
    ForeignKey to original order class

    This also will build a model class for every enabled backend.
    """
    global Payment
    global Order

    class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
        objects = PaymentManager()

        class Meta:
            ordering = ('-created_on',)
            verbose_name = _("Payment")
            verbose_name_plural = _("Payments")

    Order = order_class

    # Now build models for backends

    backend_models_modules = import_backend_modules('models')
    for backend_name, models_module in backend_models_modules.items():
        for model in models_module.build_models(Payment):
            apps.register_model(backend_name, model)
    return Payment
Example #4
0
    def setUp(self):
        super(TestModelsLoaderMixin, self).setUp()

        # If we made a fake 'models' module, add it to sys.modules.
        models_mod = self._tests_loader_models_mod

        if models_mod:
            sys.modules[models_mod.__name__] = models_mod

        self._models_loader_old_settings = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [
            self.tests_app,
        ]

        if apps:
            # Push the new set of installed apps, and begin registering
            # each of the models associated with the tests.
            apps.set_installed_apps(settings.INSTALLED_APPS)
            app_config = apps.get_containing_app_config(self.tests_app)

            for key, value in six.iteritems(models_mod.__dict__):
                if inspect.isclass(value) and issubclass(value, Model):
                    apps.register_model(app_config.label, value)

            call_command('migrate', verbosity=0, interactive=False)
        else:
            load_app(self.tests_app)
            call_command('syncdb', verbosity=0, interactive=False)
Example #5
0
    def setUp(self):
        super(TestModelsLoaderMixin, self).setUp()

        # If we made a fake 'models' module, add it to sys.modules.
        models_mod = self._tests_loader_models_mod

        if models_mod:
            sys.modules[models_mod.__name__] = models_mod

        self._models_loader_old_settings = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [
            self.tests_app,
        ]

        if apps:
            # Push the new set of installed apps, and begin registering
            # each of the models associated with the tests.
            apps.set_installed_apps(settings.INSTALLED_APPS)
            app_config = apps.get_containing_app_config(self.tests_app)

            if models_mod:
                for key, value in six.iteritems(models_mod.__dict__):
                    if inspect.isclass(value) and issubclass(value, Model):
                        apps.register_model(app_config.label, value)

            call_command('migrate', verbosity=0, interactive=False)
        else:
            load_app(self.tests_app)
            call_command('syncdb', verbosity=0, interactive=False)
Example #6
0
    def test_failing_migration(self):
        #21280 - If a migration fails to serialize, it shouldn't generate an empty file.
        apps.register_model('migrations', UnserializableModel)

        with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
            with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}):
                    call_command("makemigrations", "migrations", verbosity=0)

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")
        self.assertFalse(os.path.exists(initial_file))
Example #7
0
    def test_failing_migration(self):
        # If a migration fails to serialize, it shouldn't generate an empty file. #21280
        apps.register_model('migrations', UnserializableModel)

        with self.temporary_migration_module() as migration_dir:
            with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
                call_command("makemigrations", "migrations", verbosity=0)

            initial_file = os.path.join(migration_dir, "0001_initial.py")
            self.assertFalse(os.path.exists(initial_file))
Example #8
0
    def test_failing_migration(self):
        # If a migration fails to serialize, it shouldn't generate an empty file. #21280
        apps.register_model('migrations', UnserializableModel)

        with self.temporary_migration_module() as migration_dir:
            with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
                call_command("makemigrations", "migrations", verbosity=0)

            initial_file = os.path.join(migration_dir, "0001_initial.py")
            self.assertFalse(os.path.exists(initial_file))
Example #9
0
def cleanup_registry():
    """
    The app registry bleeds between tests. This fixture removes all dynamically
    declared models after each test.
    """
    try:
        yield
    finally:
        apps.all_models[TEST_APP_LABEL].clear()
        apps.register_model(TEST_APP_LABEL, ModelSchema)
        apps.register_model(TEST_APP_LABEL, FieldSchema)
Example #10
0
    def setUp(self):
        super(TestModelsLoaderMixin, self).setUp()

        # If we made a fake 'models' module, add it to sys.modules.
        models_mod = self._tests_loader_models_mod

        if models_mod:
            sys.modules[models_mod.__name__] = models_mod

        self._models_loader_old_settings = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [
            self.tests_app,
        ]

        if apps:
            # Push the new set of installed apps, and begin registering
            # each of the models associated with the tests.
            apps.set_installed_apps(settings.INSTALLED_APPS)
            app_config = apps.get_containing_app_config(self.tests_app)

            if models_mod:
                app_label = app_config.label

                for key, value in six.iteritems(models_mod.__dict__):
                    if inspect.isclass(value) and issubclass(value, Model):
                        # The model was likely registered under another app,
                        # so we need to remove the old one and add the new
                        # one.
                        try:
                            del apps.all_models[value._meta.app_label][
                                value._meta.model_name]
                        except KeyError:
                            pass

                        value._meta.app_label = app_label
                        apps.register_model(app_label, value)

            call_command('migrate',
                         run_syncdb=True,
                         verbosity=0,
                         interactive=False)
        else:
            load_app(self.tests_app)
            call_command('syncdb', verbosity=0, interactive=False)
Example #11
0
    def setUp(self):
        super(TestModelsLoaderMixin, self).setUp()

        # If we made a fake 'models' module, add it to sys.modules.
        models_mod = self._tests_loader_models_mod

        if models_mod:
            sys.modules[models_mod.__name__] = models_mod

        self._models_loader_old_settings = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [
            self.tests_app,
        ]

        if apps:
            # Push the new set of installed apps, and begin registering
            # each of the models associated with the tests.
            apps.set_installed_apps(settings.INSTALLED_APPS)
            app_config = apps.get_containing_app_config(self.tests_app)

            if models_mod:
                app_label = app_config.label

                for key, value in six.iteritems(models_mod.__dict__):
                    if inspect.isclass(value) and issubclass(value, Model):
                        # The model was likely registered under another app,
                        # so we need to remove the old one and add the new
                        # one.
                        try:
                            del apps.all_models[value._meta.app_label][
                                value._meta.model_name]
                        except KeyError:
                            pass

                        value._meta.app_label = app_label
                        apps.register_model(app_label, value)

            call_command('migrate', run_syncdb=True, verbosity=0,
                         interactive=False)
        else:
            load_app(self.tests_app)
            call_command('syncdb', verbosity=0, interactive=False)
Example #12
0
 def cache_dynamic_models(cls):
     from django.conf import settings
     # Add Dynamic Models to cache:
     # Useful link:  https://dynamic-models.readthedocs.org/en/latest/pdfindex.html?highlight=re
     # Not sure where to call this...probably in a try/except block
     from localground.apps.site.models import Form
     from django.db.models.loading import cache
     from django.apps import apps
     # the prefetch_related really cuts down on queries...but the DYNAMIC_MODELS_CACHED
     # flag isn't working!  Need to come up w/something else
     forms = Form.objects.prefetch_related(
         'field_set',
         'field_set__data_type').all()
     for form in forms:
         m = form.TableModel
         
         #first remove from cache:
         app_models = apps.all_models[form.TableModel._meta.app_label]
         del app_models[form.TableModel._meta.model_name]
         
         # then register
         apps.register_model(m._meta.app_label, m)
Example #13
0
    def test_files_content(self):
        self.assertTableNotExists("migrations_unicodemodel")
        apps.register_model("migrations", UnicodeModel)
        with self.temporary_migration_module() as migration_dir:
            call_command("makemigrations", "migrations", verbosity=0)

            # Check for empty __init__.py file in migrations folder
            init_file = os.path.join(migration_dir, "__init__.py")
            self.assertTrue(os.path.exists(init_file))

            with open(init_file, "r") as fp:
                content = force_text(fp.read())
            self.assertEqual(content, "")

            # Check for existing 0001_initial.py file in migration folder
            initial_file = os.path.join(migration_dir, "0001_initial.py")
            self.assertTrue(os.path.exists(initial_file))

            with codecs.open(initial_file, "r", encoding="utf-8") as fp:
                content = fp.read()
                self.assertIn("# -*- coding: utf-8 -*-", content)
                self.assertIn("migrations.CreateModel", content)
                self.assertIn("initial = True", content)

                if six.PY3:
                    self.assertIn("úñí©óðé µóðéø", content)  # Meta.verbose_name
                    self.assertIn("úñí©óðé µóðéøß", content)  # Meta.verbose_name_plural
                    self.assertIn("ÚÑÍ¢ÓÐÉ", content)  # title.verbose_name
                    self.assertIn("“Ðjáñgó”", content)  # title.default
                else:
                    self.assertIn(
                        "\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8", content
                    )  # Meta.verbose_name
                    self.assertIn(
                        "\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf", content
                    )  # Meta.verbose_name_plural
                    self.assertIn("\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9", content)  # title.verbose_name
                    self.assertIn("\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d", content)  # title.default
Example #14
0
from django.apps import apps

from audience import autodiscover
from audience.base import variations

from .settings import APPROPRIATE_MODELS, AUDIENCE_FLAGS
from .base import register_fk

for key in APPROPRIATE_MODELS:
    model = apps.get_model(*key.split("."))
    register_fk(model, extra_params=dict(flags=AUDIENCE_FLAGS))

autodiscover()

for model in variations._registry.values():
    apps.register_model('audience', model)
Example #15
0
    def setUpClass(cls):
        cls._tests_loader_models_mod = None

        if not cls.tests_app:
            cls.tests_app = cls.__module__

        models_mod_name = '%s.models' % cls.tests_app

        try:
            models_mod = import_module(models_mod_name)
        except ImportError:
            # Set up a 'models' module, containing any models local to the
            # module that this TestCase is in.
            if ModuleSpec:
                # Python >= 3.4
                #
                # It's not enough to simply create a module type. We need to
                # create a basic spec, and then we need to have the module
                # system create a module from it. There's a handy public
                # function to do this on Python 3.5, but Python 3.4 lacks a
                # public function. Fortunately, it's easy to call a private
                # one.
                spec = ModuleSpec(name=models_mod_name,
                                  loader=None)

                if module_from_spec:
                    # Python >= 3.5
                    models_mod = module_from_spec(spec)
                else:
                    # Python == 3.4
                    models_mod = \
                        importlib._bootstrap._SpecMethods(spec).create()

                assert models_mod
            else:
                # Python < 3.4
                models_mod = types.ModuleType(str(models_mod_name))

                # Django needs a value here. Doesn't matter what it is.
                models_mod.__file__ = ''

            # Transfer all the models over into this new module.
            module_name = cls.__module__
            test_module = sys.modules[module_name]

            for key, value in six.iteritems(test_module.__dict__):
                if (inspect.isclass(value) and
                    issubclass(value, Model) and
                    value.__module__ == module_name):
                    models_mod.__dict__[key] = value

        cls._tests_loader_models_mod = models_mod

        if models_mod:
            sys.modules[models_mod.__name__] = models_mod

        cls._models_loader_old_settings = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [
            cls.tests_app,
        ]

        # If Django Evolution is being used, we'll want to clear out any
        # recorded schema information so that it can be generated from
        # scratch when we set up the database.
        if (Evolution is not None and
            Version is not None and
            getattr(settings, 'DJANGO_EVOLUTION_ENABLED', True)):
            Version.objects.all().delete()
            Evolution.objects.all().delete()

        if apps:
            # Push the new set of installed apps, and begin registering
            # each of the models associated with the tests.
            apps.set_installed_apps(settings.INSTALLED_APPS)
            app_config = apps.get_containing_app_config(cls.tests_app)

            if models_mod:
                app_label = app_config.label

                for key, value in six.iteritems(models_mod.__dict__):
                    if inspect.isclass(value) and issubclass(value, Model):
                        # The model was likely registered under another app,
                        # so we need to remove the old one and add the new
                        # one.
                        try:
                            del apps.all_models[value._meta.app_label][
                                value._meta.model_name]
                        except KeyError:
                            pass

                        value._meta.app_label = app_label
                        apps.register_model(app_label, value)

            call_command('migrate', run_syncdb=True, verbosity=0,
                         interactive=False)
        else:
            load_app(cls.tests_app)
            call_command('syncdb', verbosity=0, interactive=False)

        super(TestModelsLoaderMixin, cls).setUpClass()