Debian Codegraph @

doc/sphinxext/tests/test_docscrape.py

raw symbols SCIP
1
2 import os
3 import sys
4
5 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
6
7 from docscrape import ClassDoc, FunctionDoc, NumpyDocString
8 from docscrape_sphinx import SphinxClassDoc, SphinxDocString
9 from nose.tools import *
10
11 doc_txt = '''\
12 numpy.multivariate_normal(mean, cov, shape=None, spam=None)
13
14 Draw values from a multivariate normal distribution with specified
15 mean and covariance.
16
17 The multivariate normal or Gaussian distribution is a generalisation
18 of the one-dimensional normal distribution to higher dimensions.
19
20 Parameters
21 ----------
22 mean : (N,) ndarray
23 Mean of the N-dimensional distribution.
24
25 .. math::
26
27 (1+2+3)/3
28
29 cov : (N,N) ndarray
30 Covariance matrix of the distribution.
31 shape : tuple of ints
32 Given a shape of, for example, (m,n,k), m*n*k samples are
33 generated, and packed in an m-by-n-by-k arrangement. Because
34 each sample is N-dimensional, the output shape is (m,n,k,N).
35
36 Returns
37 -------
38 out : ndarray
39 The drawn samples, arranged according to `shape`. If the
40 shape given is (m,n,...), then the shape of `out` is is
41 (m,n,...,N).
42
43 In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
44 value drawn from the distribution.
45
46 Other Parameters
47 ----------------
48 spam : parrot
49 A parrot off its mortal coil.
50
51 Raises
52 ------
53 RuntimeError
54 Some error
55
56 Warns
57 -----
58 RuntimeWarning
59 Some warning
60
61 Warnings
62 --------
63 Certain warnings apply.
64
65 Notes
66 -----
67
68 Instead of specifying the full covariance matrix, popular
69 approximations include:
70
71 - Spherical covariance (`cov` is a multiple of the identity matrix)
72 - Diagonal covariance (`cov` has non-negative elements only on the diagonal)
73
74 This geometrical property can be seen in two dimensions by plotting
75 generated data-points:
76
77 >>> mean = [0,0]
78 >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
79
80 >>> x,y = multivariate_normal(mean,cov,5000).T
81 >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
82
83 Note that the covariance matrix must be symmetric and non-negative
84 definite.
85
86 References
87 ----------
88 .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
89 Processes," 3rd ed., McGraw-Hill Companies, 1991
90 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
91 2nd ed., Wiley, 2001.
92
93 See Also
94 --------
95 some, other, funcs
96 otherfunc : relationship
97
98 Examples
99 --------
100 >>> mean = (1,2)
101 >>> cov = [[1,0],[1,0]]
102 >>> x = multivariate_normal(mean,cov,(3,3))
103 >>> print x.shape
104 (3, 3, 2)
105
106 The following is probably true, given that 0.6 is roughly twice the
107 standard deviation:
108
109 >>> print list( (x[0,0,:] - mean) < 0.6 )
110 [True, True]
111
112 .. index:: random
113 :refguide: random;distributions, random;gauss
114
115 '''
116 doc = NumpyDocString(doc_txt)
117
118
119 def test_signature():
120 assert doc['Signature'].startswith('numpy.multivariate_normal(')
121 assert doc['Signature'].endswith('spam=None)')
122
123 def test_summary():
124 assert doc['Summary'][0].startswith('Draw values')
125 assert doc['Summary'][-1].endswith('covariance.')
126
127 def test_extended_summary():
128 assert doc['Extended Summary'][0].startswith('The multivariate normal')
129
130 def test_parameters():
131 assert_equal(len(doc['Parameters']), 3)
132 assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape'])
133
134 arg, arg_type, desc = doc['Parameters'][1]
135 assert_equal(arg_type, '(N,N) ndarray')
136 assert desc[0].startswith('Covariance matrix')
137 assert doc['Parameters'][0][-1][-2] == ' (1+2+3)/3'
138
139 def test_other_parameters():
140 assert_equal(len(doc['Other Parameters']), 1)
141 assert_equal([n for n,_,_ in doc['Other Parameters']], ['spam'])
142 arg, arg_type, desc = doc['Other Parameters'][0]
143 assert_equal(arg_type, 'parrot')
144 assert desc[0].startswith('A parrot off its mortal coil')
145
146 def test_returns():
147 assert_equal(len(doc['Returns']), 1)
148 arg, arg_type, desc = doc['Returns'][0]
149 assert_equal(arg, 'out')
150 assert_equal(arg_type, 'ndarray')
151 assert desc[0].startswith('The drawn samples')
152 assert desc[-1].endswith('distribution.')
153
154 def test_notes():
155 assert doc['Notes'][0].startswith('Instead')
156 assert doc['Notes'][-1].endswith('definite.')
157 assert_equal(len(doc['Notes']), 17)
158
159 def test_references():
160 assert doc['References'][0].startswith('..')
161 assert doc['References'][-1].endswith('2001.')
162
163 def test_examples():
164 assert doc['Examples'][0].startswith('>>>')
165 assert doc['Examples'][-1].endswith('True]')
166
167 def test_index():
168 assert_equal(doc['index']['default'], 'random')
169 print(doc['index'])
170 assert_equal(len(doc['index']), 2)
171 assert_equal(len(doc['index']['refguide']), 2)
172
173 def non_blank_line_by_line_compare(a,b):
174 a = [l for l in a.split('\n') if l.strip()]
175 b = [l for l in b.split('\n') if l.strip()]
176 for n,line in enumerate(a):
177 if not line == b[n]:
178 raise AssertionError(f"Lines {n} of a and b differ: "
179 f"\n>>> {line}\n<<< {b[n]}\n")
180
181 def test_str():
182 non_blank_line_by_line_compare(str(doc),
183 """numpy.multivariate_normal(mean, cov, shape=None, spam=None)
184
185 Draw values from a multivariate normal distribution with specified
186 mean and covariance.
187
188 The multivariate normal or Gaussian distribution is a generalisation
189 of the one-dimensional normal distribution to higher dimensions.
190
191 Parameters
192 ----------
193 mean : (N,) ndarray
194 Mean of the N-dimensional distribution.
195
196 .. math::
197
198 (1+2+3)/3
199
200 cov : (N,N) ndarray
201 Covariance matrix of the distribution.
202 shape : tuple of ints
203 Given a shape of, for example, (m,n,k), m*n*k samples are
204 generated, and packed in an m-by-n-by-k arrangement. Because
205 each sample is N-dimensional, the output shape is (m,n,k,N).
206
207 Returns
208 -------
209 out : ndarray
210 The drawn samples, arranged according to `shape`. If the
211 shape given is (m,n,...), then the shape of `out` is is
212 (m,n,...,N).
213
214 In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
215 value drawn from the distribution.
216
217 Other Parameters
218 ----------------
219 spam : parrot
220 A parrot off its mortal coil.
221
222 Raises
223 ------
224 RuntimeError :
225 Some error
226
227 Warns
228 -----
229 RuntimeWarning :
230 Some warning
231
232 Warnings
233 --------
234 Certain warnings apply.
235
236 See Also
237 --------
238 `some`_, `other`_, `funcs`_
239
240 `otherfunc`_
241 relationship
242
243 Notes
244 -----
245 Instead of specifying the full covariance matrix, popular
246 approximations include:
247
248 - Spherical covariance (`cov` is a multiple of the identity matrix)
249 - Diagonal covariance (`cov` has non-negative elements only on the diagonal)
250
251 This geometrical property can be seen in two dimensions by plotting
252 generated data-points:
253
254 >>> mean = [0,0]
255 >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
256
257 >>> x,y = multivariate_normal(mean,cov,5000).T
258 >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
259
260 Note that the covariance matrix must be symmetric and non-negative
261 definite.
262
263 References
264 ----------
265 .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
266 Processes," 3rd ed., McGraw-Hill Companies, 1991
267 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
268 2nd ed., Wiley, 2001.
269
270 Examples
271 --------
272 >>> mean = (1,2)
273 >>> cov = [[1,0],[1,0]]
274 >>> x = multivariate_normal(mean,cov,(3,3))
275 >>> print x.shape
276 (3, 3, 2)
277
278 The following is probably true, given that 0.6 is roughly twice the
279 standard deviation:
280
281 >>> print list( (x[0,0,:] - mean) < 0.6 )
282 [True, True]
283
284 .. index:: random
285 :refguide: random;distributions, random;gauss""")
286
287
288 def test_sphinx_str():
289 sphinx_doc = SphinxDocString(doc_txt)
290 non_blank_line_by_line_compare(str(sphinx_doc),
291 """
292 .. index:: random
293 single: random;distributions, random;gauss
294
295 Draw values from a multivariate normal distribution with specified
296 mean and covariance.
297
298 The multivariate normal or Gaussian distribution is a generalisation
299 of the one-dimensional normal distribution to higher dimensions.
300
301 :Parameters:
302
303 **mean** : (N,) ndarray
304
305 Mean of the N-dimensional distribution.
306
307 .. math::
308
309 (1+2+3)/3
310
311 **cov** : (N,N) ndarray
312
313 Covariance matrix of the distribution.
314
315 **shape** : tuple of ints
316
317 Given a shape of, for example, (m,n,k), m*n*k samples are
318 generated, and packed in an m-by-n-by-k arrangement. Because
319 each sample is N-dimensional, the output shape is (m,n,k,N).
320
321 :Returns:
322
323 **out** : ndarray
324
325 The drawn samples, arranged according to `shape`. If the
326 shape given is (m,n,...), then the shape of `out` is is
327 (m,n,...,N).
328
329 In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
330 value drawn from the distribution.
331
332 :Other Parameters:
333
334 **spam** : parrot
335
336 A parrot off its mortal coil.
337
338 :Raises:
339
340 **RuntimeError** :
341
342 Some error
343
344 :Warns:
345
346 **RuntimeWarning** :
347
348 Some warning
349
350 .. warning::
351
352 Certain warnings apply.
353
354 .. seealso::
355
356 :obj:`some`, :obj:`other`, :obj:`funcs`
357
358 :obj:`otherfunc`
359 relationship
360
361 .. rubric:: Notes
362
363 Instead of specifying the full covariance matrix, popular
364 approximations include:
365
366 - Spherical covariance (`cov` is a multiple of the identity matrix)
367 - Diagonal covariance (`cov` has non-negative elements only on the diagonal)
368
369 This geometrical property can be seen in two dimensions by plotting
370 generated data-points:
371
372 >>> mean = [0,0]
373 >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis
374
375 >>> x,y = multivariate_normal(mean,cov,5000).T
376 >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show()
377
378 Note that the covariance matrix must be symmetric and non-negative
379 definite.
380
381 .. rubric:: References
382
383 .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic
384 Processes," 3rd ed., McGraw-Hill Companies, 1991
385 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification,"
386 2nd ed., Wiley, 2001.
387
388 .. only:: latex
389
390 [1]_, [2]_
391
392 .. rubric:: Examples
393
394 >>> mean = (1,2)
395 >>> cov = [[1,0],[1,0]]
396 >>> x = multivariate_normal(mean,cov,(3,3))
397 >>> print x.shape
398 (3, 3, 2)
399
400 The following is probably true, given that 0.6 is roughly twice the
401 standard deviation:
402
403 >>> print list( (x[0,0,:] - mean) < 0.6 )
404 [True, True]
405 """)
406
407
408 doc2 = NumpyDocString("""
409 Returns array of indices of the maximum values of along the given axis.
410
411 Parameters
412 ----------
413 a : {array_like}
414 Array to look in.
415 axis : {None, integer}
416 If None, the index is into the flattened array, otherwise along
417 the specified axis""")
418
419 def test_parameters_without_extended_description():
420 assert_equal(len(doc2['Parameters']), 2)
421
422 doc3 = NumpyDocString("""
423 my_signature(*params, **kwds)
424
425 Return this and that.
426 """)
427
428 def test_escape_stars():
429 signature = str(doc3).split('\n')[0]
430 assert_equal(signature, r'my_signature(\*params, \*\*kwds)')
431
432 doc4 = NumpyDocString(
433 """a.conj()
434
435 Return an array with all complex-valued elements conjugated.""")
436
437 def test_empty_extended_summary():
438 assert_equal(doc4['Extended Summary'], [])
439
440 doc5 = NumpyDocString(
441 """
442 a.something()
443
444 Raises
445 ------
446 LinAlgException
447 If array is singular.
448
449 Warns
450 -----
451 SomeWarning
452 If needed
453 """)
454
455 def test_raises():
456 assert_equal(len(doc5['Raises']), 1)
457 name,_,desc = doc5['Raises'][0]
458 assert_equal(name,'LinAlgException')
459 assert_equal(desc,['If array is singular.'])
460
461 def test_warns():
462 assert_equal(len(doc5['Warns']), 1)
463 name,_,desc = doc5['Warns'][0]
464 assert_equal(name,'SomeWarning')
465 assert_equal(desc,['If needed'])
466
467 def test_see_also():
468 doc6 = NumpyDocString(
469 """
470 z(x,theta)
471
472 See Also
473 --------
474 func_a, func_b, func_c
475 func_d : some equivalent func
476 foo.func_e : some other func over
477 multiple lines
478 func_f, func_g, :meth:`func_h`, func_j,
479 func_k
480 :obj:`baz.obj_q`
481 :class:`class_j`: fubar
482 foobar
483 """)
484
485 assert len(doc6['See Also']) == 12
486 for func, desc, role in doc6['See Also']:
487 if func in ('func_a', 'func_b', 'func_c', 'func_f',
488 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q'):
489 assert(not desc)
490 else:
491 assert(desc)
492
493 if func == 'func_h':
494 assert role == 'meth'
495 elif func == 'baz.obj_q':
496 assert role == 'obj'
497 elif func == 'class_j':
498 assert role == 'class'
499 else:
500 assert role is None
501
502 if func == 'func_d':
503 assert desc == ['some equivalent func']
504 elif func == 'foo.func_e':
505 assert desc == ['some other func over', 'multiple lines']
506 elif func == 'class_j':
507 assert desc == ['fubar', 'foobar']
508
509 def test_see_also_print():
510 class Dummy:
511 """
512 See Also
513 --------
514 func_a, func_b
515 func_c : some relationship
516 goes here
517 func_d
518 """
519 pass
520
521 obj = Dummy()
522 s = str(FunctionDoc(obj, role='func'))
523 assert(':func:`func_a`, :func:`func_b`' in s)
524 assert(' some relationship' in s)
525 assert(':func:`func_d`' in s)
526
527 doc7 = NumpyDocString("""
528
529 Doc starts on second line.
530
531 """)
532
533 def test_empty_first_line():
534 assert doc7['Summary'][0].startswith('Doc starts')
535
536
537 def test_no_summary():
538 str(SphinxDocString("""
539 Parameters
540 ----------"""))
541
542
543 def test_unicode():
544 doc = SphinxDocString("""
545 öäöäöäöäöåååå
546
547 öäöäöäööäååå
548
549 Parameters
550 ----------
551 ååå : äää
552 ööö
553
554 Returns
555 -------
556 ååå : ööö
557 äää
558
559 """)
560 assert doc['Summary'][0] == 'öäöäöäöäöåååå'.encode()
561
562 def test_plot_examples():
563 cfg = dict(use_plots=True)
564
565 doc = SphinxDocString("""
566 Examples
567 --------
568 >>> import matplotlib.pyplot as plt
569 >>> plt.plot([1,2,3],[4,5,6])
570 >>> plt.show()
571 """, config=cfg)
572 assert 'plot::' in str(doc), str(doc)
573
574 doc = SphinxDocString("""
575 Examples
576 --------
577 .. plot::
578
579 import matplotlib.pyplot as plt
580 plt.plot([1,2,3],[4,5,6])
581 plt.show()
582 """, config=cfg)
583 assert str(doc).count('plot::') == 1, str(doc)
584
585 def test_class_members():
586
587 class Dummy:
588 """
589 Dummy class.
590
591 """
592 def spam(self, a, b):
593 """Spam\n\nSpam spam."""
594 pass
595 def ham(self, c, d):
596 """Cheese\n\nNo cheese."""
597 pass
598
599 for cls in (ClassDoc, SphinxClassDoc):
600 doc = cls(Dummy, config=dict(show_class_members=False))
601 assert 'Methods' not in str(doc), (cls, str(doc))
602 assert 'spam' not in str(doc), (cls, str(doc))
603 assert 'ham' not in str(doc), (cls, str(doc))
604
605 doc = cls(Dummy, config=dict(show_class_members=True))
606 assert 'Methods' in str(doc), (cls, str(doc))
607 assert 'spam' in str(doc), (cls, str(doc))
608 assert 'ham' in str(doc), (cls, str(doc))
609
610 if cls is SphinxClassDoc:
611 assert '.. autosummary::' in str(doc), str(doc)
612
613 if __name__ == "__main__":
614 import nose
615 nose.run()