1# Copyright 2019, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Classes for bug events history."""
16
17# pylint: disable=line-too-long
18
19import datetime
20import logging
21import json
22import os
23
24import constants
25
26from metrics import metrics_utils
27
28_META_FILE = os.path.join(os.path.expanduser('~'),
29                          '.config', 'asuite', 'atest_history.json')
30_DETECT_OPTION_FILTER = ['-v', '--verbose']
31_DETECTED_SUCCESS = 1
32_DETECTED_FAIL = 0
33# constants of history key
34_LATEST_EXIT_CODE = 'latest_exit_code'
35_UPDATED_AT = 'updated_at'
36
37class BugDetector:
38    """Class for handling if a bug is detected by comparing test history."""
39
40    def __init__(self, argv, exit_code, history_file=None):
41        """BugDetector constructor
42
43        Args:
44            argv: A list of arguments.
45            exit_code: An integer of exit code.
46            history_file: A string of a given history file path.
47        """
48        self.detect_key = self.get_detect_key(argv)
49        self.exit_code = exit_code
50        self.file = history_file if history_file else _META_FILE
51        self.history = self.get_history()
52        self.caught_result = self.detect_bug_caught()
53        self.update_history()
54
55    def get_detect_key(self, argv):
56        """Get the key for history searching.
57
58        1. remove '-v' in argv to argv_no_verbose
59        2. sort the argv_no_verbose
60
61        Args:
62            argv: A list of arguments.
63
64        Returns:
65            A string of ordered command line.
66        """
67        argv_without_option = [x for x in argv if x not in _DETECT_OPTION_FILTER]
68        argv_without_option.sort()
69        return ' '.join(argv_without_option)
70
71    def get_history(self):
72        """Get a history object from a history file.
73
74        e.g.
75        {
76            "SystemUITests:.ScrimControllerTest":{
77                "latest_exit_code": 5, "updated_at": "2019-01-26T15:33:08.305026"},
78            "--host hello_world_test ":{
79                "latest_exit_code": 0, "updated_at": "2019-02-26T15:33:08.305026"},
80        }
81
82        Returns:
83            An object of loading from a history.
84        """
85        history = {}
86        if os.path.exists(self.file):
87            with open(self.file) as json_file:
88                try:
89                    history = json.load(json_file)
90                except ValueError as e:
91                    logging.debug(e)
92                    metrics_utils.handle_exc_and_send_exit_event(
93                        constants.ACCESS_HISTORY_FAILURE)
94        return history
95
96    def detect_bug_caught(self):
97        """Detection of catching bugs.
98
99        When latest_exit_code and current exit_code are different, treat it
100        as a bug caught.
101
102        Returns:
103            A integer of detecting result, e.g.
104            1: success
105            0: fail
106        """
107        if not self.history:
108            return _DETECTED_FAIL
109        latest = self.history.get(self.detect_key, {})
110        if latest.get(_LATEST_EXIT_CODE, self.exit_code) == self.exit_code:
111            return _DETECTED_FAIL
112        return _DETECTED_SUCCESS
113
114    def update_history(self):
115        """Update the history file.
116
117        1. update latest_bug result to history cache.
118        2. trim history cache to size from oldest updated time.
119        3. write to the file.
120        """
121        latest_bug = {
122            self.detect_key: {
123                _LATEST_EXIT_CODE: self.exit_code,
124                _UPDATED_AT: datetime.datetime.now().isoformat()
125            }
126        }
127        self.history.update(latest_bug)
128        num_history = len(self.history)
129        if num_history > constants.UPPER_LIMIT:
130            sorted_history = sorted(self.history.items(),
131                                    key=lambda kv: kv[1][_UPDATED_AT])
132            self.history = dict(
133                sorted_history[(num_history - constants.TRIM_TO_SIZE):])
134        with open(self.file, 'w') as outfile:
135            try:
136                json.dump(self.history, outfile, indent=0)
137            except ValueError as e:
138                logging.debug(e)
139                metrics_utils.handle_exc_and_send_exit_event(
140                    constants.ACCESS_HISTORY_FAILURE)
141