summaryrefslogtreecommitdiffstats
path: root/tools/android/adb_profile_chrome/profiler_unittest.py
blob: 819c440b73702011f9210ae95e2232ed939fe819 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import tempfile
import unittest
import zipfile

from adb_profile_chrome import profiler
from adb_profile_chrome import ui


class FakeController(object):
  def __init__(self, contents='fake-contents'):
    self.contents = contents
    self.interval = None
    self.stopped = False
    self.filename = None

  def StartTracing(self, interval):
    self.interval = interval

  def StopTracing(self):
    self.stopped = True

  def PullTrace(self):
    with tempfile.NamedTemporaryFile(delete=False) as f:
      self.filename = f.name
      f.write(self.contents)
      return f.name

  def __repr__(self):
    return 'faketrace'


class ProfilerTest(unittest.TestCase):
  def setUp(self):
    ui.EnableTestMode()

  def testCaptureBasicProfile(self):
    controller = FakeController()
    interval = 1.5
    result = profiler.CaptureProfile([controller], interval)

    try:
      self.assertEquals(controller.interval, interval)
      self.assertTrue(controller.stopped)
      self.assertTrue(os.path.exists(result))
      self.assertFalse(os.path.exists(controller.filename))
      self.assertTrue(result.endswith('.html'))
    finally:
      os.remove(result)

  def testCaptureJsonProfile(self):
    controller = FakeController()
    result = profiler.CaptureProfile([controller], 1, write_json=True)

    try:
      self.assertFalse(result.endswith('.html'))
      with open(result) as f:
        self.assertEquals(f.read(), controller.contents)
    finally:
      os.remove(result)

  def testCaptureMultipleProfiles(self):
    controllers = [FakeController('c1'), FakeController('c2')]
    result = profiler.CaptureProfile(controllers, 1, write_json=True)

    try:
      self.assertTrue(result.endswith('.zip'))
      self.assertTrue(zipfile.is_zipfile(result))
      with zipfile.ZipFile(result) as f:
        self.assertEquals(
            f.namelist(),
            [controllers[0].filename[1:], controllers[1].filename[1:]])
    finally:
      os.remove(result)