xref: /aosp_15_r20/external/toolchain-utils/llvm_tools/test_helpers.py (revision 760c253c1ed00ce9abd48f8546f08516e57485fe)
1# Copyright 2019 The ChromiumOS Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Helper functions for unit testing."""
6
7import contextlib
8import json
9import os
10import tempfile
11
12
13class ArgsOutputTest:
14    """Testing class to simulate a argument parser object."""
15
16    def __init__(self, svn_option="google3"):
17        self.chromeos_path = "/abs/path/to/chroot"
18        self.last_tested = "/abs/path/to/last_tested_file.json"
19        self.llvm_version = svn_option
20        self.extra_change_lists = None
21        self.options = ["latest-toolchain"]
22        self.builders = ["some-builder"]
23
24
25# FIXME: Migrate modules with similar helper to use this module.
26def CallCountsToMockFunctions(mock_function):
27    """A decorator that passes a call count to the function it decorates.
28
29    Examples:
30        @CallCountsToMockFunctions
31        def foo(call_count):
32            return call_count
33        ...
34        ...
35        [foo(), foo(), foo()]
36        [0, 1, 2]
37    """
38
39    counter = [0]
40
41    def Result(*args, **kwargs):
42        # For some values of `counter`, the mock function would simulate
43        # raising an exception, so let the test case catch the exception via
44        # `unittest.TestCase.assertRaises()` and to also handle recursive
45        # functions.
46        prev_counter = counter[0]
47        counter[0] += 1
48
49        ret_value = mock_function(prev_counter, *args, **kwargs)
50
51        return ret_value
52
53    return Result
54
55
56def WritePrettyJsonFile(file_name, json_object):
57    """Writes the contents of the file to the json object.
58
59    Args:
60        file_name: The file that has contents to be used for the json object.
61        json_object: The json object to write to.
62    """
63
64    json.dump(file_name, json_object, indent=4, separators=(",", ": "))
65
66
67def CreateTemporaryJsonFile():
68    """Makes a temporary .json file."""
69
70    return CreateTemporaryFile(suffix=".json")
71
72
73@contextlib.contextmanager
74def CreateTemporaryFile(suffix=""):
75    """Makes a temporary file."""
76
77    fd, temp_file_path = tempfile.mkstemp(suffix=suffix)
78
79    os.close(fd)
80
81    try:
82        yield temp_file_path
83
84    finally:
85        if os.path.isfile(temp_file_path):
86            os.remove(temp_file_path)
87