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.
5 """Worker thread base class.
7 Worker threads are used to run multiple PyUITests simultaneously. They
8 synchronize calls to the browser."""
15 # A static lock used to synchronize worker threads access to the browser.
16 __lock = threading.RLock()
19 """A decorator to wrap a lock around function calls."""
20 def syncFun(*args, **kwargs):
22 return fn(*args, **kwargs)
27 def RunWorkerThreads(pyauto_test, test_worker_class, tasks, num_threads,
29 """Creates a matrix of tasks and starts test worker threads to run them.
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.
38 # Convert relative test path into an absolute path.
39 test_url = pyauto_test.GetFileURLForDataPath(test_path)
41 # Add shutdown magic to end of queue.
42 for _ in xrange(num_threads):
46 for _ in xrange(num_threads):
47 threads.append(test_worker_class(pyauto_test, tasks, test_url))
49 # Wait for threads to exit, gracefully or otherwise.
50 for thread in threads:
53 return sum(thread.failures for thread in threads)
56 class WorkerThread(threading.Thread):
57 """Thread which for each queue task: opens tab, runs task, closes tab."""
59 # Atomic, monotonically increasing task identifier. Used to ID tabs.
60 _task_id = itertools.count()
62 def __init__(self, pyauto_test, tasks, url):
63 """Sets up WorkerThread class variables.
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.
70 threading.Thread.__init__(self)
71 self.__pyauto = pyauto_test
77 def RunTask(self, unique_url, task):
78 """Runs the specific task on the url test page.
80 This method should be overridden to start the test on the unique_url page.
83 unique_url: A unique identifier of the test page.
84 task: A tuple with information needed to run the test.
86 True if the task finished as expected.
88 raise NotImplementedError('RunTask should be defined in a subclass.')
91 """For each task in queue: opens new tab, calls RunTask(), then closes tab.
93 No exception handling is done to make sure the main thread exits properly
94 during Chrome crashes or other failures.
96 For a clean shutdown, put the magic exit value None in the queue.
99 task = self.__tasks.get()
100 # Check for magic exit values.
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):
108 self.CloseTabByURL(unique_url)
109 self.__tasks.task_done()
111 def __FindTabLocked(self, url):
112 """Returns the tab index for the tab belonging to this url.
114 __lock must be owned by caller.
118 for tab in self.__pyauto.GetBrowserInfo()['windows'][0]['tabs']:
119 if tab['url'] == url:
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.
126 # We limit access of subclasses to the following functions. If subclasses
127 # access other PyUITest functions, then there is no guarantee of thread
130 # For details on the args check pyauto.PyUITest class.
132 def AppendTab(self, url):
133 self.__pyauto.AppendTab(pyauto.GURL(url))
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))
141 def CloseTabByURL(self, url):
142 """Closes the tab with the given url."""
143 self.__pyauto.CloseTab(tab_index=self.__FindTabLocked(url))
146 def GetDOMValue(self, name, url=None):
147 return self.__pyauto.GetDOMValue(name, tab_index=self.__FindTabLocked(url))
149 def WaitUntil(self, *args, **kwargs):
150 """We do not need to lock WaitUntil since it does not call into Chrome.
152 Ensure that the function passed in the args is thread safe.
154 return self.__pyauto.WaitUntil(*args, **kwargs)