C-Dash: Add search in tests
[csit.git] / csit.infra.dash / app / cdash / stats / graphs.py
1 # Copyright (c) 2024 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """
15 """
16
17 import plotly.graph_objects as go
18 import pandas as pd
19
20 from ..utils.constants import Constants as C
21
22
23 def select_data(data: pd.DataFrame, itm: str) -> pd.DataFrame:
24     """Select the data for graphs from the provided data frame.
25
26     :param data: Data frame with data for graphs.
27     :param itm: Item (in this case job name) which data will be selected from
28         the input data frame.
29     :type data: pandas.DataFrame
30     :type itm: str
31     :returns: A data frame with selected data.
32     :rtype: pandas.DataFrame
33     """
34
35     df = data.loc[(data["job"] == itm)].sort_values(
36         by="start_time", ignore_index=True)
37     df = df.dropna(subset=["duration", ])
38
39     return df
40
41
42 def graph_statistics(df: pd.DataFrame, job: str, layout: dict) -> tuple:
43     """Generate graphs:
44     1. Passed / failed tests,
45     2. Job durations
46     with additional information shown in hover.
47
48     :param df: Data frame with input data.
49     :param job: The name of job which data will be presented in the graphs.
50     :param layout: Layout of plot.ly graph.
51     :type df: pandas.DataFrame
52     :type job: str
53     :type layout: dict
54     :returns: Tuple with two generated graphs (pased/failed tests and job
55         duration).
56     :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
57     """
58
59     data = select_data(df, job)
60     if data.empty:
61         return None, None
62
63     hover = list()
64     for _, row in data.iterrows():
65         hover_itm = (
66             f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
67             f"duration: "
68             f"{(int(row['duration']) // 3600):02d}:"
69             f"{((int(row['duration']) % 3600) // 60):02d}<br>"
70             f"passed: {row['passed']}<br>"
71             f"failed: {row['failed']}<br>"
72             f"{row['dut_type']}-ref: {row['dut_version']}<br>"
73             f"csit-ref: {row['job']}/{row['build']}<br>"
74             f"hosts: {', '.join(row['hosts'])}"
75         )
76         hover.append(hover_itm)
77
78     # Job durations:
79     fig_duration = go.Figure(
80         data=go.Scatter(
81             x=data["start_time"],
82             y=data["duration"],
83             name="Duration",
84             text=hover,
85             hoverinfo="text"
86         )
87     )
88
89     tickvals = [0, ]
90     step = max(data["duration"]) / 5
91     for i in range(5):
92         tickvals.append(int(step * (i + 1)))
93     layout_duration = layout.get("plot-stats-duration", dict())
94     if layout_duration:
95         layout_duration["yaxis"]["tickvals"] = tickvals
96         layout_duration["yaxis"]["ticktext"] = [
97             f"{(val // 3600):02d}:{((val % 3600) // 60):02d}" \
98                 for val in tickvals
99         ]
100         fig_duration.update_layout(layout_duration)
101
102     # Passed / failed:
103     bar_width = C.STATS_BAR_WIDTH_WEEKLY \
104         if "weekly" in job else C.STATS_BAR_WIDTH_DAILY
105     fig_passed = go.Figure(
106         data=[
107             go.Bar(
108                 x=data["start_time"],
109                 y=data["passed"],
110                 name="Passed",
111                 hovertext=hover,
112                 hoverinfo="text",
113                 width=bar_width
114             ),
115             go.Bar(
116                 x=data["start_time"],
117                 y=data["failed"],
118                 name="Failed",
119                 hovertext=hover,
120                 hoverinfo="text",
121                 width=bar_width
122             )
123         ]
124     )
125     layout_pf = layout.get("plot-stats-passed", dict())
126     if layout_pf:
127         fig_passed.update_layout(layout_pf)
128
129     return fig_passed, fig_duration