Passed
Push — master ( 9fde6d...7c51a9 )
by Alexander
02:59
created

tcms.core.views   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 132
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 74
dl 0
loc 132
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A navigation() 0 5 1
A server_error() 0 8 1
A dashboard() 0 32 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
B TranslationMode.get_browser_language() 0 35 6
A TranslationMode.get() 0 21 1
1
# -*- coding: utf-8 -*-
2
from django import http
3
from django.views import i18n
4
from django.conf import settings
5
from django.template import loader
6
from django.shortcuts import render
7
from django.db.models import Count, Q
8
from django.utils import translation
9
from django.utils.translation import trans_real
10
from django.views.generic.base import View
11
from django.views.decorators.http import require_GET
12
from django.contrib.auth.decorators import login_required
13
from django.views.decorators.csrf import requires_csrf_token
14
15
from tcms.testplans.models import TestPlan
16
from tcms.testruns.models import TestRun
17
18
19
@require_GET
20
@login_required
21
def dashboard(request):  # pylint: disable=missing-permission-required
22
    """List all recent TestPlans and TestRuns"""
23
    test_plans = TestPlan.objects.filter(
24
        author=request.user
25
    ).order_by(
26
        '-plan_id'
27
    ).select_related(
28
        'product', 'type'
29
    ).annotate(
30
        num_runs=Count('run', distinct=True)
31
    )
32
    test_plans_disable_count = test_plans.filter(is_active=False).count()
33
34
    test_runs = TestRun.objects.filter(
35
        Q(manager=request.user) |
36
        Q(default_tester=request.user) |
37
        Q(case_run__assignee=request.user),
38
        stop_date__isnull=True,
39
    ).order_by('-run_id').distinct()
40
41
    context_data = {
42
        'test_plans_count': test_plans.count(),
43
        'test_plans_disable_count': test_plans_disable_count,
44
        'last_15_test_plans': test_plans.filter(is_active=True)[:15],
45
46
        'last_15_test_runs': test_runs[:15],
47
48
        'test_runs_count': test_runs.count(),
49
    }
50
    return render(request, 'dashboard.html', context_data)
51
52
53
def navigation(request):  # pylint: disable=missing-permission-required
54
    """
55
    iframe navigation workaround until we migrate everything to patternfly
56
    """
57
    return render(request, 'navigation.html')
58
59
60
@requires_csrf_token
61
def server_error(request):  # pylint: disable=missing-permission-required
62
    """
63
        Render the error page with request object which supports
64
        static URLs so we can load a nice picture.
65
    """
66
    template = loader.get_template('500.html')
67
    return http.HttpResponseServerError(template.render({}, request))
68
69
70
class TranslationMode(View):  # pylint: disable=missing-permission-required
71
    """
72
        Turns on and off translation mode by switching language to
73
        Esperanto!
74
    """
75
    @staticmethod
76
    def get_browser_language(request):
77
        """
78
            Returns *ONLY* the language that is sent by the browser via the
79
            Accept-Language headers. Defaults to ``settings.LANGUAGE_CODE`` if
80
            that doesn't work!
81
82
            This is the language we switch back to when translation mode is turned off.
83
84
            Copied from the bottom half of
85
            ``django.utils.translation.trans_real.get_language_from_request()``
86
87
            .. note::
88
89
                Using ``get_language_from_request()`` doesn't work for us because
90
                it first inspects session and cookies and we've already set Esperanto
91
                in both the session and the cookie!
92
        """
93
        accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
94
        for accept_lang, _unused in trans_real.parse_accept_lang_header(accept):
95
            if accept_lang == '*':
96
                break
97
98
            if not trans_real.language_code_re.search(accept_lang):
99
                continue
100
101
            try:
102
                return translation.get_supported_language_variant(accept_lang)
103
            except LookupError:
104
                continue
105
106
        try:
107
            return translation.get_supported_language_variant(settings.LANGUAGE_CODE)
108
        except LookupError:
109
            return settings.LANGUAGE_CODE
110
111
    def get(self, request):
112
        """
113
            In the HTML template we'd like to work with simple links
114
            however the view which actually switches the language needs
115
            to be called via POST so we simulate that here!
116
117
            If the URL doesn't explicitly specify language then we turn-off
118
            translation mode by switching back to browser preferred language.
119
        """
120
        browser_lang = self.get_browser_language(request)
121
        post_body = "%s=%s" % (i18n.LANGUAGE_QUERY_PARAMETER,
122
                               request.GET.get(i18n.LANGUAGE_QUERY_PARAMETER, browser_lang))
123
        request.META['REQUEST_METHOD'] = 'POST'
124
        request.META['CONTENT_LENGTH'] = len(post_body)
125
        request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
126
127
        post_request = request.__class__(request.META)
128
        # pylint: disable=protected-access
129
        post_request._post = http.QueryDict(post_body, encoding=post_request._encoding)
130
131
        return i18n.set_language(post_request)
132