2

Sometimes I'm writing small utilities functions and pack them as python package.
How small? 30 - 60 lines of python.
And my question is do you think writing the tests inside the actual code is bad? abusing?

I can see a great benefits like usage examples inside the code itself without jumping between files (again from really small projects). Example:

#!/usr/bin/env python
# Actual code
def increment(number, by=1):
    return number += by

# Tests
def test_increment_positive():
    assert increment(1) == 2

def test_increment_negative():
    assert increment(-5) == -4

def test_increment_zero():
    assert increment(0) == 1

The general Idea taken from the monitoring framework riemann which I use, in riemann you write your tests file along with your code link

1 Answer 1

5

You can write doctests inside your documentation to indicate how your function should be used:

def increment(number, by=1):
    """ Increments the given number by some other number
    >>> increment(3)
    4
    >>> increment(5,3)
    8
    """
    return number += by

From the documentation:

  • To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.
  • To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
  • To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.