-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_doctools.py
More file actions
535 lines (381 loc) · 12.7 KB
/
Copy pathtest_doctools.py
File metadata and controls
535 lines (381 loc) · 12.7 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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
"""
test_doctools
~~~~~~~~~~~~~~~
Test functions in doctools.py
"""
# stdlib
import math
import sys
from typing import Iterable, NamedTuple, get_type_hints
# 3rd party
import pytest
from coincidence import PEP_563, max_version
# this package
from domdf_python_tools import doctools
from domdf_python_tools.bases import Dictable
from domdf_python_tools.compat import PYPY
from domdf_python_tools.doctools import (
base_int_docstrings,
base_new_docstrings,
container_docstrings,
operator_docstrings,
prettify_docstrings
)
# TODO: test sphinxification of docstrings
class Cafe:
"""
Generic class for a Cafe
"""
def __init__(self):
self._dish1 = "egg and bacon"
self._dish2 = "egg sausage and bacon"
self._dish3 = "egg and spam"
self._dish4 = "egg bacon and spam"
self._opens_at = 7
self._closes_at = 6
@property
def menu(self):
"""
Returns the menu of the cafe
:return:
:rtype:
"""
return [self._dish1, self._dish2, self._dish3, self._dish4]
@property
def opening_hours(self):
"""
Returns the opening hours of the Cafe
:rtype: str
"""
return f"Open every day {self._opens_at}am - {self._closes_at}pm"
def set_opening_hours(self, opens_at, closes_at):
"""
Sets the opening hours of the Cafe
:param opens_at:
:type opens_at:
:param closes_at:
:type closes_at:
:return:
:rtype:
"""
self._opens_at = opens_at
self._closes_at = closes_at
@property
def owner(self):
"""
Returns the owner of the Cafe
:rtype: str
"""
return "Unknown"
@property
def serves_spam(self):
"""
Returns whether the Cafe serves spam
:rtype: bool
"""
return True
class SpamCafe(Cafe):
"""
Cafe that serves Spam to Vikings
"""
def __init__(self):
super().__init__()
self._todays_special = (
"Lobster Thermidor au Crevette with a Mornay "
"sauce served in a Provencale manner with "
"shallots and aubergines garnished with truffle "
"pate, brandy and with a fried egg on top and spam."
)
@doctools.is_documented_by(Cafe.menu) # type: ignore[prop-decorator]
@property
def menu(self):
return super().menu + [self._todays_special]
@doctools.is_documented_by(Cafe.opening_hours) # type: ignore[prop-decorator]
@property
def opening_hours(self):
return f"""Open Monday-Saturday {self._opens_at}am - {self._closes_at}pm
Please note our opening hours may vary due to COVID-19"""
@doctools.append_docstring_from(Cafe.set_opening_hours)
def set_opening_hours(self, opens_at, closes_at):
"""I will not buy this record, it is scratched.
"""
self._opens_at = opens_at
self._closes_at = closes_at
@doctools.append_docstring_from(math.ceil)
def ceil(self, x):
"""
I don't know why the cafe has a ceil function, but we'd better document it properly.
"""
return math.ceil(x)
@property
def owner(self):
return "Terry Jones"
def documented_function(a: float, b: float, c: float, d: float) -> float:
"""
This function is documented. It multiplies the four values `a`, `b`, `c`, and `d` together.
:type a: float
:type b: float
:type c: float
:type d: float
"""
return a * b * c * d
@doctools.is_documented_by(documented_function)
def undocumented_function(a: float, b: float, c: float, d: int) -> float:
return d * c * b * a
@doctools.append_docstring_from(documented_function)
def partially_documented_function(a: float, b: float, c: float, d: float) -> None:
"""
This function works like ``documented_function`` except it returns the result telepathically.
"""
d * c * b * a # pylint: disable=pointless-statement
class DummyClass:
@doctools.is_documented_by(documented_function)
def function_in_class_with_same_args(self, a, b, c, d):
return
@pytest.mark.parametrize(
"docstring, expects",
[
("\t\t\t ", ''),
("\t\t\t Spam", "Spam"),
("\t\t\t Spam \t\t\t", "Spam \t\t\t"),
("\t\t\t Spam\n \t\t\t", "Spam\n"),
(" \t\t\t", ''),
(" \t\t\tSpam", "Spam"),
(" \t\t\tSpam\t\t\t ", "Spam\t\t\t "),
(" \t\t\tSpam\n\t\t\t ", "Spam\n"),
('', ''),
(None, ''),
(False, ''),
(0, ''),
([], ''),
],
)
def test_deindent_string(docstring, expects):
assert doctools.deindent_string(docstring) == expects
@pytest.mark.xfail(PEP_563, reason="The future of PEP 563 is unclear at this time.")
def test_decorators():
# Check the ``SpamCafe`` class has has its docstrings modified appropriately.
# menu and opening_hours should have been copied from menu of the superclass
assert SpamCafe.menu.__doc__ == Cafe.menu.__doc__
assert SpamCafe.opening_hours.__doc__ == Cafe.opening_hours.__doc__
# set_opening_hours and ceil should have extra text at the beginning
assert (SpamCafe.set_opening_hours.__doc__ or '').startswith("I will not buy this record, it is scratched.")
doc = (doctools.deindent_string(SpamCafe.set_opening_hours.__doc__))
assert doc.endswith(doctools.deindent_string(Cafe.set_opening_hours.__doc__))
# Dedented both strings to be sure of equivalence
expected = "I don't know why the cafe has a ceil function, but we'd better document it properly."
assert (SpamCafe.ceil.__doc__ or '').startswith(expected)
doc = doctools.deindent_string(SpamCafe.ceil.__doc__).rstrip()
assert doc.endswith(doctools.deindent_string(math.ceil.__doc__).rstrip())
# Dedented both strings to be sure of equivalence
# Functions
assert undocumented_function.__doc__ == documented_function.__doc__
assert undocumented_function.__name__ == "undocumented_function"
if PEP_563:
assert undocumented_function.__annotations__ == {
'a': "float",
'b': "float",
'c': "float",
'd': "int",
"return": "float",
}
else:
assert undocumented_function.__annotations__ == {
'a': float,
'b': float,
'c': float,
'd': int,
"return": float,
}
expected = "This function works like ``documented_function`` except it returns the result telepathically."
assert (partially_documented_function.__doc__ or '').startswith(expected)
doc = (doctools.deindent_string(partially_documented_function.__doc__))
assert doc.endswith(doctools.deindent_string(documented_function.__doc__))
# Dedented both strings to be sure of equivalence
assert DummyClass.function_in_class_with_same_args.__doc__ == documented_function.__doc__
assert DummyClass.function_in_class_with_same_args.__name__ == "function_in_class_with_same_args"
def test_document_object_from_another():
def funA() -> None:
pass
doctools.document_object_from_another(funA, str)
assert funA.__doc__ == str.__doc__
doctools.document_object_from_another(funA, int)
assert funA.__doc__ == int.__doc__
doctools.document_object_from_another(funA, math.ceil)
assert funA.__doc__ == math.ceil.__doc__
def test_append_doctring_from_another():
def funB():
"Hello" # noqa: Q002
def funC():
"World" # noqa: Q002
def funD():
pass
assert funB.__doc__ == "Hello"
assert funC.__doc__ == "World"
doctools.append_doctring_from_another(funB, funC)
assert funB.__doc__ == "Hello\n\nWorld\n"
doctools.append_doctring_from_another(funD, funB)
assert funD.__doc__ == "Hello\n\nWorld\n"
def test_still_callable():
cafe = Cafe()
assert cafe.menu == [
"egg and bacon",
"egg sausage and bacon",
"egg and spam",
"egg bacon and spam",
]
assert cafe.opening_hours == "Open every day 7am - 6pm"
cafe.set_opening_hours(9, 5)
assert cafe.opening_hours == "Open every day 9am - 5pm"
assert cafe.owner == "Unknown"
assert cafe.serves_spam is True
spam_cafe = SpamCafe()
assert spam_cafe.menu == [
"egg and bacon",
"egg sausage and bacon",
"egg and spam",
"egg bacon and spam",
"Lobster Thermidor au Crevette with a Mornay "
"sauce served in a Provencale manner with "
"shallots and aubergines garnished with truffle "
"pate, brandy and with a fried egg on top and spam.",
]
assert spam_cafe.opening_hours == """Open Monday-Saturday 7am - 6pm
Please note our opening hours may vary due to COVID-19"""
spam_cafe.set_opening_hours(9, 5)
assert spam_cafe.opening_hours == """Open Monday-Saturday 9am - 5pm
Please note our opening hours may vary due to COVID-19"""
assert spam_cafe.owner == "Terry Jones"
assert spam_cafe.serves_spam is True
assert spam_cafe.ceil(5.5) == 6
assert documented_function(1, 2, 3, 4) == 24
assert undocumented_function(1, 2, 3, 4) == 24
assert partially_documented_function(1, 2, 3, 4) is None
def test_make_sphinx_links():
original = """
This is a docstring that contains references to ``str``, ``int``, ``float`` and ``None``,
but lacks proper references to them when rendered in Sphinx.
:return: pi
:rtype: float
"""
sphinx = """
This is a docstring that contains references to :class:`str`, :class:`int`, :class:`float` and :py:obj:`None`,
but lacks proper references to them when rendered in Sphinx.
:return: pi
:rtype: float
"""
assert doctools.make_sphinx_links(original) == sphinx
def test_sphinxify_docstring():
@doctools.sphinxify_docstring()
def demo_function():
"""
This is a docstring that contains references to ``str``, ``int``, and ``float``
but lacks proper references to them when rendered in Sphinx.
:return: pi
:rtype: float
""" # noqa: SXL001
return math.pi
if sys.version_info >= (3, 13):
assert demo_function.__doc__ == """
This is a docstring that contains references to :class:`str`, :class:`int`, and :class:`float`
but lacks proper references to them when rendered in Sphinx.
:return: pi
:rtype: float
"""
else:
assert demo_function.__doc__ == """
This is a docstring that contains references to :class:`str`, :class:`int`, and :class:`float`
but lacks proper references to them when rendered in Sphinx.
:return: pi
:rtype: float
"""
@prettify_docstrings
class Klasse:
def __delattr__(self, item): ...
def __dir__(self): ...
def __eq__(self, other): ...
def __getattribute__(self, item): ...
def __ge__(self, other): ...
def __gt__(self, other): ...
def __hash__(self): ...
def __lt__(self, other): ...
def __le__(self, other): ...
def __ne__(self, other): ...
def __setattr__(self, item, value): ...
def __sizeof__(self): ...
def __str__(self): ...
def __contains__(self, item): ...
def __getitem__(self, item): ...
def __setitem__(self, item, value): ...
def __delitem__(self, item): ...
def __and__(self): ...
def __add__(self, other): ...
def __abs__(self): ...
def __divmod__(self, other): ...
def __floordiv__(self, other): ...
def __invert__(self): ...
def __lshift__(self, other): ...
def __mod__(self, other): ...
def __mul__(self, other): ...
def __neg__(self): ...
def __or__(self, other): ...
def __pos__(self): ...
def __pow__(self, other): ...
def __radd__(self, other): ...
def __rand__(self, other): ...
def __rdivmod__(self, other): ...
def __rfloordiv__(self, other): ...
def __rlshift__(self, other): ...
def __rmod__(self, other): ...
def __rmul__(self, other): ...
def __ror__(self, other): ...
def __rpow__(self, other): ...
def __rrshift__(self, other): ...
def __rshift__(self, other): ...
def __rsub__(self, other): ...
def __rtruediv__(self, other): ...
def __rxor__(self, other): ...
def __sub__(self, other): ...
def __truediv__(self, other): ...
def __xor__(self, other): ...
def __float__(self): ...
def __int__(self): ...
def __repr__(self): ...
def __bool__(self): ...
def test_prettify_docstrings():
all_docstrings = {
**base_new_docstrings,
**container_docstrings,
**operator_docstrings,
**base_int_docstrings,
}
for attr_name, docstring in all_docstrings.items():
if PYPY and attr_name in {"__delattr__", "__dir__"}:
continue
assert getattr(Klasse, attr_name).__doc__ == docstring
assert get_type_hints(Klasse.__eq__)["return"] is bool
assert get_type_hints(Klasse.__ge__)["return"] is bool
assert get_type_hints(Klasse.__gt__)["return"] is bool
assert get_type_hints(Klasse.__lt__)["return"] is bool
assert get_type_hints(Klasse.__le__)["return"] is bool
assert get_type_hints(Klasse.__ne__)["return"] is bool
assert get_type_hints(Klasse.__repr__)["return"] is str
assert get_type_hints(Klasse.__str__)["return"] is str
assert get_type_hints(Klasse.__int__)["return"] is int
assert get_type_hints(Klasse.__float__)["return"] is float
assert get_type_hints(Klasse.__bool__)["return"] is bool
assert Klasse.__repr__.__doc__ == "Return a string representation of the :class:`~tests.test_doctools.Klasse`."
@max_version("3.7")
def test_prettify_with_method():
class F(Iterable):
pass
assert prettify_docstrings(F).__getitem__.__doc__ != "Return ``self[key]``." # type: ignore[misc]
class G(Dictable):
pass
assert prettify_docstrings(G).__getitem__.__doc__ != "Return ``self[key]``." # type: ignore[misc]
def test_prettify_namedtuple():
@prettify_docstrings
class T(NamedTuple):
a: str
b: float
assert T.__repr__.__doc__ == "Return a string representation of the :class:`~tests.test_doctools.T`."