-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathtest-appimage.py
More file actions
executable file
·319 lines (258 loc) · 9.31 KB
/
test-appimage.py
File metadata and controls
executable file
·319 lines (258 loc) · 9.31 KB
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
#! /usr/bin/env python3
import argparse
from enum import auto, Enum
import inspect
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from types import FunctionType
from typing import NamedTuple
from python_appimage.manylinux import PythonVersion
ARGS = None
def assert_eq(expected, found):
if expected != found:
raise AssertionError('expected "{}", found "{}"'.format(
expected, found))
class Script(NamedTuple):
'''Python script wrapper'''
content: str
def run(self, appimage: Path):
'''Run the script through an appimage'''
with tempfile.TemporaryDirectory() as tmpdir:
script = f'{tmpdir}/script.py'
with open(script, 'w') as f:
f.write(inspect.getsource(assert_eq))
f.write(os.linesep)
f.write(self.content)
return system(f'{appimage} {script}')
class Status(Enum):
'''Test exit status'''
FAILED = auto()
SKIPPED = auto()
SUCCESS = auto()
def __str__(self):
return self.name
def system(cmd):
'''Run a system command'''
r = subprocess.run(cmd, capture_output=True, shell=True)
if r.returncode != 0:
raise ValueError(r.stderr.decode())
else:
return r.stdout.decode()
class TestContext:
'''Context for testing an image'''
def __init__(self, appimage):
self.appimage = appimage
# Guess python version from appimage name.
version, _, abi, *_ = appimage.name.split('-', 3)
version = version[6:]
if abi.endswith('t'):
version += '-nogil'
self.version = PythonVersion.from_str(version)
# Get some specific AppImage env variables.
self.env = eval(Script('''
import os
appdir = os.environ['APPDIR']
env = {}
for var in ('SSL_CERT_FILE', 'TCL_LIBRARY', 'TK_LIBRARY', 'TKPATH'):
try:
env[var] = os.environ[var].replace(appdir, '$APPDIR')
except KeyError:
pass
print(env)
''').run(appimage))
# Extract the AppImage.
tmpdir = tempfile.TemporaryDirectory()
dst = Path(tmpdir.name) / appimage.name
shutil.copy(appimage, dst)
system(f'cd {tmpdir.name} && ./{appimage.name} --appimage-extract')
self.appdir = Path(tmpdir.name) / 'squashfs-root'
self.tmpdir = tmpdir
def list_content(self, path=None):
'''List the content of an extracted directory'''
path = self.appdir if path is None else self.appdir / path
return sorted(os.listdir(path))
def run(self):
'''Run all tests'''
tests = []
for key, value in self.__class__.__dict__.items():
if isinstance(value, FunctionType):
if key.startswith('test_'):
tests.append(value)
n = len(tests)
m = max(len(test.__doc__) for test in tests)
for i, test in enumerate(tests):
sys.stdout.write(
f'[ {self.appimage.name} | {i + 1:2}/{n} ] {test.__doc__:{m}}'
)
sys.stdout.flush()
try:
status = test(self)
except Exception as e:
status = Status.FAILED
sys.stdout.write(
f' -> {status} ({test.__name__}){os.linesep}')
sys.stdout.flush()
raise e
else:
sys.stdout.write(f' -> {status}{os.linesep}')
sys.stdout.flush()
def test_root_content(self):
'''Check the appimage root content'''
content = self.list_content()
expected = ['.DirIcon', 'AppRun', 'opt', 'python.png',
f'python{self.version.long()}.desktop', 'usr']
assert_eq(expected, content)
return Status.SUCCESS
def test_python_content(self):
'''Check the appimage python content'''
prefix = f'opt/python{self.version.flavoured()}'
content = self.list_content(prefix)
assert_eq(['bin', 'include', 'lib'], content)
content = self.list_content(f'{prefix}/bin')
assert_eq(
[f'pip{self.version.short()}', f'python{self.version.flavoured()}'],
content
)
content = self.list_content(f'{prefix}/include')
if (self.version.major == 3) and (self.version.minor <= 7):
expected = [f'python{self.version.short()}m']
else:
expected = [f'python{self.version.flavoured()}']
assert_eq(expected, content)
content = self.list_content(f'{prefix}/lib')
assert_eq([f'python{self.version.flavoured()}'], content)
return Status.SUCCESS
def test_system_content(self):
'''Check the appimage system content'''
content = self.list_content('usr')
assert_eq(['bin', 'lib', 'share'], content)
content = self.list_content('usr/bin')
expected = [
'pip', f'pip{self.version.major}', f'pip{self.version.short()}',
'python', f'python{self.version.major}',
f'python{self.version.short()}'
]
assert_eq(expected, content)
return Status.SUCCESS
def test_tcltk_bundling(self):
'''Check Tcl/Tk bundling'''
if 'TK_LIBRARY' not in self.env:
return Status.SKIPPED
else:
for var in ('TCL_LIBRARY', 'TK_LIBRARY', 'TKPATH'):
path = Path(self.env[var].replace('$APPDIR', str(self.appdir)))
assert path.exists()
return Status.SUCCESS
def test_ssl_bundling(self):
'''Check SSL certs bundling'''
var = 'SSL_CERT_FILE'
path = Path(self.env[var].replace('$APPDIR', str(self.appdir)))
assert path.exists()
return Status.SUCCESS
def test_bin_symlinks(self):
'''Check /usr/bin symlinks'''
assert_eq(
(self.appdir /
f'opt/python{self.version.flavoured()}/bin/pip{self.version.short()}'),
(self.appdir / f'usr/bin/pip{self.version.short()}').resolve()
)
assert_eq(
f'pip{self.version.short()}',
str((self.appdir / f'usr/bin/pip{self.version.major}').readlink())
)
assert_eq(
f'pip{self.version.major}',
str((self.appdir / 'usr/bin/pip').readlink())
)
assert_eq(
f'python{self.version.short()}',
str((self.appdir / f'usr/bin/python{self.version.major}').readlink())
)
assert_eq(
f'python{self.version.major}',
str((self.appdir / 'usr/bin/python').readlink())
)
return Status.SUCCESS
def test_appimage_hook(self):
'''Test the appimage hook'''
Script(f'''
import os
assert_eq(os.environ['APPIMAGE_COMMAND'], '{self.appimage}')
import sys
assert_eq('{self.appimage}', sys.executable)
assert_eq('{self.appimage}', sys._base_executable)
''').run(self.appimage)
return Status.SUCCESS
def test_python_prefix(self):
'''Test the python prefix'''
Script(f'''
import os
import sys
expected = os.environ["APPDIR"] + '/opt/python{self.version.flavoured()}'
assert_eq(expected, sys.prefix)
''').run(self.appimage)
return Status.SUCCESS
def test_ssl_request(self):
'''Test SSL request (see issue #24)'''
if self.version.major == 2:
return Status.SKIPPED
else:
Script('''
from http import HTTPStatus
import urllib.request
with urllib.request.urlopen('https://wikipedia.org') as r:
assert_eq(r.status, HTTPStatus.OK)
''').run(self.appimage)
return Status.SUCCESS
def test_pip_install(self):
'''Test pip installing to an extracted AppImage'''
r = system(f'{self.appdir}/AppRun -m pip install pip-install-test')
assert('Successfully installed pip-install-test' in r)
path = self.appdir / f'opt/python{self.version.flavoured()}/lib/python{self.version.flavoured()}/site-packages/pip_install_test'
assert(path.exists())
return Status.SUCCESS
def test_tkinter_usage(self):
'''Test basic tkinter usage'''
try:
os.environ['DISPLAY']
self.env['TK_LIBRARY']
except KeyError:
return Status.SKIPPED
else:
tkinter = 'tkinter' if self.version.major > 2 else 'Tkinter'
Script(f'''
import {tkinter} as tkinter
tkinter.Tk()
''').run(self.appimage)
return Status.SUCCESS
def test_venv_usage(self):
'''Test venv creation'''
if self.version.major == 2:
return Status.SKIPPED
else:
system(' && '.join((
f'cd {self.tmpdir.name}',
f'./{self.appimage.name} -m venv ENV',
'. ENV/bin/activate',
)))
python = Path(f'{self.tmpdir.name}/ENV/bin/python')
assert_eq(self.appimage.name, str(python.readlink()))
return Status.SUCCESS
def test():
'''Test Python AppImage(s)'''
for appimage in ARGS.appimage:
context = TestContext(appimage)
context.run()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = test.__doc__)
parser.add_argument('appimage',
help = 'path to appimage(s)',
nargs = '+',
type = lambda x: Path(x).absolute()
)
ARGS = parser.parse_args()
test()