Note that there are some explanatory texts on larger screens.

plurals
  1. POPython Introspection: Defining dynamic class methods during runtime
    primarykey
    data
    text
    <p>I'm trying to create a unit test, that checks that every function in <code>mymodule</code> has its own <code>TestCase</code> instance.<br> To reduce boiler-plate code and manual effort I wanted to use introspection/reflection to dynamically add <code>lambda</code> functions as class methods to the initially empty class <code>Test_TestCases</code>.<br> The following code kind of works - it does indeed add lambdas as class methods and <code>unittest.main()</code> finds and correctly calls them.</p> <pre><code>import unittest from unittest import TestCase import mymodule class Test_TestCases(TestCase): """Class whose test_* methods will be created during runtime.""" pass ################################################################################ if __name__ == "__main__": for item in dir(mymodule): attr = getattr(pws, item) if callable(attr): testname = "Test_%s" % item setattr(Test_TestCases, "test_%s_is_tested" % item, lambda self: self.assertTrue(testname in globals()) and issubclass(getattr(globals(), testname), TestCase)) unittest.main() </code></pre> <p>The problem is, that all tests succeed even though I do have untested functions in my unit test module.<br> After a little trying around I figured out that the variable <code>testname</code> has the same value every time the <code>lambda</code> is called.<br> I could minimize the problem to this piece of code for reproducability:</p> <pre><code>lambdas = [] for i in range(5): lambdas.append(lambda: str(i)) print ", ".join(f() for f in lambdas) </code></pre> <p>I'd expect this output:</p> <pre><code>0, 1, 2, 3, 4 </code></pre> <p>but instead I get:</p> <pre><code>4, 4, 4, 4, 4 </code></pre> <p>It seems that the lambdas are initialized lazily.<br> Could anyone please explain this behaviour or give me a hint on how I would accomplish my goal properly?</p> <p>Thanks in advance</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload