1 import unittest 2 from test import support 3 from io import StringIO 4 import pstats 5 from pstats import SortKey 6 7 8 9 class AddCallersTestCase(unittest.TestCase): 10 """Tests for pstats.add_callers helper.""" 11 12 def test_combine_results(self): 13 # pstats.add_callers should combine the call results of both target 14 # and source by adding the call time. See issue1269. 15 # new format: used by the cProfile module 16 target = {"a": (1, 2, 3, 4)} 17 source = {"a": (1, 2, 3, 4), "b": (5, 6, 7, 8)} 18 new_callers = pstats.add_callers(target, source) 19 self.assertEqual(new_callers, {'a': (2, 4, 6, 8), 'b': (5, 6, 7, 8)}) 20 # old format: used by the profile module 21 target = {"a": 1} 22 source = {"a": 1, "b": 5} 23 new_callers = pstats.add_callers(target, source) 24 self.assertEqual(new_callers, {'a': 2, 'b': 5}) 25 26 27 class StatsTestCase(unittest.TestCase): 28 def setUp(self): 29 stats_file = support.findfile('pstats.pck') 30 self.stats = pstats.Stats(stats_file) 31 32 def test_add(self): 33 stream = StringIO() 34 stats = pstats.Stats(stream=stream) 35 stats.add(self.stats, self.stats) 36 37 def test_sort_stats_int(self): 38 valid_args = {-1: 'stdname', 39 0: 'calls', 40 1: 'time', 41 2: 'cumulative'} 42 for arg_int, arg_str in valid_args.items(): 43 self.stats.sort_stats(arg_int) 44 self.assertEqual(self.stats.sort_type, 45 self.stats.sort_arg_dict_default[arg_str][-1]) 46 47 def test_sort_stats_string(self): 48 for sort_name in ['calls', 'ncalls', 'cumtime', 'cumulative', 49 'filename', 'line', 'module', 'name', 'nfl', 'pcalls', 50 'stdname', 'time', 'tottime']: 51 self.stats.sort_stats(sort_name) 52 self.assertEqual(self.stats.sort_type, 53 self.stats.sort_arg_dict_default[sort_name][-1]) 54 55 def test_sort_stats_partial(self): 56 sortkey = 'filename' 57 for sort_name in ['f', 'fi', 'fil', 'file', 'filen', 'filena', 58 'filenam', 'filename']: 59 self.stats.sort_stats(sort_name) 60 self.assertEqual(self.stats.sort_type, 61 self.stats.sort_arg_dict_default[sortkey][-1]) 62 63 def test_sort_stats_enum(self): 64 for member in SortKey: 65 self.stats.sort_stats(member) 66 self.assertEqual( 67 self.stats.sort_type, 68 self.stats.sort_arg_dict_default[member.value][-1]) 69 70 def test_sort_starts_mix(self): 71 self.assertRaises(TypeError, self.stats.sort_stats, 72 'calls', 73 SortKey.TIME) 74 self.assertRaises(TypeError, self.stats.sort_stats, 75 SortKey.TIME, 76 'calls') 77 78 79 if __name__ == "__main__": 80 unittest.main() 81