~bzr-pqm/bzr/bzr.dev

608 by Martin Pool
- Split selftests out into a new module and start changing them
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
609 by Martin Pool
- cleanup test code
17
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
18
import logging
19
import unittest
20
import tempfile
21
import os
1139 by Martin Pool
- merge in merge improvements and additional tests
22
import sys
1143 by Martin Pool
- remove dead code and remove some small errors (pychecker)
23
import subprocess
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
24
25
from testsweet import run_suite
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
26
import bzrlib.commands
1139 by Martin Pool
- merge in merge improvements and additional tests
27
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
28
import bzrlib.trace
1092.1.18 by Robert Collins
merge from mpool
29
import bzrlib.fetch
719 by Martin Pool
- reorganize selftest code
30
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
31
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
32
MODULES_TO_TEST = []
33
MODULES_TO_DOCTEST = []
720 by Martin Pool
- start moving external tests into the testsuite framework
34
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
35
from logging import debug, warning, error
36
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
37
class CommandFailed(Exception):
38
    pass
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
39
40
class TestCase(unittest.TestCase):
41
    """Base class for bzr unit tests.
42
    
43
    Tests that need access to disk resources should subclass 
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
44
    TestCaseInTempDir not TestCase.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
45
46
    Error and debug log messages are redirected from their usual
47
    location into a temporary file, the contents of which can be
48
    retrieved by _get_log().
49
       
50
    There are also convenience functions to invoke bzr's command-line
51
    routine, and to build and check bzr trees."""
52
53
    BZRPATH = 'bzr'
54
55
    def setUp(self):
56
        # this replaces the default testsweet.TestCase; we don't want logging changed
57
        unittest.TestCase.setUp(self)
58
        bzrlib.trace.disable_default_logging()
59
        self._enable_file_logging()
60
61
62
    def _enable_file_logging(self):
63
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
64
65
        self._log_file = os.fdopen(fileno, 'w+')
66
67
        hdlr = logging.StreamHandler(self._log_file)
68
        hdlr.setLevel(logging.DEBUG)
69
        hdlr.setFormatter(logging.Formatter('%(levelname)4.4s  %(message)s'))
70
        logging.getLogger('').addHandler(hdlr)
71
        logging.getLogger('').setLevel(logging.DEBUG)
72
        self._log_hdlr = hdlr
73
        debug('opened log file %s', name)
74
        
75
        self._log_file_name = name
76
77
        
78
    def tearDown(self):
79
        logging.getLogger('').removeHandler(self._log_hdlr)
80
        bzrlib.trace.enable_default_logging()
81
        logging.debug('%s teardown', self.id())
82
        self._log_file.close()
83
        unittest.TestCase.tearDown(self)
84
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
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
93
    def run_bzr(self, *args, **kwargs):
1119 by Martin Pool
doc
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.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
102
        """
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
103
        retcode = kwargs.get('retcode', 0)
1092.1.16 by Robert Collins
provide a helper to redirect output as desired
104
        result = self.apply_redirected(None, None, None,
105
                                       bzrlib.commands.run_bzr, args)
106
        self.assertEquals(result, retcode)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
107
        
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
108
    def check_inventory_shape(self, inv, shape):
109
        """
110
        Compare an inventory to a list of expected names.
111
112
        Fail if they are not precisely equal.
113
        """
114
        extras = []
115
        shape = list(shape)             # copy
116
        for path, ie in inv.entries():
117
            name = path.replace('\\', '/')
118
            if ie.kind == 'dir':
119
                name = name + '/'
120
            if name in shape:
121
                shape.remove(name)
122
            else:
123
                extras.append(name)
124
        if shape:
125
            self.fail("expected paths not found in inventory: %r" % shape)
126
        if extras:
127
            self.fail("unexpected paths found in inventory: %r" % extras)
128
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
129
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
130
                         a_callable=None, *args, **kwargs):
131
        """Call callable with redirected std io pipes.
132
133
        Returns the return code."""
134
        from StringIO import StringIO
135
        if not callable(a_callable):
136
            raise ValueError("a_callable must be callable.")
137
        if stdin is None:
138
            stdin = StringIO("")
139
        if stdout is None:
140
            stdout = self._log_file
141
        if stderr is None:
142
            stderr = self._log_file
143
        real_stdin = sys.stdin
144
        real_stdout = sys.stdout
145
        real_stderr = sys.stderr
146
        result = None
147
        try:
148
            sys.stdout = stdout
149
            sys.stderr = stderr
150
            sys.stdin = stdin
151
            result = a_callable(*args, **kwargs)
152
        finally:
153
            sys.stdout = real_stdout
154
            sys.stderr = real_stderr
155
            sys.stdin = real_stdin
156
        return result
157
158
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
159
BzrTestBase = TestCase
160
161
     
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
162
class TestCaseInTempDir(TestCase):
163
    """Derived class that runs a test within a temporary directory.
164
165
    This is useful for tests that need to create a branch, etc.
166
167
    The directory is created in a slightly complex way: for each
168
    Python invocation, a new temporary top-level directory is created.
169
    All test cases create their own directory within that.  If the
170
    tests complete successfully, the directory is removed.
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
171
172
    InTempDir is an old alias for FunctionalTestCase.
173
    """
174
175
    TEST_ROOT = None
176
    _TEST_NAME = 'test'
177
    OVERRIDE_PYTHON = 'python'
178
179
    def check_file_contents(self, filename, expect):
180
        self.log("check contents of file %s" % filename)
181
        contents = file(filename, 'r').read()
182
        if contents != expect:
183
            self.log("expected: %r" % expect)
184
            self.log("actually: %r" % contents)
185
            self.fail("contents of %s not as expected")
186
187
    def _make_test_root(self):
188
        import os
189
        import shutil
190
        import tempfile
191
        
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
192
        if TestCaseInTempDir.TEST_ROOT is not None:
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
193
            return
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
194
        TestCaseInTempDir.TEST_ROOT = os.path.abspath(
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
195
                                 tempfile.mkdtemp(suffix='.tmp',
196
                                                  prefix=self._TEST_NAME + '-',
197
                                                  dir=os.curdir))
198
    
199
        # make a fake bzr directory there to prevent any tests propagating
200
        # up onto the source directory's real branch
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
201
        os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
202
203
    def setUp(self):
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
204
        super(TestCaseInTempDir, self).setUp()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
205
        import os
206
        self._make_test_root()
207
        self._currentdir = os.getcwdu()
208
        self.test_dir = os.path.join(self.TEST_ROOT, self.id())
209
        os.mkdir(self.test_dir)
210
        os.chdir(self.test_dir)
211
        
212
    def tearDown(self):
213
        import os
214
        os.chdir(self._currentdir)
1141 by Martin Pool
- rename FunctionalTest to TestCaseInTempDir
215
        super(TestCaseInTempDir, self).tearDown()
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
216
217
    def _formcmd(self, cmd):
218
        if isinstance(cmd, basestring):
219
            cmd = cmd.split()
220
        if cmd[0] == 'bzr':
221
            cmd[0] = self.BZRPATH
222
            if self.OVERRIDE_PYTHON:
223
                cmd.insert(0, self.OVERRIDE_PYTHON)
224
        self.log('$ %r' % cmd)
225
        return cmd
226
227
    def runcmd(self, cmd, retcode=0):
228
        """Run one command and check the return code.
229
230
        Returns a tuple of (stdout,stderr) strings.
231
232
        If a single string is based, it is split into words.
233
        For commands that are not simple space-separated words, please
234
        pass a list instead."""
235
        cmd = self._formcmd(cmd)
236
        self.log('$ ' + ' '.join(cmd))
1143 by Martin Pool
- remove dead code and remove some small errors (pychecker)
237
        actual_retcode = subprocess.call(cmd, stdout=self._log_file,
238
                                         stderr=self._log_file)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
239
        if retcode != actual_retcode:
240
            raise CommandFailed("test failed: %r returned %d, expected %d"
241
                                % (cmd, actual_retcode, retcode))
242
243
    def backtick(self, cmd, retcode=0):
244
        """Run a command and return its output"""
245
        cmd = self._formcmd(cmd)
1143 by Martin Pool
- remove dead code and remove some small errors (pychecker)
246
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._log_file)
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
247
        outd, errd = child.communicate()
248
        self.log(outd)
249
        actual_retcode = child.wait()
250
251
        outd = outd.replace('\r', '')
252
253
        if retcode != actual_retcode:
254
            raise CommandFailed("test failed: %r returned %d, expected %d"
255
                                % (cmd, actual_retcode, retcode))
256
257
        return outd
258
259
260
261
    def build_tree(self, shape):
262
        """Build a test tree according to a pattern.
263
264
        shape is a sequence of file specifications.  If the final
265
        character is '/', a directory is created.
266
267
        This doesn't add anything to a branch.
268
        """
269
        # XXX: It's OK to just create them using forward slashes on windows?
270
        import os
271
        for name in shape:
272
            assert isinstance(name, basestring)
273
            if name[-1] == '/':
274
                os.mkdir(name[:-1])
275
            else:
276
                f = file(name, 'wt')
277
                print >>f, "contents of", name
278
                f.close()
279
                
280
281
282
class MetaTestLog(TestCase):
283
    def test_logging(self):
284
        """Test logs are captured when a test fails."""
285
        logging.info('an info message')
286
        warning('something looks dodgy...')
287
        logging.debug('hello, test is running')
288
        ##assert 0
289
290
1092.1.20 by Robert Collins
import and use TestUtil to do regex based partial test runs
291
def selftest(verbose=False, pattern=".*"):
292
    return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern)
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
293
294
295
def test_suite():
1092.1.20 by Robert Collins
import and use TestUtil to do regex based partial test runs
296
    from bzrlib.selftest.TestUtil import TestLoader, TestSuite
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
297
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
908 by Martin Pool
- merge john's plugins-have-test_suite.patch:
298
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
721 by Martin Pool
- framework for running external commands from unittest suite
299
    from doctest import DocTestSuite
300
    import os
301
    import shutil
302
    import time
745 by Martin Pool
- redirect stdout/stderr while running tests
303
    import sys
721 by Martin Pool
- framework for running external commands from unittest suite
304
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
305
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
306
307
    testmod_names = \
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
308
                  ['bzrlib.selftest.MetaTestLog',
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
309
                   'bzrlib.selftest.test_parent',
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
310
                   'bzrlib.selftest.testinv',
311
                   'bzrlib.selftest.testfetch',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
312
                   'bzrlib.selftest.versioning',
1123 by Martin Pool
* move bzr-specific code from testsweet into bzrlib.selftest
313
                   'bzrlib.selftest.whitebox',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
314
                   'bzrlib.selftest.testmerge3',
315
                   'bzrlib.selftest.testhashcache',
316
                   'bzrlib.selftest.teststatus',
317
                   'bzrlib.selftest.testlog',
318
                   'bzrlib.selftest.blackbox',
319
                   'bzrlib.selftest.testrevisionnamespaces',
320
                   'bzrlib.selftest.testbranch',
321
                   'bzrlib.selftest.testrevision',
1092.1.23 by Robert Collins
move merge_core tests into the selftest package. Also reduce double-run of those tests
322
                   'bzrlib.selftest.test_merge_core',
1092.1.26 by Robert Collins
start writing star-topology test, realise we need smart-add change
323
                   'bzrlib.selftest.test_smart_add',
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
324
                   'bzrlib.selftest.testdiff',
1092.1.18 by Robert Collins
merge from mpool
325
                   'bzrlib.fetch'
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
326
                   ]
327
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
328
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
329
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
330
        if m not in MODULES_TO_DOCTEST:
331
            MODULES_TO_DOCTEST.append(m)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
332
1102 by Martin Pool
- merge test refactoring from robertc
333
    TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
334
    print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
744 by Martin Pool
- show nicer descriptions while running tests
335
    print
721 by Martin Pool
- framework for running external commands from unittest suite
336
    suite = TestSuite()
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
337
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
855 by Martin Pool
- Patch from John to allow plugins to add their own tests.
338
    for m in MODULES_TO_TEST:
339
         suite.addTest(TestLoader().loadTestsFromModule(m))
340
    for m in (MODULES_TO_DOCTEST):
721 by Martin Pool
- framework for running external commands from unittest suite
341
        suite.addTest(DocTestSuite(m))
908 by Martin Pool
- merge john's plugins-have-test_suite.patch:
342
    for p in bzrlib.plugin.all_plugins:
343
        if hasattr(p, 'test_suite'):
344
            suite.addTest(p.test_suite())
1092.1.17 by Robert Collins
remove TEST_CLASSES dead code and provide a bzrlib.test_suite() convenience method
345
    return suite
764 by Martin Pool
- log messages from a particular test are printed if that test fails
346