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