简体   繁体   中英

Python: How do I mock a function call that sets a class variable

Say I have the classes in module.py

class A():
    INPUTS = {}

    def __init__():
        self.inputs = do_something(self.INPUTS)

class B(A):
    INPUTS = function_with_external_API_call()

    def something_to_test():
        pass # do stuff

In my unit tests (using pytest) I want to have an instance of B so that I can test B.something_to_test() . However importing the class B triggers function_with_external_API_call() .

This solution works but it seems like a bad solution.

with requests_mock.mock() as m:
    m.get(
        'https://url.com',
        json={'data': [{'id': '1'}]}
    )
    from module import B

How do I mock the function call so that I can import the class B and replace INPUTS with a mocked value?

I don't really understand fully what you try to do but INPUTS is in your case a class attribute . If you want INPUTS to be modified & called, I think it would be simpler to do like:

class A(object):
    def __init__(self, mookup=None):
        self.INPUTS = mookup

class B(A):
    def __init__(self):
        super().__init__(self.function_to_call)
    def function_to_call(self):
        pass

If this does not answer your question, can you please add more precisions to your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM