forked from geldata/gel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_docs.py
469 lines (384 loc) · 16 KB
/
test_docs.py
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
##
# Copyright (c) 2017-present MagicStack Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from typing import *
import collections
import json
import os
import re
import subprocess
import sys
import tempfile
import textwrap
import unittest
try:
import docutils.nodes
import docutils.parsers
import docutils.utils
import docutils.frontend
except ImportError:
docutils = None # type: ignore
try:
import sphinx
except ImportError:
sphinx = None # type: ignore
from graphql.language import parser as graphql_parser
from edb.edgeql import parser as ql_parser
def find_edgedb_root():
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class TestDocSnippets(unittest.TestCase):
"""Lint and validate EdgeDB documentation files.
Checks:
* all source code in "code-block" directives is parsed to
check that the syntax is valid;
* lines must be shorter than 79 characters;
* any ReST warnings (like improper headers or broken indentation)
are reported as errors.
"""
MAX_LINE_LEN = 79
CodeSnippet = collections.namedtuple(
'CodeSnippet',
['filename', 'lineno', 'lang', 'code'])
class RestructuredTextStyleError(Exception):
pass
if docutils is not None:
class CustomDocutilsReporter(docutils.utils.Reporter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.lint_errors = set()
def system_message(self, level, message, *children, **kwargs):
skip = (
message.startswith('Unknown interpreted text role') or
message.startswith('No role entry for') or
message.startswith('Unknown directive type') or
message.startswith('No directive entry for') or
level < 2 # Ignore DEBUG and INFO messages.
)
msg = super().system_message(
level, message, *children, **kwargs)
if not skip:
self.lint_errors.add(
f"{message} at {msg['source']} on line "
f"{msg.get('line', '?')}")
return msg
def find_rest_files(self, path: str) -> List[str]:
def scan(path):
with os.scandir(path) as it:
for entry in it:
if entry.is_file() and entry.name.endswith('.rst'):
files.append(entry.path)
if entry.is_dir():
scan(entry.path)
files: List[str] = []
scan(path)
return files
def extract_code_blocks(self, source: str, filename: str):
blocks = []
parser_class = docutils.parsers.get_parser_class('rst')
parser = parser_class()
settings = docutils.frontend.OptionParser(
components=(parser_class, )).get_default_values()
settings.syntax_highlight = 'none'
min_error_code = 100 # Ignore all errors, we process them manually.
reporter = self.CustomDocutilsReporter(
filename, min_error_code, min_error_code)
document = docutils.nodes.document(settings, reporter, source=filename)
document.note_source(filename, -1)
parser.parse(source, document)
lines = source.split('\n')
for lineno, line in enumerate(lines, 1):
if len(line) > self.MAX_LINE_LEN:
reporter.lint_errors.add(
f'Line longer than {self.MAX_LINE_LEN} characters in '
f'{filename}, line {lineno}')
if reporter.lint_errors:
raise self.RestructuredTextStyleError(
'\n\nRestructuredText lint errors:\n' +
'\n'.join(reporter.lint_errors))
directives = []
for node in document.traverse():
if node.tagname == 'literal_block':
if 'code' in node.attributes['classes']:
directives.append(node)
else:
block = node.astext()
# certain literal blocks also contain code-blocks
if re.match(r'^\.\. eql:(operator|function|constraint)::',
block):
# figure out the line offset of the start of the block
node_parent = node
while node_parent and node_parent.line is None:
node_parent = node_parent.parent
if node_parent:
node_parent_line = \
node_parent.line - block.count('\n')
else:
node_parent_line = 0
subdoc = docutils.nodes.document(
settings, reporter, source=filename)
subdoc.note_source(filename, node_parent_line)
# cut off the first chunk
block = block.split('\n\n', maxsplit=1)[1]
# dedent the rest
block = textwrap.dedent(block)
parser.parse(block, subdoc)
subdirs = subdoc.traverse(
condition=lambda node: (
node.tagname == 'literal_block' and
'code' in node.attributes['classes'])
)
for subdir in subdirs:
subdir.line += node_parent_line
directives.append(subdir)
for directive in directives:
classes = directive.attributes['classes']
if len(classes) < 2 or classes[0] != 'code':
continue
lang = directive.attributes['classes'][1]
code = directive.astext()
lineno = directive.line
if lineno is None:
# Some docutils blocks (like tables) do not support
# line numbers, so we try to traverse the parent tree
# to find the nearest block with a line number.
parent_directive = directive
while parent_directive and parent_directive.line is None:
parent_directive = parent_directive.parent
if parent_directive and parent_directive.line is not None:
lineno = parent_directive.line
else:
lineno = lineno
blocks.append(self.CodeSnippet(filename, str(lineno), lang, code))
return blocks
def extract_snippets_from_repl(self, replblock):
in_query = False
snips = []
for line in replblock.split('\n'):
if not in_query:
m = re.match(r'(?P<p>[\w\[:\]>]+>\s)(?P<l>.*)', line)
if m:
# >>> prompt
in_query = True
snips.append(
(len(m.group('p')), [])
)
snips[len(snips) - 1][1].append(m.group('l'))
else:
# output
if not snips:
raise AssertionError(
f'invalid REPL block (starts with output); '
f'offending line {line!r}')
else:
# ... prompt?
m = re.match(r'(?P<p>\.+\s)(?P<l>.*)', line)
if m:
# yes, it's "... " line
if not snips:
raise AssertionError(
f'invalid REPL block (... before >>>); '
f'offending line {line!r}')
if len(m.group('p')) != snips[len(snips) - 1][0]:
raise AssertionError(
f'invalid REPL block: number of "." does not '
f'match number of ">"; '
f'offending line {line!r}')
snips[len(snips) - 1][1].append(m.group('l'))
else:
# no, this is output
in_query = False
return ['\n'.join(s[1]) for s in snips
# ignore the "\c" and other REPL commands
if not re.match(r'\\\w+', s[1][0])]
def run_block_test(self, block):
try:
lang = block.lang
if lang.endswith('-repl'):
lang = lang.rpartition('-')[0]
code = self.extract_snippets_from_repl(block.code)
elif lang.endswith('-diff'):
# In the diff block we need to truncate "-"/"+" at the
# beginning of each line. We will make two copies of
# the code as the before and after version. Both will
# be validated.
before = []
after = []
for line in block.code.split('\n'):
if line == "":
continue
first = line.strip()[0]
if first == '-':
before.append(line[1:])
elif first == '+':
after.append(line[1:])
else:
before.append(line[1:])
after.append(line[1:])
code = ['\n'.join(before), '\n'.join(after)]
# truncate the "-diff" from the language
lang = lang[:-5]
else:
code = [block.code]
for snippet in code:
if lang == 'edgeql':
ql_parser.parse_block(snippet)
elif lang == 'sdl':
# Strip all the "using extension ..." and comment
# lines as they interfere with our module
# detection.
sdl = re.sub(
r'(using\s+extension\s+\w+;)|(#.*?\n)',
'',
snippet
).strip()
# the snippet itself may either contain a module
# block or have a fully-qualified top-level name
if not sdl or re.match(
r'''(?xm)
(\bmodule\s+\w+\s*{) |
(^.*
(type|annotation|link|property|constraint)
\s+(\w+::\w+)\s+
({|extending)
)
''',
sdl):
ql_parser.parse_sdl(snippet)
else:
ql_parser.parse_sdl(f'module default {{ {snippet} }}')
elif lang == 'edgeql-result':
# REPL results
pass
elif lang == 'pseudo-eql':
# Skip "pseudo-eql" language as we don't have a
# parser for it.
pass
elif lang == 'graphql':
graphql_parser.parse(snippet)
elif lang == 'graphql-schema':
# The graphql-schema can be highlighted using graphql
# lexer, but it does not have a dedicated parser.
pass
elif lang == 'json':
json.loads(snippet)
elif lang in {
'bash',
'powershell',
'shell',
'c',
'javascript',
'python',
'typescript',
'go',
'yaml'
}:
pass
elif lang[-5:] == '-diff':
pass
else:
raise LookupError(f'unknown code-lang {lang}')
except Exception as ex:
raise AssertionError(
f'unable to parse {block.lang} code block in '
f'{block.filename}, around line {block.lineno}') from ex
@unittest.skipIf(docutils is None, 'docutils is missing')
def test_cqa_doc_snippets(self):
edgepath = edgepath = find_edgedb_root()
docspath = os.path.join(edgepath, 'docs')
for filename in self.find_rest_files(docspath):
with open(filename, 'rt') as f:
source = f.read()
blocks = self.extract_code_blocks(source, filename)
for block in blocks:
self.run_block_test(block)
@unittest.skipIf(docutils is None, 'docutils is missing')
def test_doc_test_broken_code_block_01(self):
source = '''
In large applications, the schema will usually be split
into several :ref:`modules<ref_schema_evolution_modules>`.
.. code-block:: edgeql
SELECT 122 + foo();
A *schema module* defines the effective namespace for
elements it defines.
.. code-block:: edgeql
SELECT 42;
# ^ expected to return 42
SELECT foo(
Schema modules can import other modules to use schema
elements they define.
'''
blocks = self.extract_code_blocks(source, '<test>')
self.assertEqual(len(blocks), 2)
self.assertEqual(blocks[0].code, 'SELECT 122 + foo();')
self.run_block_test(blocks[0])
with self.assertRaisesRegex(AssertionError, 'unable to parse edgeql'):
self.run_block_test(blocks[1])
@unittest.skipIf(docutils is None, 'docutils is missing')
def test_doc_test_broken_code_block_02(self):
source = r'''
String operator with a buggy example.
.. eql:operator:: LIKE: str LIKE str -> bool
str NOT LIKE str -> bool
Case-sensitive simple string matching.
Example:
.. code-block:: edgeql-repl
db> SELECT 'a%%c' NOT LIKE 'a\%c';
{true}
'''
blocks = self.extract_code_blocks(source, '<test>')
self.assertEqual(len(blocks), 1)
self.assertEqual(blocks[0].code,
"db> SELECT 'a%%c' NOT LIKE 'a\\%c';\n{true}")
with self.assertRaisesRegex(AssertionError, 'unable to parse edgeql'):
self.run_block_test(blocks[0])
@unittest.skipIf(docutils is None, 'docutils is missing')
def test_doc_test_broken_long_lines(self):
source = f'''
aaaaaa aa aaa:
- aaa
- {'a' * self.MAX_LINE_LEN}
- aaa
'''
with self.assertRaisesRegex(self.RestructuredTextStyleError,
r'lint errors:[.\s]*Line longer'):
self.extract_code_blocks(source, '<test>')
@unittest.skipIf(docutils is None, 'docutils is missing')
def test_doc_test_bad_header(self):
source = textwrap.dedent('''
Section
-----
aaa aaa aaa
''')
with self.assertRaisesRegex(
self.RestructuredTextStyleError,
r'lint errors:[.\s]*Title underline too short'):
self.extract_code_blocks(source, '<test>')
@unittest.skipIf(sphinx is None, 'sphinx is missing')
def test_doc_full_build(self):
docs_root = os.path.join(find_edgedb_root(), 'docs')
with tempfile.TemporaryDirectory() as td:
proc = subprocess.run(
[
sys.executable,
'-m', 'sphinx',
'-W',
'-n',
'-b', 'xml',
'-q',
'-D', 'master_doc=index',
docs_root,
td,
],
text=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
if proc.returncode:
raise AssertionError(
f'Unable to build docs with Sphinx.\n\n'
f'STDOUT:\n{proc.stdout}\n\n'
f'STDERR:\n{proc.stderr}\n'
)