xref: /aosp_15_r20/tools/asuite/aidegen/aidegen_run_unittests.py (revision c2e18aaa1096c836b086f94603d04f4eb9cf37f5)
1#!/usr/bin/env python3
2#
3# Copyright 2019 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""Main entrypoint for all of aidegen's unittest."""
17
18import logging
19import os
20import sys
21import unittest
22from importlib import import_module
23
24# Setup logging to be silent so unittests can pass through TF.
25logging.disable(logging.ERROR)
26
27
28def get_test_modules():
29    """Returns a list of testable modules.
30
31    Finds all the test files (*_unittest.py) and gets their relative
32    paths (internal/lib/utils_test.py) and translate it to an import path and
33    strip the py ext (internal.lib.utils_test).
34
35    Returns:
36        List of strings (the testable module import path).
37    """
38    testable_modules = []
39    package = os.path.dirname(os.path.realpath(__file__))
40    base_path = os.path.dirname(package)
41
42    for dirpath, _, files in os.walk(package):
43        for _file in files:
44            if _file.endswith("_unittest.py"):
45                # Now transform it into a relative import path.
46                full_file_path = os.path.join(dirpath, _file)
47                rel_file_path = os.path.relpath(full_file_path, base_path)
48                rel_file_path, _ = os.path.splitext(rel_file_path)
49                rel_file_path = rel_file_path.replace(os.sep, ".")
50                testable_modules.append(rel_file_path)
51
52    return testable_modules
53
54
55def main():
56    """Main unittest entry."""
57    test_modules = get_test_modules()
58    for mod in test_modules:
59        import_module(mod)
60
61    loader = unittest.defaultTestLoader
62    test_suite = loader.loadTestsFromNames(test_modules)
63    runner = unittest.TextTestRunner(verbosity=2)
64    result = runner.run(test_suite)
65    sys.exit(not result.wasSuccessful())
66
67
68if __name__ == '__main__':
69    main()
70