0

I have a private method in a module, for example

wallets.py

def __foo():
    return 0

When I try to test this method with this code

test_wallets.py

from unittest import TestCase
from db.services import wallets

class GetTokenQuantity(TestCase):
    def test_get_token_quantity(self):
        token_quantity = wallets.__foo()

I get this error AttributeError: module 'db.services.wallets' has no attribute '_GetTokenQuantity__foo'

How can I test this private method?

3
  • 1
    Actually that error shows that your code is working correctly. If you returned a "0", then it means the code was not private as it was supposed to be. In short, the test does pass. Commented Mar 21, 2023 at 0:27
  • Yes, but how do I test whether the returned value is correct or not? Commented Mar 21, 2023 at 0:32
  • It might actually be easier to test this with Pytest than with Unittest. since UnitTest uses classes, it's going to run into the private name mangling problem. Pytest doesn't require you to put your test cases into a class so name mangling shouldn't be an issue. Commented Mar 21, 2023 at 0:37

1 Answer 1

0

Try replacing leading double underscore (US) with a single.

E.g.

__foo

Becomes:

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

4 Comments

I can't do this, the convention in this code base is to use double underscore for private methods.
In python, that is not a good idea. I would suggest to rethink the convention for code base.
Why isn’t it a good idea?
The issue you're running into now is a good example of why it isn't a good idea. :) Double-underscore names get "mangled" and to access them from outside their native context (like in a test) you need to sort of reverse-engineer the mangling and/or bypass it by using getattr etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.