-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmorelia.py
executable file
·575 lines (428 loc) · 19.3 KB
/
morelia.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# -*- coding: utf-8 -*-
# __ __ _ _
# | \/ | ___ _ __ ___| (_) __ _
# | |\/| |/ _ \| '__/ _ \ | |/ _` |
# | | | | (_) | | | __/ | | (_| |
# |_| |_|\___/|_| \___|_|_|\__,_|
# o o | o
# ,_ __| ,
# | |_| / | | / | | / \_
# \/ |_/ |_/|_/\_/|_/|_/ \/
__version__ = '0.1.6'
# TODO get working with python 3,4,5, etc...
# TODO put http://www.dawnoftimecomics.com/index.php on comixpedia!
import re
# TODO what happens with blank table items?
# ERGO river is to riparian as pond is to ___?
class Morelia:
def __init__(self): self.parent = None
def _parse(self, predicate, list = [], line_number = 0):
self.concept = self.my_class_name()
self.predicate = predicate
self.steps = []
self.line_number = line_number
# TODO escape the sample regices already!
# and the default code should be 'print <arg_names, ... >'
for s in list[::-1]:
mpt = self.my_parent_type()
try:
if issubclass(s.__class__, mpt):
s.steps.append(self) # TODO squeek if can't find parent
self.parent = s
break
except TypeError, e:
self.enforce(False, 'Only one Feature per file') # CONSIDER prevent it don't trap it!!!
return self
def my_class_name(self): return re.sub(r'.*\.', '', str(self.__class__))
def prefix(self): return ''
def my_parent_type(self): return None
def _my_regex(self): # TODO calculate name inside
name = self.i_look_like()
return '\s*(' + name + '):?\s+(.*)'
def evaluate_steps(self, v):
v.visit(self)
for step in self.steps: step.evaluate_steps(v)
def test_step(self, v): pass
def i_look_like(self): return self.my_class_name()
def count_dimensions(self):
return sum([step.count_dimension() for step in self.steps])
def count_dimension(self): # CONSIDER beautify this crud!
return 0
def validate_predicate(self):
return # looks good! (-:
def enforce(self, condition, diagnostic):
if not condition:
raise SyntaxError(self.format_fault(diagnostic))
def format_fault(self, diagnostic):
parent_reconstruction = ''
if self.parent: parent_reconstruction = self.parent.reconstruction().replace('\n', '\\n')
reconstruction = self.reconstruction().replace('\n', '\\n')
args = (self.get_filename(), self.line_number, parent_reconstruction, reconstruction, diagnostic)
return '\n File "%s", line %s, in %s\n %s\n%s' % args
def reconstruction(self):
recon = self.prefix() + self.concept + ': ' + self.predicate
if recon[-1] != '\n': recon += '\n'
return recon
def get_filename(self):
node = self
while node:
if not node.parent and hasattr(node, 'filename'): return node.filename
node = node.parent
return None
class Viridis(Morelia):
def prefix(self): return ' '
def find_step_name(self, suite):
self.method = None
self.find_by_doc_string(suite)
if not self.method: self.find_by_name(suite)
if self.method: return self.method_name
doc_string = self.suggest_doc_string()
arguments = '(self' + self.extra_arguments + ')' # note this line ain't tested! C-:
method_name = 'step_' + re.sub('[^\w]+', '_', self.predicate)
diagnostic = 'Cannot match step: ' + self.predicate + '\n' + \
'suggest:\n\n' + \
' def ' + method_name + arguments + ':\n' + \
' ' + doc_string + '\n\n' + \
' # code\n\n'
suite.fail(diagnostic)
def suggest_doc_string(self, predicate = None): # CONSIDER invent Ruby scan here, to dazzle the natives
self.extra_arguments = ''
if not predicate: predicate = self.predicate
predicate = predicate.replace("'", "\\'")
predicate = predicate.replace('\n', '\\n')
self._add_extra_args(r'\<(.+?)\>', predicate)
predicate = re.sub(r'\<.+?\>', '(.+)', predicate)
self._add_extra_args(r'"(.+?)"', predicate)
predicate = re.sub(r'".+?"', '"([^"]+)"', predicate)
predicate = re.sub(r' \s+', '\\s+', predicate)
predicate = predicate.replace('\n', '\\n')
return "r'" + predicate + "'"
def _add_extra_args(self, matcher, predicate):
args = re.findall(matcher, predicate)
for arg in args: self.extra_arguments += ', ' + arg
def find_by_name(self, suite):
self.method_name = None
clean = re.sub(r'[^\w]', '_?', self.predicate)
self.matches = []
for s in self.find_steps(suite, '^step_' + clean + '$'): # NOTE the ^$ ain't tested
self.method_name = s
self.method = suite.__getattribute__(s)
return
def find_by_doc_string(self, suite):
self.method_name = None
for s in self.find_steps(suite, '^step_'):
self.method_name = s
method = suite.__getattribute__(s)
doc = method.__doc__
if doc:
doc = re.compile('^' + doc + '$') # CONSIDER deal with users who put in the ^$
m = doc.match(self.augment_predicate())
if m:
self.matches = m.groups()
self.method = method
return
def find_steps(self, suite, regexp):
matcher = re.compile(regexp)
list = []
for s in dir(suite):
if matcher.match(s): list.append(s)
return list
def evaluate(self, suite):
self.find_step_name(suite)
self.method(*self.matches)
class Parser:
def __init__(self):
self.thangs = [ Feature, Scenario,
Step, Given, When, Then, And,
Row, Comment ]
self.steps = []
def parse_file(self, filename):
prose = open(filename, 'r').read()
self.parse_features(prose)
self.steps[0].filename = filename
return self
def parse_features(self, prose):
self.parse_feature(prose)
return self
def evaluate(self, suite):
self.rip(TestVisitor(suite)) # CONSIDER rename to Viridis
def report(self, suite):
rv = ReportVisitor(suite)
self.rip(rv)
return str(rv)
def rip(self, v):
if self.steps != []:
self.steps[0].evaluate_steps(v)
def parse_feature(self, lines):
self.line_number = 0
for self.line in lines.split('\n'):
self.line_number += 1
if not self.anneal_last_broken_line() and \
not self._parse_line():
if 0 < len(self.steps):
self._append_to_previous_node()
else:
s = Step()
s.concept = '???'
s.predicate = self.line
s.line_number = self.line_number
s.enforce(False, 'feature files must start with a Feature')
return self.steps
def anneal_last_broken_line(self):
if self.steps == []: return False # CONSIDER no need me
last_line = self.last_node.predicate
if re.search(r'\\\s*$', last_line):
last = self.last_node
last.predicate += '\n' + self.line
return True
return False
# TODO permit line breakers in comments
# | Given a table with one row
# \| i \| be \| a \| lonely \| row | table with only one row, line 1
def _parse_line(self):
self.line = self.line.rstrip()
for klass in self.thangs:
self.thang = klass()
rx = self.thang._my_regex()
m = re.compile(rx).match(self.line)
if m and len(m.groups()) > 0:
return self._register_line(m.groups())
def _register_line(self, groups):
predicate = ''
if len(groups) > 1: predicate = groups[1]
node = self.thang
node._parse(predicate, self.steps, self.line_number)
self.steps.append(node)
self.last_node = node
return node
def _append_to_previous_node(self):
previous = self.steps[-1]
previous.predicate += '\n' + self.line.strip()
previous.predicate = previous.predicate.strip()
previous.validate_predicate()
class ReportVisitor:
def __init__(self, suite): self.suite = suite
string = ''
def permute_schedule(self, node): return [[0]]
def step_schedule(self, node): return [ [ x for x in range(len(node.steps)) ] ]
def visit(self, node):
recon, we_owe = node.to_html()
if recon[-1] != '\n': recon += '\n' # TODO clean this outa def reconstruction(s)!
self.string += recon
return we_owe
def owed(self, owed): self.string += owed
def __str__(self):
return self.string
class TestVisitor:
def __init__(self, suite): self.suite = suite
def permute_schedule(self, node): return node.permute_schedule()
def step_schedule(self, node): return node.step_schedule()
def visit(self, node):
# print node.reconstruction() # CONSIDER if verbose
self.suite.step = node
node.test_step(self)
def owed(self, igme): pass
class Feature(Morelia):
def my_parent_type(self): return None
def test_step(self, v):
self.enforce(0 < len(self.steps), 'Feature without Scenario(s)')
def to_html(self):
return ['\n<div><table><tr style="background-color: #aaffbb;" width="100%">' +
'<td align="right" valign="top" width="100">' +
'<em>' + self.concept + '</em>:</td><td colspan="101">' +
_clean_html(self.predicate) + '</td></tr></table></div>', '']
class Scenario(Morelia):
def my_parent_type(self): return Feature
def evaluate_steps(self, visitor):
step_schedule = visitor.step_schedule(self) # TODO test this permuter directly (and rename it already)
for step_indices in step_schedule: # TODO think of a way to TDD this C-:
schedule = visitor.permute_schedule(self)
for indices in schedule:
self.row_indices = indices
self.evaluate_test_case(visitor, step_indices) # note this works on reports too!
def evaluate_test_case(self, visitor, step_indices = None): # note this permutes reports too!
self.enforce(0 < len(self.steps), 'Scenario without step(s) - Step, Given, When, Then, And, or #')
name = self.steps[0].find_step_name(visitor.suite)
visitor.suite = visitor.suite.__class__(name)
# print self.predicate # CONSIDER if verbose
visitor.suite.setUp()
try:
u_owe = visitor.visit(self)
for idx, step in enumerate(self.steps):
if step_indices == None or idx in step_indices: # TODO take out the default arg
step.evaluate_steps(visitor)
visitor.owed(u_owe)
finally:
visitor.suite.tearDown()
def permute_schedule(self): # TODO rename to permute_row_schedule
dims = self.count_Row_dimensions()
return _permute_indices(dims)
def step_schedule(self): # TODO rename to permute_step_schedule !
sched = []
pre_slug = []
# TODO deal with steps w/o whens
for idx, s in enumerate(self.steps):
if s.__class__ == When:
break
else:
pre_slug.append(idx)
for idx, s in enumerate(self.steps):
if s.__class__ == When:
slug = pre_slug[:]
slug.append(idx)
for idx in range(idx + 1, len(self.steps)):
s = self.steps[idx]
if s.__class__ == When: break
slug.append(idx)
sched.append(slug)
if sched == []: return [pre_slug]
return sched
def _embellish(self):
self.row_indices = []
for step in self.steps:
rowz = int(step.steps != [] and step.steps[0].__class__ is Row)
self.row_indices.append(rowz)
return self.row_indices.count(1) > 0
def count_Row_dimensions(self):
return [step.count_dimensions() for step in self.steps]
def reconstruction(self):
return '\n' + self.concept + ': ' + self.predicate
def to_html(self):
return ['\n<div><table width="100%"><tr style="background-color: #cdffb8;">' +
'<td align="right" valign="top" width="100"><em>' + self.concept + '</em>:</td><td colspan="101">' + \
_clean_html(self.predicate) + '</td></tr>', '</table></div>']
class Step(Viridis):
def my_parent_type(self): return Scenario
def test_step(self, v):
self.find_step_name(v.suite)
# ERGO use "born again pagan" somewhere
try:
self.method(*self.matches)
except (Exception, SyntaxError), e:
new_exception = self.format_fault(str(e))
e.args = (new_exception,) + (e.args[1:])
if type(e) == SyntaxError: raise SyntaxError(new_exception)
raise
def augment_predicate(self): # CONSIDER unsucktacularize me pleeeeeeze
if self.parent == None: return self.predicate
dims = self.parent.count_Row_dimensions()
if set(dims) == set([0]): return self.predicate
rep = re.compile(r'\<(\w+)\>')
replitrons = rep.findall(self.predicate)
if replitrons == []: return self.predicate
self.copy = self.predicate[:]
for self.replitron in replitrons:
for x in range(0, len(self.parent.row_indices)):
self.table = self.parent.steps[x].steps
if self.table != []:
q = 0
for self.title in self.table[0].harvest():
self.replace_replitron(x, q)
q += 1
return self.copy
def replace_replitron(self, x, q):
if self.title != self.replitron: return
at = self.parent.row_indices[x] + 1
if at >= len(self.table):
print 'CONSIDER this should never happen'
return
# CONSIDER we hit this too many times - hit once and stash the result
# CONSIDER better diagnostics when we miss these
stick = self.table[at].harvest()
found = stick[q] # CONSIDER this array overrun is what you get when your table is ragged
# CONSIDER only if it's not nothing?
found = found.replace('\n', '\\n') # CONSIDER crack the multi-line argument bug, and take this hack out!
self.copy = self.copy.replace('<'+self.replitron+'>', found)
# CONSIDER mix replitrons and matchers!
def to_html(self):
return '\n<tr><td align="right" valign="top"><em>' + self.concept + '</em></td><td colspan="101">' + _clean_html(self.predicate) + '</td></tr>', ''
class Given(Step): # CONSIDER distinguish these by fault signatures!
def prefix(self): return ' '
class When(Step): # TODO cycle these against the Scenario
def prefix(self): return ' '
def to_html(self):
return '\n<tr style="background-color: #cdffb8; background: url(http://www.zeroplayer.com/images/stuff/aqua_gradient.png) no-repeat; background-size: 100%;"><td align="right" valign="top"><em>' + self.concept + '</em></td><td colspan="101">' + _clean_html(self.predicate) + '</td></tr>', ''
class Then(Step):
def prefix(self): return ' '
class And(Step):
def prefix(self): return ' '
# CONSIDER how to validate that every row you think you wrote actually ran?
class Row(Morelia):
def i_look_like(self): return r'\|'
def my_parent_type(self): return Step
def prefix(self): return ' '
def reconstruction(self): # TODO strip the reconstruction at error time
recon = self.prefix() + '| ' + self.predicate
if recon[-1] != '\n': recon += '\n'
return recon
def to_html(self):
html = '\n<tr><td></td>'
idx = self.parent.steps.index(self)
em = 'span'
if idx == 0:
color = 'silver'
em = 'em'
elif ((2 + idx) / 3) % 2 == 0:
color = '#eeffff'
else:
color = '#ffffee'
for col in self.harvest():
html += '<td style="background-color: %s;"><%s>' % (color, em) + _clean_html(col) + '</%s></td>' % em
html += '<td> </td></tr>' # CONSIDER the table needn't stretch out so!
return html, ''
def count_dimension(self):
if self is self.parent.steps[0]: return 0
return 1 # TODO raise an error (if the table has one row!)
def harvest(self):
row = re.split(r' \|', re.sub(r'\|$', '', self.predicate))
row = [s.strip() for s in row]
return row
# TODO sample data with "post-it haiku"
# CONSIDER trailing comments
class Comment(Morelia):
def i_look_like(self): return r'\#'
def my_parent_type(self): return Morelia # aka "any"
def _my_regex(self):
name = self.i_look_like()
return '\s*(' + name + ')(.*)'
def validate_predicate(self):
self.enforce(self.predicate.count('\n') == 0, 'linefeed in comment')
def reconstruction(self):
recon = ' # ' + self.predicate
if recon[-1] != '\n': recon += '\n'
return recon
def to_html(self):
return '\n# <em>' + _clean_html(self.predicate) + '</em><br/>', ''
def _special_range(n): # CONSIDER better name
return xrange(n) if n else [0]
def _permute_indices(arr):
return list(_product(*_imap(_special_range, arr)))
# tx to Chris Rebert, et al, on the Python newsgroup for curing my brainlock here!!
def _product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
def _imap(function, *iterables):
iterables = map(iter, iterables)
while True:
args = [i.next() for i in iterables]
if function is None:
yield tuple(args)
else:
yield function(*args)
def _clean_html(string):
return string.replace('&', '&').replace('<', '<').replace('>', '>'). \
replace('"', '"').replace("'", ''')
# CONSIDER display all missing steps not just the first
# ERGO Morelia should raise a form in any state!
# ERGO get Morelia working with more Pythons - virtualenv it!
# ERGO moralia should try the regex first then the step name
# ERGO pay for "Bartender" by Sacred Hoop
if __name__ == '__main__':
import os
os.system('python ../tests/morelia_suite.py') # NOTE this might not return the correct shell value