Previous topic

Welcome to DDT’s documentation!

Next topic

API

This Page

Example usage

DDT consists of a class decorator ddt (for your TestCase subclass) and two method decorators (for your tests that want to be multiplied):

  • data: contains as many arguments as values you want to feed to the test.
  • file_data: will load test data from a JSON file.

This allows you to write your tests as:

import unittest
from ddt import ddt, data, file_data
from .mycode import larger_than_two, has_three_elements, is_a_greeting


class mylist(list):
    pass


def annotated(a, b):
    r = mylist([a, b])
    setattr(r, "__name__", "test_%d_greater_than_%d" % (a, b))
    return r


@ddt
class FooTestCase(unittest.TestCase):

    def test_undecorated(self):
        self.assertTrue(larger_than_two(24))

    @data(3, 4, 12, 23)
    def test_larger_than_two(self, value):
        self.assertTrue(larger_than_two(value))

    @data(1, -3, 2, 0)
    def test_not_larger_than_two(self, value):
        self.assertFalse(larger_than_two(value))

    @data(annotated(2, 1), annotated(10, 5))
    def test_greater(self, value):
        a, b = value
        self.assertGreater(a, b)

    @file_data('test_data_dict.json')
    def test_file_data_dict(self, value):
        self.assertTrue(has_three_elements(value))

    @file_data('test_data_list.json')
    def test_file_data_list(self, value):
        self.assertTrue(is_a_greeting(value))

Where test_data_dict.json:

{
    "unsorted_list": [ 10, 12, 15 ],
    "sorted_list": [ 15, 12, 50 ]
}

and test_data_list.json:

[
    "Hello",
    "Goodbye"
]

And then run them with:

$ nosetests -v test/test_example.py
test_10_greater_than_5 (test.test_example.FooTestCase) ... ok
test_2_greater_than_1 (test.test_example.FooTestCase) ... ok
test_file_data_dict_sorted_list (test.test_example.FooTestCase) ... ok
test_file_data_dict_unsorted_list (test.test_example.FooTestCase) ... ok
test_file_data_list_Goodbye (test.test_example.FooTestCase) ... ok
test_file_data_list_Hello (test.test_example.FooTestCase) ... ok
test_larger_than_two_12 (test.test_example.FooTestCase) ... ok
test_larger_than_two_23 (test.test_example.FooTestCase) ... ok
test_larger_than_two_3 (test.test_example.FooTestCase) ... ok
test_larger_than_two_4 (test.test_example.FooTestCase) ... ok
test_not_larger_than_two_-3 (test.test_example.FooTestCase) ... ok
test_not_larger_than_two_0 (test.test_example.FooTestCase) ... ok
test_not_larger_than_two_1 (test.test_example.FooTestCase) ... ok
test_not_larger_than_two_2 (test.test_example.FooTestCase) ... ok
test_undecorated (test.test_example.FooTestCase) ... ok

----------------------------------------------------------------------
Ran 15 tests in 0.002s

OK

6 test methods + some magic decorators = 15 test cases.