/usr/lib/python2.7/dist-packages/autopilot/testcase.py is in python-autopilot 1.4.1+15.10.20150911-0ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Autopilot Functional Test Tool
# Copyright (C) 2012-2013 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Quick Start
===========
The :class:`AutopilotTestCase` is the main class test authors will be
interacting with. Every autopilot test case should derive from this class.
:class:`AutopilotTestCase` derives from :class:`testtools.TestCase`, so test
authors can use all the methods defined in that class as well.
**Writing tests**
Tests must be named: ``test_<testname>``, where *<testname>* is the name of the
test. Test runners (including autopilot itself) look for methods with this
naming convention. It is recommended that you make your test names descriptive
of what each test is testing. For example, possible test names include::
test_ctrl_p_opens_print_dialog
test_dash_remembers_maximized_state
**Launching the Application Under Test**
If you are writing a test for an application, you need to use the
:meth:`~AutopilotTestCase.launch_test_application` method. This will launch the
application, enable introspection, and return a proxy object representing the
root of the application introspection tree.
"""
from __future__ import absolute_import
import logging
import os
import six
from testscenarios import TestWithScenarios
from testtools import TestCase
from testtools.matchers import Equals
from autopilot.application import (
ClickApplicationLauncher,
get_application_launcher_wrapper,
NormalApplicationLauncher,
UpstartApplicationLauncher,
)
from autopilot.display import Display
from autopilot.globals import get_debug_profile_fixture
from autopilot.input import Keyboard, Mouse
from autopilot.introspection import (
get_proxy_object_for_existing_process,
)
from autopilot.keybindings import KeybindingsHelper
from autopilot.matchers import Eventually
from autopilot.process import ProcessManager
from autopilot.utilities import deprecated, on_test_started
from autopilot._timeout import Timeout
try:
from autopilot import tracepoint as tp
HAVE_TRACEPOINT = True
except ImportError:
HAVE_TRACEPOINT = False
_logger = logging.getLogger(__name__)
try:
from testscenarios.scenarios import multiply_scenarios
except ImportError:
from itertools import product
def multiply_scenarios(*scenarios):
"""Multiply two or more iterables of scenarios.
It is safe to pass scenario generators or iterators.
:returns: A list of compound scenarios: the cross-product of all
scenarios, with the names concatenated and the parameters
merged together.
"""
result = []
scenario_lists = map(list, scenarios)
for combination in product(*scenario_lists):
names, parameters = zip(*combination)
scenario_name = ','.join(names)
scenario_parameters = {}
for parameter in parameters:
scenario_parameters.update(parameter)
result.append((scenario_name, scenario_parameters))
return result
def _lttng_trace_test_started(test_id):
if HAVE_TRACEPOINT:
tp.emit_test_started(test_id)
else:
_logger.warning(
"No tracing available - install the python-autopilot-trace "
"package!")
def _lttng_trace_test_ended(test_id):
if HAVE_TRACEPOINT:
tp.emit_test_ended(test_id)
class AutopilotTestCase(TestWithScenarios, TestCase, KeybindingsHelper):
"""Wrapper around testtools.TestCase that adds significant functionality.
This class should be the base class for all autopilot test case classes.
Not using this class as the base class disables several important
convenience methods, and also prevents the use of the failed-test
recording tools.
"""
def setUp(self):
super(AutopilotTestCase, self).setUp()
on_test_started(self)
self.useFixture(get_debug_profile_fixture()(self.addDetail))
_lttng_trace_test_started(self.id())
self.addCleanup(_lttng_trace_test_ended, self.id())
self._process_manager = None
self._mouse = None
self._kb = None
self._display = None
# Work around for bug lp:1297592.
_ensure_uinput_device_created()
try:
self._app_snapshot = _get_process_snapshot()
self.addCleanup(self._compare_system_with_app_snapshot)
except RuntimeError:
_logger.warning(
"Process manager backend unavailable, application snapshot "
"support disabled.")
@property
def process_manager(self):
if self._process_manager is None:
self._process_manager = ProcessManager.create()
return self._process_manager
@property
def keyboard(self):
if self._kb is None:
self._kb = Keyboard.create()
return self._kb
@property
def mouse(self):
if self._mouse is None:
self._mouse = Mouse.create()
return self._mouse
@property
def display(self):
if self._display is None:
self._display = Display.create()
return self._display
def launch_test_application(self, application, *arguments, **kwargs):
"""Launch ``application`` and return a proxy object for the
application.
Use this method to launch an application and start testing it. The
positional arguments are used as arguments to the application to lanch.
Keyword arguments are used to control the manner in which the
application is launched.
This method is designed to be flexible enough to launch all supported
types of applications. Autopilot can automatically determine how to
enable introspection support for dynamically linked binary
applications. For example, to launch a binary Gtk application, a test
might start with::
app_proxy = self.launch_test_application('gedit')
Applications can be given command line arguments by supplying
positional arguments to this method. For example, if we want to launch
``gedit`` with a certain document loaded, we might do this::
app_proxy = self.launch_test_application(
'gedit', '/tmp/test-document.txt')
... a Qt5 Qml application is launched in a similar fashion::
app_proxy = self.launch_test_application(
'qmlscene', 'my_scene.qml')
If you wish to launch an application that is not a dynamically linked
binary, you must specify the application type. For example, a Qt4
python application might be launched like this::
app_proxy = self.launch_test_application(
'my_qt_app.py', app_type='qt')
Similarly, a python/Gtk application is launched like so::
app_proxy = self.launch_test_application(
'my_gtk_app.py', app_type='gtk')
:param application: The application to launch. The application can be
specified as:
* A full, absolute path to an executable file.
(``/usr/bin/gedit``)
* A relative path to an executable file.
(``./build/my_app``)
* An app name, which will be searched for in $PATH (``my_app``)
:keyword app_type: If set, provides a hint to autopilot as to which
kind of introspection to enable. This is needed when the
application you wish to launch is *not* a dynamically linked
binary. Valid values are 'gtk' or 'qt'. These strings are case
insensitive.
:keyword launch_dir: If set to a directory that exists the process
will be launched from that directory.
:keyword capture_output: If set to True (the default), the process
output will be captured and attached to the test as test detail.
:keyword emulator_base: If set, specifies the base class to be used for
all emulators for this loaded application.
:raises ValueError: if unknown keyword arguments are passed.
:return: A proxy object that represents the application. Introspection
data is retrievable via this object.
"""
_logger.info(
"Attempting to launch application '%s' with arguments '%s' as a "
"normal process",
application,
' '.join(arguments)
)
launcher = self.useFixture(
NormalApplicationLauncher(self.addDetail, **kwargs)
)
return self._launch_test_application(launcher, application, *arguments)
def launch_click_package(self, package_id, app_name=None, app_uris=[],
**kwargs):
"""Launch a click package application with introspection enabled.
This method takes care of launching a click package with introspection
exabled. You probably want to use this method if your application is
packaged in a click application, or is started via upstart.
Usage is similar to the
:py:meth:`AutopilotTestCase.launch_test_application`::
app_proxy = self.launch_click_package(
"com.ubuntu.dropping-letters"
)
:param package_id: The Click package name you want to launch. For
example: ``com.ubuntu.dropping-letters``
:param app_name: Currently, only one application can be packaged in a
click package, and this parameter can be left at None. If
specified, it should be the application name you wish to launch.
:param app_uris: Parameters used to launch the click package. This
parameter will be left empty if not used.
:keyword emulator_base: If set, specifies the base class to be used for
all emulators for this loaded application.
:raises RuntimeError: If the specified package_id cannot be found in
the click package manifest.
:raises RuntimeError: If the specified app_name cannot be found within
the specified click package.
:returns: proxy object for the launched package application
"""
if isinstance(app_uris, (six.text_type, six.binary_type)):
app_uris = [app_uris]
_logger.info(
"Attempting to launch click application '%s' from click package "
" '%s' and URIs '%s'",
app_name if app_name is not None else "(default)",
package_id,
','.join(app_uris)
)
launcher = self.useFixture(
ClickApplicationLauncher(self.addDetail, **kwargs)
)
return self._launch_test_application(launcher, package_id, app_name,
app_uris)
def launch_upstart_application(self, application_name, uris=[], **kwargs):
"""Launch an application with upstart.
This method launched an application via the ``ubuntu-app-launch``
library, on platforms that support it.
Usage is similar to the
:py:meth:`AutopilotTestCase.launch_test_application`::
app_proxy = self.launch_upstart_application("gallery-app")
:param application_name: The name of the application to launch.
:keyword emulator_base: If set, specifies the base class to be used for
all emulators for this loaded application.
:raises RuntimeError: If the specified application cannot be launched.
:raises ValueError: If unknown keyword arguments are specified.
"""
if isinstance(uris, (six.text_type, six.binary_type)):
uris = [uris]
_logger.info(
"Attempting to launch application '%s' with URIs '%s' via "
"upstart-app-launch",
application_name,
','.join(uris)
)
launcher = self.useFixture(
UpstartApplicationLauncher(self.addDetail, **kwargs)
)
return self._launch_test_application(launcher, application_name, uris)
# Wrapper function tying the newer ApplicationLauncher behaviour with the
# previous (to be depreciated) behaviour
def _launch_test_application(self, launcher_instance, application, *args):
dbus_bus = launcher_instance.dbus_bus
if dbus_bus != 'session':
self.patch_environment("DBUS_SESSION_BUS_ADDRESS", dbus_bus)
pid = launcher_instance.launch(application, *args)
process = getattr(launcher_instance, 'process', None)
application_name = getattr(
launcher_instance,
'dbus_application_name',
None
)
proxy_obj = get_proxy_object_for_existing_process(
pid=pid,
process=process,
dbus_bus=dbus_bus,
emulator_base=launcher_instance.emulator_base,
application_name=application_name,
)
proxy_obj.set_process(process)
return proxy_obj
def _compare_system_with_app_snapshot(self):
"""Compare the currently running application with the last snapshot.
This method will raise an AssertionError if there are any new
applications currently running that were not running when the snapshot
was taken.
"""
try:
_compare_system_with_process_snapshot(
_get_process_snapshot,
self._app_snapshot
)
finally:
self._app_snapshot = None
def patch_environment(self, key, value):
"""Patch the process environment, setting *key* with value *value*.
This patches os.environ for the duration of the test only. After
calling this method, the following should be True::
os.environ[key] == value
After the test, the patch will be undone (including deleting the key if
if didn't exist before this method was called).
.. note:: Be aware that patching the environment in this way only
affects the current autopilot process, and any processes spawned by
autopilot. If you are planing on starting an application from within
autopilot and you want this new application to read the patched
environment variable, you must patch the environment *before*
launching the new process.
:param string key: The name of the key you wish to set. If the key
does not already exist in the process environment it will be created
(and then deleted when the test ends).
:param string value: The value you wish to set.
"""
if key in os.environ:
def _undo_patch(key, old_value):
_logger.info(
"Resetting environment variable '%s' to '%s'",
key,
old_value
)
os.environ[key] = old_value
old_value = os.environ[key]
self.addCleanup(_undo_patch, key, old_value)
else:
def _remove_patch(key):
try:
_logger.info(
"Deleting previously-created environment "
"variable '%s'",
key
)
del os.environ[key]
except KeyError:
_logger.warning(
"Attempted to delete environment key '%s' that doesn't"
"exist in the environment",
key
)
self.addCleanup(_remove_patch, key)
_logger.info(
"Setting environment variable '%s' to '%s'",
key,
value
)
os.environ[key] = value
def assertVisibleWindowStack(self, stack_start):
"""Check that the visible window stack starts with the windows passed
in.
.. note:: Minimised windows are skipped.
:param stack_start: An iterable of
:class:`~autopilot.process.Window` instances.
:raises AssertionError: if the top of the window stack does not
match the contents of the stack_start parameter.
"""
stack = [
win for win in
self.process_manager.get_open_windows() if not win.is_hidden]
for pos, win in enumerate(stack_start):
self.assertThat(
stack[pos].x_id, Equals(win.x_id),
"%r at %d does not equal %r" % (stack[pos], pos, win))
def assertProperty(self, obj, **kwargs):
"""Assert that *obj* has properties equal to the key/value pairs in
kwargs.
This method is intended to be used on objects whose attributes do not
have the :meth:`wait_for` method (i.e.- objects that do not come from
the autopilot DBus interface).
For example, from within a test, to assert certain properties on a
`~autopilot.process.Window` instance::
self.assertProperty(my_window, is_maximized=True)
.. note:: assertProperties is a synonym for this method.
:param obj: The object to test.
:param kwargs: One or more keyword arguments to match against the
attributes of the *obj* parameter.
:raises ValueError: if no keyword arguments were given.
:raises ValueError: if a named attribute is a callable object.
:raises AssertionError: if any of the attribute/value pairs in
kwargs do not match the attributes on the object passed in.
"""
if not kwargs:
raise ValueError("At least one keyword argument must be present.")
for prop_name, desired_value in kwargs.items():
none_val = object()
attr = getattr(obj, prop_name, none_val)
if attr == none_val:
raise AssertionError(
"Object %r does not have an attribute named '%s'"
% (obj, prop_name))
if callable(attr):
raise ValueError(
"Object %r's '%s' attribute is a callable. It must be a "
"property." % (obj, prop_name))
self.assertThat(
lambda: getattr(obj, prop_name),
Eventually(Equals(desired_value)))
assertProperties = assertProperty
@deprecated(
"the 'app_type' argument to the launch_test_application method"
)
def pick_app_launcher(self, app_path):
"""Given an application path, return an object suitable for launching
the application.
This function attempts to guess what kind of application you are
launching. If, for some reason the default implementation returns the
wrong launcher, test authors may override this method to provide their
own implemetnation.
The default implementation calls
:py:func:`autopilot.application.get_application_launcher_wrapper`
"""
# default implementation is in autopilot.application:
return get_application_launcher_wrapper(app_path)
def _get_process_snapshot():
"""Return a snapshot of running processes on the system.
:returns: a list of running processes.
:raises RuntimeError: if the process manager is unsavailble on this
platform.
"""
return ProcessManager.create().get_running_applications()
def _compare_system_with_process_snapshot(snapshot_fn, old_snapshot):
"""Compare an existing process snapshot with current running processes.
:param snapshot_fn: A callable that returns the current running process
list.
:param old_snapshot: A list of processes to compare against.
:raises AssertionError: If, after 10 seconds, there are still running
processes that were not present in ``old_snapshot``.
"""
new_apps = []
for _ in Timeout.default():
current_apps = snapshot_fn()
new_apps = [app for app in current_apps if app not in old_snapshot]
if not new_apps:
return
raise AssertionError(
"The following apps were started during the test and not closed: "
"%r" % new_apps)
def _ensure_uinput_device_created():
# This exists for a work around for bug lp:1297592. Need to create
# an input device before an application launch.
try:
from autopilot.input._uinput import Touch, _UInputTouchDevice
if _UInputTouchDevice._device is None:
Touch.create()
except Exception as e:
_logger.warning(
"Failed to create Touch device for bug lp:1297595 workaround: "
"%s" % str(e)
)
|