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 unittest
7
8from telemetry.internal.browser import browser_finder
9from telemetry.internal.util import path
10from telemetry.testing import options_for_unittests
11
12current_browser_options = None
13current_browser = None
14
15
16def teardown_browser():
17  global current_browser
18  global current_browser_options
19
20  if current_browser:
21    current_browser.Close()
22  current_browser = None
23  current_browser_options = None
24
25
26class BrowserTestCase(unittest.TestCase):
27  @classmethod
28  def setUpClass(cls):
29    cls._platform = None
30    global current_browser
31    global current_browser_options
32
33    options = options_for_unittests.GetCopy()
34
35    cls.CustomizeBrowserOptions(options.browser_options)
36    if not current_browser or (current_browser_options !=
37                               options.browser_options):
38      if current_browser:
39        teardown_browser()
40
41      browser_to_create = browser_finder.FindBrowser(options)
42      if not browser_to_create:
43        raise Exception('No browser found, cannot continue test.')
44
45      try:
46        current_browser = browser_to_create.Create(options)
47        current_browser_options = options.browser_options
48      except:
49        cls.tearDownClass()
50        raise
51    cls._browser = current_browser
52    cls._platform = current_browser.platform
53    cls._device = options.device
54
55  @classmethod
56  def tearDownClass(cls):
57    if cls._platform:
58      cls._platform.StopAllLocalServers()
59
60  @classmethod
61  def CustomizeBrowserOptions(cls, options):
62    """Override to add test-specific options to the BrowserOptions object"""
63    pass
64
65  @classmethod
66  def UrlOfUnittestFile(cls, filename):
67    cls._platform.SetHTTPServerDirectories(path.GetUnittestDataDir())
68    file_path = os.path.join(path.GetUnittestDataDir(), filename)
69    return cls._platform.http_server.UrlOf(file_path)
70