def handle(self, *args, **options):
        if args:
            appname, = args

        if options.get('no_color', False):
            style = no_style()
        else:
            style = color_style()

        if getattr(settings, 'ADMIN_FOR', None):
            settings_modules = [
                __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR
            ]
        else:
            settings_modules = [settings]

        self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), ))

        language = options.get('language', None)
        if language is not None:
            translation.activate(language)
            self.LANGUAGES = [(code, name) for code, name in self.LANGUAGES
                              if code == language]

        decorator = options.get('decorator')
        if not decorator:
            decorator = ['login_required']

        format_style = options.get('format_style')
        if format_style not in FMTR:
            raise CommandError(
                "Format style '%s' does not exist. Options: %s" %
                (format_style, FMTR.keys()))
        pretty_json = format_style == 'pretty-json'
        if pretty_json:
            format_style = 'json'
        fmtr = FMTR[format_style]

        urlconf = options.get('urlconf')

        views = []
        for settings_mod in settings_modules:
            if not hasattr(settings_mod, urlconf):
                raise CommandError(
                    "Settings module {} does not have the attribute {}.".
                    format(settings_mod, urlconf))

            try:
                urlconf = __import__(getattr(settings_mod, urlconf), {}, {},
                                     [''])
            except Exception as e:
                if options.get('traceback', None):
                    import traceback
                    traceback.print_exc()
                print(
                    style.ERROR("Error occurred while trying to load %s: %s" %
                                (getattr(settings_mod, urlconf), str(e))))
                continue

            view_functions = self.extract_views_from_urlpatterns(
                urlconf.urlpatterns)
            for (func, regex, url_name) in view_functions:
                if hasattr(func, '__globals__'):
                    func_globals = func.__globals__
                elif hasattr(func, 'func_globals'):
                    func_globals = func.func_globals
                else:
                    func_globals = {}

                decorators = [d for d in decorator if d in func_globals]

                if isinstance(func, functools.partial):
                    func = func.func
                    decorators.insert(0, 'functools.partial')

                if hasattr(func, '__name__'):
                    func_name = func.__name__
                elif hasattr(func, '__class__'):
                    func_name = '%s()' % func.__class__.__name__
                else:
                    func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))

                module = '{0}.{1}'.format(func.__module__, func_name)
                url_name = url_name or ''
                url = simplify_regex(regex)
                decorator = ', '.join(decorators)

                if format_style == 'json':
                    views.append({
                        "url": url,
                        "module": module,
                        "name": url_name,
                        "decorators": decorator
                    })
                else:
                    views.append(
                        fmtr.format(
                            module='{0}.{1}'.format(
                                style.MODULE(func.__module__),
                                style.MODULE_NAME(func_name)),
                            url_name=style.URL_NAME(url_name),
                            url=style.URL(url),
                            decorator=decorator,
                        ))

        if not options.get('unsorted', False) and format_style != 'json':
            views = sorted(views)

        if format_style == 'aligned':
            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            views = [
                '   '.join('{0:<{1}}'.format(cdata, width)
                           for width, cdata in zip(widths, row))
                for row in views
            ]
        elif format_style == 'table':
            # Reformat all data and show in a table format

            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            table_views = []

            header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'),
                      style.MODULE_NAME('Name'),
                      style.MODULE_NAME('Decorator'))
            table_views.append(' | '.join(
                '{0:<{1}}'.format(title, width)
                for width, title in zip(widths, header)))
            table_views.append('-+-'.join('-' * width for width in widths))

            for row in views:
                table_views.append(' | '.join(
                    '{0:<{1}}'.format(cdata, width)
                    for width, cdata in zip(widths, row)))

            # Replace original views so we can return the same object
            views = table_views

        elif format_style == 'json':
            if pretty_json:
                return json.dumps(views, indent=4)
            return json.dumps(views)

        return "\n".join([v for v in views]) + "\n"
Beispiel #2
0
    def handle(self, *args, **options):
        style = no_style() if options['no_color'] else color_style()

        language = options['language']
        if language is not None:
            translation.activate(language)
            self.LANGUAGES = [
                (code, name)
                for code, name in getattr(settings, 'LANGUAGES', [])
                if code == language
            ]
        else:
            self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), ))

        decorator = options['decorator']
        if not decorator:
            decorator = ['login_required']

        host = options['base']
        mock_pk = options['mock_pk']

        format_style = options['format_style']
        if format_style not in FMTR:
            raise CommandError(
                "Format style '%s' does not exist. Options: %s" % (
                    format_style,
                    ", ".join(sorted(FMTR.keys())),
                ))
        pretty_json = format_style == 'pretty-json'
        if pretty_json:
            format_style = 'json'
        fmtr = FMTR[format_style]

        urlconf = options['urlconf']

        views = []
        if not hasattr(settings, urlconf):
            raise CommandError(
                "Settings module {} does not have the attribute {}.".format(
                    settings, urlconf))

        try:
            urlconf = __import__(getattr(settings, urlconf), {}, {}, [''])
        except Exception as e:
            if options['traceback']:
                import traceback
                traceback.print_exc()
            raise CommandError("Error occurred while trying to load %s: %s" %
                               (getattr(settings, urlconf), str(e)))

        view_functions = self.extract_views_from_urlpatterns(
            urlconf.urlpatterns)
        coverage = len(view_functions)
        for (func, regex, url_name) in view_functions:
            if hasattr(func, '__globals__'):
                func_globals = func.__globals__
            elif hasattr(func, 'func_globals'):
                func_globals = func.func_globals
            else:
                func_globals = {}

            decorators = [d for d in decorator if d in func_globals]

            try:
                p = re.compile(r'<.*?>|\(.*?\)|\[.*?\]')
                url = p.sub(str(mock_pk), regex).replace('^', '').replace(
                    '\\', '').replace('$', '')  #mock pk 1
                conn = urllib.request.urlopen(host + url)
                response = conn.getcode()
                conn.close()
            except urllib.error.HTTPError as e:
                response = str(e.code)
                coverage -= 1
            except urllib.error.URLError as e:
                response = e.reason
                coverage -= 1
            except Exception as e:
                print(url, e)
                coverage -= 1
                response = e

            if isinstance(func, functools.partial):
                func = func.func
                decorators.insert(0, 'functools.partial')

            if hasattr(func, '__name__'):
                func_name = func.__name__
            elif hasattr(func, '__class__'):
                func_name = '%s()' % func.__class__.__name__
            else:
                func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))

            module = '{0}.{1}'.format(func.__module__, func_name)
            url_name = url_name or ''
            url = simplify_regex(regex)
            decorator = ', '.join(decorators)
            code = response

            if format_style == 'json':
                views.append({
                    "url": url,
                    "module": module,
                    "name": url_name,
                    "decorators": decorator,
                    "code": code
                })
            else:
                views.append(
                    fmtr.format(module='{0}.{1}'.format(
                        style.MODULE(func.__module__),
                        style.MODULE_NAME(func_name)),
                                url_name=style.URL_NAME(url_name),
                                url=style.URL(url),
                                decorator=decorator,
                                code=code).strip())

        if not options['unsorted'] and format_style != 'json':
            views = sorted(views)

        if format_style == 'aligned':
            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            views = [
                '   '.join('{0:<{1}}'.format(cdata, width)
                           for width, cdata in zip(widths, row))
                for row in views
            ]
        elif format_style == 'table':
            # Reformat all data and show in a table format

            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            table_views = []

            header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'),
                      style.MODULE_NAME('Name'),
                      style.MODULE_NAME('Decorator'))
            table_views.append(' | '.join(
                '{0:<{1}}'.format(title, width)
                for width, title in zip(widths, header)))
            table_views.append('-+-'.join('-' * width for width in widths))

            for row in views:
                table_views.append(' | '.join(
                    '{0:<{1}}'.format(cdata, width)
                    for width, cdata in zip(widths, row)))

            # Replace original views so we can return the same object
            views = table_views

        elif format_style == 'json':
            if pretty_json:
                return json.dumps(views, indent=4)
            return json.dumps(views)

        return "\n".join([v for v in views
                          ]) + "\n coverage: " + str(coverage) + " / " + str(
                              len(view_functions)) + "\n"
 def test_no_style(self):
     with force_color_support:
         style = color.no_style().MODULE_NAME
         text = 'csv'
         styled_text = style(text)
         self.assertEqual(text, styled_text)
Beispiel #4
0
    def handle(self, *args, **options):
        if args:
            appname, = args

        if options['no_color']:
            style = no_style()
        else:
            style = color_style()

        if getattr(settings, 'ADMIN_FOR', None):
            settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR]
        else:
            settings_modules = [settings]

        self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), ))

        language = options['language']
        if language is not None:
            translation.activate(language)
            self.LANGUAGES = [(code, name) for code, name in self.LANGUAGES if code == language]

        decorator = options['decorator']
        if not decorator:
            decorator = ['login_required']

        format_style = options['format_style']
        if format_style not in FMTR:
            raise CommandError("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys()))
        pretty_json = format_style == 'pretty-json'
        if pretty_json:
            format_style = 'json'
        fmtr = FMTR[format_style]

        urlconf = options['urlconf']

        views = []
        for settings_mod in settings_modules:
            if not hasattr(settings_mod, urlconf):
                raise CommandError("Settings module {} does not have the attribute {}.".format(settings_mod, urlconf))

            try:
                urlconf = __import__(getattr(settings_mod, urlconf), {}, {}, [''])
            except Exception as e:
                if options['traceback']:
                    import traceback
                    traceback.print_exc()
                print(style.ERROR("Error occurred while trying to load %s: %s" % (getattr(settings_mod, urlconf), str(e))))
                continue

            view_functions = self.extract_views_from_urlpatterns(urlconf.urlpatterns)
            for (func, regex, url_name) in view_functions:
                if hasattr(func, '__globals__'):
                    func_globals = func.__globals__
                elif hasattr(func, 'func_globals'):
                    func_globals = func.func_globals
                else:
                    func_globals = {}

                decorators = [d for d in decorator if d in func_globals]

                if isinstance(func, functools.partial):
                    func = func.func
                    decorators.insert(0, 'functools.partial')

                if hasattr(func, '__name__'):
                    func_name = func.__name__
                elif hasattr(func, '__class__'):
                    func_name = '%s()' % func.__class__.__name__
                else:
                    func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))

                module = '{0}.{1}'.format(func.__module__, func_name)
                url_name = url_name or ''
                url = simplify_regex(regex)
                decorator = ', '.join(decorators)

                if format_style == 'json':
                    views.append({"url": url, "module": module, "name": url_name, "decorators": decorator})
                else:
                    views.append(fmtr.format(
                        module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)),
                        url_name=style.URL_NAME(url_name),
                        url=style.URL(url),
                        decorator=decorator,
                    ).strip())

        if not options['unsorted'] and format_style != 'json':
            views = sorted(views)

        if format_style == 'aligned':
            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            views = [
                '   '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row))
                for row in views
            ]
        elif format_style == 'table':
            # Reformat all data and show in a table format

            views = [row.split(',', 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            table_views = []

            header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator'))
            table_views.append(
                ' | '.join('{0:<{1}}'.format(title, width) for width, title in zip(widths, header))
            )
            table_views.append('-+-'.join('-' * width for width in widths))

            for row in views:
                table_views.append(
                    ' | '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row))
                )

            # Replace original views so we can return the same object
            views = table_views

        elif format_style == 'json':
            if pretty_json:
                return json.dumps(views, indent=4)
            return json.dumps(views)

        return "\n".join([v for v in views]) + "\n"
Beispiel #5
0
    def handle(self, *args, **options):
        style = no_style() if options["no_color"] else color_style()

        language = options["language"]
        if language is not None:
            translation.activate(language)
            self.LANGUAGES = [
                (code, name)
                for code, name in getattr(settings, "LANGUAGES", [])
                if code == language
            ]
        else:
            self.LANGUAGES = getattr(settings, "LANGUAGES", ((None, None),))

        decorator = options["decorator"]
        if not decorator:
            decorator = ["login_required"]

        format_style = options["format_style"]
        if format_style not in FMTR:
            raise CommandError(
                "Format style '%s' does not exist. Options: %s"
                % (format_style, ", ".join(sorted(FMTR.keys())),)
            )
        pretty_json = format_style == "pretty-json"
        if pretty_json:
            format_style = "json"
        fmtr = FMTR[format_style]

        urlconf = options["urlconf"]

        views = []
        if not hasattr(settings, urlconf):
            raise CommandError(
                "Settings module {} does not have the attribute {}.".format(
                    settings, urlconf
                )
            )

        try:
            urlconf = __import__(getattr(settings, urlconf), {}, {}, [""])
        except Exception as e:
            if options["traceback"]:
                import traceback

                traceback.print_exc()
            raise CommandError(
                "Error occurred while trying to load %s: %s"
                % (getattr(settings, urlconf), str(e))
            )

        view_functions = self.extract_views_from_urlpatterns(urlconf.urlpatterns)
        for (func, regex, url_name) in view_functions:
            if hasattr(func, "__globals__"):
                func_globals = func.__globals__
            elif hasattr(func, "func_globals"):
                func_globals = func.func_globals
            else:
                func_globals = {}

            decorators = [d for d in decorator if d in func_globals]

            if isinstance(func, functools.partial):
                func = func.func
                decorators.insert(0, "functools.partial")

            if hasattr(func, "__name__"):
                func_name = func.__name__
            elif hasattr(func, "__class__"):
                func_name = "%s()" % func.__class__.__name__
            else:
                func_name = re.sub(r" at 0x[0-9a-f]+", "", repr(func))

            module = "{0}.{1}".format(func.__module__, func_name)
            url_name = url_name or ""
            url = simplify_regex(regex)
            decorator = ", ".join(decorators)

            if format_style == "json":
                views.append(
                    {
                        "url": url,
                        "module": module,
                        "name": url_name,
                        "decorators": decorator,
                    }
                )
            else:
                views.append(
                    fmtr.format(
                        module="{0}.{1}".format(
                            style.MODULE(func.__module__), style.MODULE_NAME(func_name)
                        ),
                        url_name=style.URL_NAME(url_name),
                        url=style.URL(url),
                        decorator=decorator,
                    ).strip()
                )

        if not options["unsorted"] and format_style != "json":
            views = sorted(views)

        if format_style == "aligned":
            views = [row.split(",", 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            views = [
                "   ".join(
                    "{0:<{1}}".format(cdata, width) for width, cdata in zip(widths, row)
                )
                for row in views
            ]
        elif format_style == "table":
            # Reformat all data and show in a table format

            views = [row.split(",", 3) for row in views]
            widths = [len(max(columns, key=len)) for columns in zip(*views)]
            table_views = []

            header = (
                style.MODULE_NAME("URL"),
                style.MODULE_NAME("Module"),
                style.MODULE_NAME("Name"),
                style.MODULE_NAME("Decorator"),
            )
            table_views.append(
                " | ".join(
                    "{0:<{1}}".format(title, width)
                    for width, title in zip(widths, header)
                )
            )
            table_views.append("-+-".join("-" * width for width in widths))

            for row in views:
                table_views.append(
                    " | ".join(
                        "{0:<{1}}".format(cdata, width)
                        for width, cdata in zip(widths, row)
                    )
                )

            # Replace original views so we can return the same object
            views = table_views

        elif format_style == "json":
            if pretty_json:
                return json.dumps(views, indent=4)
            return json.dumps(views)

        return "\n".join([v for v in views if settings.ADMIN_URL not in v]) + "\n"