1870a07cd50c6d7fbe14d655b9107496af749108
[librarian.git] / tests / utils.py
1 from __future__ import with_statement
2
3 import os
4 from distutils.core import Command
5 from unittest import TextTestRunner, TestLoader
6 from glob import glob
7 from os.path import dirname, join, realpath, splitext, basename, walk
8 from os import listdir
9 import codecs
10
11 class AutoTestMetaclass(type):
12
13     def __new__(cls, name, bases, class_dict):        
14         test_dir = class_dict.pop('TEST_DIR')
15         path = realpath( join(dirname(__file__), 'files', test_dir) )
16
17         for file in listdir(path):
18             base, ext = splitext(file)
19             if ext != '.xml':
20                 continue
21
22             class_dict['test_'+base] = cls.make_test_runner(base, \
23                     join(path, base +'.xml'), join(path, base + '.out') )
24
25         return type.__new__(cls, name, bases, class_dict)
26     
27     @staticmethod
28     def make_test_runner(name, inputf, outputf):
29         def runner(self):
30             with open(inputf, 'rb') as ifd:
31                 with codecs.open(outputf, 'rb', encoding='utf-8') as ofd:
32                     self.run_auto_test(ifd.read(), ofd.read())            
33         return runner
34
35
36 def get_file_path(dir_name, file_name):
37     return realpath(join(dirname(__file__), 'files', dir_name, file_name))
38
39 class TestCommand(Command):
40     user_options = []
41
42     def initialize_options(self):
43         self._dir = os.getcwd()
44
45     def finalize_options(self):
46         pass
47
48     def run(self):
49         '''
50         Finds all the tests modules in tests/, and runs them.
51         '''
52         testfiles = []
53         for t in glob(join(self._dir, 'tests', '*.py')):
54             module_name = splitext(basename(t))[0]
55             if module_name.startswith('test'):
56                 testfiles.append('.'.join(['tests', module_name])
57                 )
58
59         tests = TestLoader().loadTestsFromNames(testfiles)
60         t = TextTestRunner(verbosity=2)
61         t.run(tests)
62