Debian Codegraph @

tests/autopilot/lomiriuitoolkit/fixture_setup.py

raw
1 # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
2 #
3 # Copyright (C) 2014, 2015 Canonical Ltd.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation; version 3.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import copy
18 import json
19 import logging
20 import os
21 import shutil
22 import subprocess
23 import tempfile
24
25 import fixtures
26 from autopilot import display
27 from gi.repository import Gio
28
29 from lomiriuitoolkit import base
30
31
32 DEFAULT_QML_FILE_CONTENTS = ("""
33 import QtQuick 2.0
34 import Lomiri.Components 1.1
35
36 MainView {
37 width: units.gu(48)
38 height: units.gu(60)
39
40 Label {
41 objectName: 'testLabel'
42 text: 'Test application.'
43 }
44 }
45 """)
46 DEFAULT_DESKTOP_FILE_DICT = {
47 'Type': 'Application',
48 'Name': 'test',
49 'Exec': '{launcher} {qml_file_path}',
50 'Icon': 'Not important'
51 }
52
53
54 logger = logging.getLogger(__name__)
55
56
57 class FakeApplication(fixtures.Fixture):
58
59 def __init__(
60 self, qml_file_contents=DEFAULT_QML_FILE_CONTENTS,
61 desktop_file_dict=None, url_dispatcher_protocols=None):
62 super().__init__()
63 self._qml_file_contents = qml_file_contents
64 if desktop_file_dict is None:
65 self._desktop_file_dict = copy.deepcopy(DEFAULT_DESKTOP_FILE_DICT)
66 else:
67 self._desktop_file_dict = copy.deepcopy(desktop_file_dict)
68 self.url_dispatcher_protocols = url_dispatcher_protocols
69
70 def setUp(self):
71 super().setUp()
72 self.qml_file_path, self.desktop_file_path = (
73 self._create_test_application())
74 desktop_file_name = os.path.basename(self.desktop_file_path)
75 self.application_name, _ = os.path.splitext(desktop_file_name)
76 if self.url_dispatcher_protocols:
77 self.url_dispatcher_file_path = (
78 self._register_url_dispatcher_protocols(self.application_name))
79
80 def _create_test_application(self):
81 qml_file_path = self._write_test_qml_file()
82 self.addCleanup(os.remove, qml_file_path)
83 desktop_file_path = self._write_test_desktop_file(qml_file_path)
84 self.addCleanup(os.remove, desktop_file_path)
85 return qml_file_path, desktop_file_path
86
87 def _write_test_qml_file(self):
88 qml_file = self._named_temporary_file(suffix='.qml')
89 qml_file.write(self._qml_file_contents)
90 qml_file.close()
91 return qml_file.name
92
93 def _named_temporary_file(self, dir=None, mode='w+t',
94 delete=False, suffix=''):
95 # Discard files with underscores which look like an APP_ID to Unity
96 # See https://bugs.launchpad.net/lomiri-ui-toolkit/+bug/1329141
97 chars = tempfile._RandomNameSequence.characters.strip("_")
98 tempfile._RandomNameSequence.characters = chars
99 return tempfile.NamedTemporaryFile(dir=dir, mode=mode,
100 delete=delete, suffix=suffix)
101
102 def _write_test_desktop_file(self, qml_file_path):
103 desktop_file_dir = self._get_local_desktop_file_directory()
104 if not os.path.exists(desktop_file_dir):
105 os.makedirs(desktop_file_dir)
106 desktop_file = self._named_temporary_file(suffix='.desktop',
107 dir=desktop_file_dir)
108 self._desktop_file_dict['Exec'] = (
109 self._desktop_file_dict['Exec'].format(
110 launcher=base.get_toolkit_launcher_command(),
111 qml_file_path=qml_file_path))
112 desktop_file.write('[Desktop Entry]\n')
113 for key, value in self._desktop_file_dict.items():
114 desktop_file.write('{key}={value}\n'.format(key=key, value=value))
115 desktop_file.close()
116 return desktop_file.name
117
118 def _get_local_desktop_file_directory(self):
119 return os.path.join(
120 os.environ.get('HOME'), '.local', 'share', 'applications')
121
122 def _register_url_dispatcher_protocols(self, application_name):
123 url_dispatcher_file_path = self._write_url_dispatcher_file(
124 application_name)
125 self.addCleanup(os.remove, url_dispatcher_file_path)
126 self._update_url_dispatcher_directory(url_dispatcher_file_path)
127 return url_dispatcher_file_path
128
129 def _write_url_dispatcher_file(self, application_name):
130 url_dispatcher_dir = self._get_local_url_dispatcher_directory()
131 if not os.path.exists(url_dispatcher_dir):
132 os.makedirs(url_dispatcher_dir)
133
134 protocol_list = [
135 {'protocol': protocol}
136 for protocol in self.url_dispatcher_protocols]
137
138 url_dispatcher_file_path = os.path.join(
139 url_dispatcher_dir, application_name + '.url-dispatcher')
140 with open(url_dispatcher_file_path, 'w') as url_dispatcher_file:
141 url_dispatcher_file.write(json.dumps(protocol_list))
142
143 return url_dispatcher_file_path
144
145 def _get_local_url_dispatcher_directory(self):
146 return os.path.join(
147 os.environ.get('HOME'), '.config', 'url-dispatcher', 'urls')
148
149 def _update_url_dispatcher_directory(self, url_dispatcher_file_path):
150 # FIXME This should be updated calling
151 # initctl start url-dispatcher-update-user, but it is not working.
152 # https://bugs.launchpad.net/lomiri/+source/url-dispatcher/+bug/1461496
153 # --elopio - 2015-06-02
154 subprocess.check_output(
155 '/usr/lib/*/url-dispatcher/update-directory ' +
156 url_dispatcher_file_path, shell=True)
157
158
159 class FakeHome(fixtures.Fixture):
160
161 # We copy the Xauthority file to allow executions using XVFB. If it is not
162 # on the user's HOME directory, nothing will happen.
163 should_copy_xauthority_file = True
164
165 def __init__(self, directory=None):
166 super().__init__()
167 self.directory = directory
168
169 def setUp(self):
170 super().setUp()
171 self.directory = self._make_directory_if_not_specified()
172 if self.should_copy_xauthority_file:
173 self._copy_xauthority_file(self.directory)
174 self.useFixture(
175 fixtures.EnvironmentVariable('HOME', newvalue=self.directory))
176
177 def _make_directory_if_not_specified(self):
178 if self.directory is None:
179 parent_directory = os.path.join(
180 os.environ.get('HOME'), 'autopilot', 'fakeenv')
181 if not os.path.exists(parent_directory):
182 os.makedirs(parent_directory)
183 temp_dir_fixture = fixtures.TempDir(parent_directory)
184 self.useFixture(temp_dir_fixture)
185 return temp_dir_fixture.path
186 else:
187 return self.directory
188
189 def _copy_xauthority_file(self, directory):
190 """Copy the .Xauthority file if it exists in the user's home."""
191 xauthority_file_path = os.path.join(
192 os.environ.get('HOME'), '.Xauthority')
193 if os.path.isfile(xauthority_file_path):
194 shutil.copyfile(
195 xauthority_file_path,
196 os.path.join(directory, '.Xauthority'))
197
198
199 class HideUnity7Launcher(fixtures.Fixture):
200
201 """Hide the Unity7 launcher if it is visible and restore it on clean up."""
202
203 _UNITYSHELL_GSETTINGS_SCHEMA = 'org.compiz.unityshell'
204 _UNITYSHELL_GSETTINGS_PATH = (
205 '/org/compiz/profiles/unity/plugins/unityshell/')
206 _UNITYSHELL_LAUNCHER_KEY = 'launcher-hide-mode'
207 _UNITYSHELL_LAUNCHER_HIDDEN_MODE = 1 # launcher hidden
208
209 def setUp(self):
210 super().setUp()
211 self._hide_launcher()
212
213 def _hide_launcher(self):
214 if (self._UNITYSHELL_GSETTINGS_SCHEMA in
215 Gio.Settings.list_relocatable_schemas()):
216 unityshell_schema = Gio.Settings.new_with_path(
217 self._UNITYSHELL_GSETTINGS_SCHEMA,
218 self._UNITYSHELL_GSETTINGS_PATH)
219 self._hide_launcher_from_schema(unityshell_schema)
220 else:
221 logger.warning('Unity Shell gsettings schema not found.')
222
223 def _hide_launcher_from_schema(self, unityshell_schema):
224 original_mode = self._get_launcher_mode(unityshell_schema)
225 self.addCleanup(
226 self._set_launcher_mode, unityshell_schema, original_mode)
227 self._set_launcher_mode(
228 unityshell_schema, self._UNITYSHELL_LAUNCHER_HIDDEN_MODE)
229
230 def _get_launcher_mode(self, unityshell_schema):
231 return unityshell_schema.get_int(self._UNITYSHELL_LAUNCHER_KEY)
232
233 def _set_launcher_mode(self, unityshell_schema, mode):
234 unityshell_schema.set_int(self._UNITYSHELL_LAUNCHER_KEY, mode)
235
236
237 class SimulateDevice(fixtures.Fixture):
238
239 def __init__(self, app_width, app_height, grid_unit_px):
240 super().__init__()
241 self.app_width = app_width
242 self.app_height = app_height
243 self.grid_unit_px = grid_unit_px
244 self._screen = None
245
246 def setUp(self):
247 super().setUp()
248 if self._is_geometry_larger_than_display(
249 self.app_width, self.app_height):
250 scale_divisor = self._get_scale_divisor()
251 self.grid_unit_px = self.grid_unit_px // scale_divisor
252 self.app_width = self.app_width // scale_divisor
253 self.app_height = self.app_height // scale_divisor
254 self.useFixture(
255 fixtures.EnvironmentVariable(
256 'GRID_UNIT_PX', str(self.grid_unit_px)))
257
258 def _get_scale_divisor(self):
259 scale_divisor = 2
260 while self._is_geometry_larger_than_display(
261 self.app_width // scale_divisor,
262 self.app_height // scale_divisor):
263 scale_divisor = scale_divisor * 2
264 return scale_divisor
265
266 def _is_geometry_larger_than_display(self, width, height):
267 screen = self._get_screen()
268 screen_width = screen.get_screen_width()
269 screen_height = screen.get_screen_height()
270 return (width > screen_width) or (height > screen_height)
271
272 def _get_screen(self):
273 if self._screen is None:
274 self._screen = display.Display.create()
275 return self._screen