forked from stuartherbert/sublime-phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phpunit.py
608 lines (506 loc) · 18.6 KB
/
phpunit.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import functools
import os
import re
import subprocess
import time
import thread
import sublime
import sublime_plugin
# the AsyncProcess class has been cribbed from:
# https://github.com/maltize/sublime-text-2-ruby-tests/blob/master/run_ruby_test.py
class AsyncProcess(object):
def __init__(self, cmd, listener):
self.cmd = cmd
self.listener = listener
print "DEBUG_EXEC: " + self.cmd
self.proc = subprocess.Popen([self.cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if self.proc.stdout:
thread.start_new_thread(self.read_stdout, ())
if self.proc.stderr:
thread.start_new_thread(self.read_stderr, ())
def read_stdout(self):
while True:
data = os.read(self.proc.stdout.fileno(), 2**15)
if data != "":
sublime.set_timeout(functools.partial(self.listener.append_data, self.proc, data), 0)
else:
self.proc.stdout.close()
self.listener.is_running = False
self.listener.append_data(self.proc, "\n--- PROCESS COMPLETE ---")
break
def read_stderr(self):
while True:
data = os.read(self.proc.stderr.fileno(), 2**15)
if data != "":
sublime.set_timeout(functools.partial(self.listener.append_data, self.proc, data), 0)
else:
self.proc.stderr.close()
self.listener.is_running = False
break
# the StatusProcess class has been cribbed from:
# https://github.com/maltize/sublime-text-2-ruby-tests/blob/master/run_ruby_test.py
class StatusProcess(object):
def __init__(self, msg, listener):
self.msg = msg
self.listener = listener
thread.start_new_thread(self.run_thread, ())
def run_thread(self):
progress = ""
while True:
if self.listener.is_running:
if len(progress) >= 10:
progress = ""
progress += "."
sublime.set_timeout(functools.partial(self.listener.update_status, self.msg, progress), 0)
time.sleep(1)
else:
break
class OutputView(object):
def __init__(self, name, window):
self.output_name = name
self.window = window
def show_output(self):
self.ensure_output_view()
self.window.run_command("show_panel", {"panel": "output." + self.output_name})
def show_empty_output(self):
self.ensure_output_view()
self.clear_output_view()
self.show_output()
def ensure_output_view(self):
if not hasattr(self, 'output_view'):
self.output_view = self.window.get_output_panel(self.output_name)
def clear_output_view(self):
self.ensure_output_view()
self.output_view.set_read_only(False)
edit = self.output_view.begin_edit()
self.output_view.erase(edit, sublime.Region(0, self.output_view.size()))
self.output_view.end_edit(edit)
self.output_view.set_read_only(True)
def append_data(self, proc, data):
str = data.decode("utf-8")
str = str.replace('\r\n', '\n').replace('\r', '\n')
selection_was_at_end = (len(self.output_view.sel()) == 1
and self.output_view.sel()[0]
== sublime.Region(self.output_view.size()))
self.output_view.set_read_only(False)
edit = self.output_view.begin_edit()
self.output_view.insert(edit, self.output_view.size(), str)
if selection_was_at_end:
self.output_view.show(self.output_view.size())
self.output_view.end_edit(edit)
self.output_view.set_read_only(True)
class CommandBase:
def __init__(self, window):
self.window = window
def show_output(self):
if not hasattr(self, 'output_view'):
self.output_view = OutputView('phpunit', self.window)
self.output_view.show_output()
def show_empty_output(self):
if not hasattr(self, 'output_view'):
self.output_view = OutputView('phpunit', self.window)
self.output_view.clear_output_view()
self.output_view.show_output()
def start_async(self, caption, executable):
self.is_running = True
self.proc = AsyncProcess(executable, self)
StatusProcess(caption, self)
def append_data(self, proc, data):
self.output_view.append_data(proc, data)
def update_status(self, msg, progress):
sublime.status_message(msg + " " + progress)
class PhpunitCommand(CommandBase):
def run(self, path, testfile='', classname=''):
self.show_empty_output()
cmd = "cd '" + path[0] + "' && phpunit"
if len(path) > 0:
cmd = cmd + " -c '" + path[1] + "' "
if testfile != '':
cmd = cmd + " '" + testfile + "'"
if classname != '':
cmd = cmd + " '" + classname + "'"
self.append_data(self, "$ " + cmd + "\n")
self.start_async("Running PHPUnit", cmd)
class ActiveFile:
def is_test_buffer(self):
filename = os.path.splitext(os.path.basename(self.file_name()))[0]
if filename.endswith('Test'):
return True
return False
def is_phpunitxml(self):
# is this a phpunit.xml file?
filename = os.path.basename(self.file_name())
if filename == 'phpunit.xml' or filename == 'phpunit.xml.dist':
return True
return False
def determineClassToTest(self):
class_to_test = os.path.splitext(os.path.basename(self.file_name()))[0]
if not class_to_test.endswith('Test'):
class_to_test = class_to_test + "Test"
return class_to_test
def determineTestFile(self):
filename = os.path.splitext(os.path.basename(self.file_name()))[0]
if filename.endswith('Test'):
return self.file_name()
return None
def findPhpunitXml(self):
dir_name = os.path.dirname(self.file_name())
path = self.findFolderContainingFile(dir_name, 'phpunit.xml')
if (path is not None):
return path
return self.findFolderContainingFile(dir_name, 'phpunit.xml.dist')
def findFolderContainingFile(self, path, filename):
if path == '/':
return None
if os.path.exists(path + '/' + filename):
return [ path, filename ]
return self.findFolderContainingFile(os.path.dirname(path), filename)
def resetSearchedFolders(self):
self.searchedFolders = {}
def findFileFor(self, path, suffix, depth):
if depth == 0:
return None
if path == '/':
return None
# optimisation - avoid looking in the same place twice
pathToSearch = path + '/'
filenameToTest = pathToSearch + suffix
# print "Looking for " + filenameToTest
if os.path.exists(filenameToTest):
return filenameToTest
found_path = self.searchSubfoldersFor(path, suffix)
if found_path is not None:
return found_path
# avoid looking in here again
self.searchedFolders[pathToSearch] = True
depth = depth - 1
return self.findFileFor(os.path.dirname(path), suffix, depth)
def searchSubfoldersFor(self, path, suffix):
# print "searchSubfoldersFor: " + path + ' ' + suffix
for root, dirs, names in os.walk(path):
for subdir in dirs:
# print "looking at dir " + subdir
# optimisation - avoid looking in hidden places
if subdir[0] == '.':
# print "skipping hidden folder " + subdir
continue
# optimisation - avoid looking down dead ends
frontToTest = subdir + '/'
if suffix[:len(frontToTest)] == frontToTest:
# print "skipping matching prefix " + frontToTest
continue
# optimisation - avoid looking in the same place twice
pathToSearch = path + '/' + subdir + '/'
if pathToSearch in self.searchedFolders:
# print "Skipping " + pathToSearch
continue
self.searchedFolders[pathToSearch] = True
# if we get here, we have not discarded this folder yet
filenameToTest = pathToSearch + suffix
# print "Looking in subfolders for " + filenameToTest
if os.path.exists(filenameToTest):
# print "Found " + filenameToTest
return filenameToTest
found_path = self.searchSubfoldersFor(path + '/' + subdir, suffix)
if found_path is not None:
# print "Found path!!"
return found_path
# print "Run out of options"
return None
def cannot_find_xml(self):
sublime.status_message("Cannot find phpunit.xml or phpunit.xml.dist file")
def xml_file_needed(self):
return "You need a phpunit.xml or phpunit.xml.dist file to use PHPUnit"
class ActiveView(ActiveFile):
def is_php_buffer(self):
# is this a PHP buffer?
if re.search('.+\PHP.tmLanguage', self.view.settings().get('syntax')):
return True
return False
def file_name(self):
return self.view.file_name()
def find_tested_file(self):
classname = self.determine_full_class_name()
path_to_search = self.file_name().replace('/' + classname + '.php', '')
if classname[-4:] == 'Test':
classname = classname[:-4]
classname = classname + '.php'
depth_to_search = 4
self.resetSearchedFolders()
path = self.findFileFor(path_to_search, classname, depth_to_search)
if path is None:
return None
return [ path, classname ]
def find_test_file(self):
classname = self.determine_full_class_name()
depth_to_search = 3
path_to_search = self.file_name().replace('/' + classname + '.php', '')
self.resetSearchedFolders()
path = self.findFileFor(path_to_search, classname + 'Test.php', depth_to_search)
if path is None:
return None
return [ path, classname ]
def determine_full_class_name(self):
namespace = self.extract_namespace()
classname = self.extract_classname()
path = ''
if len(namespace) > 0:
namespace = namespace.replace('\\', '/')
path = path + namespace + '/'
classname = classname.replace('_', '/')
path = path + classname
return path
def extract_namespace(self):
namespaces = self.view.find_all("^namespace ([A-Za-z0-9_\\\]+);")
if namespaces is None or len(namespaces) == 0:
return ''
for namespace in namespaces:
line = self.view.substr(namespace)
return line[10:-1]
def extract_classname(self):
classes = self.view.find_all("^class [A-Za-z0-9_]+")
if classes is None or len(classes) == 0:
return None
for classname in classes:
line = self.view.substr(classname)
return line[6:]
class ActiveWindow(ActiveFile):
def file_name(self):
if hasattr(self, '_file_name'):
return self._file_name
return None
def determine_filename(self, args=[]):
if len(args) == 0:
active_view = self.window.active_view()
filename = active_view.file_name()
else:
filename = args[0]
self._file_name = filename
def is_php_buffer(self):
ext = os.path.splitext(self.file_name())[1]
if ext == 'php':
return True
return False
class PhpunitTextBase(sublime_plugin.TextCommand, ActiveView):
def run(self, args):
print 'Not implemented'
class PhpunitTestThisClass(PhpunitTextBase):
def run(self, args):
path = self.findPhpunitXml()
if path is None:
self.cannot_find_xml()
return
file_to_test = self.find_test_file()
if file_to_test is None:
self.cannot_find_test_file()
return
cmd = PhpunitCommand(self.view.window())
cmd.run(path, file_to_test[0], file_to_test[1])
def description(self):
return 'Test This Class...'
def is_enabled(self):
if not self.is_php_buffer():
return False
if self.is_test_buffer():
return False
path = self.findPhpunitXml()
if path is None:
return False
path = self.find_test_file()
if path is None:
return False
return True
def is_visible(self):
if not self.is_php_buffer():
return False
if self.is_test_buffer():
return False
path = self.findPhpunitXml()
if path is None:
return False
return True
class PhpunitOpenTestClass(PhpunitTextBase):
def run(self, args):
file_to_open = self.find_test_file()
if file_to_open is None:
self.cannot_find_test_file()
return
self.view.window().open_file(file_to_open[0])
def description(self):
return 'Open Test Class'
def is_enabled(self):
if not self.is_php_buffer():
return False
if self.is_test_buffer():
return False
path = self.find_test_file()
if path is None:
return False
return True
def is_visible(self):
if not self.is_php_buffer():
return False
if self.is_test_buffer():
return False
return True
class PhpunitOpenClassBeingTested(PhpunitTextBase):
def run(self, args):
file_to_open = self.find_tested_file()
if file_to_open is None:
self.cannot_find_tested_file()
return
self.view.window().open_file(file_to_open[0])
def description(self):
return 'Open Class Being Tested'
def is_enabled(self):
if not self.is_php_buffer():
return False
if not self.is_test_buffer():
return False
path = self.find_tested_file()
if path is None:
return False
return True
def is_visible(self):
if not self.is_php_buffer():
return False
if not self.is_test_buffer():
return False
return True
class PhpunitRunThisPhpunitXmlCommand(PhpunitTextBase):
def run(self, args):
phpunit_xml_file = self.file_name()
dir_to_cd = os.path.dirname(phpunit_xml_file)
cmd = PhpunitCommand(self.view.window())
cmd.run([dir_to_cd, os.path.basename(phpunit_xml_file)])
def is_enabled(self):
return self.is_visible()
def is_visible(self):
return self.is_phpunitxml()
def description(self, paths=[]):
return 'Run Using This XML File...'
class PhpunitRunTheseTestsCommand(PhpunitTextBase):
def run(self, args):
path = self.findPhpunitXml()
if path is None:
self.cannot_find_xml()
return
file_to_test = self.determineTestFile()
cmd = PhpunitCommand(self.view.window())
cmd.run(path, file_to_test)
def description(self):
return 'Run These Tests...'
def is_enabled(self):
if not self.is_php_buffer():
return False
if not self.is_test_buffer():
return False
path = self.findPhpunitXml()
if path is None:
return False
return True
def is_visible(self):
return self.is_enabled()
class PhpunitRunAllTestsCommand(PhpunitTextBase):
def run(self, args):
path = self.findPhpunitXml()
if path is None:
self.cannot_find_xml()
return
cmd = PhpunitCommand(self.view.window())
cmd.run(path)
def description(self):
return 'Run All Unit Tests...'
def is_enabled(self):
if not self.is_php_buffer():
return False
if self.is_phpunitxml():
return False
path = self.findPhpunitXml()
if path is None:
return False
return True
def is_visible(self):
return self.is_enabled()
class PhpunitNotAvailableCommand(PhpunitTextBase):
def is_visible(self):
if self.is_php_buffer():
return False
if self.is_phpunitxml():
return False
return True
def is_enabled(self):
return False
def description(self):
return self.xml_file_needed()
class PhpunitWindowBase(sublime_plugin.WindowCommand, ActiveWindow):
def run(self, paths=[]):
print "not implemented"
class RunPhpunitOnXmlCommand(PhpunitWindowBase):
def run(self, paths=[]):
self.determine_filename(paths)
filename = self.file_name()
dir_to_cd = os.path.dirname(filename)
cmd = PhpunitCommand(self.window)
cmd.run([dir_to_cd, os.path.basename(filename)])
def is_enabled(self, paths=[]):
return self.is_visible(paths)
def is_visible(self, paths=[]):
self.determine_filename(paths)
return self.is_phpunitxml()
def description(self, paths=[]):
return 'Run Using This XML File...'
class RunPhpunitOnTheseTestsCommand(PhpunitWindowBase):
def run(self, paths=[]):
self.determine_filename(paths)
path = self.findPhpunitXml()
if path is None:
self.cannot_find_xml()
return
file_to_test = self.determineTestFile()
cmd = PhpunitCommand(self.window.active_view().window())
cmd.run(path, file_to_test)
def is_enabled(self, paths=[]):
return self.is_visible(paths)
def is_visible(self, paths=[]):
self.determine_filename(paths)
if not self.is_test_buffer():
return False
path = self.findPhpunitXml()
if path is None:
return False
return True
def description(self, paths=[]):
return 'Run These Tests...'
class RunPhpunitTestsCommand(PhpunitWindowBase):
def run(self, paths=[]):
self.determine_filename(paths)
path = self.findPhpunitXml()
if path is None:
self.cannot_find_xml()
return
cmd = PhpunitCommand(self.window)
cmd.run(path)
def is_enabled(self, paths=[]):
return self.is_visible(paths)
def is_visible(self, paths=[]):
self.determine_filename(paths)
if self.is_phpunitxml():
return False
path = self.findPhpunitXml()
if path is None:
return False
return True
def description(self, paths=[]):
return 'Run All PHPUnit Tests...'
class CannotRunPhpunitCommand(PhpunitWindowBase):
def is_visible(self, paths=[]):
self.determine_filename(paths)
path = self.findPhpunitXml()
if path is not None:
return False
return True
def is_enabled(self):
return False
def description(self):
return self.xml_file_needed()