Bläddra i källkod

Doctest example.

Fred Damstra 7 år sedan
förälder
incheckning
6a9c17247b
2 ändrade filer med 40 tillägg och 0 borttagningar
  1. 16 0
      README.md
  2. 24 0
      examples/doctest-example.py

+ 16 - 0
README.md

@@ -5,6 +5,22 @@ Just notes on various things
 ## docstrings
 Use 'em.
 
+### doctest
+In your docstring, put examples that look like the command-line, such as
+```
+def square(x):
+    """
+    Returns x times itself.
+    >>> square(2)
+    4
+    """
+    return x*x
+```
+Then `import doctest` and `doctest.testmod()` inside `__main__`, and python will run the
+tests to verify correctness.
+
+Run with `python -v` to see the output of the doctest module.
+
 ## ArgParse
 
 

+ 24 - 0
examples/doctest-example.py

@@ -0,0 +1,24 @@
+#! /usr/bin/python3
+#
+# This example shows some built in unit tests for functions, alone with
+# docstring examples.
+
+def square(x):
+    """ 
+    Returns x times itself.
+    >>> square(2)
+    4
+    >>> square(4)
+    16
+    >>> square(333)
+    110889
+    """
+    return x*x
+
+if __name__ == "__main__":
+    """
+    This is how doctest would be used in a module.
+    """
+    import doctest
+    doctest.testmod()
+