replacing __dict__ with an OrderedDict

Peter Otten __peter__ at web.de
Fri Jan 6 06:44:21 EST 2012


Ulrich Eckhardt wrote:

> The topic explains pretty much what I'm trying to do under Python
> 2.7[1]. The reason for this is that I want dir(SomeType) to show the
> attributes in the order of their declaration. This in turn should
> hopefully make unittest execute my tests in the order of their
> declaration[2], so that the output becomes more readable and structured,
> just as my test code (hopefully) is.
> 
> I've been toying around with metaclasses, trying to replace __dict__
> directly, or using type() to construct the class, but either I hit
> read-only attributes or the changes seem to be ignored.

Alternatively you can write your own test loader:

$ cat ordered_unittest2.py
import unittest

class Test(unittest.TestCase):
    def test_gamma(self):
        pass
    def test_beta(self):
        pass
    def test_alpha(self):
        pass

class Loader(unittest.TestLoader):
    def getTestCaseNames(self, testCaseClass):
        """Return a sequence of method names found within testCaseClass
        sorted by co_firstlineno.
        """
        def first_lineno(name):
            method = getattr(testCaseClass, name)
            return method.im_func.__code__.co_firstlineno

        function_names = super(Loader, self).getTestCaseNames(testCaseClass)
        function_names.sort(key=first_lineno)
        return function_names


if __name__ == "__main__":
    unittest.main(testLoader=Loader())

$ python2.7 ordered_unittest2.py -v
test_gamma (__main__.Test) ... ok
test_beta (__main__.Test) ... ok
test_alpha (__main__.Test) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK
$





More information about the Python-list mailing list