-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
867 lines (612 loc) · 24.6 KB
/
tests.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# -*- coding: utf-8 -*-
import re
import sys
import unittest
from flask import Flask
from flask.ext.script._compat import StringIO, text_type
from flask.ext.script import Command, Manager, Option, prompt, prompt_bool, prompt_choices
from pytest import raises
class Catcher(object):
"""Helper decorator to test raw_input."""
## see: http://stackoverflow.com/questions/13480632/python-stringio-selectively-place-data-into-stdin
def __init__(self, handler):
self.handler = handler
self.inputs = []
def __enter__(self):
self.__stdin = sys.stdin
self.__stdout = sys.stdout
sys.stdin = self
sys.stdout = self
def __exit__(self, type, value, traceback):
sys.stdin = self.__stdin
sys.stdout = self.__stdout
def write(self, value):
self.__stdout.write(value)
result = self.handler(value)
if result is not None:
self.inputs.append(result)
def readline(self):
return self.inputs.pop()
def getvalue(self):
return self.__stdout.getvalue()
def truncate(self, pos):
return self.__stdout.truncate(pos)
def run(command_line, manager_run):
'''
Runs a manager command line, returns exit code
'''
sys.argv = command_line.split()
exit_code = None
try:
manager_run()
except SystemExit as e:
exit_code = e.code
return exit_code
class SimpleCommand(Command):
'simple command'
def run(self):
print('OK')
class NamedCommand(Command):
'named command'
def run(self):
print('OK')
class ExplicitNamedCommand(Command):
'named command'
name = 'named'
def run(self):
print('OK')
class NamespacedCommand(Command):
'namespaced command'
namespace = 'ns'
def run(self):
print('OK')
class CommandWithArgs(Command):
'command with args'
option_list = (
Option('name'),
)
def run(self, name):
print(name)
class CommandWithOptionalArg(Command):
'command with optional arg'
option_list = (
Option('-n','--name', required=False),
)
def run(self, name="NotGiven"):
print("OK name="+str(name))
class CommandWithOptions(Command):
'command with options'
option_list = (
Option('-n', '--name',
help='name to pass in',
dest='name'),
)
def run(self, name):
print(name)
class CommandWithDynamicOptions(Command):
'command with options'
def __init__(self, default_name='Joe'):
self.default_name = default_name
def get_options(self):
return (
Option('-n', '--name',
help='name to pass in',
dest='name',
default=self.default_name),
)
def run(self, name):
print(name)
class CommandWithCatchAll(Command):
'command with catch all args'
capture_all_args = True
def get_options(self):
return (Option('--foo', dest='foo',
action='store_true'),)
def run(self, remaining_args, foo):
print(remaining_args)
class EmptyContext(object):
def __enter__(self):
pass
def __exit__(self, a,b,c):
pass
class AppForTesting(object):
def __init__(self, verbose=False):
self.verbose = verbose
def test_request_context(self):
return EmptyContext()
def __call__(self,**kw):
if self.verbose:
print("APP "+" ".join("%s=%s" % (k,v) for k,v in kw.items()))
return self
class TestManager:
def setup(self):
self.app = AppForTesting()
def test_with_default_commands(self):
manager = Manager(self.app)
manager.set_defaults()
assert 'runserver' in manager._commands
assert 'shell' in manager._commands
def test_without_default_commands(self):
manager = Manager(self.app, with_default_commands=False)
manager.set_defaults()
assert 'runserver' not in manager._commands
assert 'shell' not in manager._commands
def test_add_command(self):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
assert isinstance(manager._commands['simple'], SimpleCommand)
def test_add_named_command(self):
manager = Manager(self.app)
manager.add_command(NamedCommand())
assert 'named' in manager._commands
assert isinstance(manager._commands['named'], NamedCommand)
def test_add_explicit_named_command(self):
manager = Manager(self.app)
manager.add_command(ExplicitNamedCommand())
name = ExplicitNamedCommand.name
assert name in manager._commands
assert isinstance(manager._commands[name], ExplicitNamedCommand)
def test_add_namespaced_command(self):
manager = Manager(self.app)
manager.add_command('one', NamespacedCommand())
manager.add_command('two', NamespacedCommand())
assert 'ns' in manager._commands
assert isinstance(manager._commands['ns'], Manager)
ns = manager._commands['ns']
assert isinstance(ns._commands['one'], NamespacedCommand)
assert isinstance(ns._commands['two'], NamespacedCommand)
def test_add_namespaced_simple_command(self):
manager = Manager(self.app)
manager.add_command('hello', SimpleCommand(), namespace='ns')
manager.add_command('world', SimpleCommand(), namespace='ns')
assert 'ns' in manager._commands
assert isinstance(manager._commands['ns'], Manager)
ns = manager._commands['ns']
assert isinstance(ns._commands['hello'], SimpleCommand)
assert isinstance(ns._commands['world'], SimpleCommand)
def test_add_command_class(self):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand)
assert isinstance(manager._commands['simple'], SimpleCommand)
def test_simple_command_decorator(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print('hello')
assert 'hello' in manager._commands
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello' in out
def test_simple_command_decorator_with_pos_arg(self, capsys):
manager = Manager(self.app)
@manager.command
def hello(name):
print('hello ' + name)
assert 'hello' in manager._commands
code = run('manage.py hello joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
def test_method_command_decorator_with_pos_arg(self, capsys):
manager = Manager(self.app)
class SomeTest(object):
def hello(self,name):
print('hello ' + name)
sometest = SomeTest()
manager.command(sometest.hello)
assert 'hello' in manager._commands
code = run('manage.py hello joe', lambda: manager.run())
out, err = capsys.readouterr()
assert 'hello joe' in out
def test_command_decorator_with_options(self, capsys):
manager = Manager(self.app)
@manager.command
def hello(name='fred'):
'Prints your name'
print('hello ' + name)
assert 'hello' in manager._commands
code = run('manage.py hello --name=joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
code = run('manage.py hello -n joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
code = run('manage.py hello -?', manager.run)
out, err = capsys.readouterr()
assert 'Prints your name' in out
code = run('manage.py hello --help', manager.run)
out, err = capsys.readouterr()
assert 'Prints your name' in out
def test_no_help(self, capsys):
"""
Tests that erasing --help really works.
"""
manager = Manager(self.app)
manager.help_args = ()
@manager.command
def hello(name='fred'):
'Prints your name'
print('hello ' + name)
assert 'hello' in manager._commands
code = run('manage.py --help hello', manager.run)
out, err = capsys.readouterr()
print(out)
assert 'too many arguments' in err
code = run('manage.py hello --help', manager.run)
out, err = capsys.readouterr()
print(out)
assert 'too many arguments' in err
def test_command_decorator_with_boolean_options(self, capsys):
manager = Manager(self.app)
@manager.command
def verify(verified=False):
'Checks if verified'
print('VERIFIED ? ' + 'YES' if verified else 'NO')
assert 'verify' in manager._commands
code = run('manage.py verify --verified', manager.run)
out, err = capsys.readouterr()
assert 'YES' in out
code = run('manage.py verify -v', manager.run)
out, err = capsys.readouterr()
assert 'YES' in out
code = run('manage.py verify', manager.run)
out, err = capsys.readouterr()
assert 'NO' in out
code = run('manage.py verify -?', manager.run)
out, err = capsys.readouterr()
assert 'Checks if verified' in out
def test_simple_command_decorator_with_pos_arg_and_options(self, capsys):
manager = Manager(self.app)
@manager.command
def hello(name, url=None):
if url:
assert type(url) is text_type
print('hello ' + name + ' from ' + url)
else:
assert type(name) is text_type
print('hello ' + name)
assert 'hello' in manager._commands
code = run('manage.py hello joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
code = run('manage.py hello joe --url=reddit.com', manager.run)
out, err = capsys.readouterr()
assert 'hello joe from reddit.com' in out
def test_command_decorator_with_additional_options(self, capsys):
manager = Manager(self.app)
@manager.option('-n', '--name', dest='name', help='Your name')
def hello(name):
print('hello ' + name)
assert 'hello' in manager._commands
code = run('manage.py hello --name=joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
code = run('manage.py hello -?', manager.run)
out, err = capsys.readouterr()
assert 'Your name' in out
@manager.option('-n', '--name', dest='name', help='Your name')
@manager.option('-u', '--url', dest='url', help='Your URL')
def hello_again(name, url=None):
if url:
print('hello ' + name + ' from ' + url)
else:
print('hello ' + name)
assert 'hello_again' in manager._commands
code = run('manage.py hello_again --name=joe', manager.run)
out, err = capsys.readouterr()
assert 'hello joe' in out
code = run('manage.py hello_again --name=joe --url=reddit.com', manager.run)
out, err = capsys.readouterr()
assert 'hello joe from reddit.com' in out
def test_global_option_provided_before_and_after_command(self, capsys):
manager = Manager(self.app)
manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
manager.add_command('simple', SimpleCommand())
assert isinstance(manager._commands['simple'], SimpleCommand)
code = run('manage.py -c Development simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
code = run('manage.py simple -c Development', manager.run)
out, err = capsys.readouterr()
assert code == 2
assert 'OK' not in out
def test_global_option_value(self, capsys):
def create_app(config_name='Empty'):
print(config_name)
return self.app
manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
manager.add_command('simple', SimpleCommand())
assert isinstance(manager._commands['simple'], SimpleCommand)
code = run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'Empty' not in out # config_name is overwritten by default option value
assert 'Development' in out
assert 'OK' in out
def test_get_usage(self):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
usage = manager.create_parser('manage.py').format_help()
assert 'simple command' in usage
def test_get_usage_with_specified_usage(self):
manager = Manager(self.app, usage='hello')
manager.add_command('simple', SimpleCommand())
usage = manager.create_parser('manage.py').format_help()
assert 'simple command' in usage
assert 'hello' in usage
def test_run_existing_command(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
code = run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert 'OK' in out
def test_run_non_existant_command(self, capsys):
manager = Manager(self.app)
run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert 'invalid choice' in err
def test_run_existing(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
code = run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert 0 == code
assert 'OK' in out
def test_run_existing_bind_later(self, capsys):
manager = Manager(self.app)
code = run('manage.py simple', lambda: manager.run({'simple': SimpleCommand()}))
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
def test_run_not_existing(self, capsys):
manager = Manager(self.app)
code = run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert code == 2
assert 'OK' not in out
def test_run_no_name(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
code = run('manage.py', manager.run)
out, err = capsys.readouterr()
assert code == 2
assert 'simple command' in out
def test_run_good_options(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', CommandWithOptions())
code = run('manage.py simple --name=Joe', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'Joe' in out
def test_run_dynamic_options(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', CommandWithDynamicOptions('Fred'))
code = run('manage.py simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'Fred' in out
def test_run_catch_all(self, capsys):
manager = Manager(self.app)
manager.add_command('catch', CommandWithCatchAll())
code = run('manage.py catch pos1 --foo pos2 --bar', manager.run)
out, err = capsys.readouterr()
out_list = [o.strip('u\'') for o in out.strip('[]\n').split(', ')]
assert code == 0
assert ['pos1', 'pos2', '--bar'] == out_list
def test_run_bad_options(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', CommandWithOptions())
code = run('manage.py simple --foo=bar', manager.run)
assert code == 2
def test_init_with_flask_instance(self):
manager = Manager(self.app)
assert callable(manager.app)
def test_init_with_callable(self):
manager = Manager(lambda: self.app)
assert callable(manager.app)
def test_raise_index_error(self):
manager = Manager(self.app)
@manager.command
def error():
raise IndexError()
with raises(IndexError):
run('manage.py error', manager.run)
def test_run_with_default_command(self, capsys):
manager = Manager(self.app)
manager.add_command('simple', SimpleCommand())
code = run('manage.py', lambda: manager.run(default_command='simple'))
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
def test_command_with_prompt(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print(prompt(name='hello'))
@Catcher
def hello_john(msg):
if re.search("hello", msg):
return 'john'
with hello_john:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello: john' in out
def test_command_with_default_prompt(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print(prompt(name='hello', default='romeo'))
@Catcher
def hello(msg):
if re.search("hello", msg):
return '\n' # just hit enter
with hello:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello [romeo]: romeo' in out
@Catcher
def hello_juliette(msg):
if re.search("hello", msg):
return 'juliette'
with hello_juliette:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello [romeo]: juliette' in out
def test_command_with_prompt_bool(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print(prompt_bool(name='correct', default=True, yes_choices=['y'],
no_choices=['n']) and 'yes' or 'no')
@Catcher
def correct_default(msg):
if re.search("correct", msg):
return '\n' # just hit enter
@Catcher
def correct_y(msg):
if re.search("correct", msg):
return 'y'
@Catcher
def correct_n(msg):
if re.search("correct", msg):
return 'n'
with correct_default:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'correct [y]: yes' in out
with correct_y:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'correct [y]: yes' in out
with correct_n:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'correct [y]: no' in out
def test_command_with_prompt_choices(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print(prompt_choices(name='hello', choices=['peter', 'john', 'sam']))
@Catcher
def hello_john(msg):
if re.search("hello", msg):
return 'john'
with hello_john:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello - (peter, john, sam): john' in out
def test_command_with_default_prompt_choices(self, capsys):
manager = Manager(self.app)
@manager.command
def hello():
print(prompt_choices(name='hello', choices=['peter', 'charlie', 'sam'], default="john"))
@Catcher
def hello_john(msg):
if re.search("hello", msg):
return '\n'
with hello_john:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello - (peter, charlie, sam) [john]: john' in out
@Catcher
def hello_charlie(msg):
if re.search("hello", msg):
return 'charlie'
with hello_charlie:
code = run('manage.py hello', manager.run)
out, err = capsys.readouterr()
assert 'hello - (peter, charlie, sam) [john]: charlie' in out
class TestSubManager:
def setup(self):
self.app = AppForTesting()
def test_add_submanager(self):
sub_manager = Manager()
manager = Manager(self.app)
manager.add_command('sub_manager', sub_manager)
assert isinstance(manager._commands['sub_manager'], Manager)
assert sub_manager.parent == manager
assert sub_manager.get_options() == manager.get_options()
def test_run_submanager_command(self, capsys):
sub_manager = Manager()
sub_manager.add_command('simple', SimpleCommand())
manager = Manager(self.app)
manager.add_command('sub_manager', sub_manager)
code = run('manage.py sub_manager simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
def test_submanager_has_options(self, capsys):
sub_manager = Manager()
sub_manager.add_command('simple', SimpleCommand())
manager = Manager(self.app)
manager.add_command('sub_manager', sub_manager)
manager.add_option('-c', '--config', dest='config', required=False)
code = run('manage.py sub_manager simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
code = run('manage.py -c Development sub_manager simple', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'OK' in out
def test_submanager_separate_options(self, capsys):
sub_manager = Manager(AppForTesting(verbose=True), with_default_commands=False)
sub_manager.add_command('opt', CommandWithOptionalArg())
sub_manager.add_option('-n', '--name', dest='name_sub', required=False)
manager = Manager(AppForTesting(verbose=True), with_default_commands=False)
manager.add_command('sub_manager', sub_manager)
manager.add_option('-n', '--name', dest='name_main', required=False)
code = run('manage.py -n MyMainName sub_manager -n MySubName opt -n MyName', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'APP name_main=MyMainName' in out
assert 'APP name_sub=MySubName' in out
assert 'OK name=MyName' in out
def test_manager_usage_with_submanager(self, capsys):
sub_manager = Manager(usage='Example sub-manager')
manager = Manager(self.app)
manager.add_command('sub_manager', sub_manager)
code = run('manage.py -?', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'Example sub-manager' in out
def test_submanager_usage_and_help_and_description(self, capsys):
sub_manager = Manager(usage='sub_manager [--foo]',
help='shorter desc for submanager',
description='longer desc for submanager')
sub_manager.add_command('simple', SimpleCommand())
manager = Manager(self.app)
manager.add_command('sub_manager', sub_manager)
code = run('manage.py -?', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'sub_manager [--foo]' not in out
assert 'shorter desc for submanager' in out
assert 'longer desc for submanager' not in out
code = run('manage.py sub_manager', manager.run)
out, err = capsys.readouterr()
assert code == 2
assert 'sub_manager [--foo]' in out
assert 'shorter desc for submanager' not in out
assert 'longer desc for submanager' in out
assert 'simple command' in out
code = run('manage.py sub_manager -?', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'sub_manager [--foo]' in out
assert 'shorter desc for submanager' not in out
assert 'longer desc for submanager' in out
assert 'simple command' in out
code = run('manage.py sub_manager simple -?', manager.run)
out, err = capsys.readouterr()
assert code == 0
assert 'sub_manager [--foo] simple [-?]' in out
assert 'simple command' in out
def test_submanager_has_no_default_commands(self):
sub_manager = Manager()
manager = Manager()
manager.add_command('sub_manager', sub_manager)
manager.set_defaults()
assert 'runserver' not in sub_manager._commands
assert 'shell' not in sub_manager._commands