-
Notifications
You must be signed in to change notification settings - Fork 1
/
lesson-25.py
executable file
·235 lines (193 loc) · 6.72 KB
/
lesson-25.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python3
# lesson-25.py - add name to account, create multiple instances of account and test transactions
#
# Learn:
# testing
# instrumenting code to assist with testing
# multiple instantiation of a class
# default parameter value
# program startup flag
# program exit code
#
# automate from the command line, for example:
# printf "w\n.02\nd\n125.32\nw\n100\nd\n1\nt\nq\n" | ./take-25.py 100.01; echo
import re
import sys
class Account:
def __init__(self, name, balance, showBalanceAfterTransaction=True):
self.name = name
self.balance = balance
self.startingBalance = balance
self.showBalanceAfterTransaction = showBalanceAfterTransaction
self.transactions = []
def getName(self):
return self.name
def getBalance(self):
return self.balance
def showBalance(self):
print('%s: balance is $%0.2f.' % (self.name, self.balance))
print()
def showTransactions(self):
balance = self.startingBalance
print(' op amount balance')
print('-------- ---------- ----------')
print(' %10.2f (starting)' % balance)
for transaction in self.transactions:
[op, amount] = transaction
if op == 'w':
opLabel = 'withdraw'
balance -= amount
else:
opLabel = 'deposit'
balance += amount
print('%-8s %10.2f %10.2f' % (opLabel, amount, balance))
print()
def withdrawal(self, amount):
if amount > self.balance:
print("Sorry, you don't have that much!")
else:
print('%s: withdraw $%0.2f.' % (self.name, amount))
self.balance = float('%.2f' % (self.balance - amount)) # prevent accumulation error
self.transactions.append(['w', amount])
if self.showBalanceAfterTransaction:
self.showBalance()
def deposit(self, amount):
print('%s: deposit $%0.2f.' % (self.name, amount))
self.balance = float('%.2f' % (self.balance + amount)) # prevent accumulation error
self.transactions.append(['d', amount])
if self.showBalanceAfterTransaction:
self.showBalance()
def processTransactions(account):
while True:
amount = None
op = Input().getOperation()
if op == 'q':
break
elif op == 't':
account.showTransactions()
elif op is not None:
amount = Input().getAmount()
if amount is None:
pass
elif op == 'd':
account.deposit(amount)
else:
account.withdrawal(amount)
class Input:
def getOperation(self):
op = input('Enter d for deposit, w for withdrawal, t for transactions, or q to quit: ')
if op != 'q' and op != 'd' and op != 'w' and op != 't':
print('Invalid operation. Please try again.')
op = None
return op
def validateDollarAmount(self, amountStr):
tooMuchPrecision = re.compile('.*\.\d\d\d.*')
if tooMuchPrecision.match(str(amountStr)):
raise Exception('You cannot supply fractions of a cent.')
def getAmount(self):
amount = None
try:
value = input('Enter amount: ')
amount = float(value)
if amount <= 0:
raise Exception('The amount must be positive.')
self.validateDollarAmount(value)
except ValueError:
print('Invalid amount. Please try again.')
except Exception as e:
print(e)
amount = None
return amount
class Test:
def __init__(self):
self.numTests = 0
self.numPass = 0
def testBalance(self, account, expected):
self.numTests += 1
actual = account.getBalance()
name = account.getName()
if actual == expected:
self.numPass += 1
print('%s: OK balance = %.2f' % (name, actual))
else:
print('%s: ERROR balance = %.2f, but expected %.2f' % (name, actual, expected))
def summarizeResults(self):
numFailed = self.numTests - self.numPass
print()
print('%d tests total' % self.numTests)
if numFailed == 0:
print('all passed')
else:
print('%d passed' % self.numPass)
print('%d failed' % numFailed)
return numFailed == 0
def run(self):
a1 = Account('a1', 0, False)
self.testBalance(a1, 0)
a2 = Account('a2', 100, False)
self.testBalance(a2, 100)
a1.deposit(10)
a1.deposit(10)
a1.deposit(10)
a1.withdrawal(5)
self.testBalance(a1, 25.0)
a2.withdrawal(25)
a2.withdrawal(15)
a2.withdrawal(0.50)
a2.deposit(15)
self.testBalance(a2, 74.5)
a1.withdrawal(3.25)
a1.deposit(4)
self.testBalance(a1, 25.75)
a2.deposit(1.30)
a2.withdrawal(11.29)
self.testBalance(a2, 64.51)
allPassed = self.summarizeResults()
return allPassed
class App:
defaultBalance = 0.0
def usage(self):
print('usage: %s [-t|amount]' % sys.argv[0])
print('where -t means to run test')
print('and amount is a starting balance dollar amount')
def parseAndValidateBalance(self, value):
try:
balance = float(value)
if balance < 0:
raise Exception('The balance cannot be negative.')
Input().validateDollarAmount(value)
except ValueError:
raise Exception('Invalid starting balance. Try something like 17.25 or 0 (the default).')
return balance
def getArgs(self):
isTestFlag = False
balance = App.defaultBalance
if len(sys.argv) > 2:
raise Exception('Unrecognized arguments.')
elif len(sys.argv) == 2:
value = sys.argv[1]
if value == '-t':
isTestFlag = True
else:
balance = self.parseAndValidateBalance(value)
return (isTestFlag, balance)
def processUserInputs(self, balance):
print('Welcome to the bank.')
account = Account('MySavings', balance)
account.showBalance()
account.processTransactions()
def run(self):
try:
(isTestFlag, balance) = self.getArgs()
except Exception as e:
print(e)
self.usage()
sys.exit(1)
if not isTestFlag:
self.processUserInputs(balance)
elif not Test().run():
sys.exit(1)
def main():
App().run()
sys.exit(0)
main()