test_funcutils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. from boltons.funcutils import (copy_function,
  3. total_ordering,
  4. format_invocation,
  5. InstancePartial,
  6. CachedInstancePartial,
  7. noop)
  8. class Greeter(object):
  9. def __init__(self, greeting):
  10. self.greeting = greeting
  11. def greet(self, excitement='.'):
  12. return self.greeting.capitalize() + excitement
  13. partial_greet = InstancePartial(greet, excitement='!')
  14. cached_partial_greet = CachedInstancePartial(greet, excitement='...')
  15. def native_greet(self):
  16. return self.greet(';')
  17. class SubGreeter(Greeter):
  18. pass
  19. def test_partials():
  20. g = SubGreeter('hello')
  21. assert g.greet() == 'Hello.'
  22. assert g.native_greet() == 'Hello;'
  23. assert g.partial_greet() == 'Hello!'
  24. assert g.cached_partial_greet() == 'Hello...'
  25. assert CachedInstancePartial(g.greet, excitement='s')() == 'Hellos'
  26. g.native_greet = 'native reassigned'
  27. assert g.native_greet == 'native reassigned'
  28. g.partial_greet = 'partial reassigned'
  29. assert g.partial_greet == 'partial reassigned'
  30. g.cached_partial_greet = 'cached_partial reassigned'
  31. assert g.cached_partial_greet == 'cached_partial reassigned'
  32. def test_copy_function():
  33. def callee():
  34. return 1
  35. callee_copy = copy_function(callee)
  36. assert callee is not callee_copy
  37. assert callee() == callee_copy()
  38. def test_total_ordering():
  39. @total_ordering
  40. class Number(object):
  41. def __init__(self, val):
  42. self.val = int(val)
  43. def __gt__(self, other):
  44. return self.val > other
  45. def __eq__(self, other):
  46. return self.val == other
  47. num = Number(3)
  48. assert num > 0
  49. assert num == 3
  50. assert num < 5
  51. assert num >= 2
  52. assert num != 1
  53. def test_format_invocation():
  54. assert format_invocation('d') == "d()"
  55. assert format_invocation('f', ('a', 'b')) == "f('a', 'b')"
  56. assert format_invocation('g', (), {'x': 'y'}) == "g(x='y')"
  57. assert format_invocation('h', ('a', 'b'), {'x': 'y', 'z': 'zz'}) == "h('a', 'b', x='y', z='zz')"
  58. def test_noop():
  59. assert noop() is None
  60. assert noop(1, 2) is None
  61. assert noop(a=1, b=2) is None