r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

Show parent comments

19

u/[deleted] Nov 14 '17

God no. You can't test that closure. You just made that whole function a black box.

5

u/Hellios Nov 14 '17

I think closures can be tested just fine.

import unittest

def foo(n):
    def add_one():
        return n + 1

    return add_one

class AddOneTest(unittest.TestCase):

    def test_add_one_increases_value_given(self):
        add_one = foo(1)

        self.assertGreater(add_one(), 1)

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

You have the same control over the code under test as you would in the class example. Pass in a mock object to __init__ and get an object with a mock inside it or pass a mock object to a function and get a closure with a mock inside it. Either way there's dependency injection and visibility into what's happening under the hood. Far from black box testing.

4

u/[deleted] Nov 14 '17

Definitely still not a unit test on functionf.