1#  Copyright (C) 2023 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
15import os
16import logging
17from typing import Any, Dict
18
19# Keep consistent with
20# https://g3doc.corp.google.com/wireless/android/test_tools/crystalball/cbpp/README.md
21CB_FILENAME = 'test_results.txt'
22
23
24def export_to_crystalball(data: Dict[str, Any], output_dir: str, test_name: str) -> None:
25    """Writes data to a CrystalBall output file.
26
27    Repeated calls with the same output dir will append data to the same file.
28
29    :param data: input data
30    :param output_dir: directory of the output file
31    :param test_name: name used by CrystalBall to identify the set of metrics
32    :return: None
33    """
34    cb_path = os.path.join(output_dir, CB_FILENAME)
35    logging.debug(f'Exporting test metrics of {test_name} to CrystalBall at {cb_path}')
36    with open(cb_path, 'a') as f:
37        f.write(test_name + '\n\n')
38        f.writelines(['%s:%s\n' % (key, value) for key, value in data.items()])
39        f.write('\n\n')
40