1# Copyright 2014 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import os 6import tempfile 7import unittest 8import zipfile 9 10from profile_chrome import profiler 11from profile_chrome import ui 12 13 14class FakeController(object): 15 def __init__(self, contents='fake-contents'): 16 self.contents = contents 17 self.interval = None 18 self.stopped = False 19 self.filename = None 20 21 def StartTracing(self, interval): 22 self.interval = interval 23 24 def StopTracing(self): 25 self.stopped = True 26 27 def PullTrace(self): 28 with tempfile.NamedTemporaryFile(delete=False) as f: 29 self.filename = f.name 30 f.write(self.contents) 31 return f.name 32 33 def __repr__(self): 34 return 'faketrace' 35 36 37class ProfilerTest(unittest.TestCase): 38 def setUp(self): 39 ui.EnableTestMode() 40 41 def testCaptureBasicProfile(self): 42 controller = FakeController() 43 interval = 1.5 44 result = profiler.CaptureProfile([controller], interval) 45 46 try: 47 self.assertEquals(controller.interval, interval) 48 self.assertTrue(controller.stopped) 49 self.assertTrue(os.path.exists(result)) 50 self.assertFalse(os.path.exists(controller.filename)) 51 self.assertTrue(result.endswith('.html')) 52 finally: 53 os.remove(result) 54 55 def testCaptureJsonProfile(self): 56 controller = FakeController() 57 result = profiler.CaptureProfile([controller], 1, write_json=True) 58 59 try: 60 self.assertFalse(result.endswith('.html')) 61 with open(result) as f: 62 self.assertEquals(f.read(), controller.contents) 63 finally: 64 os.remove(result) 65 66 def testCaptureMultipleProfiles(self): 67 controllers = [FakeController('c1'), FakeController('c2')] 68 result = profiler.CaptureProfile(controllers, 1, write_json=True) 69 70 try: 71 self.assertTrue(result.endswith('.zip')) 72 self.assertTrue(zipfile.is_zipfile(result)) 73 with zipfile.ZipFile(result) as f: 74 self.assertEquals( 75 f.namelist(), 76 [controllers[0].filename[1:], controllers[1].filename[1:]]) 77 finally: 78 os.remove(result) 79