Skip to content

Instantly share code, notes, and snippets.

@omaciel
Last active January 2, 2016 03:59
Show Gist options
  • Save omaciel/8247296 to your computer and use it in GitHub Desktop.
Save omaciel/8247296 to your computer and use it in GitHub Desktop.
An example of using a python MetaClass for Data Driven testing

An example of using python metaclasses to perform data driven tests.

nosetests test_metaclass.py
test_baz_exists (tests.cli.test_foo.TestMetaClass) ... ok
test_greater_than_zero_1 (tests.cli.test_foo.TestMetaClass) ... ok
test_greater_than_zero_2 (tests.cli.test_foo.TestMetaClass) ... ok
test_greater_than_zero_3 (tests.cli.test_foo.TestMetaClass) ... ok
test_greater_than_zero_4 (tests.cli.test_foo.TestMetaClass) ... ok
Ran 5 tests in 0.001s
OK
import unittest
from ddt import data
from ddt import ddt
class MetaTest(type):
"""
Metaclass to tweak test classes dynamically
"""
def __new__(cls, name, bases, dic):
"""Add test methods to new classes"""
_klass = super(MetaTest, cls).__new__(cls, name, bases, dic)
setattr(_klass, "test_greater_than_zero", cls.test_greater_than_zero)
return _klass
@staticmethod
@data(1, 2, 3, 4)
def test_greater_than_zero(cls, value):
"""Simple test"""
cls.assertTrue(value > 0)
class Base(unittest.TestCase):
"""Base class for all tests"""
@classmethod
def setUpClass(cls):
"""Adds a baz attribute to test classes"""
cls.baz = "Bazinga"
@ddt
class TestMetaClass(Base):
"""A simple test class"""
__metaclass__ = MetaTest
def test_baz_exists(self):
"""Checks that baz is not None"""
self.assertTrue(self.baz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment