~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/selftest/__init__.py

  • Committer: Martin Pool
  • Date: 2005-09-16 03:32:44 UTC
  • mfrom: (1185.1.23)
  • mto: (1185.8.2) (974.1.91)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: mbp@sourcefrog.net-20050916033244-18c4f4bcba663e42
- merge in many integration fixes from Robert

  * xml escaping of unprintable characters

  * 'make clean'

  * new, more consistent Branch constructors 

  * RemoteBranch tests against local farmework

  * scott's non-verbose commit fix 

This seems to break this usage though 

  bzr diff -r 1207..1208 ../bzr.robertc-integration

robertc@robertcollins.net-20050915175953-a16fdc627ce7c541

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
import logging
 
19
import unittest
 
20
import tempfile
 
21
import os
 
22
import sys
 
23
import errno
 
24
import subprocess
 
25
import shutil
 
26
 
 
27
import testsweet
 
28
import bzrlib.commands
 
29
 
 
30
import bzrlib.trace
 
31
import bzrlib.fetch
 
32
 
 
33
 
 
34
MODULES_TO_TEST = []
 
35
MODULES_TO_DOCTEST = []
 
36
 
 
37
from logging import debug, warning, error
 
38
 
 
39
class CommandFailed(Exception):
 
40
    pass
 
41
 
 
42
class TestCase(unittest.TestCase):
 
43
    """Base class for bzr unit tests.
 
44
    
 
45
    Tests that need access to disk resources should subclass 
 
46
    TestCaseInTempDir not TestCase.
 
47
 
 
48
    Error and debug log messages are redirected from their usual
 
49
    location into a temporary file, the contents of which can be
 
50
    retrieved by _get_log().
 
51
       
 
52
    There are also convenience functions to invoke bzr's command-line
 
53
    routine, and to build and check bzr trees."""
 
54
 
 
55
    BZRPATH = 'bzr'
 
56
 
 
57
    def setUp(self):
 
58
        # this replaces the default testsweet.TestCase; we don't want logging changed
 
59
        unittest.TestCase.setUp(self)
 
60
        bzrlib.trace.disable_default_logging()
 
61
        self._enable_file_logging()
 
62
 
 
63
 
 
64
    def _enable_file_logging(self):
 
65
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
66
 
 
67
        self._log_file = os.fdopen(fileno, 'w+')
 
68
 
 
69
        hdlr = logging.StreamHandler(self._log_file)
 
70
        hdlr.setLevel(logging.DEBUG)
 
71
        hdlr.setFormatter(logging.Formatter('%(levelname)4.4s  %(message)s'))
 
72
        logging.getLogger('').addHandler(hdlr)
 
73
        logging.getLogger('').setLevel(logging.DEBUG)
 
74
        self._log_hdlr = hdlr
 
75
        debug('opened log file %s', name)
 
76
        
 
77
        self._log_file_name = name
 
78
 
 
79
    def tearDown(self):
 
80
        logging.getLogger('').removeHandler(self._log_hdlr)
 
81
        bzrlib.trace.enable_default_logging()
 
82
        logging.debug('%s teardown', self.id())
 
83
        self._log_file.close()
 
84
        unittest.TestCase.tearDown(self)
 
85
 
 
86
    def log(self, *args):
 
87
        logging.debug(*args)
 
88
 
 
89
    def _get_log(self):
 
90
        """Return as a string the log for this test"""
 
91
        return open(self._log_file_name).read()
 
92
 
 
93
    def run_bzr(self, *args, **kwargs):
 
94
        """Invoke bzr, as if it were run from the command line.
 
95
 
 
96
        This should be the main method for tests that want to exercise the
 
97
        overall behavior of the bzr application (rather than a unit test
 
98
        or a functional test of the library.)
 
99
 
 
100
        Much of the old code runs bzr by forking a new copy of Python, but
 
101
        that is slower, harder to debug, and generally not necessary.
 
102
        """
 
103
        retcode = kwargs.get('retcode', 0)
 
104
        result = self.apply_redirected(None, None, None,
 
105
                                       bzrlib.commands.run_bzr, args)
 
106
        self.assertEquals(result, retcode)
 
107
        
 
108
        
 
109
    def check_inventory_shape(self, inv, shape):
 
110
        """
 
111
        Compare an inventory to a list of expected names.
 
112
 
 
113
        Fail if they are not precisely equal.
 
114
        """
 
115
        extras = []
 
116
        shape = list(shape)             # copy
 
117
        for path, ie in inv.entries():
 
118
            name = path.replace('\\', '/')
 
119
            if ie.kind == 'dir':
 
120
                name = name + '/'
 
121
            if name in shape:
 
122
                shape.remove(name)
 
123
            else:
 
124
                extras.append(name)
 
125
        if shape:
 
126
            self.fail("expected paths not found in inventory: %r" % shape)
 
127
        if extras:
 
128
            self.fail("unexpected paths found in inventory: %r" % extras)
 
129
 
 
130
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
131
                         a_callable=None, *args, **kwargs):
 
132
        """Call callable with redirected std io pipes.
 
133
 
 
134
        Returns the return code."""
 
135
        from StringIO import StringIO
 
136
        if not callable(a_callable):
 
137
            raise ValueError("a_callable must be callable.")
 
138
        if stdin is None:
 
139
            stdin = StringIO("")
 
140
        if stdout is None:
 
141
            if hasattr(self, "_log_file"):
 
142
                stdout = self._log_file
 
143
            else:
 
144
                stdout = StringIO()
 
145
        if stderr is None:
 
146
            if hasattr(self, "_log_file"):
 
147
                stderr = self._log_file
 
148
            else:
 
149
                stderr = StringIO()
 
150
        real_stdin = sys.stdin
 
151
        real_stdout = sys.stdout
 
152
        real_stderr = sys.stderr
 
153
        try:
 
154
            sys.stdout = stdout
 
155
            sys.stderr = stderr
 
156
            sys.stdin = stdin
 
157
            return a_callable(*args, **kwargs)
 
158
        finally:
 
159
            sys.stdout = real_stdout
 
160
            sys.stderr = real_stderr
 
161
            sys.stdin = real_stdin
 
162
 
 
163
 
 
164
BzrTestBase = TestCase
 
165
 
 
166
     
 
167
class TestCaseInTempDir(TestCase):
 
168
    """Derived class that runs a test within a temporary directory.
 
169
 
 
170
    This is useful for tests that need to create a branch, etc.
 
171
 
 
172
    The directory is created in a slightly complex way: for each
 
173
    Python invocation, a new temporary top-level directory is created.
 
174
    All test cases create their own directory within that.  If the
 
175
    tests complete successfully, the directory is removed.
 
176
 
 
177
    InTempDir is an old alias for FunctionalTestCase.
 
178
    """
 
179
 
 
180
    TEST_ROOT = None
 
181
    _TEST_NAME = 'test'
 
182
    OVERRIDE_PYTHON = 'python'
 
183
 
 
184
    def check_file_contents(self, filename, expect):
 
185
        self.log("check contents of file %s" % filename)
 
186
        contents = file(filename, 'r').read()
 
187
        if contents != expect:
 
188
            self.log("expected: %r" % expect)
 
189
            self.log("actually: %r" % contents)
 
190
            self.fail("contents of %s not as expected")
 
191
 
 
192
    def _make_test_root(self):
 
193
        if TestCaseInTempDir.TEST_ROOT is not None:
 
194
            return
 
195
        i = 0
 
196
        while True:
 
197
            root = 'test%04d.tmp' % i
 
198
            try:
 
199
                os.mkdir(root)
 
200
            except OSError, e:
 
201
                if e.errno == errno.EEXIST:
 
202
                    i += 1
 
203
                    continue
 
204
                else:
 
205
                    raise
 
206
            # successfully created
 
207
            TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
 
208
            break
 
209
        # make a fake bzr directory there to prevent any tests propagating
 
210
        # up onto the source directory's real branch
 
211
        os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
 
212
 
 
213
    def setUp(self):
 
214
        super(TestCaseInTempDir, self).setUp()
 
215
        import os
 
216
        self._make_test_root()
 
217
        self._currentdir = os.getcwdu()
 
218
        self.test_dir = os.path.join(self.TEST_ROOT, self.id())
 
219
        os.mkdir(self.test_dir)
 
220
        os.chdir(self.test_dir)
 
221
        
 
222
    def tearDown(self):
 
223
        import os
 
224
        os.chdir(self._currentdir)
 
225
        super(TestCaseInTempDir, self).tearDown()
 
226
 
 
227
    def _formcmd(self, cmd):
 
228
        if isinstance(cmd, basestring):
 
229
            cmd = cmd.split()
 
230
        if cmd[0] == 'bzr':
 
231
            cmd[0] = self.BZRPATH
 
232
            if self.OVERRIDE_PYTHON:
 
233
                cmd.insert(0, self.OVERRIDE_PYTHON)
 
234
        self.log('$ %r' % cmd)
 
235
        return cmd
 
236
 
 
237
    def runcmd(self, cmd, retcode=0):
 
238
        """Run one command and check the return code.
 
239
 
 
240
        Returns a tuple of (stdout,stderr) strings.
 
241
 
 
242
        If a single string is based, it is split into words.
 
243
        For commands that are not simple space-separated words, please
 
244
        pass a list instead."""
 
245
        cmd = self._formcmd(cmd)
 
246
        self.log('$ ' + ' '.join(cmd))
 
247
        actual_retcode = subprocess.call(cmd, stdout=self._log_file,
 
248
                                         stderr=self._log_file)
 
249
        if retcode != actual_retcode:
 
250
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
251
                                % (cmd, actual_retcode, retcode))
 
252
 
 
253
    def backtick(self, cmd, retcode=0):
 
254
        """Run a command and return its output"""
 
255
        cmd = self._formcmd(cmd)
 
256
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._log_file)
 
257
        outd, errd = child.communicate()
 
258
        self.log(outd)
 
259
        actual_retcode = child.wait()
 
260
 
 
261
        outd = outd.replace('\r', '')
 
262
 
 
263
        if retcode != actual_retcode:
 
264
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
265
                                % (cmd, actual_retcode, retcode))
 
266
 
 
267
        return outd
 
268
 
 
269
 
 
270
 
 
271
    def build_tree(self, shape):
 
272
        """Build a test tree according to a pattern.
 
273
 
 
274
        shape is a sequence of file specifications.  If the final
 
275
        character is '/', a directory is created.
 
276
 
 
277
        This doesn't add anything to a branch.
 
278
        """
 
279
        # XXX: It's OK to just create them using forward slashes on windows?
 
280
        import os
 
281
        for name in shape:
 
282
            assert isinstance(name, basestring)
 
283
            if name[-1] == '/':
 
284
                os.mkdir(name[:-1])
 
285
            else:
 
286
                f = file(name, 'wt')
 
287
                print >>f, "contents of", name
 
288
                f.close()
 
289
                
 
290
 
 
291
 
 
292
class MetaTestLog(TestCase):
 
293
    def test_logging(self):
 
294
        """Test logs are captured when a test fails."""
 
295
        logging.info('an info message')
 
296
        warning('something looks dodgy...')
 
297
        logging.debug('hello, test is running')
 
298
        ##assert 0
 
299
 
 
300
 
 
301
def selftest(verbose=False, pattern=".*"):
 
302
    return testsweet.run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern)
 
303
 
 
304
 
 
305
def test_suite():
 
306
    from bzrlib.selftest.TestUtil import TestLoader, TestSuite
 
307
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
 
308
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
 
309
    from doctest import DocTestSuite
 
310
    import os
 
311
    import shutil
 
312
    import time
 
313
    import sys
 
314
 
 
315
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
 
316
 
 
317
    testmod_names = \
 
318
                  ['bzrlib.selftest.MetaTestLog',
 
319
                   'bzrlib.selftest.test_parent',
 
320
                   'bzrlib.selftest.testinv',
 
321
                   'bzrlib.selftest.testfetch',
 
322
                   'bzrlib.selftest.versioning',
 
323
                   'bzrlib.selftest.whitebox',
 
324
                   'bzrlib.selftest.testmerge3',
 
325
                   'bzrlib.selftest.testmerge',
 
326
                   'bzrlib.selftest.testhashcache',
 
327
                   'bzrlib.selftest.teststatus',
 
328
                   'bzrlib.selftest.testlog',
 
329
                   'bzrlib.selftest.blackbox',
 
330
                   'bzrlib.selftest.testrevisionnamespaces',
 
331
                   'bzrlib.selftest.testbranch',
 
332
                   'bzrlib.selftest.testremotebranch',
 
333
                   'bzrlib.selftest.testrevision',
 
334
                   'bzrlib.selftest.test_merge_core',
 
335
                   'bzrlib.selftest.test_smart_add',
 
336
                   'bzrlib.selftest.testdiff',
 
337
                   'bzrlib.selftest.test_xml',
 
338
                   'bzrlib.fetch',
 
339
                   'bzrlib.selftest.teststore',
 
340
                   'bzrlib.selftest.testgraph',
 
341
                   ]
 
342
 
 
343
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
 
344
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
 
345
        if m not in MODULES_TO_DOCTEST:
 
346
            MODULES_TO_DOCTEST.append(m)
 
347
 
 
348
    TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
 
349
    print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
 
350
    print
 
351
    suite = TestSuite()
 
352
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
 
353
    for m in MODULES_TO_TEST:
 
354
         suite.addTest(TestLoader().loadTestsFromModule(m))
 
355
    for m in (MODULES_TO_DOCTEST):
 
356
        suite.addTest(DocTestSuite(m))
 
357
    for p in bzrlib.plugin.all_plugins:
 
358
        if hasattr(p, 'test_suite'):
 
359
            suite.addTest(p.test_suite())
 
360
    return suite
 
361