comparison test/test.py @ 0:b0942f44413f

import from git://github.com/mozilla/toolbox.git
author Jeff Hammel <k0scist@gmail.com>
date Sun, 11 May 2014 09:15:35 -0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:b0942f44413f
1 #!/usr/bin/env python
2
3 """
4 doctest runner for toolbox
5 """
6
7 import doctest
8 import json
9 import os
10 import shutil
11 import sys
12 from cgi import escape
13 from optparse import OptionParser
14 from paste.fixture import TestApp
15 from time import time
16 from toolbox.dispatcher import Dispatcher
17
18 # global
19 directory = os.path.dirname(os.path.abspath(__file__))
20
21
22 class ToolboxTestApp(TestApp):
23 """WSGI app wrapper for testing JSON responses"""
24
25 def __init__(self, **kw):
26 dispatcher_args = dict(model_type='memory_cache', fields=('usage', 'author', 'type', 'language', 'dependencies'))
27 dispatcher_args.update(kw)
28 app = Dispatcher(**dispatcher_args)
29 TestApp.__init__(self, app)
30
31 def get(self, url='/', **kwargs):
32 kwargs.setdefault('params', {})['format'] = 'json'
33 response = TestApp.get(self, url, **kwargs)
34 return json.loads(response.body)
35
36 def new(self, **kwargs):
37 kwargs['form-render-date'] = str(time())
38 return self.post('/new', params=kwargs)
39
40 def cleanup(self):
41 pass
42
43
44 class FileCacheTestApp(ToolboxTestApp):
45 """test the MemoryCache file-backed backend"""
46
47 def __init__(self):
48 self.json_dir = os.path.join(directory, 'test_json')
49 shutil.rmtree(self.json_dir, ignore_errors=True)
50 os.makedirs(self.json_dir)
51 ToolboxTestApp.__init__(self, model_type='file_cache', directory=self.json_dir)
52
53 def cleanup(self):
54 shutil.rmtree(self.json_dir, ignore_errors=True)
55
56
57 class CouchTestApp(ToolboxTestApp):
58 """test the MemoryCache file-backed backend"""
59
60 def __init__(self):
61 ToolboxTestApp.__init__(self, model_type='couch', dbname='test_json')
62 for project in self.app.model.projects():
63 self.app.model.delete(project)
64
65 def cleanup(self):
66 for project in self.app.model.projects():
67 self.app.model.delete(project)
68
69
70 app_classes = {'memory_cache': ToolboxTestApp,
71 'file_cache': FileCacheTestApp,
72 'couch': CouchTestApp}
73
74
75 def run_tests(app_cls,
76 raise_on_error=False,
77 cleanup=True,
78 report_first=False,
79 output=sys.stdout):
80
81 results = {}
82
83 # gather tests
84 tests = [ test for test in os.listdir(directory)
85 if test.endswith('.txt') ]
86 output.write("Tests:\n%s\n" % '\n'.join(tests))
87
88 for test in tests:
89
90 # create an app
91 app = app_cls()
92
93 # doctest arguments
94 extraglobs = {'here': directory, 'app': app, 'urlescape': escape}
95 doctest_args = dict(extraglobs=extraglobs, raise_on_error=raise_on_error)
96 if report_first:
97 doctest_args['optionflags'] = doctest.REPORT_ONLY_FIRST_FAILURE
98
99 # run the test
100 try:
101 results[test] = doctest.testfile(test, **doctest_args)
102 except doctest.DocTestFailure, failure:
103 raise
104 except doctest.UnexpectedException, failure:
105 raise failure.exc_info[0], failure.exc_info[1], failure.exc_info[2]
106 finally:
107 if cleanup:
108 app.cleanup()
109
110 return results
111
112
113 def main(args=sys.argv[1:]):
114
115 # parse command line args
116 parser = OptionParser()
117 parser.add_option('--no-cleanup', dest='cleanup',
118 default=True, action='store_false',
119 help="cleanup following the tests")
120 parser.add_option('--raise', dest='raise_on_error',
121 default=False, action='store_true',
122 help="raise on first error")
123 parser.add_option('--report-first', dest='report_first',
124 default=False, action='store_true',
125 help="report the first error only (all tests will still run)")
126 parser.add_option('--model', dest='model', default='file_cache',
127 help="model to use")
128 options, args = parser.parse_args(args)
129
130 # get arguments to run_tests
131 kw = dict([(i, getattr(options, i)) for i in ('raise_on_error', 'cleanup', 'report_first')])
132 if options.model is not None:
133 try:
134 kw['app_cls'] = app_classes[options.model]
135 except KeyError:
136 parser.error("Model '%s' unknown (choose from: %s)" % (options.model, app_classes.keys()))
137
138 # run the tests
139 results = run_tests(**kw)
140 if sum([i.failed for i in results.values()]):
141 sys.exit(1) # error
142
143
144 if __name__ == '__main__':
145 main()