Guest User

Untitled

a guest
Jul 15th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. def make_closure(value):
  2.     def func(self, *args, **kwargs):
  3.         return value(*args, **kwargs)
  4.     return func
  5.  
  6. def lazymock(**kwargs):
  7.     class Foo(object): pass
  8.     for key, value in kwargs.iteritems():
  9.         if isinstance(value, types.FunctionType):
  10.             setattr(Foo, key, make_closure(value))
  11.         else:
  12.             setattr(Foo, key, value)
  13.     return Foo()
  14.  
  15. # And we should really test lazymock, so...
  16.  
  17. class TestLazymock(unittest.TestCase):
  18.     def testSimple(self):
  19.         x = lazymock(foo=3)
  20.         self.assertEqual(x.foo, 3)
  21.  
  22.     def testMany(self):
  23.         x = lazymock(foo=3, bar='Hello')
  24.         self.assertEqual(x.foo, 3)
  25.         self.assertEqual(x.bar, 'Hello')
  26.  
  27.     def testFunction(self):
  28.         x = lazymock(foo=lambda x: x + 3)
  29.         self.assertEqual(x.foo(3), 6)
Add Comment
Please, Sign In to add comment