forked from python/pymanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_install_command.py
More file actions
409 lines (337 loc) · 13.1 KB
/
test_install_command.py
File metadata and controls
409 lines (337 loc) · 13.1 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
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
import json
import os
import pytest
import secrets
from pathlib import Path, PurePath
from manage import install_command as IC
from manage import installs
@pytest.fixture
def alias_checker(tmp_path):
with AliasChecker(tmp_path) as checker:
yield checker
class AliasChecker:
class Cmd:
global_dir = "out"
launcher_exe = "launcher.txt"
launcherw_exe = "launcherw.txt"
default_platform = "-64"
def __init__(self, platform=None):
self.scratch = {}
if platform:
self.default_platform = platform
def __init__(self, tmp_path):
self.Cmd.global_dir = tmp_path / "out"
self.Cmd.launcher_exe = tmp_path / "launcher.txt"
self.Cmd.launcherw_exe = tmp_path / "launcherw.txt"
self._expect_target = "target-" + secrets.token_hex(32)
self._expect = {
"-32": "-32-" + secrets.token_hex(32),
"-64": "-64-" + secrets.token_hex(32),
"-arm64": "-arm64-" + secrets.token_hex(32),
"w-32": "w-32-" + secrets.token_hex(32),
"w-64": "w-64-" + secrets.token_hex(32),
"w-arm64": "w-arm64-" + secrets.token_hex(32),
}
for k, v in self._expect.items():
(tmp_path / f"launcher{k}.txt").write_text(v)
def __enter__(self):
return self
def __exit__(self, *exc_info):
pass
def check(self, cmd, tag, name, expect, windowed=0):
IC._write_alias(
cmd,
{"tag": tag},
{"name": f"{name}.txt", "windowed": windowed},
self._expect_target,
)
print(*cmd.global_dir.glob("*"), sep="\n")
assert (cmd.global_dir / f"{name}.txt").is_file()
assert (cmd.global_dir / f"{name}.txt.__target__").is_file()
assert (cmd.global_dir / f"{name}.txt").read_text() == expect
assert (cmd.global_dir / f"{name}.txt.__target__").read_text() == self._expect_target
def check_32(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["-32"])
def check_w32(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["w-32"], windowed=1)
def check_64(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["-64"])
def check_w64(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["w-64"], windowed=1)
def check_arm64(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["-arm64"])
def check_warm64(self, cmd, tag, name):
self.check(cmd, tag, name, self._expect["w-arm64"], windowed=1)
def test_write_alias_tag_with_platform(alias_checker):
alias_checker.check_32(alias_checker.Cmd(), "1.0-32", "testA")
alias_checker.check_w32(alias_checker.Cmd(), "1.0-32", "testB")
alias_checker.check_64(alias_checker.Cmd(), "1.0-64", "testC")
alias_checker.check_w64(alias_checker.Cmd(), "1.0-64", "testD")
alias_checker.check_arm64(alias_checker.Cmd(), "1.0-arm64", "testE")
alias_checker.check_warm64(alias_checker.Cmd(), "1.0-arm64", "testF")
def test_write_alias_default_platform(alias_checker):
alias_checker.check_32(alias_checker.Cmd("-32"), "1.0", "testA")
alias_checker.check_w32(alias_checker.Cmd("-32"), "1.0", "testB")
alias_checker.check_64(alias_checker.Cmd(), "1.0", "testC")
alias_checker.check_w64(alias_checker.Cmd(), "1.0", "testD")
alias_checker.check_arm64(alias_checker.Cmd("-arm64"), "1.0", "testE")
alias_checker.check_warm64(alias_checker.Cmd("-arm64"), "1.0", "testF")
def test_write_alias_fallback_platform(alias_checker):
alias_checker.check_64(alias_checker.Cmd("-spam"), "1.0", "testA")
alias_checker.check_w64(alias_checker.Cmd("-spam"), "1.0", "testB")
def test_write_alias_launcher_missing(fake_config, assert_log, tmp_path):
fake_config.launcher_exe = tmp_path / "non-existent.exe"
fake_config.default_platform = '-32'
fake_config.global_dir = tmp_path / "bin"
IC._write_alias(
fake_config,
{"tag": "test"},
{"name": "test.exe"},
tmp_path / "target.exe",
)
assert_log(
"Checking for launcher.*",
"Checking for launcher.*",
"Checking for launcher.*",
"Create %s linking to %s",
"Skipping %s alias because the launcher template was not found.",
assert_log.end_of_log(),
)
def test_write_alias_launcher_unreadable(fake_config, assert_log, tmp_path):
class FakeLauncherPath:
stem = "test"
suffix = ".exe"
parent = tmp_path
@staticmethod
def is_file():
return True
@staticmethod
def read_bytes():
raise OSError("no reading for the test")
fake_config.scratch = {}
fake_config.launcher_exe = FakeLauncherPath
fake_config.default_platform = '-32'
fake_config.global_dir = tmp_path / "bin"
IC._write_alias(
fake_config,
{"tag": "test"},
{"name": "test.exe"},
tmp_path / "target.exe",
)
assert_log(
"Checking for launcher.*",
"Create %s linking to %s",
"Failed to read launcher template at %s\\.",
"Failed to read %s",
assert_log.end_of_log(),
)
def test_write_alias_launcher_unlinkable(fake_config, assert_log, tmp_path):
def fake_link(x, y):
raise OSError("Error for testing")
fake_config.scratch = {}
fake_config.launcher_exe = tmp_path / "launcher.txt"
fake_config.launcher_exe.write_bytes(b'Arbitrary contents')
fake_config.default_platform = '-32'
fake_config.global_dir = tmp_path / "bin"
IC._write_alias(
fake_config,
{"tag": "test"},
{"name": "test.exe"},
tmp_path / "target.exe",
_link=fake_link
)
assert_log(
"Checking for launcher.*",
"Create %s linking to %s",
"Failed to create hard link.+",
"Created %s as copy of %s",
assert_log.end_of_log(),
)
def test_write_alias_launcher_unlinkable_remap(fake_config, assert_log, tmp_path):
# This is for the fairly expected case of the PyManager install being on one
# drive, but the global commands directory being on another. In this
# situation, we can't hard link directly into the app files, and will need
# to copy. But we only need to copy once, so if a launcher_remap has been
# set (in the current process), then we have an available copy already and
# can link to that.
def fake_link(x, y):
if x.match("launcher.txt"):
raise OSError(17, "Error for testing")
fake_config.scratch = {
"install_command._write_alias.launcher_remap": {"launcher.txt": tmp_path / "actual_launcher.txt"},
}
fake_config.launcher_exe = tmp_path / "launcher.txt"
fake_config.launcher_exe.write_bytes(b'Arbitrary contents')
(tmp_path / "actual_launcher.txt").write_bytes(b'Arbitrary contents')
fake_config.default_platform = '-32'
fake_config.global_dir = tmp_path / "bin"
IC._write_alias(
fake_config,
{"tag": "test"},
{"name": "test.exe"},
tmp_path / "target.exe",
_link=fake_link
)
assert_log(
"Checking for launcher.*",
"Create %s linking to %s",
"Failed to create hard link.+",
("Created %s as hard link to %s", ("test.exe", "actual_launcher.txt")),
assert_log.end_of_log(),
)
@pytest.mark.parametrize("default", [1, 0])
def test_write_alias_default(alias_checker, monkeypatch, tmp_path, default):
prefix = Path(tmp_path) / "runtime"
class Cmd:
global_dir = Path(tmp_path) / "bin"
launcher_exe = None
scratch = {}
def get_installs(self):
return [
{
"alias": [
{"name": "python3.exe", "target": "p.exe"},
{"name": "pythonw3.exe", "target": "pw.exe", "windowed": 1},
],
"default": default,
"prefix": prefix,
}
]
prefix.mkdir(exist_ok=True, parents=True)
(prefix / "p.exe").write_bytes(b"")
(prefix / "pw.exe").write_bytes(b"")
written = []
def write_alias(*a):
written.append(a)
monkeypatch.setattr(IC, "_write_alias", write_alias)
monkeypatch.setattr(IC, "SHORTCUT_HANDLERS", {})
IC.update_all_shortcuts(Cmd())
if default:
# Main test: python.exe and pythonw.exe are added in automatically
assert sorted(w[2]["name"] for w in written) == ["python.exe", "python3.exe", "pythonw.exe", "pythonw3.exe"]
else:
assert sorted(w[2]["name"] for w in written) == ["python3.exe", "pythonw3.exe"]
# Ensure we still only have the two targets
assert set(w[3].name for w in written) == {"p.exe", "pw.exe"}
def test_print_cli_shortcuts(patched_installs, assert_log, monkeypatch, tmp_path):
class Cmd:
scratch = {}
global_dir = Path(tmp_path)
def get_installs(self):
return installs.get_installs(None)
(tmp_path / "fake.exe").write_bytes(b"")
monkeypatch.setitem(os.environ, "PATH", f"{os.environ['PATH']};{Cmd.global_dir}")
IC.print_cli_shortcuts(Cmd())
assert_log(
assert_log.skip_until("Installed %s", ["Python 2.0-64", PurePath("C:\\2.0-64")]),
assert_log.skip_until("%s will be launched by %s", ["Python 1.0-64", "py1.0[-64].exe"]),
("%s will be launched by %s", ["Python 1.0-32", "py1.0-32.exe"]),
)
def test_print_path_warning(patched_installs, assert_log, tmp_path):
class Cmd:
scratch = {}
global_dir = Path(tmp_path)
def get_installs(self):
return installs.get_installs(None)
(tmp_path / "fake.exe").write_bytes(b"")
IC.print_cli_shortcuts(Cmd())
assert_log(
assert_log.skip_until(".*Global shortcuts directory is not on PATH")
)
def test_merge_existing_index(tmp_path):
# This function is for multiple downloaded index.jsons, so it merges based
# on the url property, which should usually be a local file.
existing = tmp_path / "index.json"
with open(existing, "w", encoding="utf-8") as f:
json.dump({"versions": [
{"id": "test-1", "url": "test-file-1.zip"},
{"id": "test-2", "url": "test-file-2.zip"},
{"id": "test-3", "url": "test-file-3.zip"},
]}, f)
new = [
# Ensure new versions appear first
{"id": "test-4", "url": "test-file-4.zip"},
# Ensure matching ID doesn't result in overwrite
{"id": "test-1", "url": "test-file-1b.zip"},
# Ensure matching URL excludes original entry
{"id": "test-2b", "url": "test-file-2.zip"},
]
IC._merge_existing_index(new, existing)
assert new == [
{"id": "test-4", "url": "test-file-4.zip"},
{"id": "test-1", "url": "test-file-1b.zip"},
{"id": "test-2b", "url": "test-file-2.zip"},
{"id": "test-1", "url": "test-file-1.zip"},
{"id": "test-3", "url": "test-file-3.zip"},
]
def test_merge_existing_index_not_found(tmp_path):
existing = tmp_path / "index.json"
try:
existing.unlink()
except FileNotFoundError:
pass
# Expect no failure and no change
new = [1, 2, 3]
IC._merge_existing_index(new, existing)
assert new == [1, 2, 3]
def test_merge_existing_index_not_valid(tmp_path):
existing = tmp_path / "index.json"
with open(existing, "w", encoding="utf-8") as f:
print("It's not a list of installs", file=f)
print("But more importantly,", file=f)
print("it's not valid JSON!", file=f)
# Expect no failure and no change
new = [1, 2, 3]
IC._merge_existing_index(new, existing)
assert new == [1, 2, 3]
def test_preserve_site(tmp_path):
root = tmp_path / "root"
preserved = tmp_path / "_root"
site = root / "site-packages"
not_site = root / "site-not-packages"
A = site / "A"
B = site / "B.txt"
C = site / "C.txt"
A.mkdir(parents=True, exist_ok=True)
B.write_bytes(b"")
C.write_bytes(b"original")
class Cmd:
preserve_site_on_upgrade = False
force = False
repair = False
state = IC._preserve_site(Cmd, root)
assert not state
assert not preserved.exists()
Cmd.preserve_site_on_upgrade = True
Cmd.force = True
state = IC._preserve_site(Cmd, root)
assert not state
assert not preserved.exists()
Cmd.force = False
Cmd.repair = True
state = IC._preserve_site(Cmd, root)
assert not state
assert not preserved.exists()
Cmd.repair = False
state = IC._preserve_site(Cmd, root)
assert state == [(site, preserved / "0"), (None, preserved)]
assert preserved.is_dir()
root.rename(root.parent / "ex_root_1")
IC._restore_site(Cmd, state)
assert root.is_dir()
assert A.is_dir()
assert B.is_file()
assert C.is_file()
assert b"original" == C.read_bytes()
assert not preserved.exists()
state = IC._preserve_site(Cmd, root)
assert state == [(site, preserved / "0"), (None, preserved)]
assert not C.exists()
C.parent.mkdir(parents=True, exist_ok=True)
C.write_bytes(b"updated")
IC._restore_site(Cmd, state)
assert A.is_dir()
assert B.is_file()
assert C.is_file()
assert b"updated" == C.read_bytes()
assert not preserved.exists()