1

I've been searching on internet to find an example of using flexmock on python modules, but all doc's seem to be for object/class. I'm wondering if it's possible to mock some variables returned by a module. What if that module calls another module?

ex.

def function_inside_function(id, some_string):
    test_log = {"id": id, "definition": some_string}
    return test_log

def function1(id):
    some_string = 'blah' + id  # i am totally bs-ing here
    log = function_inside_function(id, some_string)
    return log

so now I want to test each function separately by using flexmock to mock some values

back then when doing the same thing with an object, I could do (say the object is assigned to be test_object)

flexmock(test_object).should_receive('some_func').and_return('some_value')

where some_func is being called inside that object

but when I try to do the same with a module, I kept getting

FlexmockError: <function function1 at some_address> does not have attribute function_inside_function

I want to know if it's possible to use flexmock on modules, and, if yes. how?

JChao
  • 2,178
  • 5
  • 35
  • 65

1 Answers1

0

After a lot of research and trial n error, it turns out that I have to use sys.modules

say my module is imported from path.to.module, then the syntax would be

flexmock(sys.modules['path.to.module']).should_receive('function.of.object').and_return(response)

function.of.object is the function being called. For example, requests.get. using only get will not work.

response is the response you try to mock. in the requests.get example, the response would be a requests.Response(), and then you can use setattr to set the attributes if flexmock complains about it. (Is there a better way to do it?)

JChao
  • 2,178
  • 5
  • 35
  • 65