testing - Mocking out methods on any instance of a python class -
i want mock out methods on instance of class in production code in order facilitate testing. there library in python facilitate this?
basically, want following, in python (the following code ruby, using mocha library):
def test_stubbing_an_instance_method_on_all_instances_of_a_class product.any_instance.stubs(:name).returns('stubbed_name') assert_equal 'stubbed_name', someclassthatusesproduct.get_new_product_name end
the important thing note above need mock out on class level, since i'm need mock out methods on instance created thing i'm testing.
use case:
i have class querymaker
calls method on instance of remoteapi
. want mock out remoteapi.get_data_from_remote_server
method return constant. how do inside test without having put special case within remoteapi
code check environment it's running in.
example of wanted in action:
# a.py class a(object): def foo(self): return "a's foo" # b.py import class b(object): def bar(self): x = a() return x.foo() # test.py import b import b def new_foo(self): return "new foo" a.foo = new_foo y = b() if y.bar() == "new foo": print "success!"
easiest way use class method. should use instance method, it's pain create those, whereas there's built-in function creates class method. class method, stub reference class (rather instance) first argument, since it's stub doesn't matter. so:
product.name = classmethod(lambda cls: "stubbed_name")
note signature of lambda must match signature of method you're replacing. also, of course, since python (like ruby) dynamic language, there no guarantee won't switch out stubbed method else before hands on instance, though expect know pretty if happens.
edit: on further investigation, can leave out classmethod()
:
product.name = lambda self: "stubbed_name"
i trying preserve original method's behavior closely possible, looks it's not necessary (and doesn't preserve behavior i'd hoped, anyhow).
Comments
Post a Comment