Exemple #1
0
def _reset_django(settings):
    """
    Hackish way to reset the django instance settings and AppConfig
    :param settings: django settings module
    """
    if settings._wrapped != empty:
        clear_url_caches()
        if DJANGO_1_5:
            from django.db.models.loading import cache as apps
            apps.app_store = SortedDict()
            apps.loaded = False
            apps.handled = {}
            apps.postponed = []
            apps.nesting_level = 0
            apps._get_models_cache = {}
        elif DJANGO_1_6:
            from django.db.models.loading import cache as apps
            apps.app_store = SortedDict()
            apps.loaded = False
            apps.handled = set()
            apps.postponed = []
            apps.nesting_level = 0
            apps._get_models_cache = {}
        else:
            from django.apps import apps
            apps.clear_cache()
        settings._wrapped = empty
        clear_url_caches()
Exemple #2
0
    def setUp(self):
        clear_url_caches()

        self.old_settings = {}

        self._update_setting('DEBUG', True)
        self._update_setting('TEMPLATE_DEBUG', True)

        self._update_setting('ROOT_URLCONF',
            'i18nurls.tests.urls'
        )

        self._update_setting('MIDDLEWARE_CLASSES', (
            'i18nurls.middleware.LocaleMiddleware',
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ))

        self._update_setting('LANGUAGES', (
            ('nl', 'Dutch'),
            ('en', 'English'),
        ))
Exemple #3
0
def register_plugin_urls(plugin_name):
    for index, plugin_url in find_plugin_urls(plugin_name):
        if plugin_url and index < 0:
            urlpatterns = _get_url_resolver().url_patterns
            urlpatterns += (plugin_url, )
    update_admin_urls()
    urlresolvers.clear_url_caches()
    def stopTest(self, test):
        """
        After test is run, clear urlconf, caches and database
        """

        test_case = get_test_case_class(test)
        if issubclass(test_case, DjangoTestCase):
            return

        from django.db import transaction
        from django.conf import settings

        test_case = get_test_case_class(test)
        test_case_instance = get_test_case_instance(test)

        if hasattr(test_case_instance, 'is_skipped') and test_case_instance.is_skipped():
            return

        if hasattr(test_case, '_old_root_urlconf'):
            settings.ROOT_URLCONF = test_case._old_root_urlconf
            clear_url_caches()
        flush_cache(test)

        if getattr_test(test, 'no_database_interaction', False):
            # for true unittests, we can leave database handling for later,
            # as unittests by definition do not interacts with database
            return
        
        if getattr_test(test, 'database_single_transaction'):
            transaction.rollback()
            transaction.leave_transaction_management()

        if getattr_test(test, "database_flush", True):
            for db in self._get_tests_databases(getattr_test(test, 'multi_db')):
                getattr(settings, "TEST_DATABASE_FLUSH_COMMAND", flush_database)(self, database=db)
Exemple #5
0
 def testTransReverses(self):
     translation.activate('en')
     self.assertEqual(reverse(the_president), '/en/garfield/the-president/')
     # Simulate URLResolver cache reset between requests
     clear_url_caches()
     translation.activate('fr')
     self.assertEqual(reverse(the_president), http.urlquote(u'/fr/garfield/le-président/'))
Exemple #6
0
    def beforeTest(self, test):

        if not self.settings_path:
            # short circuit if no settings file can be found
            return

        from django.core.management import call_command
        from django.core.urlresolvers import clear_url_caches
        from django.db import connection, transaction
        from django.core import mail

        mail.outbox = []

        transaction_support = self._has_transaction_support(test)
        if transaction_support:
            transaction.enter_transaction_management()
            transaction.managed(True)
            self.disable_transaction_support(transaction)

        if isinstance(test, nose.case.Test) and \
            isinstance(test.test, nose.case.MethodTestCase) and \
            hasattr(test.context, 'fixtures'):
                # We have to use this slightly awkward syntax due to the fact
                # that we're using *args and **kwargs together.
                call_command('loaddata', *test.context.fixtures, **{'verbosity': 0})

        if isinstance(test, nose.case.Test) and \
            isinstance(test.test, nose.case.MethodTestCase) and \
            hasattr(test.context, 'urls'):
                # We have to use this slightly awkward syntax due to the fact
                # that we're using *args and **kwargs together.
                self.old_urlconf = settings.ROOT_URLCONF
                settings.ROOT_URLCONF = self.urls
                clear_url_caches()
Exemple #7
0
 def reset_urlconf(self):
     url_conf = getattr(settings, 'ROOT_URLCONF', False)
     if url_conf:
         reload(import_module(url_conf))
     reload(import_module('pages.urls'))
     reload(import_module('pages.testproj.urls'))
     clear_url_caches()
Exemple #8
0
def unregister_from_admin(admin_site, model=None, old_table_name=None, app_label=None, object_name=None):
    " Removes the dynamic model from the given admin site "

    if old_table_name is None and model is not None:
        old_table_name = model._meta.db_table

    if app_label is None and object_name is None and model is not None:
        app_label = model._meta.app_label
        object_name = model._meta.object_name

    # First deregister the current definition
    # This is done "manually" because model will be different
    # db_table is used to check for class equivalence.
    if old_table_name:
        for reg_model in admin_site._registry.keys():
            if old_table_name == reg_model._meta.db_table:
                del admin_site._registry[reg_model]

    # Try looking for same app_label/object_name
    if app_label and object_name:
        for reg_model in admin_site._registry.keys():
            if app_label == reg_model._meta.app_label and object_name == reg_model._meta.object_name:
                del admin_site._registry[reg_model]

    # Try the normal approach too
    if model is not None:
        try:
            admin_site.unregister(model)
        except NotRegistered:
            pass

    # Reload the URL conf and clear the URL cache
    # It's important to use the same string as ROOT_URLCONF
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()
Exemple #9
0
def register_dynamic_model(dynamic_model, create_tables=True, admin_site_collection=None):
    remove_from_model_cache(dynamic_model)
    class_metadata_definition = dynamic_model.create_metadata_definition()
    class_definition = dynamic_model.create_class_definition(class_metadata_definition)
    if class_metadata_definition:
        # remove old definition
        class_definition_exists, metadata_definition_exists = False, False
        for registered_model in admin.site._registry.keys():  # print 'comparing registered (%s) against model (%s)' % (registered_model._meta.db_table, class_metadata_definition._meta.db_table,)
            class_definition_exists = remove_if_exists(class_definition, registered_model, admin_site_collection)
            metadata_definition_exists = remove_if_exists(class_metadata_definition, registered_model, admin_site_collection)
        unregister_class(class_metadata_definition, admin_site_collection)
        unregister_class(class_definition, admin_site_collection)
        table_names = connection.introspection.table_names()
        if class_metadata_definition._meta.db_table in table_names or metadata_definition_exists:
            dynamic_model.ensure_integrity(class_metadata_definition)
        else:
            create_table(dynamic_model, class_metadata_definition)
        if not class_definition._meta.db_table in table_names and not class_definition_exists:
            create_table(dynamic_model, class_definition)
        else:
            dynamic_model.ensure_integrity(class_definition)
        # add new definition
        if dynamic_model.active:
            class_definition_admin = create_dynamic_admin(class_metadata_definition, class_definition)
            for admin_site in admin_site_collection:
                admin_site.register(class_metadata_definition, class_definition_admin)
        #restart_cache()
        #from django.utils.datastructures import SortedDict
        #app_cache.app_models[DynamicDatasheet._meta.app_label]=SortedDict()
        reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches()
Exemple #10
0
    def pytest_runtest_setup(self, item):
        item_obj = self._get_item_obj(item)

        # Set the URLs if the py.test.urls() decorator has been applied
        if hasattr(item.obj, "urls"):
            self._old_urlconf = settings.ROOT_URLCONF
            settings.ROOT_URLCONF = item.obj.urls
            clear_url_caches()

        # This is a Django unittest TestCase
        if self._is_unittest(item_obj):
            # We have to run these here since py.test's unittest plugin skips
            # __call__()
            item_obj.client = Client()
            item_obj._pre_setup()
            item_obj.setUp()
            return

        if not settings.DATABASE_SUPPORTS_TRANSACTIONS:
            call_command("flush", verbosity=self.verbosity, interactive=not self.noinput)
        else:
            transaction.enter_transaction_management()
            transaction.managed(True)
            disable_transaction_methods()

            from django.contrib.sites.models import Site

            Site.objects.clear_cache()

        mail.outbox = []
    def __init__(self, *args, **kwargs):
        """
        This ensures that verbose raw ID widgets work in inlines,
        especially in FeinCMS content types.

        Since the Django admin only initialises InlineModelAdmin objects
        as they're needed, we have to update the URLs used to generate the
        preview HTML that's called when the foreign object has been edited
        as we go along. Not brilliant.

        The other option would be to introspect all registered ModelAdmin
        objects for defined inlines, and it might be good to eventually
        switch to that approach.
        """
        super(ImprovedRawIdStackedMixin, self).__init__(*args, **kwargs)
        if getattr(self.admin_site, '_inline_urls', None) is None:
            # Store the URLs in an "_inline_urls" attribute of the
            # AdminSite object. Use a dictionary so each inline is
            # only added once, which allows us to simply grab .values()
            # for a list of URLs to register
            self.admin_site._inline_urls = {}
        name = self.model._meta.object_name.lower()
        if name not in self.admin_site._inline_urls:
            # When we're adding a previously unseen inline, recalculate
            # the urlpatterns objects in adminboost.urls and clear
            # Django's URL cache
            self.admin_site._inline_urls[name] = self.get_inline_url()
            reload(urls)
            clear_url_caches()
    def setUp(self):
        clear_app_resolvers()
        clear_url_caches()

        if APP_MODULE in sys.modules:
            del sys.modules[APP_MODULE]
        self.reload_urls()
    def test_get_i18n_apphook_with_explicit_current_app(self):
        self.apphook_clear()
        titles = self.create_base_structure(NS_APP_NAME, ['en', 'de'], 'instance_1')
        public_de_title = titles[1]
        de_title = Title.objects.get(page=public_de_title.page.publisher_draft, language="de")
        de_title.slug = "de"
        de_title.save()
        de_title.page.publish('de')

        self.reload_urls()
        self.apphook_clear()

        page2 = create_page("page2", "nav_playground.html",
                            "en", created_by=self.superuser, published=True, parent=de_title.page.parent,
                            apphook=NS_APP_NAME,
                            apphook_namespace="instance_2")
        create_title("de", "de_title", page2, slug="slug")
        page2.publish('de')
        clear_app_resolvers()
        clear_url_caches()

        if APP_MODULE in sys.modules:
            del sys.modules[APP_MODULE]

        self.reload_urls()
        with force_language("de"):
            reverse('namespaced_app_ns:current-app', current_app="instance_1")
            reverse('namespaced_app_ns:current-app', current_app="instance_2")
            reverse('namespaced_app_ns:current-app')
        with force_language("en"):
            reverse('namespaced_app_ns:current-app', current_app="instance_1")
            reverse('namespaced_app_ns:current-app', current_app="instance_2")
            reverse('namespaced_app_ns:current-app')
        self.apphook_clear()
    def tearDown(self):
        clear_app_resolvers()
        clear_url_caches()

        if APP_MODULE in sys.modules:
            del sys.modules[APP_MODULE]
        self.apphook_clear()
Exemple #15
0
def _fetch_meta():
	mintime = timezone.make_aware(datetime.min, timezone.get_current_timezone())
	conn = httplib.HTTPConnection("table.finance.yahoo.com", timeout=10)
	stocks = Stock.objects.all() 
	for stock in stocks:
		id = str(stock.stock_id)
		code = "%s.%s" % (id[2:], "sz" if id[0:2] == "sz" else "ss")
		metaclass = create_stock_metaclass(id)
		create_stock_metatable(metaclass)
		count = metaclass.objects.count()
		latest = metaclass.objects.order_by("-time")[0].time if count > 0 else mintime
		content = getpage(conn, "/table.csv?s=%s" % code)
		if content is not None:
			srecords = content.split('\n')[1:]
			records = [x.split(',') for x in srecords]
			wstocks = []
			for record in records:
				if len(record) != 7:
					continue
				time = datetime.strptime(record[0], "%Y-%m-%d")
				time = timezone.make_aware(time, timezone.get_current_timezone())
				if time > latest:
					m = metaclass(time=time, open=float(record[1]), high=float(record[2]),
						low=float(record[3]), close=float(record[4]), vol=int(record[5]), adj=float(record[6]))
					wstocks.append(m)
			if len(wstocks) > 0:
				metaclass.objects.bulk_create(wstocks)
	conn.close()
	reload(import_module(settings.ROOT_URLCONF))
	clear_url_caches()				
Exemple #16
0
    def finalize(self, result=None):
        """
        Clean up any created database and schema.
        """
        if not self.settings_path:
            # short circuit if no settings file can be found
            return

        from django.test.utils import teardown_test_environment
        from django.db import connection
        from django.conf import settings
        from django.core.urlresolvers import clear_url_caches

        self.call_plugins_method('beforeDestroyTestDb', settings, connection)
        connection.creation.destroy_test_db(self.old_db, verbosity=self.verbosity)
        self.call_plugins_method('afterDestroyTestDb', settings, connection)

        self.call_plugins_method(
            'beforeTeardownTestEnv', settings, teardown_test_environment)
        teardown_test_environment()
        self.call_plugins_method('afterTeardownTestEnv', settings)

        if hasattr(self, 'old_urlconf'):
            settings.ROOT_URLCONF = self.old_urlconf
            clear_url_caches()
def text_description_to_model(module, text, app_label, admin_register=True):
    dct = yaml.load(text)
    for model_name in dct.keys():
        fields = dct[model_name]['fields']
        attrs = {}

        for field in fields:
            attrs[field['id']] = _field_by_type(field['type'], field['title'])

        attrs['__module__'] = module.__name__

        model_name = str(model_name).capitalize()
        NewModel = type(model_name, (Model,), attrs)

        setattr(module, model_name, NewModel)

        new_ct = ContentType()
        new_ct.app_label = app_label
        new_ct.name = model_name
        new_ct.model = model_name.lower()
        new_ct.save()

        if admin_register:

            class Admin(admin.ModelAdmin):
                pass

            admin.site.register(NewModel, Admin)

    if admin_register:
        reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches()
Exemple #18
0
    def _post_teardown(self):
        """ Performs any post-test things. This includes:

            * Putting back the original ROOT_URLCONF if it was changed.
        """
        if hasattr(self, "_old_root_urlconf"):
            settings.ROOT_URLCONF = self._old_root_urlconf
            clear_url_caches()
 def setUpURLs(self):
     from django_html_filter.decorators import html_filter, html_filter_exempt
     settings.ROOT_URLCONF = patterns('',
         url(r'^$', test_view, name='test_view'),
         url(r'^exempt/$', html_filter_exempt(test_view), name='exempt'),
         url(r'^filtered/$', html_filter()(test_view), name='filtered'),
         url(r'^args/$', html_filter(strip_whitespace=True)(test_view), name='args'))
     clear_url_caches()
Exemple #20
0
def reload_urls(settings):
    url_modules = [settings.ROOT_URLCONF]

    clear_url_caches()

    for module in url_modules:
        if module in sys.modules:
            del sys.modules[module]
Exemple #21
0
 def unload_urls(self, to_original=False):
     __import__(self.settings.ROOT_URLCONF)
     project_url_module = sys.modules[self.settings.ROOT_URLCONF]
     while self.__class__._original_urls:
         project_url_module.urlpatterns = self.__class__._original_urls.pop()
         if not to_original:
             break
     clear_url_caches()
 def save_model(self, request, object, form, change):
     import dynamic_urls
     instance = form.save()
     # for sites that are not in debug mode reload
     # the dynamic urls, i'm not sure if this is the
     # best way though
     reload(dynamic_urls)
     clear_url_caches()
     return instance
Exemple #23
0
    def clear_cache(self):
        # If we don't do this, nothing gets correctly set for the URL Prefix
        urlconf = settings.ROOT_URLCONF
        if urlconf in sys.modules:
            reload(sys.modules[urlconf])
        import_module(urlconf)

        # Don't forget to clear out the cache for `reverse`
        clear_url_caches()
Exemple #24
0
 def adminRegister(self, class_model):
     """ Register models in admin """
     try:
         admin.site.unregister(class_model)
     except:
         pass
     admin.site.register(class_model)
     reload(import_module(settings.ROOT_URLCONF))
     clear_url_caches()
Exemple #25
0
    def _reset_urls(self, urlconf_modules):
        """Reset `urls.py` for a set of Django apps."""
        for urlconf in urlconf_modules:
            if urlconf in sys.modules:
                reload(sys.modules[urlconf])
        clear_url_caches()

        # Resolve a URL so that the new urlconf gets loaded
        resolve('/')
Exemple #26
0
    def setUp(self):
        create_app_config()
        cache.clear()
        cache_buffer.reset()

        # Reload the urls to reinitialize the vision routes
        import hatch.urls
        reload(hatch.urls)
        clear_url_caches()
Exemple #27
0
 def _reload_urls(self):
     """Clears out the URL caches, reloads the root urls module, and
     re-triggers the autodiscovery mechanism for Horizon. Allows URLs
     to be re-calculated after registering new dashboards. Useful
     only for testing and should never be used on a live site.
     """
     urlresolvers.clear_url_caches()
     reload(import_module(settings.ROOT_URLCONF))
     base.Horizon._urls()
Exemple #28
0
    def _test_method(self, method, read_only_enabled, is_superuser,
                     expect_503):
        """Test a request.

        This tests various states related to read-only mode.

        Args:
            method (unicode):
                The HTTP method to test.

            read_only_enabled (bool):
                Whether read-only mode should be enabled during the test.

            is_superuser (bool):
                Whether to test using a superuser.

            expect_503 (bool):
                Whether the response is expected to be an HTTP 503 or not.
        """
        self.siteconfig.set('site_read_only', read_only_enabled)
        self.siteconfig.save()

        if is_superuser:
            self.client.login(username='******', password='******')
        else:
            self.client.login(username='******', password='******')

        try:
            settings = {
                'ROOT_URLCONF': 'reviewboard.webapi.tests.test_base',
            }
            with self.settings(**settings):
                # If we don't clear the URL caches then lookups for the URL will
                # break (due to using the URLs cached from the regular Review Board
                # URL conf).
                clear_url_caches()

                if method == 'post':
                    resource_url = self.resource.get_list_url()
                else:
                    resource_url = self.resource.get_item_url(obj_id='123')

                method = getattr(self.client, method)
                rsp = method(resource_url)
        finally:
            clear_url_caches()

        content = json.loads(rsp.content)

        if expect_503:
            self.assertEqual(rsp.status_code, 503)
            self.assertEqual(content['stat'], 'fail')
            self.assertEqual(content['err']['msg'], READ_ONLY_ERROR.msg)
            self.assertEqual(content['err']['code'], READ_ONLY_ERROR.code)
        else:
            self.assertEqual(rsp.status_code, 418)
            self.assertEqual(content['stat'], 'ok')
    def reset_urlresolvers_caches(self):
        # reset urlresolvers cache in order to update
        # urlpatterns provided by adminsite, to include
        # the just registered models
        if get_urlconf() is None:
            set_urlconf(settings.ROOT_URLCONF)

        reload_importlib_module(get_urlconf())
        clear_url_caches()
def patch_root_urlconf():
    try:
        reverse('djdt:render_panel')
    except NoReverseMatch:
        urlconf_module = import_module(settings.ROOT_URLCONF)
        urlconf_module.urlpatterns += patterns('',                      # noqa
            url(r'^__debug__/', include(debug_toolbar.urls)),
        )
        clear_url_caches()
Exemple #31
0
def reload_settings(settings, databases=None):
    """Special routine to reload django settings.

    Including:
    urlconf module, context processor, templatetags settings, database settings.
    """
    if databases:
        settings.DATABASES.update(databases)

    # check if there's settings to reload
    if hasattr(settings, 'ROOT_URLCONF'):
        if settings.ROOT_URLCONF in sys.modules:
            imp.reload(sys.modules[settings.ROOT_URLCONF])
        import django
        if hasattr(django, 'setup'):
            django.setup()
        import_module(settings.ROOT_URLCONF)
        set_urlconf(settings.ROOT_URLCONF)
        settings.LANGUAGE_CODE = 'en'  # all tests should be run with English by default

        # Make the ConnectionHandler use the new settings, otherwise the ConnectionHandler will have old configuraton.
        from django.db.utils import ConnectionHandler
        import django.db
        from django.db.utils import load_backend
        import django.db.transaction
        import django.db.models
        import django.db.models.sql.query
        import django.core.management.commands.syncdb
        import django.db.models.sql.compiler
        import django.db.backends
        import django.db.backends.mysql.base
        import django.core.management.commands.loaddata

        # all modules which imported django.db.connections should be changed to get new ConnectionHanlder
        django.db.models.sql.compiler.connections = django.db.models.connections = \
            django.core.management.commands.loaddata.connections = \
            django.db.backends.connections = django.db.backends.mysql.base.connections = \
            django.core.management.commands.syncdb.connections = django.db.transaction.connections = \
            django.db.connections = django.db.models.base.connections = django.db.models.sql.query.connections = \
            ConnectionHandler(settings.DATABASES)

        # default django connection and backend should be also changed
        django.db.connection = django.db.connections[django.db.DEFAULT_DB_ALIAS]
        django.db.backend = load_backend(django.db.connection.settings_dict['ENGINE'])

        import django.core.cache
        django.core.cache.cache = django.core.cache.get_cache(django.core.cache.DEFAULT_CACHE_ALIAS)

        # clear django urls cache
        clear_url_caches()
        # clear django contextprocessors cache
        context._standard_context_processors = None
        # clear django templatetags cache
        base.templatetags_modules = None

        # reload translation files
        imp.reload(translation)
        imp.reload(trans_real)

        # clear django template loaders cache
        loader.template_source_loaders = None
        from django.template.loaders import app_directories
        imp.reload(app_directories)
    def startTest(self, test):
        """
        When preparing test, check whether to make our database fresh
        """
        #####
        ### FIXME: Method is a bit ugly, would be nice to refactor if's to more granular method
        ### Additionally, it would be nice to separate handlings as plugins et al...but what about
        ### the context?
        #####

        from django.db import transaction, connection
        try:
            from django.db import DEFAULT_DB_ALIAS, connections
        except ImportError:
            MULTIDB_SUPPORT = False
        else:
            MULTIDB_SUPPORT = True

        from django.test.testcases import call_command
        from django.core import mail
        from django.conf import settings

        test_case = get_test_case_class(test)
        self.previous_test_needed_flush = self.need_flush
        mail.outbox = []
        enable_test(test_case, 'django_plugin_started')

        # clear URLs if needed
        if hasattr(test_case, 'urls'):
            test_case._old_root_urlconf = settings.ROOT_URLCONF
            settings.ROOT_URLCONF = test_case.urls
            clear_url_caches()

        #####
        ### Database handling follows
        #####

        if getattr(test_case, 'no_database_interaction', False):
            # for true unittests, we can leave database handling for later,
            # as unittests by definition do not interacts with database
            return

        # make self.transaction available
        test_case.transaction = transaction
        self.commits_could_be_used = False

        if getattr(test_case, 'multi_db', False):
            if not MULTIDB_SUPPORT:
                test_case.skipped = True
                return
            else:
                databases = connections
        else:
            if MULTIDB_SUPPORT:
                databases = [DEFAULT_DB_ALIAS]
            else:
                databases = [connection]

        if getattr(test_case, "database_flush", True):
            for db in databases:
                getattr(settings, "TEST_DATABASE_FLUSH_COMMAND",
                        flush_database)(self, database=db)
            # it's possible that some garbage will be left after us, flush next time
            self.need_flush = True
            # commits are allowed during tests
            self.commits_could_be_used = True

        # previous test needed flush, clutter could have stayed in database
        elif self.previous_test_needed_flush is True:
            for db in databases:
                getattr(settings, "TEST_DATABASE_FLUSH_COMMAND",
                        flush_database)(self, database=db)
            self.need_flush = False

        # otherwise we should have done our job
        else:
            self.need_flush = False

        if (hasattr(test_case, "database_single_transaction")
                and test_case.database_single_transaction is True):
            transaction.enter_transaction_management()
            transaction.managed(True)

        # fixtures are loaded inside transaction, thus we don't need to flush
        # between database_single_transaction tests when their fixtures differ
        if hasattr(test_case, 'fixtures'):
            if self.commits_could_be_used:
                commit = True
            else:
                commit = False
            for db in databases:
                call_command(
                    'loaddata', *test_case.fixtures, **{
                        'verbosity': 0,
                        'commit': commit,
                        'database': db
                    })
Exemple #33
0
 def tearDown(self):
     # Make sure we will leave an empty cache for other testcases.
     clear_url_caches()
     super(URLTestCaseBase, self).tearDown()
Exemple #34
0
 def setUp(self):
     # Make sure the cache is empty before we are doing our tests.
     super(URLTestCaseBase, self).tearDown()
     clear_url_caches()
     reload_urlconf()
Exemple #35
0
 def _reload_urlconf(self):
     """ Helper method to reload url config."""
     reload(sys.modules[settings.ROOT_URLCONF])
     clear_url_caches()
Exemple #36
0
    def _test_method(self,
                     method,
                     feature_enabled,
                     local_site=None,
                     feature_local_site_enabled=None,
                     obj_id=None):
        """Test an HTTP method on the resource.

        Args:
            method (unicode):
                The HTTP method (e.g., ``"POST"`` or ``"PUT"``).

            feature_enabled (bool):
                Whether or not the feature should be enabled globally.

            local_site (reviewboard.site.models.LocalSite, optional):
                If provided, the request will be made against the API using the
                given LocalSite.

            feature_local_site_enabled (bool, optional):
                Whether or not the feature is enabled on the given LocalSite.

                This argument must be provided if ``local_site`` is provided,

            obj_id (unicode, optional):
                If provided, the request will be made against the item
                resource. Otherwise the request is made against the list
                resource.
        """
        # When a LocalSite is provided, we want to enable/disable the feature
        # only for that LocalSite and do the opposite for the global settings
        # to ensure that we are picking up the setting from the LocalSite and
        # not from the global settings.
        if local_site is not None:
            if feature_local_site_enabled is None:
                raise ValueError('feature_local_site_enabled must not be None')

            if not local_site.extra_data:
                local_site.extra_data = {}

            local_site.extra_data['enabled_features'] = {
                TestingFeature.feature_id: feature_local_site_enabled,
            }

            local_site.save(update_fields=('extra_data', ))

        method = getattr(self.client, method)

        local_site_name = None

        if local_site:
            local_site_name = local_site.name

        settings = {
            'ENABLED_FEATURES': {
                TestingFeature.feature_id: feature_enabled,
            },
            'ROOT_URLCONF': 'reviewboard.webapi.tests.test_base',
        }

        try:
            # If we don't clear the URL caches then lookups for the URL will
            # break (due to using the URLs cached from the regular Review Board
            # URL conf).
            clear_url_caches()

            with self.settings(**settings):
                if obj_id is None:
                    resource_url = self.resource.get_list_url(
                        local_site_name=local_site_name)
                else:
                    resource_url = self.resource.get_item_url(
                        local_site_name=local_site_name, obj_id=obj_id)

                rsp = method(resource_url)
        finally:
            clear_url_caches()

        content = json.loads(rsp.content.decode('utf-8'))

        if feature_enabled or feature_local_site_enabled:
            self.assertEqual(rsp.status_code, 418)
            self.assertEqual(content['stat'], 'ok')
            self.assertEqual(content['obj_id'], obj_id)
        else:
            self.assertEqual(rsp.status_code, 403)
            self.assertEqual(content['stat'], 'fail')
            self.assertEqual(content['err']['msg'], PERMISSION_DENIED.msg)
            self.assertEqual(content['err']['code'], PERMISSION_DENIED.code)
Exemple #37
0
 def tearDown(self):
     # Make sure we will leave an empty cache for other testcases.
     clear_url_caches()
Exemple #38
0
 def setUp(self):
     # Make sure the cache is empty before we are doing our tests.
     clear_url_caches()
Exemple #39
0
    def setUp(self):
        super(DirectSEOBase, self).setUp()

        db_backend = settings.DATABASES['default']['ENGINE'].split('.')[-1]

        # Set columns that are utf8 in production to utf8
        if db_backend == 'mysql':
            cursor = connections['default'].cursor()
            cursor.execute("alter table seo_customfacet convert to character "
                           "set utf8 collate utf8_unicode_ci")
            cursor.execute("alter table seo_seositefacet convert to character "
                           "set utf8 collate utf8_unicode_ci")
            cursor.execute("alter table seo_company convert to character set "
                           "utf8 collate utf8_unicode_ci")
            cursor.execute(
                "alter table seo_queryredirect convert to character "
                "set utf8 collate utf8_unicode_ci")
            cursor.execute("alter table taggit_tag convert to character set "
                           "utf8 collate utf8_unicode_ci")
            cursor.execute("alter table taggit_taggeditem convert to "
                           "character set "
                           "utf8 collate utf8_unicode_ci")
            cursor.execute("alter table seo_seositeredirect convert to "
                           "character set utf8 collate utf8_unicode_ci")
            cursor.execute("alter table django_redirect convert to "
                           "character set utf8 collate utf8_unicode_ci")
            # We have a data migration that does this, but we don't run
            # migrations during tests (Django 1.6.5
            cursor.execute("ALTER TABLE django_flatpage CONVERT TO "
                           "CHARACTER SET utf8 COLLATE utf8_general_ci")
            cursor.execute("ALTER TABLE seo_custompage CONVERT TO "
                           "CHARACTER SET utf8 COLLATE utf8_general_ci")

        setattr(settings, 'ROOT_URLCONF', 'dseo_urls')
        setattr(settings, "PROJECT", 'dseo')
        clear_url_caches()

        self.base_middleware_classes = settings.MIDDLEWARE_CLASSES
        middleware_classes = self.base_middleware_classes + (
            'wildcard.middleware.WildcardMiddleware',
            'middleware.RedirectOverrideMiddleware')
        setattr(settings, 'MIDDLEWARE_CLASSES', middleware_classes)

        self.base_context_processors = settings.TEMPLATE_CONTEXT_PROCESSORS
        context_processors = self.base_context_processors + (
            "social_links.context_processors.social_links_context",
            "seo.context_processors.site_config_context",
        )
        setattr(settings, 'TEMPLATE_CONTEXT_PROCESSORS', context_processors)
        context._standard_context_processors = None

        self.conn = Solr('http://127.0.0.1:8983/solr/seo')
        self.conn.delete(q="*:*")
        cache.clear()
        clear_url_caches()

        setattr(settings, 'MEMOIZE', False)

        # As we added tests that created more and more companies, we
        # approached the hardcoded companies in import_jobs_testdata.json.
        # When we hit those ids, we began to get IntegrityErrors during
        # testing. Reset the sequence used by CompanyFactory to clear this
        # build-up.
        CompanyFactory.reset_sequence()
Exemple #40
0
 def setUp(self):
     clear_url_caches()
Exemple #41
0
 def setUp(self):
     clear_url_caches()
     self.client = Client()
Exemple #42
0
 def tearDown(self):
     from django.core.urlresolvers import clear_url_caches
     clear_url_caches()
Exemple #43
0
    def tearDown(self):
        clear_app_resolvers()
        clear_url_caches()

        if APP_MODULE in sys.modules:
            del sys.modules[APP_MODULE]
 def setUp(self):
     clear_url_caches()
     super(TestNoI18N, self).setUp()
 def _clear_urlconf():
     clear_url_caches()
     set_urlconf(None)
 def tearDown(self):
     super(TestNoI18N, self).tearDown()
     clear_url_caches()
Exemple #47
0
def root_urlconf_changed(**kwargs):
    if kwargs['setting'] == 'ROOT_URLCONF':
        from django.core.urlresolvers import clear_url_caches, set_urlconf
        clear_url_caches()
        set_urlconf(None)
Exemple #48
0
def postset_root_urlconf():
    from django.core.urlresolvers import clear_url_caches
    clear_url_caches()
def reload_url_conf():
    # Reload URLs to pick up the overridden settings
    if settings.ROOT_URLCONF in sys.modules:
        reload(sys.modules[settings.ROOT_URLCONF])
    import_module(settings.ROOT_URLCONF)
    clear_url_caches()
Exemple #50
0
 def tearDown(self):
     # make sure URLConf is reset no matter what
     urlresolvers.clear_url_caches()
     reload_urlconf()
Exemple #51
0
 def tearDown(self):
     clear_url_caches()
Exemple #52
0
 def _urlconf_teardown(self):
     set_urlconf(None)
     if hasattr(self, '_old_root_urlconf'):
         settings.ROOT_URLCONF = self._old_root_urlconf
         clear_url_caches()
Exemple #53
0
 def _urlconf_setup(self):
     if hasattr(self, 'urls'):
         self._old_root_urlconf = settings.ROOT_URLCONF
         settings.ROOT_URLCONF = self.urls
         clear_url_caches()
Exemple #54
0
 def tearDownClass(cls):
     super(ClearURLs, cls).tearDownClass()
     clear_url_caches()
def instalar_plugin(request):
    conteudo_arquivo = """aplicacoes = (
    'django.contrib.auth',
    'third_party.grappelli',
    'third_party.djblets',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'django.contrib.syndication',
    'django.contrib.messages',
    'modulos.catalogo',
    'modulos.cinema',
    'modulos.configuracao',
    'modulos.disco_virtual',
    'modulos.index_enquete',
    'modulos.index_evento',
    'modulos.index_gallery',
    'modulos.newsletter',
    'modulos.noticia',
    'modulos.novidades',
    "modulos.onde_encontrar",
    'modulos.paginas',
    'modulos.popup',
    'modulos.produtos',
    'modulos.sociable',
    'modulos.tags',
    'modulos.scrum',
    'third_party.debug_toolbar',
    'third_party.tagging',

)"""
    caminho_xml = "%s/../plugins_instalados.py" % settings.MEDIA_ROOT
    arquivo_xml = open(caminho_xml, "w")
    arquivo_xml.write(unicode(conteudo_arquivo).encode('utf-8'))
    arquivo_xml.close()
    return HttpResponse("Instalado")
    app = load_app("modulos.noticia")
    admin_teste = import_module("modulos.noticia.admin")
    connection = connections["default"]
    cursor = connection.cursor()
    style = color.no_style()
    sql_tabelas = sql.sql_create(app, style, connection)
  #  for sql_query in sql_tabelas:
      #  cursor.execute(sql_query)
    varaveis = import_module(get_urlconf())

    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

    #varaveis.urlpatterns = patterns('',
    #(r'^admin/configuracao/', include('modulos.configuracao.admin_urls')),
    #(r'^admin/index_enquete/', include('modulos.index_enquete.admin_urls')),
    #(r'^admin/', include(admin.site.urls)),
    #(r'^disco_virtual/', include('modulos.disco_virtual.urls')),
    #(r'^onde-encontrar/', include('modulos.onde_encontrar.urls')),
    #(r'^enquete/', include('modulos.index_enquete.urls')),
    #(r'^eventos/', include('modulos.index_evento.urls')),
    #(r'^galerias/', include('modulos.index_gallery.urls')),
    #(r'^grappelli/', include('grappelli.urls')),
    #(r'^newsletter/', include('modulos.newsletter.urls')),
    #(r'^popup/', include('modulos.popup.urls')),
    #(r'^noticia/', include('modulos.noticia.urls')),
    #(r'^utils/', include('modulos.utils.urls')),
    #(r'^site_media/(.*)', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),


#)
    return HttpResponse("Instalado")
Exemple #56
0
 def setUpClass(cls):
     clear_url_caches()
     super(ClearURLs, cls).setUpClass()
Exemple #57
0
 def restore():
     django.conf.settings.ROOT_URLCONF = original_urlconf
     # Copy the pattern from
     # https://github.com/django/django/blob/master/django/test/signals.py#L152
     clear_url_caches()
     set_urlconf(None)
Exemple #58
0
def _clear_url_caches(setting, value, **kwargs):
    if setting == 'ROOT_URLCONF':
        clear_url_caches()
Exemple #59
0
 def setUp(self):
     cache.clear()
     clear_url_caches()
Exemple #60
0
 def setUp(self):
     from django.core.urlresolvers import clear_url_caches
     clear_url_caches()