auto-optimize 1.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.
Files changed (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,779 @@
1
+ #!/usr/bin/env python3
2
+ """The tables the unit-test PR's body is rendered from.
3
+
4
+ python3 tests_pr_tables.py collection --collect-output collect.txt --root SUITE --out DIR
5
+ python3 tests_pr_tables.py files --repo SUITE --base COMMIT --head BRANCH --out DIR
6
+ python3 tests_pr_tables.py coverage --existing 'make test=base.json' --suite suite.json --out DIR
7
+ python3 tests_pr_tables.py names --source pkg --tests tests --out DIR
8
+
9
+ Each subcommand reads what step 1's runs left (pytest's collection, git,
10
+ gcovr or coverage.py JSON, the package's source) and writes a tab-separated
11
+ table, with a header line, into the folder DIR, `$WORK/ship/pr-tests`.
12
+ `tests_pr_body.py DIR` renders the body from them and from one prose file.
13
+ Every format, and which section each table feeds, is in
14
+ references/pr-tests.md; `--help` has every flag.
15
+
16
+ Standard library only, Python 3.9 or later. The same inputs give the same
17
+ tables, byte for byte.
18
+ """
19
+
20
+ import os
21
+ import re
22
+ import ast
23
+ import sys
24
+ import json
25
+ import fnmatch
26
+ import argparse
27
+ import subprocess
28
+
29
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
30
+
31
+ import publish
32
+
33
+
34
+ # How a test function says it records the current output rather than a
35
+ # derived value (references/step1-unit-tests.md, *Where expected values come
36
+ # from*): "pins the current output", "pin the current values", "pins current
37
+ # behaviour". Searched in the function's source: its docstring and comments.
38
+ MARKER = r'\bpins?\b(?:\W+\w+){0,6}?\W+current\b'
39
+
40
+ # Parts per file up to this many source files, per directory above it
41
+ # (references/step1-unit-tests.md, *Report its coverage*).
42
+ PARTS_PER_FILE = 30
43
+
44
+ FOLDER = '$WORK/ship/pr-tests'
45
+
46
+
47
+ def fail(message):
48
+ publish.fail('tests_pr_tables', message)
49
+
50
+
51
+ def note(message):
52
+ sys.stderr.write('tests_pr_tables: {}\n'.format(message))
53
+
54
+
55
+ def clean(value):
56
+ """A table cell: tabs and line breaks would split the row."""
57
+
58
+ return re.sub(r'[\t\r\n]+', ' ', str(value))
59
+
60
+
61
+ def write_tsv(directory, name, header, rows):
62
+ """Replace `directory/name` with the table, whole or not at all."""
63
+
64
+ os.makedirs(directory, exist_ok=True)
65
+ path = os.path.join(directory, name)
66
+ publish.write(path, '\t'.join(header) + '\n' + ''.join('\t'.join(clean(
67
+ value) for value in row) + '\n' for row in rows))
68
+
69
+ return path
70
+
71
+
72
+ def read_tsv(path, required):
73
+ """Rows of a tab-separated file with a header, as dicts; refuses a
74
+ missing column or a row of the wrong width."""
75
+
76
+ try:
77
+ with open(path, encoding='utf-8') as infile:
78
+ lines = [line.rstrip('\r\n') for line in infile]
79
+ except OSError as error:
80
+ fail('could not read {}: {}'.format(path, error))
81
+
82
+ lines = [line for line in lines if line.strip()
83
+ and not line.lstrip().startswith('#')]
84
+
85
+ if not lines:
86
+ fail('{} is empty: it needs a header line ({})'.format(path,
87
+ '\t'.join(required)))
88
+
89
+ header = [field.strip() for field in lines[0].split('\t')]
90
+ missing = [column for column in required if column not in header]
91
+
92
+ if missing:
93
+ fail('{} has no {} column: the header is tab-separated and holds {}'
94
+ .format(path, ', '.join(missing), ', '.join(required)))
95
+
96
+ rows = []
97
+
98
+ for number, line in enumerate(lines[1:], 2):
99
+ fields = line.split('\t')
100
+
101
+ if len(fields) > len(header):
102
+ fail('{} line {}: {} fields, where the header has {}'.format(path,
103
+ number, len(fields), len(header)))
104
+
105
+ fields += [''] * (len(header) - len(fields))
106
+ rows.append(dict(zip(header, [field.strip() for field in fields])))
107
+
108
+ return rows
109
+
110
+
111
+ # collection ------------------------------------------------------------------
112
+
113
+ def parse_collection(text):
114
+ """Node ids and the selected count from `pytest --collect-only -q`."""
115
+
116
+ nodeids, started = [], False
117
+
118
+ for line in text.splitlines():
119
+ if not line.strip() or line.startswith('=') or line[0].isspace():
120
+ if started:
121
+ break
122
+ continue
123
+
124
+ if '::' in line:
125
+ nodeids.append(line.rstrip())
126
+ started = True
127
+ elif started:
128
+ break
129
+
130
+ summary = [line for line in text.splitlines()
131
+ if re.search(r'\btests? collected\b|\bno tests collected\b', line)]
132
+
133
+ return nodeids, summary[-1].strip(' =') if summary else ''
134
+
135
+
136
+ def function_texts(path):
137
+ """{qualified name: source text} of every function in a test module."""
138
+
139
+ try:
140
+ with open(path, encoding='utf-8') as infile:
141
+ source = infile.read()
142
+ except OSError as error:
143
+ fail('could not read {}: {}'.format(path, error))
144
+
145
+ try:
146
+ tree = ast.parse(source)
147
+ except SyntaxError as error:
148
+ fail('could not parse {}: {}'.format(path, error))
149
+
150
+ lines = source.splitlines()
151
+ found = {}
152
+
153
+ def visit(body, prefix):
154
+ for node in body:
155
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
156
+ found[prefix + node.name] = '\n'.join(
157
+ lines[node.lineno - 1:node.end_lineno])
158
+ elif isinstance(node, ast.ClassDef):
159
+ visit(node.body, prefix + node.name + '.')
160
+
161
+ visit(tree.body, '')
162
+ return found
163
+
164
+
165
+ def collection(args):
166
+ try:
167
+ with open(args.collect_output, encoding='utf-8') as infile:
168
+ text = infile.read()
169
+ except OSError as error:
170
+ fail('could not read {}: {}'.format(args.collect_output, error))
171
+
172
+ nodeids, summary = parse_collection(text)
173
+
174
+ if not nodeids:
175
+ fail('{} lists no test: it must be the output of `pytest '
176
+ '--collect-only -q`, one node id per line'.format(args.collect_output))
177
+
178
+ if not summary:
179
+ fail('{} has no "N tests collected" line: save the whole output of '
180
+ '`pytest --collect-only -q`'.format(args.collect_output))
181
+
182
+ if re.search(r'\berrors?\b', summary):
183
+ fail('the collection had errors ({}): fix them before counting'.format(
184
+ summary))
185
+
186
+ counted = re.search(r'(\d+)(?:/\d+)? tests? collected', summary)
187
+
188
+ if not counted or int(counted.group(1)) != len(nodeids):
189
+ fail('{} lists {} node ids, but pytest says "{}"'.format(
190
+ args.collect_output, len(nodeids), summary))
191
+
192
+ if len(set(nodeids)) != len(nodeids):
193
+ twice = sorted({n for n in nodeids if nodeids.count(n) > 1})
194
+ fail('node ids collected twice: {}'.format(', '.join(twice[:5])))
195
+
196
+ pinned = {}
197
+
198
+ if args.root:
199
+ marker = re.compile(args.marker, re.IGNORECASE | re.DOTALL)
200
+ unknown = []
201
+
202
+ for module in sorted({publish.split_nodeid(n)[0] for n in nodeids}):
203
+ texts = function_texts(os.path.join(args.root, module))
204
+
205
+ for nodeid in nodeids:
206
+ if publish.split_nodeid(nodeid)[0] != module:
207
+ continue
208
+
209
+ name = publish.split_nodeid(nodeid)[1]
210
+ text = texts.get(name)
211
+
212
+ if text is None:
213
+ # A test inherited from a class elsewhere: its name alone.
214
+ short = name.rsplit('.', 1)[-1]
215
+ text = next((t for q, t in sorted(texts.items())
216
+ if q.rsplit('.', 1)[-1] == short), None)
217
+
218
+ if text is None:
219
+ unknown.append(nodeid)
220
+
221
+ pinned[nodeid] = 'yes' if text and marker.search(text) else 'no'
222
+
223
+ if unknown:
224
+ note('{} test(s) have no function in their module\'s source, so they '
225
+ 'count as not pinned: {}'.format(len(unknown), ', '.join(
226
+ unknown[:5])))
227
+
228
+ path = write_tsv(args.out, 'collection.tsv', ['nodeid', 'pinned'],
229
+ [[n, pinned.get(n, '')] for n in nodeids])
230
+
231
+ modules = {}
232
+
233
+ for nodeid in nodeids:
234
+ module = publish.split_nodeid(nodeid)[0]
235
+ modules[module] = modules.get(module, 0) + 1
236
+
237
+ functions = {publish.split_nodeid(n) for n in nodeids}
238
+ print('collection: {} tests in {} modules, {} test functions{}; wrote {}'
239
+ .format(len(nodeids), len(modules), len(functions), ', {} pinning the '
240
+ 'current output'.format(len({publish.split_nodeid(n) for n in nodeids
241
+ if pinned.get(n) == 'yes'})) if args.root else '', path))
242
+
243
+ for module, count in sorted(modules.items()):
244
+ print(' {:6d} {}'.format(count, module))
245
+
246
+ return 0
247
+
248
+
249
+ # files -----------------------------------------------------------------------
250
+
251
+ def files(args):
252
+ out = subprocess.run(['git', '-C', args.repo, 'diff', '--name-status',
253
+ '--no-renames', '{}...{}'.format(args.base, args.head)],
254
+ capture_output=True, text=True)
255
+
256
+ if out.returncode != 0:
257
+ fail('git diff {}...{} failed: {}'.format(args.base, args.head,
258
+ out.stderr.strip()))
259
+
260
+ rows = []
261
+
262
+ for line in out.stdout.splitlines():
263
+ status, _, path = line.partition('\t')
264
+
265
+ if path:
266
+ rows.append([status.strip()[:1], path])
267
+
268
+ if not rows:
269
+ fail('{}...{} changes no file'.format(args.base, args.head))
270
+
271
+ rows.sort(key=lambda row: row[1])
272
+ path = write_tsv(args.out, 'files.tsv', ['status', 'path'], rows)
273
+ publish.write_json(os.path.join(args.out, 'branch.json'), {
274
+ 'suite': os.path.abspath(args.repo), 'base': args.base,
275
+ 'branch': args.head})
276
+
277
+ print('files: {} changed between {} and {}; wrote {} and branch.json'
278
+ .format(len(rows), args.base, args.head, path))
279
+
280
+ return 0
281
+
282
+
283
+ # coverage --------------------------------------------------------------------
284
+
285
+ def normalize(path, strip):
286
+ path = path.replace('\\', '/')
287
+
288
+ for prefix in strip:
289
+ prefix = prefix.replace('\\', '/')
290
+
291
+ if prefix and path.startswith(prefix):
292
+ path = path[len(prefix):].lstrip('/')
293
+ break
294
+
295
+ return os.path.normpath(path).replace('\\', '/') if path else path
296
+
297
+
298
+ def test_of(context):
299
+ """A coverage.py context as a test id: `--cov-context=test` appends
300
+ `|run`, `|setup` or `|teardown`."""
301
+
302
+ return re.sub(r'\|(run|setup|teardown)$', '', context)
303
+
304
+
305
+ def load_one(path, strip):
306
+ """{file: [executable set, covered set]} and {test: set of files run},
307
+ the second None when the file holds no per-test contexts."""
308
+
309
+ try:
310
+ with open(path, encoding='utf-8') as infile:
311
+ data = json.load(infile)
312
+ except (OSError, ValueError) as error:
313
+ fail('could not read {} as JSON: {}'.format(path, error))
314
+
315
+ lines, touched = {}, None
316
+
317
+ if isinstance(data, dict) and isinstance(data.get('files'), list):
318
+ # gcovr --json: one entry per source file, a line once per function
319
+ # instance that holds it.
320
+ for entry in data['files']:
321
+ name = normalize(entry.get('file', ''), strip)
322
+ executable, covered = lines.setdefault(name, [set(), set()])
323
+
324
+ for line in entry.get('lines', []):
325
+ if line.get('gcovr/noncode') or line.get('gcovr/excluded'):
326
+ continue
327
+
328
+ executable.add(line['line_number'])
329
+
330
+ if line.get('count', 0) > 0:
331
+ covered.add(line['line_number'])
332
+
333
+ elif isinstance(data, dict) and isinstance(data.get('files'), dict) \
334
+ and 'meta' in data:
335
+ # coverage json: executed and missing lines, and with
336
+ # --show-contexts the contexts that ran each line.
337
+ contexts = {}
338
+
339
+ for name, entry in data['files'].items():
340
+ name = normalize(name, strip)
341
+ executable, covered = lines.setdefault(name, [set(), set()])
342
+ executable.update(entry.get('executed_lines', []))
343
+ executable.update(entry.get('missing_lines', []))
344
+ covered.update(entry.get('executed_lines', []))
345
+
346
+ for names in (entry.get('contexts') or {}).values():
347
+ for context in names:
348
+ if context:
349
+ contexts.setdefault(test_of(context), set()).add(name)
350
+
351
+ if contexts:
352
+ touched = contexts
353
+ else:
354
+ fail('{} is neither gcovr JSON (`gcovr --json`) nor coverage.py JSON '
355
+ '(`coverage json`)'.format(path))
356
+
357
+ return lines, touched
358
+
359
+
360
+ def load_coverage(path, strip):
361
+ """A file, or a directory holding one JSON file per test (the test being
362
+ its name without `.json`): lines as `load_one`, and the tests run."""
363
+
364
+ if not os.path.isdir(path):
365
+ return load_one(path, strip)
366
+
367
+ names = sorted(name for name in os.listdir(path) if name.endswith('.json'))
368
+
369
+ if not names:
370
+ fail('{} holds no .json file: a per-test directory holds one coverage '
371
+ 'file per test'.format(path))
372
+
373
+ lines, touched = {}, {}
374
+
375
+ for name in names:
376
+ one, _ = load_one(os.path.join(path, name), strip)
377
+ test = name[:-len('.json')]
378
+ touched[test] = set()
379
+
380
+ for source, (executable, covered) in one.items():
381
+ total = lines.setdefault(source, [set(), set()])
382
+ total[0].update(executable)
383
+ total[1].update(covered)
384
+
385
+ if covered:
386
+ touched[test].add(source)
387
+
388
+ return lines, touched
389
+
390
+
391
+ def assign_parts(names, excluded, mapping, mode):
392
+ if mapping is not None:
393
+ parts = {}
394
+
395
+ for name in names:
396
+ part = next((row['part'] for row in mapping
397
+ if fnmatch.fnmatch(name, row['pattern'])), None)
398
+
399
+ if part is None:
400
+ fail('{} matches no pattern of the part map: add one (a last '
401
+ 'line `*\tother` catches the rest)'.format(name))
402
+
403
+ parts[name] = part
404
+
405
+ return parts
406
+
407
+ if mode == 'auto':
408
+ counted = [name for name in names if name not in excluded]
409
+ mode = 'file' if len(counted) <= PARTS_PER_FILE else 'dir'
410
+
411
+ if mode == 'file':
412
+ return {name: name for name in names}
413
+
414
+ return {name: (os.path.dirname(name) + '/' if os.path.dirname(name)
415
+ else '(top level)') for name in names}
416
+
417
+
418
+ def coverage(args):
419
+ strip = args.strip or []
420
+ labels, existing = [], {}
421
+
422
+ for item in args.existing or []:
423
+ label, sep, path = item.partition('=')
424
+
425
+ if not sep or not label.strip() or not path:
426
+ fail('--existing takes LABEL=PATH; got {!r}'.format(item))
427
+
428
+ label = label.strip()
429
+
430
+ if label in labels:
431
+ fail('--existing names {!r} twice'.format(label))
432
+
433
+ labels.append(label)
434
+ existing[label] = load_coverage(path, strip)
435
+
436
+ suite = [load_coverage(path, strip) for path in args.suite]
437
+
438
+ def keep(name):
439
+ return name and not any(fnmatch.fnmatch(name, glob)
440
+ for glob in args.drop or [])
441
+
442
+ names = sorted({name for lines, _ in list(existing.values()) + suite
443
+ for name in lines if keep(name)})
444
+
445
+ if not names:
446
+ fail('no source file is left in the coverage data after --drop')
447
+
448
+ excluded = {name for name in names if any(fnmatch.fnmatch(name, glob)
449
+ for glob in args.exclude or [])}
450
+ mapping = read_tsv(args.part_map, ['pattern', 'part']) \
451
+ if args.part_map else None
452
+ parts = assign_parts(names, excluded, mapping, args.parts)
453
+
454
+ for part in sorted(set(parts.values())):
455
+ members = [name for name in names if parts[name] == part]
456
+ marked = {name in excluded for name in members}
457
+
458
+ if len(marked) > 1:
459
+ fail('part {} mixes excluded files ({}) with counted ones ({}): give '
460
+ 'the excluded files a part of their own'.format(part,
461
+ ', '.join(sorted(set(members) & excluded)[:3]), ', '.join(sorted(
462
+ set(members) - excluded)[:3])))
463
+
464
+ def union(sources, name, which):
465
+ out = set()
466
+
467
+ for lines, _ in sources:
468
+ out |= lines.get(name, [set(), set()])[which]
469
+
470
+ return out
471
+
472
+ everything = list(existing.values()) + suite
473
+ rows = []
474
+
475
+ for name in names:
476
+ executable = union(everything, name, 0)
477
+ by_label = [union([existing[label]], name, 1) for label in labels]
478
+ before = set().union(*by_label) if by_label else set()
479
+ after = union(suite, name, 1)
480
+ rows.append([name, parts[name], 'yes' if name in excluded else 'no',
481
+ len(executable), len(before), len(after), len(before | after)]
482
+ + [len(covered) for covered in by_label])
483
+
484
+ path = write_tsv(args.out, 'coverage.tsv', ['file', 'part', 'excluded',
485
+ 'lines', 'existing', 'suite', 'both'] + ['existing:' + label
486
+ for label in labels], rows)
487
+
488
+ # Tests per part: from per-test data when every input has it.
489
+ def tests_by_role(sources):
490
+ if any(touched is None for _, touched in sources):
491
+ return None
492
+
493
+ merged = {}
494
+
495
+ for _, touched in sources:
496
+ for test, run in touched.items():
497
+ merged.setdefault(test, set()).update(run)
498
+
499
+ return merged
500
+
501
+ before_tests = tests_by_role(list(existing.values()))
502
+ after_tests = tests_by_role(suite)
503
+ part_names = sorted(set(parts.values()))
504
+ counted_parts = [part for part in part_names
505
+ if not any(parts[n] == part and n in excluded for n in names)]
506
+ table = []
507
+
508
+ if before_tests is not None and after_tests is not None:
509
+ def count(tests, members):
510
+ return len([test for test, run in tests.items() if run & members])
511
+
512
+ shared = set(before_tests) & set(after_tests)
513
+
514
+ if shared:
515
+ note('{} test(s) appear in both --existing and --suite and are '
516
+ 'counted once. --suite should be the run of the new tests only: '
517
+ 'otherwise its coverage row includes the existing tests'.format(
518
+ len(shared)))
519
+
520
+ combined = {}
521
+
522
+ for tests in (before_tests, after_tests):
523
+ for test, run in tests.items():
524
+ combined.setdefault(test, set()).update(run)
525
+
526
+ for part in part_names + ['(total)']:
527
+ members = {name for name in names if (parts[name] == part
528
+ if part != '(total)' else parts[name] in counted_parts)}
529
+ table.append([part, count(before_tests, members),
530
+ count(combined, members), 'per-test'])
531
+
532
+ how = 'from per-test coverage ({} existing tests, {} of this suite)'.format(
533
+ len(before_tests), len(after_tests))
534
+ elif args.part_tests:
535
+ given = {row['part']: row for row in read_tsv(args.part_tests, ['part',
536
+ 'tests_before', 'tests_after'])}
537
+ missing = [part for part in counted_parts + ['(total)']
538
+ if part not in given]
539
+ unknown = sorted(set(given) - set(part_names) - {'(total)'})
540
+
541
+ if missing or unknown:
542
+ fail('{}: {}{}'.format(args.part_tests, 'no row for {}'.format(
543
+ ', '.join(missing)) if missing else '', '{}rows for parts the '
544
+ 'coverage has not: {}'.format('; ' if missing else '', ', '.join(
545
+ unknown)) if unknown else ''))
546
+
547
+ for part in part_names + ['(total)']:
548
+ row = given.get(part)
549
+
550
+ if row is None:
551
+ table.append([part, '', '', ''])
552
+ continue
553
+
554
+ try:
555
+ before, after = int(row['tests_before']), int(row['tests_after'])
556
+ except ValueError:
557
+ fail('{}: the tests of {} are not whole numbers'.format(
558
+ args.part_tests, part))
559
+
560
+ table.append([part, before, after, 'by-file'])
561
+
562
+ how = 'from {} (tests in the files written for each part)'.format(
563
+ args.part_tests)
564
+ else:
565
+ table = [[part, '', '', ''] for part in part_names + ['(total)']]
566
+ how = 'not counted: no per-test coverage (coverage.py contexts, or a ' \
567
+ 'directory of one file per test) for every input, and no --part-tests'
568
+
569
+ for row in table:
570
+ row.insert(1, 'yes' if row[0] not in counted_parts
571
+ and row[0] != '(total)' else 'no')
572
+
573
+ parts_path = write_tsv(args.out, 'parts.tsv', ['part', 'excluded',
574
+ 'tests_before', 'tests_after', 'counted'], table)
575
+
576
+ total = sum(row[3] for row in rows if row[2] == 'no')
577
+
578
+ def share(column):
579
+ hit = sum(row[column] for row in rows if row[2] == 'no')
580
+ return '{:,} ({:.1f}%)'.format(hit, 100.0 * hit / total) if total else '0'
581
+
582
+ print('coverage: {} files, {:,} executable lines outside excluded code; '
583
+ 'existing {}, this suite {}, both {}'.format(len(rows), total,
584
+ share(4), share(5), share(6)))
585
+ print(' parts: {} ({} excluded); tests per part {}'.format(len(part_names),
586
+ len(part_names) - len(counted_parts), how))
587
+ print(' wrote {} and {}'.format(path, parts_path))
588
+
589
+ return 0
590
+
591
+
592
+ # names -----------------------------------------------------------------------
593
+
594
+ def python_files(paths):
595
+ out = []
596
+
597
+ for path in paths:
598
+ if os.path.isfile(path):
599
+ out.append(path)
600
+ continue
601
+
602
+ for directory, subdirectories, names in os.walk(path):
603
+ subdirectories[:] = sorted(d for d in subdirectories
604
+ if not d.startswith('.') and d != '__pycache__')
605
+ out += [os.path.join(directory, name) for name in sorted(names)
606
+ if name.endswith('.py')]
607
+
608
+ return sorted(set(os.path.normpath(path) for path in out))
609
+
610
+
611
+ def public_names(path):
612
+ with open(path, encoding='utf-8') as infile:
613
+ tree = ast.parse(infile.read())
614
+
615
+ exported = None
616
+
617
+ for node in tree.body:
618
+ if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name)
619
+ and target.id == '__all__' for target in node.targets) \
620
+ and isinstance(node.value, (ast.List, ast.Tuple)):
621
+ exported = {element.value for element in node.value.elts
622
+ if isinstance(element, ast.Constant)
623
+ and isinstance(element.value, str)}
624
+
625
+ names = []
626
+
627
+ for node in tree.body:
628
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef,
629
+ ast.ClassDef)) or node.name.startswith('_'):
630
+ continue
631
+
632
+ if exported is not None and node.name not in exported:
633
+ continue
634
+
635
+ names.append((node.name, node.name))
636
+
637
+ if isinstance(node, ast.ClassDef):
638
+ for sub in node.body:
639
+ if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)) \
640
+ and not sub.name.startswith('_'):
641
+ names.append((node.name + '.' + sub.name, sub.name))
642
+
643
+ return names
644
+
645
+
646
+ def identifiers(path):
647
+ with open(path, encoding='utf-8') as infile:
648
+ tree = ast.parse(infile.read())
649
+
650
+ found = set()
651
+
652
+ for node in ast.walk(tree):
653
+ if isinstance(node, ast.Name):
654
+ found.add(node.id)
655
+ elif isinstance(node, ast.Attribute):
656
+ found.add(node.attr)
657
+ elif isinstance(node, ast.alias):
658
+ found.add(node.name.rsplit('.', 1)[-1])
659
+
660
+ return found
661
+
662
+
663
+ def names(args):
664
+ tests = python_files(args.tests)
665
+ test_set = set(tests)
666
+ sources = [path for path in python_files(args.source) if path not in test_set
667
+ and not os.path.basename(path).startswith(('test_', 'conftest'))
668
+ and not any(fnmatch.fnmatch(path, glob) for glob in args.exclude or [])
669
+ and not (os.path.basename(path).startswith('_')
670
+ and os.path.basename(path) != '__init__.py')]
671
+
672
+ if not sources:
673
+ fail('no Python source file under {}'.format(', '.join(args.source)))
674
+
675
+ if not tests:
676
+ fail('no Python test file under {}'.format(', '.join(args.tests)))
677
+
678
+ named = [identifiers(path) for path in tests]
679
+ rows = []
680
+
681
+ for path in sources:
682
+ for display, identifier in public_names(path):
683
+ rows.append([display, path, sum(1 for found in named
684
+ if identifier in found)])
685
+
686
+ rows.sort(key=lambda row: (row[1], row[0]))
687
+ out = write_tsv(args.out, 'names.tsv', ['name', 'defined_in', 'tests'], rows)
688
+ unnamed = [row for row in rows if not row[2]]
689
+ print('names: {} public names in {} files; {} named by no test file; wrote {}'
690
+ .format(len(rows), len(sources), len(unnamed), out))
691
+
692
+ return 0
693
+
694
+
695
+ # -----------------------------------------------------------------------------
696
+
697
+ def build_parser():
698
+ parser = argparse.ArgumentParser(description=__doc__,
699
+ formatter_class=argparse.RawDescriptionHelpFormatter)
700
+ commands = parser.add_subparsers(dest='command', required=True)
701
+ out_help = 'the folder of tables, {}'.format(FOLDER)
702
+
703
+ sub = commands.add_parser('collection', help='collection.tsv: every test '
704
+ 'pytest collects, and whether its function pins the current output')
705
+ sub.add_argument('--collect-output', required=True, help='the saved output '
706
+ 'of `pytest --collect-only -q` over the suite')
707
+ sub.add_argument('--root', help='the directory node ids are relative to '
708
+ '(pytest\'s rootdir, `$WORK/tests/suite`); without it the pinned '
709
+ 'column is left empty')
710
+ sub.add_argument('--marker', default=MARKER, help='the regular expression, '
711
+ 'matched without regard to case in each test function\'s source, that '
712
+ 'marks it as pinning the current output (default: "pin" or "pins" '
713
+ 'followed within seven words by "current")')
714
+ sub.add_argument('--out', required=True, help=out_help)
715
+ sub.set_defaults(handler=collection)
716
+
717
+ sub = commands.add_parser('files', help='files.tsv: the files the tests '
718
+ 'branch changes, from git; and branch.json, the clone, branch and base '
719
+ 'commit the push reads')
720
+ sub.add_argument('--repo', required=True, help='the clone holding the '
721
+ 'tests branch, `$WORK/tests/suite`')
722
+ sub.add_argument('--base', required=True, help='the commit the tests '
723
+ 'branch was made from (`commit` in `$WORK/tests/branch.json`)')
724
+ sub.add_argument('--head', required=True, help='the tests branch, '
725
+ 'auto-optimize/<YYYY-MM-DD>-unit-tests')
726
+ sub.add_argument('--out', required=True, help=out_help)
727
+ sub.set_defaults(handler=files)
728
+
729
+ sub = commands.add_parser('coverage', help='coverage.tsv and parts.tsv: '
730
+ 'lines covered per file by the existing tests, this suite and both, and '
731
+ 'tests per part')
732
+ sub.add_argument('--existing', action='append', metavar='LABEL=PATH',
733
+ help='coverage of the repository\'s own tests at the base commit, one '
734
+ 'per suite or CI step, LABEL as the body names it; repeatable; none '
735
+ 'when the repository has no tests')
736
+ sub.add_argument('--suite', action='append', required=True, metavar='PATH',
737
+ help='coverage of the new suite; repeatable (several builds)')
738
+ sub.add_argument('--strip', action='append', metavar='PREFIX',
739
+ help='a prefix removed from file paths, so every input names a file '
740
+ 'the same way; repeatable')
741
+ sub.add_argument('--drop', action='append', metavar='GLOB', help='files '
742
+ 'left out of every table (the tests themselves); repeatable')
743
+ sub.add_argument('--exclude', action='append', metavar='GLOB',
744
+ help='vendored or generated files: kept as parts of their own, marked '
745
+ 'excluded, never in a total; repeatable')
746
+ sub.add_argument('--part-map', metavar='FILE', help='TSV with header '
747
+ '`pattern`, `part`: the first glob that matches a file names its part')
748
+ sub.add_argument('--parts', choices=('auto', 'file', 'dir'), default='auto',
749
+ help='without --part-map: a part per file, per directory, or (auto) per '
750
+ 'file up to {} counted files and per directory above'.format(
751
+ PARTS_PER_FILE))
752
+ sub.add_argument('--part-tests', metavar='FILE', help='TSV with header '
753
+ '`part`, `tests_before`, `tests_after` and a `(total)` row: tests per part '
754
+ 'counted from the test files written for each part, used when the '
755
+ 'inputs have no per-test data')
756
+ sub.add_argument('--out', required=True, help=out_help)
757
+ sub.set_defaults(handler=coverage)
758
+
759
+ sub = commands.add_parser('names', help='names.tsv: public Python names '
760
+ 'and how many test files name them')
761
+ sub.add_argument('--source', action='append', required=True, metavar='PATH',
762
+ help='a package directory or file; repeatable')
763
+ sub.add_argument('--tests', action='append', required=True, metavar='PATH',
764
+ help='a test directory or file; repeatable')
765
+ sub.add_argument('--exclude', action='append', metavar='GLOB',
766
+ help='source files left out (vendored, generated); repeatable')
767
+ sub.add_argument('--out', required=True, help=out_help)
768
+ sub.set_defaults(handler=names)
769
+
770
+ return parser
771
+
772
+
773
+ def main(argv=None):
774
+ args = build_parser().parse_args(argv)
775
+ return args.handler(args)
776
+
777
+
778
+ if __name__ == '__main__':
779
+ sys.exit(main())