From d9536a45ef35626568938e649538a3e9fede037e Mon Sep 17 00:00:00 2001 From: domidimi Date: Wed, 22 Jul 2015 22:36:40 +0200 Subject: [PATCH] docstring: Add decorator to format the docstrings 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: domidimi@github.com --- ddt.py | 12 ++++++++++++ test/test_example.py | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/ddt.py b/ddt.py index a084695..51d496a 100644 --- a/ddt.py +++ b/ddt.py @@ -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): @@ -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. @@ -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 diff --git a/test/test_example.py b/test/test_example.py index 35fc002..e75347b 100644 --- a/test/test_example.py +++ b/test/test_example.py @@ -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 @@ -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)