Home | History | Annotate | Download | only in media
      1 # Copyright (c) 2012 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 
      5 """Worker thread base class.
      6 
      7 Worker threads are used to run multiple PyUITests simultaneously. They
      8 synchronize calls to the browser."""
      9 
     10 import itertools
     11 import threading
     12 import pyauto
     13 
     14 
     15 # A static lock used to synchronize worker threads access to the browser.
     16 __lock = threading.RLock()
     17 
     18 def synchronized(fn):
     19   """A decorator to wrap a lock around function calls."""
     20   def syncFun(*args, **kwargs):
     21     with __lock:
     22       return fn(*args, **kwargs)
     23 
     24   return syncFun
     25 
     26 
     27 def RunWorkerThreads(pyauto_test, test_worker_class, tasks, num_threads,
     28                      test_path):
     29   """Creates a matrix of tasks and starts test worker threads to run them.
     30 
     31   Args:
     32     pyauto_test: Reference to a pyauto.PyUITest instance.
     33     test_worker_class: WorkerThread class reference.
     34     tasks: Queue of tasks to run by the worker threads.
     35     num_threads: Number of threads to run simultaneously.
     36     test_path: Path to HTML/JavaScript test code.
     37   """
     38   # Convert relative test path into an absolute path.
     39   test_url = pyauto_test.GetFileURLForDataPath(test_path)
     40 
     41   # Add shutdown magic to end of queue.
     42   for _ in xrange(num_threads):
     43     tasks.put(None)
     44 
     45   threads = []
     46   for _ in xrange(num_threads):
     47     threads.append(test_worker_class(pyauto_test, tasks, test_url))
     48 
     49   # Wait for threads to exit, gracefully or otherwise.
     50   for thread in threads:
     51     thread.join()
     52 
     53   return sum(thread.failures for thread in threads)
     54 
     55 
     56 class WorkerThread(threading.Thread):
     57   """Thread which for each queue task: opens tab, runs task, closes tab."""
     58 
     59   # Atomic, monotonically increasing task identifier.  Used to ID tabs.
     60   _task_id = itertools.count()
     61 
     62   def __init__(self, pyauto_test, tasks, url):
     63     """Sets up WorkerThread class variables.
     64 
     65     Args:
     66       pyauto_test: Reference to a pyauto.PyUITest instance.
     67       tasks: Queue containing task tuples used by RunTest().
     68       url: File URL to HTML/JavaScript test code.
     69     """
     70     threading.Thread.__init__(self)
     71     self.__pyauto = pyauto_test
     72     self.__tasks = tasks
     73     self.__url = url
     74     self.failures = 0
     75     self.start()
     76 
     77   def RunTask(self, unique_url, task):
     78     """Runs the specific task on the url test page.
     79 
     80     This method should be overridden to start the test on the unique_url page.
     81 
     82     Args:
     83       unique_url: A unique identifier of the test page.
     84       task: A tuple with information needed to run the test.
     85     Returns:
     86       True if the task finished as expected.
     87     """
     88     raise NotImplementedError('RunTask should be defined in a subclass.')
     89 
     90   def run(self):
     91     """For each task in queue: opens new tab, calls RunTask(), then closes tab.
     92 
     93     No exception handling is done to make sure the main thread exits properly
     94     during Chrome crashes or other failures.
     95 
     96     For a clean shutdown, put the magic exit value None in the queue.
     97     """
     98     while True:
     99       task = self.__tasks.get()
    100       # Check for magic exit values.
    101       if task is None:
    102         break
    103       # Make the test URL unique so we can figure out our tab index later.
    104       unique_url = '%s?%d' % (self.__url, WorkerThread._task_id.next())
    105       self.AppendTab(unique_url)
    106       if not self.RunTask(unique_url, task):
    107         self.failures += 1
    108       self.CloseTabByURL(unique_url)
    109       self.__tasks.task_done()
    110 
    111   def __FindTabLocked(self, url):
    112     """Returns the tab index for the tab belonging to this url.
    113 
    114     __lock must be owned by caller.
    115     """
    116     if url is None:
    117       return 0
    118     for tab in self.__pyauto.GetBrowserInfo()['windows'][0]['tabs']:
    119       if tab['url'] == url:
    120         return tab['index']
    121 
    122   # The following are wrappers to pyauto.PyUITest functions. They are wrapped
    123   # with an internal lock to avoid problems when more than one thread edits the
    124   # state of the browser.
    125   #
    126   # We limit access of subclasses to the following functions. If subclasses
    127   # access other PyUITest functions, then there is no guarantee of thread
    128   # safety.
    129   #
    130   # For details on the args check pyauto.PyUITest class.
    131   @synchronized
    132   def AppendTab(self, url):
    133     self.__pyauto.AppendTab(pyauto.GURL(url))
    134 
    135   @synchronized
    136   def CallJavascriptFunc(self, fun_name, fun_args=[], url=None):
    137     return self.__pyauto.CallJavascriptFunc(fun_name, fun_args,
    138                                             tab_index=self.__FindTabLocked(url))
    139 
    140   @synchronized
    141   def CloseTabByURL(self, url):
    142     """Closes the tab with the given url."""
    143     self.__pyauto.CloseTab(tab_index=self.__FindTabLocked(url))
    144 
    145   @synchronized
    146   def GetDOMValue(self, name, url=None):
    147     return self.__pyauto.GetDOMValue(name, tab_index=self.__FindTabLocked(url))
    148 
    149   def WaitUntil(self, *args, **kwargs):
    150     """We do not need to lock WaitUntil since it does not call into Chrome.
    151 
    152     Ensure that the function passed in the args is thread safe.
    153     """
    154     return self.__pyauto.WaitUntil(*args, **kwargs)
    155