Mocking Functions Using Python Mock

后端 未结 5 2008
清酒与你
清酒与你 2020-12-01 06:08

I am trying to Mock a function (that returns some external content) using the python mock module.

I\'m having some trouble mocking functions that are im

5条回答
  •  天涯浪人
    2020-12-01 06:28

    I think I have a workaround, though it's still not quite clear on how to solve the general case

    In mymodule, if I replace

    from util import get_content
    
    class MyObj:    
        def func():
            get_content()
    

    with

    import util
    
    class MyObj:    
        def func():
            util.get_content()
    

    The Mock seems to get invoked. It looks like the namespaces need to match (which makes sense). However, the weird thing is that I would expect

    import mymodule
    mymodule.get_content = mock.Mock(return_value="mocked stuff")
    

    to do the trick in the original case where I am using the from/import syntax (which now pulls in get_content into mymodule). But this still refers to the unmocked get_content.

    Turns out the namespace matters - just need to keep that in mind when writing your code.

提交回复
热议问题