2

Can I test a method inside a method in Python?

search.py

   def SearchWeb(query=None):
        """Search via API"""
        search = cool_api.api_request(query)
        def _HandleResponse(search):
            if search:
              return search['result']
        return _HandleResponse(search)

I want to create a test method for _HandleResponse using unittest

search_test.py

import unittest

class MyTest(unittest.TestCase):
    def test(self):
        response = {}
        response['result'] = 'yes'
        self.assertEqual(search._HandleResponse(response), 'yes')

But _HandleResponse is not accessible. I get:

AttributeError: 'module' object has no attribute '_HandleResponse'

I can move _HandleResponse outside SearchWeb method and that works, but wondering if this is possible?

2
  • 1
    It's not possible, the method is actually created every time the function is called. This means you have no static reference to it and you can't write a test. You have to test it through the SearchWeb function. Commented Mar 16, 2017 at 16:56
  • Can you change this to answer? Commented Mar 29, 2017 at 4:58

1 Answer 1

1

As far as I understand it's not possible.

The nested method is actually created every time the function is called. This means you have no static reference to it and you can't write a test to a function that doesn't exist. You have to test it through the SearchWeb function.

Side note: Technically there are probably (complex) things you can do but none that I can think of are worth mentioning.

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

Comments

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.