-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathtest_viewsGenerationSystem.py
More file actions
372 lines (342 loc) · 12 KB
/
test_viewsGenerationSystem.py
File metadata and controls
372 lines (342 loc) · 12 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
# Copyright (C) 2021-2026 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html
"""
Runs the dataView generation system on test data.
Creates a number of specific scenarios for running the transformation.
"""
from dataclasses import dataclass
from enum import Enum
import json
import glob
from logging import getLogger
import os
from pathlib import Path
import re
import shutil
import textwrap
from src.transform.datastructures import MajorMinorPatch
import subprocess
import unittest
log = getLogger()
versionNumRegex = re.compile(r"([0-9]+)\.([0-9]+)\.([0-9]+)")
TRANSFORM_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
class DATA_DIR(str, Enum):
ROOT = os.path.join(os.path.dirname(__file__), "test_data")
INPUT = os.path.join(ROOT, "input")
OUTPUT = os.path.join(ROOT, "output")
nvdaAPIVersionsPath = os.path.join(TRANSFORM_ROOT, "nvdaAPIVersions.json")
@dataclass
class InputAddonVersion:
path: str
addonDataBlob: str
@dataclass
class ExpectedAddonVersion:
path: str
addonVersion: str
targetPath: str | None = None
def addonJson(path: str, channel: str, *, required: str, tested: str) -> InputAddonVersion:
"""
path should be of the form: `addonName/addonVersionString.json`, eg `nvdaOcr/13.1.0.json`
All version strings should be of the form major.minor.patch.
required is the minNVDAVersion as a version string
tested is the lastTestedVersion as a version string
"""
pathRegex = re.compile(r"^(?P<addonId>[A-Za-z0-9]+)/(?P<version>[0-9]+\.[0-9]+\.[0-9]+)\.json$")
pathMatch = pathRegex.match(path)
if pathMatch is None:
raise ValueError(f"Invalid addon path format: {path}")
addonId = pathMatch.group("addonId")
addonVersionStr = pathMatch.group("version")
addonVersion = versionNumRegex.match(addonVersionStr)
minVersion = versionNumRegex.match(required)
testedVersion = versionNumRegex.match(tested)
if addonVersion is None:
raise ValueError(f"Invalid addon version format: {addonVersionStr}")
if minVersion is None:
raise ValueError(f"Invalid required version format: {required}")
if testedVersion is None:
raise ValueError(f"Invalid tested version format: {tested}")
return InputAddonVersion(
path,
f'''
{{
"addonId": "{addonId}",
"channel": "{channel}",
"addonVersionNumber": {{
"major": {addonVersion.group(1)},
"minor": {addonVersion.group(2)},
"patch": {addonVersion.group(3)}
}},
"minNVDAVersion": {{
"major": {minVersion.group(1)},
"minor": {minVersion.group(2)},
"patch": {minVersion.group(3)}
}},
"lastTestedVersion": {{
"major": {testedVersion.group(1)},
"minor": {testedVersion.group(2)},
"patch": {testedVersion.group(3)}
}}
}}\n''',
)
def write_addons(*addons: InputAddonVersion):
"""Write mock addon data to the input directory.
Arguments should be tuples of the form (path, addonDataBlob)"""
for addon in addons:
addonWritePath = os.path.join(DATA_DIR.INPUT.value, addon.path)
Path(os.path.dirname(addonWritePath)).mkdir(parents=True, exist_ok=True)
with open(addonWritePath, "w", encoding="utf-8") as addonFile:
addonFile.write(addon.addonDataBlob)
class TestTransformation(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Empty the test data before the start of tests"""
if Path(DATA_DIR.ROOT.value).exists():
shutil.rmtree(DATA_DIR.ROOT.value)
def tearDown(self):
"""Empty the test data after each test"""
if Path(DATA_DIR.ROOT.value).exists():
shutil.rmtree(DATA_DIR.ROOT.value)
def runTransformation(self, *, expectFailure: bool = False) -> subprocess.CompletedProcess[bytes]:
"""
Runs the transformation.
When expectFailure is False, raises AssertionError with rich diagnostics on failure.
When expectFailure is True, raises CalledProcessError on failure.
"""
command = (
f"python -m src.transform {DATA_DIR.nvdaAPIVersionsPath.value}"
f" {DATA_DIR.INPUT.value} {DATA_DIR.OUTPUT.value}"
)
transformProcess = subprocess.run(
command,
shell=True,
cwd=TRANSFORM_ROOT,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if transformProcess.returncode != 0:
stdout = (transformProcess.stdout or b"").decode("utf-8", errors="replace")
stderr = (transformProcess.stderr or b"").decode("utf-8", errors="replace")
debugContext = textwrap.dedent(
f"""
--- transform subprocess debug ---
exitCode: {transformProcess.returncode}
cwd: {TRANSFORM_ROOT}
command: {command}
nvdaAPIVersionsPath: {DATA_DIR.nvdaAPIVersionsPath.value}
inputPath: {DATA_DIR.INPUT.value}
outputPath: {DATA_DIR.OUTPUT.value}
stdout:
{stdout}
stderr:
{stderr}
--- end transform subprocess debug ---
""",
)
if expectFailure:
raise subprocess.CalledProcessError(
transformProcess.returncode,
command,
output=transformProcess.stdout,
stderr=transformProcess.stderr,
)
raise AssertionError(debugContext)
return transformProcess
def test_transform_empty(self):
"""Confirms an empty transformation exits with a zero exit code (successful)."""
self.runTransformation()
def test_transform_successfully(self):
"""Confirms a transformation of a single addon exits with a zero exit code (successful)."""
write_addons(addonJson("foo/0.1.1.json", "stable", required="2020.1.0", tested="2020.1.0"))
self.runTransformation()
def test_throw_error_on_nonempty_output_folder(self):
"""Confirms using an existing output directory throws an error"""
# Make the folder before transform
Path(DATA_DIR.OUTPUT.value).mkdir(parents=True, exist_ok=True)
with self.assertRaises(subprocess.CalledProcessError) as transformError:
self.runTransformation(expectFailure=True)
doubleEscapedDir = DATA_DIR.OUTPUT.value.replace(
"\\",
"\\\\",
) # stderr escapes all the backslashes twice
self.assertIn(
"FileExistsError: [WinError 183] Cannot create a file when that file already exists: "
f"'{doubleEscapedDir}'",
# requires that runTransformation and child processes log errors to stderr
transformError.exception.stderr.decode("utf-8"),
)
def _assertAddonDataWritten(self, *expectedAddons: ExpectedAddonVersion):
"""Confirms that an addon is written to a path and the file contains an expected version.
Arguments should be tuples of the form (expectedPathToAddon, expectedAddonVersionStr)"""
self.assertEqual(
len(glob.glob(f"{DATA_DIR.OUTPUT.value}/**/**.json", recursive=True)),
len(expectedAddons),
)
for expectedAddon in expectedAddons:
fullPathToAddon = os.path.join(DATA_DIR.OUTPUT.value, expectedAddon.path)
self.assertTrue(Path(fullPathToAddon).exists())
if expectedAddon.targetPath is not None:
targetPath = os.path.join(DATA_DIR.OUTPUT.value, expectedAddon.targetPath)
self.assertTrue(os.path.islink(fullPathToAddon))
self.assertEqual(
os.path.normpath(os.path.realpath(fullPathToAddon)),
os.path.normpath(os.path.realpath(targetPath)),
)
with open(fullPathToAddon, "r") as expectedAddonFile:
addonData = json.load(expectedAddonFile)
addonVersion = MajorMinorPatch(**addonData["addonVersionNumber"])
self.assertEqual(expectedAddon.addonVersion, str(addonVersion))
def test_output_file_structure_matches_expected(self):
"""Confirms that a transform of multiple addon versions is written as expected.
Cases include:
- Multiple addons
- Multiple NVDA API versions
- A beta addon
- A newer version of an addon which overrides an older version for the same NVDA API version
"""
write_addons(
addonJson("oldNewAddon/2.1.0.json", "stable", required="2020.2.0", tested="2020.3.0"),
addonJson("oldNewAddon/13.0.0.json", "stable", required="2020.3.0", tested="2020.4.0"),
addonJson("betaStableAddon/0.0.1.json", "stable", required="2020.4.0", tested="2020.4.0"),
addonJson("betaStableAddon/0.0.2.json", "beta", required="2020.4.0", tested="2020.4.0"),
)
self.runTransformation()
self._assertAddonDataWritten(
ExpectedAddonVersion("addons/oldNewAddon/2.1.0/en.json", "2.1.0"),
ExpectedAddonVersion("addons/oldNewAddon/13.0.0/en.json", "13.0.0"),
ExpectedAddonVersion("addons/betaStableAddon/0.0.1/en.json", "0.0.1"),
ExpectedAddonVersion("addons/betaStableAddon/0.0.2/en.json", "0.0.2"),
ExpectedAddonVersion(
"views/en/2020.2.0/oldNewAddon/stable.json",
"2.1.0",
targetPath="addons/oldNewAddon/2.1.0/en.json",
),
ExpectedAddonVersion(
"views/en/2020.3.0/oldNewAddon/stable.json",
"13.0.0",
targetPath="addons/oldNewAddon/13.0.0/en.json",
),
ExpectedAddonVersion(
"views/en/2020.4.0/oldNewAddon/stable.json",
"13.0.0",
targetPath="addons/oldNewAddon/13.0.0/en.json",
),
ExpectedAddonVersion(
"views/en/2020.4.0/betaStableAddon/stable.json",
"0.0.1",
targetPath="addons/betaStableAddon/0.0.1/en.json",
),
ExpectedAddonVersion(
"views/en/2020.4.0/betaStableAddon/beta.json",
"0.0.2",
targetPath="addons/betaStableAddon/0.0.2/en.json",
),
ExpectedAddonVersion(
"views/en/latest/betaStableAddon/beta.json",
"0.0.2",
targetPath="addons/betaStableAddon/0.0.2/en.json",
),
ExpectedAddonVersion(
"views/en/latest/betaStableAddon/stable.json",
"0.0.1",
targetPath="addons/betaStableAddon/0.0.1/en.json",
),
ExpectedAddonVersion(
"views/en/latest/oldNewAddon/stable.json",
"13.0.0",
targetPath="addons/oldNewAddon/13.0.0/en.json",
),
)
def test_translation_view_symlink_points_to_translated_addon_data(self):
"""Confirms language-specific views symlink to translated addon data files."""
write_addons(
InputAddonVersion(
"UIANotificationSwitch/2026.1.0.json",
"""
{
"addonId": "UIANotificationSwitch",
"displayName": "UIA Notification Switch",
"description": "English description",
"channel": "stable",
"addonVersionNumber": {
"major": 2026,
"minor": 1,
"patch": 0
},
"minNVDAVersion": {
"major": 2019,
"minor": 1,
"patch": 0
},
"lastTestedVersion": {
"major": 2019,
"minor": 1,
"patch": 0
},
"translations": [
{
"language": "ar",
"displayName": "مفتاح إشعارات UIA",
"description": "وصف عربي"
}
]
}
""",
),
)
self.runTransformation()
self._assertAddonDataWritten(
ExpectedAddonVersion("addons/UIANotificationSwitch/2026.1.0/en.json", "2026.1.0"),
ExpectedAddonVersion("addons/UIANotificationSwitch/2026.1.0/ar.json", "2026.1.0"),
ExpectedAddonVersion(
"views/ar/2019.1.0/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/ar.json",
),
ExpectedAddonVersion(
"views/ar/2019.1.1/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/ar.json",
),
ExpectedAddonVersion(
"views/ar/2019.2.0/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/ar.json",
),
ExpectedAddonVersion(
"views/ar/2019.2.1/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/ar.json",
),
ExpectedAddonVersion(
"views/ar/latest/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/ar.json",
),
ExpectedAddonVersion(
"views/en/2019.1.0/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/en.json",
),
ExpectedAddonVersion(
"views/en/2019.1.1/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/en.json",
),
ExpectedAddonVersion(
"views/en/2019.2.0/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/en.json",
),
ExpectedAddonVersion(
"views/en/2019.2.1/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/en.json",
),
ExpectedAddonVersion(
"views/en/latest/UIANotificationSwitch/stable.json",
"2026.1.0",
targetPath="addons/UIANotificationSwitch/2026.1.0/en.json",
),
)