Created
April 27, 2010 12:53
-
-
Save soplakanets/380698 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# coding: utf-8 | |
import unittest | |
class MetaTestCase(type): | |
def __new__(cls, name, supers, dictionary): | |
processBefore(dictionary) | |
processTestMethods(dictionary) | |
processAfter(dictionary) | |
return type.__new__(cls, name, supers, dictionary) | |
def processTestMethods(dictionary): | |
for key, value in dictionary.items(): | |
if isinstance(value, Test): | |
del dictionary[key] | |
dictionary["test_%s" % key] = value.function | |
def processBefore(dictionary): | |
functions = [] | |
for key, value in dictionary.items(): | |
if isinstance(value, Before): | |
functions.append(value.function) | |
dictionary["setUp"] = executorFor(functions) | |
def processAfter(dictionary): | |
functions = [] | |
for key, value in dictionary.items(): | |
if isinstance(value, After): | |
functions.append(value.function) | |
dictionary["tearDown"] = executorFor(functions) | |
def executorFor(functions): | |
return FunctionsExecutor(functions).build() | |
class FunctionsExecutor: | |
def __init__(self, functions): | |
self._functions = functions | |
def build(self): | |
def execute(that): | |
for f in self._functions: | |
f(that) | |
return execute | |
class FunctionHolder: | |
def __init__(self, function): | |
self.function = function | |
class Test(FunctionHolder): pass | |
class Before(FunctionHolder): pass | |
class After(FunctionHolder): pass | |
class TestCase(unittest.TestCase, metaclass=MetaTestCase): | |
pass | |
def test(function): | |
return Test(function) | |
def before(function): | |
return Before(function) | |
def after(function): | |
return After(function) | |
__all__ = [test, TestCase, before, after] | |
if __name__ == '__main__': | |
class SomeTest(TestCase): | |
@test | |
def someTestMethod(self): | |
print("Test method") | |
@before | |
def executeBefore(self): | |
print("Before") | |
@after | |
def executeAfter(self): | |
print("After") | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment