manifestparser 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,543 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ """
6
+ A filter is a callable that accepts an iterable of test objects and a
7
+ dictionary of values, and returns a new iterable of test objects. It is
8
+ possible to define custom filters if the built-in ones are not enough.
9
+ """
10
+
11
+ import functools
12
+ import itertools
13
+ import os
14
+ from bisect import bisect_left
15
+ from collections import defaultdict
16
+ from collections.abc import MutableSequence
17
+
18
+ from .expression import ParseError, parse
19
+ from .logger import Logger
20
+ from .util import norm_needed, normsep
21
+
22
+ # built-in filters
23
+
24
+
25
+ @functools.cache
26
+ def _match(exprs, strict, **values):
27
+ """Return the first matching expression, or None if no match."""
28
+ for e in exprs.splitlines():
29
+ if e and parse(e, strict=strict, **values):
30
+ return e
31
+ return None
32
+
33
+
34
+ def skip_if(tests, values, strict=False):
35
+ """
36
+ Sets disabled on all tests containing the `skip-if` tag and whose condition
37
+ is True. This filter is added by default.
38
+ """
39
+ for test in tests:
40
+ test_tag = test.get("skip-if")
41
+ if test_tag:
42
+ matching_expr = _match(test_tag, strict, **values)
43
+ if matching_expr:
44
+ test.setdefault("disabled", f"skip-if: {matching_expr}")
45
+ yield test
46
+
47
+
48
+ def run_if(tests, values, strict=False):
49
+ """
50
+ Sets disabled on all tests containing the `run-if` tag and whose condition
51
+ is False. This filter is added by default.
52
+ """
53
+ tag = "run-if"
54
+ for test in tests:
55
+ if tag in test and not _match(test[tag], strict, **values):
56
+ # For run-if, show all conditions since none of them matched
57
+ test.setdefault("disabled", f"{tag}: {test[tag]}")
58
+ yield test
59
+
60
+
61
+ def fail_if(tests, values, strict=False):
62
+ """
63
+ Sets expected to 'fail' on all tests containing the `fail-if` tag and whose
64
+ condition is True. This filter is added by default.
65
+ """
66
+ tag = "fail-if"
67
+ for test in tests:
68
+ if tag in test and _match(test[tag], strict, **values):
69
+ test["expected"] = "fail"
70
+ yield test
71
+
72
+
73
+ def enabled(tests, values, strict=False):
74
+ """
75
+ Removes all tests containing the `disabled` key. This filter can be
76
+ added by passing `disabled=False` into `active_tests`.
77
+ """
78
+ for test in tests:
79
+ if "disabled" not in test:
80
+ yield test
81
+
82
+
83
+ def exists(tests, values, strict=False):
84
+ """
85
+ Removes all tests that do not exist on the file system. This filter is
86
+ added by default, but can be removed by passing `exists=False` into
87
+ `active_tests`.
88
+ """
89
+ for test in tests:
90
+ if os.path.exists(test["path"]):
91
+ yield test
92
+
93
+
94
+ # built-in instance filters
95
+
96
+
97
+ class InstanceFilter:
98
+ """
99
+ Generally only one instance of a class filter should be applied at a time.
100
+ Two instances of `InstanceFilter` are considered equal if they have the
101
+ same class name. This ensures only a single instance is ever added to
102
+ `filterlist`. This class also formats filters' __str__ method for easier
103
+ debugging.
104
+ """
105
+
106
+ unique = True
107
+
108
+ __hash__ = super.__hash__
109
+
110
+ def __init__(self, *args, **kwargs):
111
+ self.fmt_args = ", ".join(
112
+ itertools.chain(
113
+ [str(a) for a in args],
114
+ [f"{k}={v}" for k, v in kwargs.items()],
115
+ )
116
+ )
117
+
118
+ def __eq__(self, other):
119
+ if self.unique:
120
+ return self.__class__ == other.__class__
121
+ return self.__hash__() == other.__hash__()
122
+
123
+ def __str__(self):
124
+ return f"{self.__class__.__name__}({self.fmt_args})"
125
+
126
+
127
+ class subsuite(InstanceFilter):
128
+ """
129
+ If `name` is None, removes all tests that have a `subsuite` key.
130
+ Otherwise removes all tests that do not have a subsuite matching `name`.
131
+
132
+ It is possible to specify conditional subsuite keys using:
133
+ subsuite = foo,condition
134
+
135
+ where 'foo' is the subsuite name, and 'condition' is the same type of
136
+ condition used for skip-if. If the condition doesn't evaluate to true,
137
+ the subsuite designation will be removed from the test.
138
+
139
+ :param name: The name of the subsuite to run (default None)
140
+ """
141
+
142
+ def __init__(self, name=None):
143
+ InstanceFilter.__init__(self, name=name)
144
+ self.name = name
145
+
146
+ def __call__(self, tests, values, strict=False):
147
+ # Look for conditional subsuites, and replace them with the subsuite
148
+ # itself (if the condition is true), or nothing.
149
+ for test in tests:
150
+ subsuite = test.get("subsuite", "")
151
+ if "," in subsuite:
152
+ try:
153
+ subsuite, cond = subsuite.split(",")
154
+ except ValueError:
155
+ raise ParseError("subsuite condition can't contain commas")
156
+ matched = parse(cond, strict, **values)
157
+ if matched:
158
+ test["subsuite"] = subsuite
159
+ else:
160
+ test["subsuite"] = ""
161
+
162
+ # Filter on current subsuite
163
+ if self.name is None:
164
+ if not test.get("subsuite"):
165
+ yield test
166
+ elif test.get("subsuite", "") == self.name:
167
+ yield test
168
+
169
+
170
+ class chunk_by_dir(InstanceFilter):
171
+ """
172
+ Basic chunking algorithm that splits directories of tests evenly at a
173
+ given depth.
174
+
175
+ For example, a depth of 2 means all test directories two path nodes away
176
+ from the base are gathered, then split evenly across the total number of
177
+ chunks. The number of tests in each of the directories is not taken into
178
+ account (so chunks will not contain an even number of tests). All test
179
+ paths must be relative to the same root (typically the root of the source
180
+ repository).
181
+
182
+ :param this_chunk: the current chunk, 1 <= this_chunk <= total_chunks
183
+ :param total_chunks: the total number of chunks
184
+ :param depth: the minimum depth of a subdirectory before it will be
185
+ considered unique
186
+ """
187
+
188
+ def __init__(self, this_chunk, total_chunks, depth):
189
+ InstanceFilter.__init__(self, this_chunk, total_chunks, depth)
190
+ self.this_chunk = this_chunk
191
+ self.total_chunks = total_chunks
192
+ self.depth = depth
193
+
194
+ def __call__(self, tests, values, strict=False):
195
+ tests_by_dir = defaultdict(list)
196
+ ordered_dirs = []
197
+ for test in tests:
198
+ path = test["relpath"]
199
+
200
+ if path.startswith(os.sep):
201
+ path = path[1:]
202
+
203
+ dirs = path.split(os.sep)
204
+ dirs = dirs[: min(self.depth, len(dirs) - 1)]
205
+ path = os.sep.join(dirs)
206
+
207
+ # don't count directories that only have disabled tests in them,
208
+ # but still yield disabled tests that are alongside enabled tests
209
+ if path not in ordered_dirs and "disabled" not in test:
210
+ ordered_dirs.append(path)
211
+ tests_by_dir[path].append(test)
212
+
213
+ # pylint: disable=W1633
214
+ tests_per_chunk = float(len(ordered_dirs)) / self.total_chunks
215
+ start = int(round((self.this_chunk - 1) * tests_per_chunk))
216
+ end = int(round(self.this_chunk * tests_per_chunk))
217
+
218
+ for i in range(start, end):
219
+ for test in tests_by_dir.pop(ordered_dirs[i]):
220
+ yield test
221
+
222
+ # find directories that only contain disabled tests. They still need to
223
+ # be yielded for reporting purposes. Put them all in chunk 1 for
224
+ # simplicity.
225
+ if self.this_chunk == 1:
226
+ disabled_dirs = [
227
+ v for k, v in tests_by_dir.items() if k not in ordered_dirs
228
+ ]
229
+ yield from itertools.chain(*disabled_dirs)
230
+
231
+
232
+ class chunk_by_manifest(InstanceFilter):
233
+ """
234
+ Chunking algorithm that tries to evenly distribute tests while ensuring
235
+ tests in the same manifest stay together.
236
+
237
+ :param this_chunk: the current chunk, 1 <= this_chunk <= total_chunks
238
+ :param total_chunks: the total number of chunks
239
+ """
240
+
241
+ def __init__(self, this_chunk, total_chunks, *args, **kwargs):
242
+ InstanceFilter.__init__(self, this_chunk, total_chunks, *args, **kwargs)
243
+ self.this_chunk = this_chunk
244
+ self.total_chunks = total_chunks
245
+
246
+ def __call__(self, tests, values, strict=False):
247
+ tests = list(tests)
248
+ manifests = set(t["manifest"] for t in tests)
249
+
250
+ tests_by_manifest = []
251
+ for manifest in manifests:
252
+ mtests = [t for t in tests if t["manifest"] == manifest]
253
+ tests_by_manifest.append(mtests)
254
+ # Sort tests_by_manifest from largest manifest to shortest; include
255
+ # manifest name as secondary key to ensure consistent order across
256
+ # multiple runs.
257
+ tests_by_manifest.sort(reverse=True, key=lambda x: (len(x), x[0]["manifest"]))
258
+
259
+ tests_by_chunk = [[] for i in range(self.total_chunks)]
260
+ for batch in tests_by_manifest:
261
+ # Sort to guarantee the chunk with the lowest score will always
262
+ # get the next batch of tests.
263
+ tests_by_chunk.sort(
264
+ key=lambda x: (len(x), x[0]["manifest"] if len(x) else "")
265
+ )
266
+ tests_by_chunk[0].extend(batch)
267
+
268
+ return (t for t in tests_by_chunk[self.this_chunk - 1])
269
+
270
+
271
+ class chunk_by_runtime(InstanceFilter):
272
+ """
273
+ Chunking algorithm that attempts to group tests into chunks based on their
274
+ average runtimes. It keeps manifests of tests together and pairs slow
275
+ running manifests with fast ones.
276
+
277
+ :param this_chunk: the current chunk, 1 <= this_chunk <= total_chunks
278
+ :param total_chunks: the total number of chunks
279
+ :param runtimes: dictionary of manifest runtime data, of the form
280
+ {<manifest path>: <average runtime>}
281
+ """
282
+
283
+ def __init__(self, this_chunk, total_chunks, runtimes):
284
+ InstanceFilter.__init__(self, this_chunk, total_chunks, runtimes)
285
+ self.this_chunk = this_chunk
286
+ self.total_chunks = total_chunks
287
+ self.runtimes = {normsep(m): r for m, r in runtimes.items()}
288
+ self.logger = Logger()
289
+
290
+ # NOTE: get_manifest is called a lot, so we 'inline' normsep when it's
291
+ # profitable.
292
+ if norm_needed:
293
+
294
+ @staticmethod
295
+ def get_manifest(test):
296
+ manifest = normsep(test.get("ancestor_manifest", ""))
297
+
298
+ # Ignore ancestor_manifests that live at the root (e.g, don't have a
299
+ # path separator). The only time this should happen is when they are
300
+ # generated by the build system and we shouldn't count generated
301
+ # manifests for chunking purposes.
302
+ if not manifest or "/" not in manifest:
303
+ manifest = normsep(test["manifest_relpath"])
304
+ return manifest
305
+
306
+ else:
307
+
308
+ @staticmethod
309
+ def get_manifest(test):
310
+ manifest = test.get("ancestor_manifest")
311
+ return (
312
+ manifest if manifest and "/" in manifest else test["manifest_relpath"]
313
+ )
314
+
315
+ def get_chunked_manifests(self, manifests):
316
+ # Find runtimes for all relevant manifests.
317
+ runtimes = [(self.runtimes[m], m) for m in manifests if m in self.runtimes]
318
+
319
+ if len(runtimes) != len(self.runtimes):
320
+ # Compute the average to use as a default for manifests that don't exist.
321
+ times = [r[0] for r in runtimes]
322
+ # pylint --py3k W1619
323
+ # pylint: disable=W1633
324
+ avg = round(sum(times) / len(times), 2) if times else 0
325
+
326
+ missing = sorted([m for m in manifests if m not in self.runtimes])
327
+ self.logger.debug(
328
+ "Applying average runtime of {}s to the following missing manifests:\n{}".format(
329
+ avg, " " + "\n ".join(missing)
330
+ )
331
+ )
332
+ runtimes.extend([(avg, m) for m in missing])
333
+
334
+ # Each chunk is of the form [<runtime>, <manifests>].
335
+ chunks = [[0, []] for i in range(self.total_chunks)]
336
+
337
+ def key(x):
338
+ return (x[0], len(x[1]))
339
+
340
+ # Sort runtimes from slowest -> fastest.
341
+ for runtime, manifest in sorted(runtimes, reverse=True):
342
+ # Sort chunks from fastest -> slowest. This guarantees the fastest
343
+ # chunk will be assigned the slowest remaining manifest.
344
+ chunk0 = chunks[0]
345
+ chunk0[0] += runtime
346
+ chunk0[1].append(manifest)
347
+
348
+ # find location that would keep chunks sorted
349
+ insertion_point = bisect_left(chunks, key(chunk0), lo=1, key=key)
350
+
351
+ # To keep chunks sorted, we need to move from
352
+ # [c_0, c_1, ... c_n]
353
+ # to
354
+ # [c_1, ..., c_{insertion_point - 1}, c_0, c_{insertion_point}, ... c_n]
355
+ #
356
+ # Do this while avoiding reallocating pieces of the underlying list
357
+ # by rotating-left the first `insertion_point' elements.
358
+ for i in range(insertion_point - 1):
359
+ chunks[i] = chunks[i + 1]
360
+ chunks[insertion_point - 1] = chunk0
361
+
362
+ return chunks
363
+
364
+ def __call__(self, tests, values, strict=False):
365
+ tests = list(tests)
366
+ manifests = set(self.get_manifest(t) for t in tests)
367
+ chunks = self.get_chunked_manifests(manifests)
368
+ runtime, this_manifests = chunks[self.this_chunk - 1]
369
+ # pylint --py3k W1619
370
+ # pylint: disable=W1633
371
+ self.logger.debug(
372
+ f"Cumulative test runtime is around {round(runtime / 60)} minutes (average is {round(sum([c[0] for c in chunks]) / (60 * len(chunks)))} minutes)"
373
+ )
374
+ return (t for t in tests if self.get_manifest(t) in this_manifests)
375
+
376
+
377
+ class tags(InstanceFilter):
378
+ """
379
+ Removes tests that don't contain any of the given tags. This overrides
380
+ InstanceFilter's __eq__ method, so multiple instances can be added.
381
+ Multiple tag filters is equivalent to joining tags with the AND operator.
382
+
383
+ To define a tag in a manifest, add a `tags` attribute to a test or DEFAULT
384
+ section. Tests can have multiple tags, in which case they should be
385
+ whitespace delimited. For example:
386
+
387
+ .. code-block:: toml
388
+
389
+ ['test_foobar.html']
390
+ tags = 'foo bar'
391
+
392
+ :param tags: A tag or list of tags to filter tests on
393
+ """
394
+
395
+ unique = False
396
+
397
+ def __init__(self, tags):
398
+ InstanceFilter.__init__(self, tags)
399
+ if isinstance(tags, str):
400
+ tags = [tags]
401
+ self.tags = tags
402
+
403
+ def __call__(self, tests, values, strict=False):
404
+ for test in tests:
405
+ if "tags" not in test:
406
+ continue
407
+
408
+ test_tags = [t.strip() for t in test["tags"].split()]
409
+ if any(t in self.tags for t in test_tags):
410
+ yield test
411
+
412
+
413
+ class failures(InstanceFilter):
414
+ """
415
+ .. code-block:: toml
416
+
417
+ ['test_fooar.html']
418
+ fail-if = [
419
+ "keyword", # <comment>
420
+ ]
421
+
422
+ :param keywords: A keyword to filter tests on
423
+ """
424
+
425
+ def __init__(self, keyword):
426
+ InstanceFilter.__init__(self, keyword)
427
+ self.keyword = keyword.strip('"')
428
+
429
+ def __call__(self, tests, values, strict=False):
430
+ for test in tests:
431
+ for key in ["skip-if", "fail-if"]:
432
+ if key not in test:
433
+ continue
434
+
435
+ matched = [
436
+ self.keyword in e and parse(e, strict, **values)
437
+ for e in test[key].splitlines()
438
+ if e
439
+ ]
440
+ if any(matched):
441
+ test["expected"] = "fail"
442
+ yield test
443
+
444
+
445
+ class pathprefix(InstanceFilter):
446
+ """
447
+ Removes tests that don't start with any of the given test paths.
448
+
449
+ :param paths: A list of test paths (or manifests) to filter on
450
+ """
451
+
452
+ def __init__(self, paths):
453
+ InstanceFilter.__init__(self, paths)
454
+ if isinstance(paths, str):
455
+ paths = [paths]
456
+ self.paths = paths
457
+ self.missing = set()
458
+
459
+ def __call__(self, tests, values, strict=False):
460
+ seen = set()
461
+ for test in tests:
462
+ for testpath in self.paths:
463
+ tp = os.path.normpath(testpath)
464
+
465
+ if tp.endswith(".ini") or tp.endswith(".toml"):
466
+ mpaths = [test["manifest_relpath"]]
467
+ if "ancestor_manifest" in test:
468
+ mpaths.append(test["ancestor_manifest"])
469
+
470
+ if os.path.isabs(tp):
471
+ root = test["manifest"][: -len(test["manifest_relpath"]) - 1]
472
+ mpaths = [os.path.join(root, m) for m in mpaths]
473
+
474
+ # only return tests that are in this manifest
475
+ if not any(os.path.normpath(m) == tp for m in mpaths):
476
+ continue
477
+ else:
478
+ # only return tests that start with this path
479
+ path = test["relpath"]
480
+ if os.path.isabs(tp):
481
+ path = test["path"]
482
+
483
+ if not os.path.normpath(path).startswith(tp):
484
+ continue
485
+
486
+ # any test path that points to a single file will be run no
487
+ # matter what, even if it's disabled
488
+ if "disabled" in test and os.path.normpath(test["relpath"]) == tp:
489
+ del test["disabled"]
490
+
491
+ seen.add(testpath)
492
+ yield test
493
+ break
494
+
495
+ self.missing = set(self.paths) - seen
496
+
497
+
498
+ # filter container
499
+
500
+ DEFAULT_FILTERS = (
501
+ skip_if,
502
+ run_if,
503
+ fail_if,
504
+ )
505
+ """
506
+ By default :func:`~.active_tests` will run the :func:`~.skip_if`,
507
+ :func:`~.run_if` and :func:`~.fail_if` filters.
508
+ """
509
+
510
+
511
+ class filterlist(MutableSequence):
512
+ """
513
+ A MutableSequence that raises TypeError when adding a non-callable and
514
+ ValueError if the item is already added.
515
+ """
516
+
517
+ def __init__(self, items=None):
518
+ self.items = []
519
+ if items:
520
+ self.items = list(items)
521
+
522
+ def _validate(self, item):
523
+ if not callable(item):
524
+ raise TypeError("Filters must be callable!")
525
+ if item in self:
526
+ raise ValueError(f"Filter {item} is already applied!")
527
+
528
+ def __getitem__(self, key):
529
+ return self.items[key]
530
+
531
+ def __setitem__(self, key, value):
532
+ self._validate(value)
533
+ self.items[key] = value
534
+
535
+ def __delitem__(self, key):
536
+ del self.items[key]
537
+
538
+ def __len__(self):
539
+ return len(self.items)
540
+
541
+ def insert(self, index, value):
542
+ self._validate(value)
543
+ self.items.insert(index, value)