~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/selftest/__init__.py

  • Committer: Martin Pool
  • Date: 2005-05-05 06:38:18 UTC
  • Revision ID: mbp@sourcefrog.net-20050505063818-3eb3260343878325
- do upload CHANGELOG to web server, even though it's autogenerated

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
2
 
 
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
 
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
 
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
18
 
from unittest import TestResult, TestCase
19
 
 
20
 
try:
21
 
    import shutil
22
 
    from subprocess import call, Popen, PIPE
23
 
except ImportError, e:
24
 
    sys.stderr.write("testbzr: sorry, this test suite requires the subprocess module\n"
25
 
                     "this is shipped with python2.4 and available separately for 2.3\n")
26
 
    raise
27
 
 
28
 
 
29
 
class CommandFailed(Exception):
30
 
    pass
31
 
 
32
 
 
33
 
class TestBase(TestCase):
34
 
    """Base class for bzr test cases.
35
 
 
36
 
    Just defines some useful helper functions; doesn't actually test
37
 
    anything.
38
 
    """
39
 
    
40
 
    # TODO: Special methods to invoke bzr, so that we can run it
41
 
    # through a specified Python intepreter
42
 
 
43
 
    OVERRIDE_PYTHON = None # to run with alternative python 'python'
44
 
    BZRPATH = 'bzr'
45
 
 
46
 
    _log_buf = ""
47
 
 
48
 
 
49
 
    def formcmd(self, cmd):
50
 
        if isinstance(cmd, basestring):
51
 
            cmd = cmd.split()
52
 
 
53
 
        if cmd[0] == 'bzr':
54
 
            cmd[0] = self.BZRPATH
55
 
            if self.OVERRIDE_PYTHON:
56
 
                cmd.insert(0, self.OVERRIDE_PYTHON)
57
 
 
58
 
        self.log('$ %r' % cmd)
59
 
 
60
 
        return cmd
61
 
 
62
 
 
63
 
    def runcmd(self, cmd, retcode=0):
64
 
        """Run one command and check the return code.
65
 
 
66
 
        Returns a tuple of (stdout,stderr) strings.
67
 
 
68
 
        If a single string is based, it is split into words.
69
 
        For commands that are not simple space-separated words, please
70
 
        pass a list instead."""
71
 
        cmd = self.formcmd(cmd)
72
 
 
73
 
        self.log('$ ' + ' '.join(cmd))
74
 
        actual_retcode = call(cmd, stdout=self.TEST_LOG, stderr=self.TEST_LOG)
75
 
 
76
 
        if retcode != actual_retcode:
77
 
            raise CommandFailed("test failed: %r returned %d, expected %d"
78
 
                                % (cmd, actual_retcode, retcode))
79
 
 
80
 
 
81
 
    def backtick(self, cmd, retcode=0):
82
 
        """Run a command and return its output"""
83
 
        cmd = self.formcmd(cmd)
84
 
        child = Popen(cmd, stdout=PIPE, stderr=self.TEST_LOG)
85
 
        outd, errd = child.communicate()
86
 
        self.log(outd)
87
 
        actual_retcode = child.wait()
88
 
 
89
 
        outd = outd.replace('\r', '')
90
 
 
91
 
        if retcode != actual_retcode:
92
 
            raise CommandFailed("test failed: %r returned %d, expected %d"
93
 
                                % (cmd, actual_retcode, retcode))
94
 
 
95
 
        return outd
96
 
 
97
 
 
98
 
 
99
 
    def build_tree(self, shape):
100
 
        """Build a test tree according to a pattern.
101
 
 
102
 
        shape is a sequence of file specifications.  If the final
103
 
        character is '/', a directory is created.
104
 
 
105
 
        This doesn't add anything to a branch.
106
 
        """
107
 
        # XXX: It's OK to just create them using forward slashes on windows?
108
 
        import os
109
 
        for name in shape:
110
 
            assert isinstance(name, basestring)
111
 
            if name[-1] == '/':
112
 
                os.mkdir(name[:-1])
113
 
            else:
114
 
                f = file(name, 'wt')
115
 
                print >>f, "contents of", name
116
 
                f.close()
117
 
 
118
 
 
119
 
    def log(self, msg):
120
 
        """Log a message to a progress file"""
121
 
        self._log_buf = self._log_buf + str(msg) + '\n'
122
 
        print >>self.TEST_LOG, msg
123
 
 
124
 
 
125
 
    def check_inventory_shape(self, inv, shape):
126
 
        """
127
 
        Compare an inventory to a list of expected names.
128
 
 
129
 
        Fail if they are not precisely equal.
130
 
        """
131
 
        extras = []
132
 
        shape = list(shape)             # copy
133
 
        for path, ie in inv.entries():
134
 
            name = path.replace('\\', '/')
135
 
            if ie.kind == 'dir':
136
 
                name = name + '/'
137
 
            if name in shape:
138
 
                shape.remove(name)
139
 
            else:
140
 
                extras.append(name)
141
 
        if shape:
142
 
            self.fail("expected paths not found in inventory: %r" % shape)
143
 
        if extras:
144
 
            self.fail("unexpected paths found in inventory: %r" % extras)
145
 
 
146
 
 
147
 
    def check_file_contents(self, filename, expect):
148
 
        self.log("check contents of file %s" % filename)
149
 
        contents = file(filename, 'r').read()
150
 
        if contents != expect:
151
 
            self.log("expected: %r" % expected)
152
 
            self.log("actually: %r" % contents)
153
 
            self.fail("contents of %s not as expected")
154
 
            
155
 
 
156
 
 
157
 
class InTempDir(TestBase):
158
 
    """Base class for tests run in a temporary branch."""
159
 
    def setUp(self):
160
 
        import os
161
 
        self.test_dir = os.path.join(self.TEST_ROOT, self.__class__.__name__)
162
 
        os.mkdir(self.test_dir)
163
 
        os.chdir(self.test_dir)
164
 
        
165
 
    def tearDown(self):
166
 
        import os
167
 
        os.chdir(self.TEST_ROOT)
168
 
 
169
 
 
170
 
 
171
 
 
172
 
 
173
 
class _MyResult(TestResult):
174
 
    """
175
 
    Custom TestResult.
176
 
 
177
 
    No special behaviour for now.
178
 
    """
179
 
    def __init__(self, out):
180
 
        self.out = out
181
 
        TestResult.__init__(self)
182
 
 
183
 
    def startTest(self, test):
184
 
        # TODO: Maybe show test.shortDescription somewhere?
185
 
        print >>self.out, '%-60.60s' % test.id(),
186
 
        self.out.flush()
187
 
        TestResult.startTest(self, test)
188
 
 
189
 
    def stopTest(self, test):
190
 
        # print
191
 
        TestResult.stopTest(self, test)
192
 
 
193
 
 
194
 
    def addError(self, test, err):
195
 
        print >>self.out, 'ERROR'
196
 
        TestResult.addError(self, test, err)
197
 
        _show_test_failure('error', test, err, self.out)
198
 
 
199
 
    def addFailure(self, test, err):
200
 
        print >>self.out, 'FAILURE'
201
 
        TestResult.addFailure(self, test, err)
202
 
        _show_test_failure('failure', test, err, self.out)
203
 
 
204
 
    def addSuccess(self, test):
205
 
        print >>self.out, 'OK'
206
 
        TestResult.addSuccess(self, test)
207
 
 
208
 
 
209
 
 
210
 
def selftest():
211
 
    from unittest import TestLoader, TestSuite
212
 
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, bzrlib.commands
213
 
 
214
 
    import bzrlib.selftest.whitebox
215
 
    import bzrlib.selftest.blackbox
216
 
    import bzrlib.selftest.versioning
217
 
    from doctest import DocTestSuite
218
 
    import os
219
 
    import shutil
220
 
    import time
221
 
    import sys
222
 
 
223
 
    TestBase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
224
 
    print '%-30s %s' % ('bzr binary', TestBase.BZRPATH)
225
 
 
226
 
    _setup_test_log()
227
 
    _setup_test_dir()
228
 
    print
229
 
 
230
 
    suite = TestSuite()
231
 
    tl = TestLoader()
232
 
 
233
 
    for m in bzrlib.selftest.whitebox, \
234
 
            bzrlib.selftest.versioning:
235
 
        suite.addTest(tl.loadTestsFromModule(m))
236
 
 
237
 
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
238
 
            bzrlib.commands:
239
 
        suite.addTest(DocTestSuite(m))
240
 
 
241
 
    suite.addTest(bzrlib.selftest.blackbox.suite())
242
 
 
243
 
    # save stdout & stderr so there's no leakage from code-under-test
244
 
    real_stdout = sys.stdout
245
 
    real_stderr = sys.stderr
246
 
    sys.stdout = sys.stderr = TestBase.TEST_LOG
247
 
    try:
248
 
        result = _MyResult(real_stdout)
249
 
        suite.run(result)
250
 
    finally:
251
 
        sys.stdout = real_stdout
252
 
        sys.stderr = real_stderr
253
 
 
254
 
    _show_results(result)
255
 
 
256
 
    return result.wasSuccessful()
257
 
 
258
 
 
259
 
 
260
 
 
261
 
def _setup_test_log():
262
 
    import time
263
 
    import os
264
 
    
265
 
    log_filename = os.path.abspath('testbzr.log')
266
 
    TestBase.TEST_LOG = open(log_filename, 'wt', buffering=1) # line buffered
267
 
 
268
 
    print >>TestBase.TEST_LOG, "bzr tests run at " + time.ctime()
269
 
    print '%-30s %s' % ('test log', log_filename)
270
 
 
271
 
 
272
 
def _setup_test_dir():
273
 
    import os
274
 
    import shutil
275
 
    
276
 
    TestBase.ORIG_DIR = os.getcwdu()
277
 
    TestBase.TEST_ROOT = os.path.abspath("testbzr.tmp")
278
 
 
279
 
    print '%-30s %s' % ('running tests in', TestBase.TEST_ROOT)
280
 
 
281
 
    if os.path.exists(TestBase.TEST_ROOT):
282
 
        shutil.rmtree(TestBase.TEST_ROOT)
283
 
    os.mkdir(TestBase.TEST_ROOT)
284
 
    os.chdir(TestBase.TEST_ROOT)
285
 
 
286
 
    # make a fake bzr directory there to prevent any tests propagating
287
 
    # up onto the source directory's real branch
288
 
    os.mkdir(os.path.join(TestBase.TEST_ROOT, '.bzr'))
289
 
 
290
 
    
291
 
 
292
 
def _show_results(result):
293
 
     print
294
 
     print '%4d tests run' % result.testsRun
295
 
     print '%4d errors' % len(result.errors)
296
 
     print '%4d failures' % len(result.failures)
297
 
 
298
 
 
299
 
 
300
 
def _show_test_failure(kind, case, exc_info, out):
301
 
    from traceback import print_exception
302
 
    
303
 
    print >>out, '-' * 60
304
 
    print >>out, case
305
 
    
306
 
    desc = case.shortDescription()
307
 
    if desc:
308
 
        print >>out, '   (%s)' % desc
309
 
         
310
 
    print_exception(exc_info[0], exc_info[1], exc_info[2], None, out)
311
 
        
312
 
    if isinstance(case, TestBase):
313
 
        print >>out
314
 
        print >>out, 'log from this test:'
315
 
        print >>out, case._log_buf
316
 
         
317
 
    print >>out, '-' * 60
318
 
    
319