get_result_by_report_file()   F
last analyzed

Complexity

Conditions 18

Size

Total Lines 78
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 49
dl 0
loc 78
rs 1.2
c 0
b 0
f 0
cc 18
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like lighthouse_garden.lighthouse.interpreter.get_result_by_report_file() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/env python3
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# -*- coding: future_fstrings -*-
3
4
import datetime
5
import json
6
import os
7
import sys
8
from collections import defaultdict
9
10
from lighthouse_garden.utility import output
11
from lighthouse_garden.lighthouse import utility, database
12
13
14
def get_result_by_report_file(target, file_name):
15
    """
16
    Generate the result by a given lighthouse report file
17
    :param target: Dict
18
    :param file_name: String
19
    :return:
20
    """
21
    output.println(f'{output.Subject.INFO} Processing result of report', verbose_only=True)
22
    _report_path = f'{utility.get_data_dir()}{file_name}.report.json'
23
    _report = None
24
25
    if os.path.isfile(_report_path):
26
        with open(_report_path, 'r') as read_file:
27
            _report = json.load(read_file)
28
    else:
29
        sys.exit(f'{output.Subject.ERROR} Report file not found: {_report_path}')
30
31
    if not isinstance(_report, dict):
32
        sys.exit(f'{output.Subject.ERROR} Report not readable')
33
34
    if _report['categories']['performance']['score']:
35
        _performance = int(round(_report['categories']['performance']['score'] * 100))
36
    else:
37
        output.println(f'{output.Subject.ERROR} Missing performance score', verbose_only=True)
38
        return None
39
40
    _result = defaultdict(lambda: defaultdict(dict))
41
    _result = {
42
        'title': target['title'],
43
        'url': target['url'],
44
        'performance': _performance,
45
        'report': f'{utility.get_data_dir(absolute_path=False)}{file_name}.report.html',
46
        'link': f'#{target["identifier"]}',
47
        'date': '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
48
    }
49
50
    # additional metrics
51
    if 'accessibility' in _report['categories'] and _report['categories']['accessibility']['score']:
52
        _result['accessibility'] = int(round(_report['categories']['accessibility']['score'] * 100))
53
54
    if 'best-practices' in _report['categories'] and _report['categories']['best-practices']['score']:
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (102/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
55
        _result['best-practices'] = int(round(_report['categories']['best-practices']['score'] * 100))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (102/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
56
57
    if 'seo' in _report['categories'] and _report['categories']['seo']['score']:
58
        _result['seo'] = int(round(_report['categories']['seo']['score'] * 100))
59
60
    database.add_value_to_history(target, _result)
61
62
    # audits
63
    _result['audits'] = {}
64
    if _report['audits']['first-contentful-paint']:
65
        _result['audits']['first-contentful-paint'] = _report['audits']['first-contentful-paint']['displayValue']
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (113/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
66
67
    if _report['audits']['largest-contentful-paint']:
68
        _result['audits']['largest-contentful-paint'] = _report['audits']['largest-contentful-paint'][
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (102/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
69
            'displayValue']
70
71
    if _report['audits']['speed-index']:
72
        _result['audits']['speed-index'] = _report['audits']['speed-index']['displayValue']
73
74
    if _report['audits']['total-blocking-time']:
75
        _result['audits']['total-blocking-time'] = _report['audits']['total-blocking-time']['displayValue']
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (107/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
76
77
    if _report['audits']['interactive']:
78
        _result['audits']['interactive'] = _report['audits']['interactive']['displayValue']
79
80
    if _report['audits']['cumulative-layout-shift']:
81
        _result['audits']['cumulative-layout-shift'] = _report['audits']['cumulative-layout-shift']['displayValue']
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (115/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
82
83
    # average
84
    _result['average'] = {
85
        'value': database.get_average_by_attribute(target, 'performance'),
86
        'min': database.get_average_peak(target, 'performance', True),
87
        'max': database.get_average_peak(target, 'performance', False),
88
        'trend': get_trend(target, 'performance')
89
    }
90
91
    return _result
92
93
94
def get_trend(target, attribute):
95
    """
96
    Calculates a performance trend in dependence of the last performance measurement to the average value
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (105/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
97
    :param target: Dict
98
    :param attribute: String
99
    :return:
100
    """
101
    _average = database.get_average_by_attribute(target, attribute)
102
    _value = database.get_last_value(target, attribute)
103
104
    _indicator = (10.0 * _average) / 100.0
105
106
    if (_average - _indicator) > _value:
107
        return -1
108
109
    if (_average + _indicator) < _value:
110
        return 1
111
112
    return 0
113
0 ignored issues
show
coding-style introduced by
Trailing newlines
Loading history...
114