summaryrefslogtreecommitdiff
path: root/cmdtest
blob: f2757f9a1eb0f98e2dbc9b659f0b4d6e2a5d0f23 (plain)
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
#!/usr/bin/python
# Copyright 2011  Lars Wirzenius
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


__version__ = '0.0'


import cliapp
import logging
import os
import sys
import tempfile
import ttystatus
import unittest

import cmdtest


class TestFailure(Exception):

    def __init__(self, test, msg):
        self.msg = 'FAIL: %s: %s' % (test.name, msg)
        
    def __str__(self):
        return self.msg


class CommandTester(cliapp.Application):

    def add_settings(self):
        self.settings.string(['command', 'c'], 
                             'test COMMAND (executable name/path)', 
                             metavar='COMMAND')

    def process_args(self, dirnames):
        self.settings.require('command')
        self.setup_ttystatus()
        self.setup_tempdir()

        td = self.load_tests(dirnames)
        self.ts['tests'] = td.tests

        errors = 0
        self.run_script(td.setup_once)
        for test in td.tests:
            self.ts['test'] = test
            self.run_script(td.setup)
            for e in self.run_test(test):
                logging.error(str(e))
                self.ts.clear()
                self.output.write('%s\n' % str(e))
                errors += 1
            self.run_script(td.teardown)
        self.run_script(td.teardown_once)
                
        ok = len(td.tests) - errors
        self.ts.finish()
        self.output.write('%d/%d tests OK, %d failures\n' % 
                            (ok, len(td.tests), errors))
        if errors:
            sys.exit(1)

    def setup_ttystatus(self):
        self.ts = ttystatus.TerminalStatus(period=0.001)
        self.ts.add(ttystatus.Literal('test '))
        self.ts.add(ttystatus.Index('test', 'tests'))
        
    def load_tests(self, dirnames):
        td = cmdtest.TestDir()
        for dirname in dirnames:
            td.scan(dirname)
        return td

    def setup_tempdir(self):
        self.tempdir = tempfile.mkdtemp()
        logging.info('Temporary directory %s' % self.tempdir)
        self.datadir = os.path.join(self.tempdir, 'data')
        os.mkdir(self.datadir)
        
    def cleanup_tempdir(self):
        logging.info('Removing temporary directory %s' % self.tempdir)
        shutil.rmtree(self.tempdir)

    def run_script(self, script_name):
        if script_name:
            self.runcmd([script_name], env=self.add_to_env())

    def add_to_env(self):
        env = dict(os.environ)
        env['DATADIR'] = self.datadir
        return env

    def run_test(self, test):
        logging.info('Test case: %s' % test.name)

        self.run_script(test.setup)

        argv = [self.settings['command']]
        if test.args:
            argv.extend(self.expand(self.lines(test.args)))

        stdin = self.cat(test.stdin or '/dev/null')
        exit, out, err = self.runcmd_unchecked(argv, 
                                               env=self.add_to_env(),
                                               stdin=stdin)
        
        expected_exit = int(self.cat(test.exit or '/dev/null').strip() or '0')
        expected_stdout = self.cat(test.stdout or '/dev/null')
        expected_stderr = self.cat(test.stderr or '/dev/null')
        
        errors = []
        if out != expected_stdout:
            diff = self.diff(expected_stdout, out)
            errors.append(TestFailure(test, 'stdout diff:\n%s' % diff))
        if err != expected_stderr:
            diff = self.diff(expected_stderr, err)
            errors.append(TestFailure(test, 'stderr diff:\n%s' % diff))
        if exit != expected_exit:
            errors.append(TestFailure(test, 
                                      'got exit code %s, expected %s' %
                                        (exit, expected_exit)))
        
        return errors

    def cat(self, filename):
        if os.path.exists(filename):
            with open(filename) as f:
                return f.read()
        else:
            return ''

    def lines(self, filename):
        return self.cat(filename).splitlines()

    def expand(self, strings):
        variables = {
            'datadir': self.datadir,
        }
        return [s % variables for s in strings]

    def diff(self, expected, actual):
        e = os.path.join(self.tempdir, 'expected')
        a = os.path.join(self.tempdir, 'actual')
        self.write_file(e, expected)
        self.write_file(a, actual)
        exit, out, err = self.runcmd_unchecked(['diff', '-u', e, a])
        return out

    def write_file(self, filename, content):
        with open(filename, 'w') as f:
            f.write(content)


if __name__ == '__main__':
    CommandTester(version=__version__).run()