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