1

OK, I know it's going to be obvious, but I cannot work out how to write a test for an internal function. Here's a trivial piece of code to illustrate the problem.

def high(x, y):
    def low(x):
        return x*2
    return y*low(x)

class TestHigh(unittest.TestCase):
    def test_high(self):
        self.assertEqual(high(1,2),4)

    def test_low(self):
        self.assertEqual(low(3),6)

results in

Exception: NameError: global name 'low' is not defined

In the "real" case I want to be able to test the lower level function in isolation to make sure all the paths are exercised, which is cumbersome when testing only from the higher level.

3 Answers 3

2

low is nested within the high function, so it's not accessible from outside the function. The equivalent for your function would be high(3,1)

Sign up to request clarification or add additional context in comments.

Comments

2

You write tests to ensure that the publicly visible interface performs according to its specification. You should not attempt to write tests for internal functionality that is not exposed.

If you cannot fully test low() through the results of high() then the untested parts of low() cannot matter to anything outside.

1 Comment

Here's my excuse. I got suckered into WingIDE's refactoring which looks neat, but if the nested functions are not individually testable it doesn't really help. Write it in testable parts in the first place seems the lesson here. Many thanks.
1

BAD: Try making a class and adding the functions as methods (or staticfunctions) to it.

(I'll leave this here as a reference for what NOT to do.)

GOOD: Write module level functions or accept that you can't test it if you nest it.

1 Comment

Please don't. This isn't Java. There is no need for a class here, and there's almost never a reason (apart from namespacing, and even then classmethods are equal or superior) to use static methods. Just use module-level functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.