1# Copyright 2024 gRPC authors. 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 15from typing import Sequence, Optional 16 17import unittest 18import sys 19import pkgutil 20 21 22class SingleLoader(object): 23 def __init__(self, pattern: str, unittest_path: str): 24 loader = unittest.TestLoader() 25 self.suite = unittest.TestSuite() 26 tests = [] 27 28 for importer, module_name, is_package in pkgutil.walk_packages([unittest_path]): 29 if pattern in module_name: 30 module = importer.find_module(module_name).load_module(module_name) 31 tests.append(loader.loadTestsFromModule(module)) 32 if len(tests) != 1: 33 raise AssertionError("Expected only 1 test module. Found {}".format(tests)) 34 self.suite.addTest(tests[0]) 35 36 def loadTestsFromNames(self, names: Sequence[str], module: Optional[str] = None) -> unittest.TestSuite: 37 return self.suite 38 39if __name__ == "__main__": 40 41 if len(sys.argv) != 3: 42 print(f"USAGE: {sys.argv[0]} TARGET_MODULE", file=sys.stderr) 43 sys.exit(1) 44 45 46 target_module = sys.argv[1] 47 unittest_path = sys.argv[2] 48 49 loader = SingleLoader(target_module, unittest_path) 50 runner = unittest.TextTestRunner(verbosity=0) 51 result = runner.run(loader.suite) 52 53 if not result.wasSuccessful(): 54 sys.exit("Test failure.")