Guest
Public paste!

mlk

By: a guest | Sep 28th, 2008 | Syntax: Python | Size: 1.90 KB | Hits: 401 | Expires: Never
Copy text to clipboard
  1. from peak.events.trellis import *
  2.  
  3. ##
  4. ## Example #1: Bank accounts and policy enforcement (validation)
  5. ##
  6.  
  7.  
  8. class Account(Component):
  9.     balance = attr(0)
  10.     interest_rate = attr(1.0)
  11.     policy = attr()
  12.  
  13.     @maintain
  14.     def enforce_policy(self):
  15.         if self.policy is not None:
  16.             self.policy.check_account(self)
  17.  
  18.  
  19.  
  20.  
  21.  
  22. class StrictPolicy(Component):
  23.     min_balance = attr(200)
  24.  
  25.     def check_account(self, account):
  26.         if account.balance < self.min_balance:
  27.             raise ValueError("Can't withdraw funds")
  28.  
  29.  
  30. class RelaxedPolicy(Component):
  31.     min_balance = attr(500)
  32.     # This rate only applies if balance > min_balance
  33.     interest_rate = attr(1.05)
  34.  
  35.     def check_account(self, account):
  36.         if account.balance < 0:
  37.             raise ValueError("Can't have negative balance")
  38.         if account.balance >= self.min_balance:
  39.             account.interest_rate = self.interest_rate
  40.         else:
  41.             account.interest_rate = 1.0
  42.  
  43.  
  44. class CreditPolicy(Component):
  45.     # This rate applies to accounts with negative balance
  46.     interest_rate = attr(0.85)
  47.  
  48.     def check_account(self, account):
  49.         if account.balance < 0:
  50.             account.interest_rate = self.interest_rate
  51.         else:
  52.             account.interest_rate = 1.0
  53.  
  54.  
  55. ##########################################
  56. ##########################################
  57.  
  58. from nose.tools import *
  59.  
  60. acc = Account(balance=1000, policy=StrictPolicy())
  61. assert_raises(ValueError, setattr, acc, 'balance', 100)
  62. assert acc.balance == 1000
  63. assert acc.interest_rate == 1.0
  64.  
  65. acc.policy = RelaxedPolicy()
  66. assert acc.interest_rate == 1.05
  67. acc.policy.min_balance = 2000
  68. assert acc.interest_rate == 1.0
  69.  
  70. acc.balance = 100
  71. assert_raises(ValueError, setattr, acc, 'balance', -100)
  72.  
  73. acc.policy = CreditPolicy()
  74. assert acc.interest_rate == 1.0
  75. acc.balance = -100
  76. assert acc.interest_rate == 0.85