1#!/usr/bin/env python3
2# coding=utf-8
3
4#
5# Copyright (c) 2022 Huawei Device Co., Ltd.
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19
20from datetime import datetime
21from inspect import stack
22import json
23import os
24import time
25from xdevice import get_cst_time
26
27
28class TS():
29    '''
30    performace test class
31    '''
32    inner_stack = stack()
33    total = 0
34    times = 0
35
36    @staticmethod
37    def start():
38        try:
39            TS.inner_stack.append(time.time())
40        except Exception:
41            from devicetest.log.logger import DeviceTestLog as log
42            log.error("start TS exception.", is_traceback=True)
43
44    @staticmethod
45    def average(prefix=''):
46        if TS.times == 0:
47            TS.times = 1
48        return ("%s ==> average: %.3f ms" % (prefix, TS.total / TS.times))
49
50    @staticmethod
51    def stop(prefix=''):
52        try:
53            if len(TS.inner_stack) > 0:
54                cur_time = (time.time() - TS.inner_stack.pop()) * 1000
55                TS.total += cur_time
56                TS.times += 1
57                return cur_time
58            return None
59        except Exception:
60            from devicetest.log.logger import DeviceTestLog as log
61            log.error("stop TS exception.", is_traceback=True)
62            return None
63
64
65class TimeHandler:
66
67    @classmethod
68    def get_formated_datetime(cls, time_value=None):
69        """
70        get formated datetime that only contains year month day hour minute
71        and second information
72
73        Obtains the datetime object, which contains only the year, month,
74        day, hour, minute, and second information.
75        Args:
76            time_value: Time to be processed. If the time does not exist,
77                        the current time is used.
78        Returns:
79            Datetime object that has been processed. The object can be
80            converted to a character string, The value is in the format of
81            2011-12-15 16:08:35.
82        """
83        if time_value is None:
84            time_value = time.time()
85        return datetime(*(time.localtime(time_value)[:6]))
86
87    @classmethod
88    def get_formated_datetime_name(cls, time_val=None):
89        """
90        get formated datetime used to generate a file that only contains
91        year month day hour minute and second information
92
93        Obtains the current character string that contains only time
94        information and underscores.
95        Args:
96            time_val: Time to be processed. If the time does not exist,
97                        the current time is used.
98        Returns:
99            The value is a character string in the format of
100            2011_12_15_16_08_35
101        """
102        result_list = []
103        for _str in cls.get_formated_datetime(time_val).timetuple()[:6]:
104            result_list.append(str("%02d" % _str))
105        return "_".join(result_list)
106
107    @classmethod
108    def convert_formated_name(cls, convert_time,
109                              formate="%Y-%m-%d %H:%M:%S.%f"):
110        """
111        Args:
112            convert_time: Time value to be processed
113        Returns: 1460907045 Format
114        """
115        strpt_time = time.strptime(convert_time, formate)
116        return int(time.mktime(strpt_time))
117
118    @classmethod
119    def get_now_datetime(cls, time_format="%Y%m%d%H%M%S%f"):
120        """
121        Args:
122            time_format: Obtain the time format, for example,
123                        f="%Y-%m-%d %H:%M:%S.%f",
124            The time in 2017-04-25 11:26:33.293963 format is returned.
125        Returns: String
126        """
127        return get_cst_time().strftime(time_format)
128
129    @classmethod
130    def get_timeout_value(cls):
131        project_path = \
132            os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
133        config = os.path.join(project_path, "project.config")
134        with open(config, 'r', encoding='utf-8') as f_time:
135            conf = json.load(f_time)
136            get_case_time = conf.get("caseTimeOut", 60 * 60 * 1)
137            return get_case_time
138
139    @classmethod
140    def get_formated_time(cls, time_format='%Y-%m-%d %H:%M:%S'):
141        """
142        get current time, for example: 2020-08-04 15:48:04
143        :param time_format: time format
144        :return: current time
145        """
146        return get_cst_time().strftime(time_format)
147
148    @classmethod
149    def get_interval_timestamp(cls, start_format_time, end_format_time,
150                               time_format='%Y-%m-%d %H:%M:%S'):
151        try:
152            start_timestamp = datetime.strptime(
153                start_format_time, time_format).timestamp()
154            end_timestamp = datetime.strptime(
155                end_format_time, time_format).timestamp()
156            interval_timestamp = round(end_timestamp - start_timestamp, 3)
157            return interval_timestamp
158        except Exception:
159            return 0.00
160
161    @staticmethod
162    def get_current_epoch_time():
163        """Current epoch time in milliseconds.
164        Returns:
165            An integer representing the current epoch time in milliseconds.
166        """
167        return int(round(time.time() * 1000))
168
169    @staticmethod
170    def get_current_human_time():
171        """Returns the current time in human readable format.
172        Returns:
173            The current time stamp in Month-Day-Year Hour:Min:Sec format.
174        """
175        return time.strftime("%m-%d-%Y %H:%M:%S ")