1#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5from django.core.management.base import BaseCommand
6from django.test.client import Client
7import os, sys, re
8import requests
9from django.conf import settings
10
11# pylint: disable=E1103
12# Instance of 'WSGIRequest' has no 'status_code' member
13# (but some types could not be inferred) (maybe-no-member)
14
15
16class Command(BaseCommand):
17    help    = "Test the response time for all toaster urls"
18
19    def handle(self, *args, **options):
20        root_urlconf = __import__(settings.ROOT_URLCONF)
21        patterns = root_urlconf.urls.urlpatterns
22        global full_url
23        for pat in patterns:
24            if pat.__class__.__name__ == 'RegexURLResolver':
25                url_root_res = str(pat).split('^')[1].replace('>', '')
26            if 'gui' in url_root_res:
27                for url_patt in pat.url_patterns:
28                    full_url = self.get_full_url(url_patt, url_root_res)
29                    info = self.url_info(full_url)
30                    status_code = info[0]
31                    load_time = info[1]
32                    print('Trying \'' + full_url + '\', ' + str(status_code) + ', ' + str(load_time))
33
34    def get_full_url(self, url_patt, url_root_res):
35        full_url = str(url_patt).split('^')[1].replace('$>', '').replace('(?P<file_path>(?:/[', '/bin/busybox').replace('.*', '')
36        full_url = str(url_root_res + full_url)
37        full_url = re.sub('\(\?P<.*?>\\\d\+\)', '1', full_url)
38        full_url = 'http://localhost:8000/' + full_url
39        return full_url
40
41    def url_info(self, full_url):
42        client = Client()
43        info = []
44        try:
45            resp = client.get(full_url, follow = True)
46        except Exception as e_status_code:
47            self.error('Url: %s, error: %s' % (full_url, e_status_code))
48            resp = type('object', (), {'status_code':0, 'content': str(e_status_code)})
49        status_code = resp.status_code
50        info.append(status_code)
51        try:
52            req = requests.get(full_url)
53        except Exception as e_load_time:
54            self.error('Url: %s, error: %s' % (full_url, e_load_time))
55        load_time = req.elapsed
56        info.append(load_time)
57        return info
58
59    def error(self, *args):
60        for arg in args:
61            print(arg, end=' ', file=sys.stderr)
62        print(file=sys.stderr)
63