def test_save_syntax_highlighting_disabled(self):
        """Testing AccountSettingsForm.save() with
        diffviewer_syntax_highlighting disabled
        """
        view = View()
        user = User.objects.get(username='******')

        profile = user.get_profile()
        profile.syntax_highlighting = True
        profile.save(update_fields=('syntax_highlighting', ))

        request = self._build_request(user)
        page = AccountSettingsPage(view, request, user)

        settings = {'diffviewer_syntax_highlighting': False}

        with self.siteconfig_settings(settings):
            form = AccountSettingsForm(page,
                                       request,
                                       user,
                                       data={
                                           'syntax_highlighting': False,
                                           'timezone': profile.timezone,
                                       })

            self.assertTrue(form.is_valid())
            form.save()

        profile = Profile.objects.get(pk=profile.pk)
        self.assertTrue(profile.syntax_highlighting)
Пример #2
0
    def serialize_for_json(self, request, response):
        """Return a JSON-serializable representation of the response."""
        # Test if response is already serializable. If so, keep it as is
        try:
            json.dumps(response)
        except TypeError as e:
            pass
        else:
            return response

        # If response is a dictionary, serialize its values
        if isinstance(response, dict):
            for key in response:
                response[key] = self.serialize_for_json(request, response[key])
            return response

        # If response is a Django Model, try to delegate to its API view.
        if isinstance(response, Model):
            View = RESTAPI.get_view_by_model(response.__class__)
            if View is not None:
                return self.serialize_for_json(request,
                        View().describe_entity(request, response))

        # Try serializing it as an iterable object
        try:
            it = iter(response)
        except TypeError:
            pass
        else:
            return [self.serialize_for_json(request, elem) for elem in it]

        # Try serializing it as an object with a describe function
        if callable(getattr(response, 'describe', None)):
            response = self.serialize_for_json(request, response.describe())

        # Test the serialization again, if it fails cast it to a string
        try:
            json.dumps(response)
        except TypeError as e:
            return str(response)
        else:
            return response
Пример #3
0
    def _register_installed_apps_views(self, apps, with_app=False):
        '''
        Set the routes for all of the installed apps (except the django.* installed apps). Will search through each module
        in the installed app and will look for a view class. If a views.py module is found, any functions found in the 
        module will also be given a routing table by default. Each route will, by default, be of the value <module_name>.<view_name>. 
        If you are worried about view names overlapping between apps, then use the with_app flag set to true and routes 
        will be of the variety of <app_name>.<module_name>.<view_name>. The path after the base route will provide positional 
        arguments to the url class for anything between the forward slashes (ie. /). For example, say you have view inside 
        a module called foo, your route table would include a route as follows:
        
            ^foo/view_name/(?([^/]*)/)*
        
        Note that view functions that are not class-based must be included in the top-level directory of an app in a file
        called views.py if they are to be included. This does not make use of the Django app loader, so it is safe to put
        models in files outside of the models.py, as long as those views are class-based.
        
        Note that class-based views must also not require any parameters in the initialization of the view.
        
        To prevent select views from not being registered in this manner, set the register_route variable on the view to False.
        
        All functions within a views.py module are also added with this view. That means that any decorators will also have
        their own views. If this is not desired behavior, then set the settings.REGISTER_VIEWS_PY_FUNCS to False.
            
        @param apps: the INSTALLED_APPS setting in the settings for your Django app.
        @param with_app: set to true if you want the app name to be included in the route
        '''
        view_inst = View()

        def add_func(app, mod, funcName, func):
            r = "{}/{}/([^\s#?]*)".format(mod, funcName)
            if with_app:
                r = "{}/{}".format(app, r.lstrip('/'))
            self.add(r.lower(), func, add_ending=False)

        def load_views(mod, mod_name, parent_mod_name=""):
            if parent_mod_name:
                name_mod = parent_mod_name + '/' + mod_name
            else:
                name_mod = mod_name
            for klass in inspect.getmembers(mod, inspect.isclass):
                try:
                    try:
                        inst = klass[1]()
                    except AttributeError:
                        continue  #object is perhaps a model object
                    if isinstance(inst, View) and type(inst) != type(
                            view_inst):  #we do not want to add the View class
                        if not hasattr(inst, 'register_route') or (
                                hasattr(inst, 'register_route')
                                and inst.register_route):
                            add_func(app, name_mod, klass[0],
                                     klass[1].as_view())
                        if hasattr(inst, 'routes'):
                            self.add_view(klass[1])
                except TypeError as e:  #not a View class if init requires input.
                    if "'function' object is not subscriptable" in str(e):
                        raise ValueError("Attempting to do something wrong")
                    if 'string indices must be integers' in str(e):
                        raise TypeError from e
                except ValueError as e:
                    print(e)
            if mod_name == "views" and (hasattr(settings,
                                                'REGISTER_VIEWS_PY_FUNCS')
                                        and settings.REGISTER_VIEWS_PY_FUNCS):
                for func in inspect.getmembers(mod, inspect.isfunction):
                    add_func(app, name_mod, func[0], func[1])

        def load_module(mod, pkg, path=""):
            '''
            Load the module and get all of the modules in it.
            '''
            print("The module and pkg of the load_module:", mod, pkg, path)
            loaded_app = il.import_module('.' + mod, pkg)
            for finder, mname, ispkg in pkgutil.walk_packages(
                [loaded_app.__path__[0]]):
                if ispkg:
                    load_module(mname, loaded_app.__package__,
                                path + '/' + mod)
                views_mod = il.import_module('.' + mname,
                                             loaded_app.__package__)
                load_views(
                    views_mod, mname, path + '/' +
                    mod)  #Check if the module itself has any view classes

        for app in settings.INSTALLED_APPS:
            app_name = app.split('.')[-1]
            #             print()
            #             print("the app: " + app_name)
            if 'django' != app.split('.')[0]:  #only do it for non-django apps
                loaded_app = il.import_module(app)
                #                 print("Loaded app path: ", loaded_app.__path__[0])
                for finder, mname, ispkg in pkgutil.walk_packages(
                    [loaded_app.__path__[0]]):
                    if ispkg:
                        load_module(mname, loaded_app.__package__)
                    else:
                        mod = il.import_module('.' + mname,
                                               loaded_app.__package__)
                        load_views(mod, mname)