[Tutor] Order of unittests

Albert-Jan Roskam sjeik_appie at hotmail.com
Sat Oct 16 12:28:04 EDT 2021


   On 16 Oct 2021 16:50, Peter Otten <__peter__ at web.de> wrote:

     On 16/10/2021 10:43, Albert-Jan Roskam wrote:
     >     On 15 Oct 2021 14:53, Peter Otten <__peter__ at web.de> wrote:

     >     ===>> Hi Peter,
     >     Thank you! That looks quite compact, so I'll give that a try on
     Monday. I
     >     could even use a lambda for my_dir(). I thought dir() was
     (re)implemented
     >     by defining, or in this case injecting, a __dir__ special method?

     I should have warned that my my_dir()

     >       # shadow the dir() built-in with an order-preserving analogue
     >       def my_dir(obj):
     >            return list(vars(obj))

     is but a sketch that only works in the exact case you gave, i. e. it
     will miss __dir__(), inherited attributes, and probably something I
     can't think of at the moment.

     A low-effort improvement that at least will not miss any names might be
     to use the built-in dir() to find the names and vars() to partially
     (un)sort them:

     # untested
     def my_dir(obj):
          names = dir(obj)
          lookup = {n: i for i, n in enumerate(vars(obj))}
          return sorted(names, key=lambda name: lookup.get(name, -1))

     I'm sure someone has produced a more thorough implementation -- you just
     have to find it ;)

   ==>> Hi again,
   I just checked
   this: https://svn.python.org/projects/python/trunk/Lib/unittest/loader.py.
   The function "makeSuite" looks useful, in particular the sortUsing
   argument. If cmp = lambda a, b: 0, this means "everything is a tie",
   therefore no sorying, right? I'm using my phone, so no Python here :-(

 def makeSuite(testCaseClass, prefix='test', sortUsing=cmp,
               suiteClass=suite.TestSuite):
     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)


More information about the Tutor mailing list