Skip to content

Commit

Permalink
docstring: Add decorator to format the docstrings
Browse files Browse the repository at this point in the history
Some test frameworks like nose use the docstring to output information
about a test. In the case of generated tests all of them would get the
same description. Add a decorator which allows formating of the
docstring for each generated test function using the test values.

Example:

@DaTa(1,2)
@format_doc
def test_A(value):
    """Test A for value {}"""
    ...

executed with "nosetests -v", will output:
Test A for value 1
Test A for value 2

Signed-off-by: [email protected]
  • Loading branch information
domidimi committed Jul 22, 2015
1 parent 9e9998b commit d9536a4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
12 changes: 12 additions & 0 deletions ddt.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
DATA_ATTR = '%values' # store the data the test must run with
FILE_ATTR = '%file_path' # store the path to JSON file
UNPACK_ATTR = '%unpack' # remember that we have to unpack values
DOC_ATTR = '%doc' # remember that we have to format the docstring


def unpack(func):
Expand All @@ -32,6 +33,15 @@ def unpack(func):
return func


def format_doc(func):
"""
Method decorator to add value formating to the decorated functions
"""
setattr(func, DOC_ATTR, True)
return func


def data(*values):
"""
Method decorator to add to your test methods.
Expand Down Expand Up @@ -145,6 +155,8 @@ def feed_data(func, new_name, *args, **kwargs):
def wrapper(self):
return func(self, *args, **kwargs)
wrapper.__name__ = new_name
if hasattr(func, DOC_ATTR):
wrapper.__doc__ = func.__doc__.format(*args, **kwargs)
return wrapper


Expand Down
15 changes: 14 additions & 1 deletion test/test_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import unittest
from ddt import ddt, data, file_data, unpack
from ddt import ddt, data, file_data, unpack, format_doc
from test.mycode import larger_than_two, has_three_elements, is_a_greeting


Expand Down Expand Up @@ -58,3 +58,16 @@ def test_dicts_extracted_into_kwargs(self, first, second, third):
@data(u'ascii', u'non-ascii-\N{SNOWMAN}')
def test_unicode(self, value):
self.assertIn(value, (u'ascii', u'non-ascii-\N{SNOWMAN}'))

@format_doc
@data(3, 4, 12, 23)
def test_larger_than_two_with_doc(self, value):
"""Larger than two with value {0}"""
self.assertTrue(larger_than_two(value))

@data([3, 2], [4, 3], [5, 3])
@unpack
@format_doc
def test_list_extrac_into_args_with_doc(self, first_value, second_value):
"""Extract into args with first value {} and second value {}"""
self.assertTrue(first_value > second_value)

0 comments on commit d9536a4

Please sign in to comment.