3

Similar to this question. However the accepted solution doesn't work for me when using ddt.

For example:

def numbers_to_words(num):
    if(num == 1): return 'One'
    if(num == 2): return 'Two'
    if(num == 3): return 'Three'
    raise Error

@ddt
class TestNumbersToWords(unittest.TestCase):
    @unpack
    @data((1, 'One'), (2, 'Two'), (3, 'Three'))
    def test_should_return_correct_word(self, input, expected):
        self.assertEqual(expected, numbers_to_words(input))

If I run this in terminal it doesn't work

python3 testSuite.py TestNumbersToWords.test_should_return_correct_word
Community
  • 1
  • 1
syclee
  • 697
  • 7
  • 18

1 Answers1

2

This is because of the way ddt is "changing" the test names. If you run your tests in verbose mode, this is what you will see:

$ python testSuite.py -v
test_should_return_correct_word_1__1___One__ (__main__.TestNumbersToWords) ... ok
test_should_return_correct_word_2__2___Two__ (__main__.TestNumbersToWords) ... ok
test_should_return_correct_word_3__3___Three__ (__main__.TestNumbersToWords) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

As you can see, the test_should_return_correct_word does not exist here. But you can provide the real name of the method being run, and it will work:

$ python test_a.py TestNumbersToWords.test_should_return_correct_word_1__1___One__
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

But you won't be able to run all the tests matching a pattern, such as TestNumbersToWords.test_should_return_correct_word*.

julienc
  • 19,087
  • 17
  • 82
  • 82
  • 1
    I see. Is there a pattern to the renaming? Like is the first test always appended with '_1__{first_arg}__{second_arg}__? – syclee Nov 21 '16 at 09:49
  • 1
    The documentation states that the format is "`original_test_name_{ordinal}_{data}`. ordinal is the position of the data argument, starting with 1", but it's not very clear. On the other hand, maybe you could try pytest and its `parametrize` decorator that does something similar: http://doc.pytest.org/en/latest/parametrize.html – julienc Nov 21 '16 at 19:24