~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-22 12:12:53 UTC
  • Revision ID: mbp@sourcefrog.net-20050922121253-eae2a3240ea5e493
- upgrade can no longer be done in current version branches
  so don't test it

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
from cStringIO import StringIO
19
18
import logging
20
19
import unittest
21
20
import tempfile
27
26
 
28
27
import testsweet
29
28
import bzrlib.commands
 
29
 
30
30
import bzrlib.trace
31
31
import bzrlib.fetch
32
32
 
76
76
        
77
77
        self._log_file_name = name
78
78
 
 
79
        
79
80
    def tearDown(self):
80
81
        logging.getLogger('').removeHandler(self._log_hdlr)
81
82
        bzrlib.trace.enable_default_logging()
83
84
        self._log_file.close()
84
85
        unittest.TestCase.tearDown(self)
85
86
 
 
87
 
86
88
    def log(self, *args):
87
89
        logging.debug(*args)
88
90
 
90
92
        """Return as a string the log for this test"""
91
93
        return open(self._log_file_name).read()
92
94
 
93
 
 
94
 
    def capture(self, cmd):
95
 
        """Shortcut that splits cmd into words, runs, and returns stdout"""
96
 
        return self.run_bzr_captured(cmd.split())[0]
97
 
 
98
 
    def run_bzr_captured(self, argv, retcode=0):
99
 
        """Invoke bzr and return (result, stdout, stderr).
100
 
 
101
 
        Useful for code that wants to check the contents of the
102
 
        output, the way error messages are presented, etc.
 
95
    def run_bzr(self, *args, **kwargs):
 
96
        """Invoke bzr, as if it were run from the command line.
103
97
 
104
98
        This should be the main method for tests that want to exercise the
105
99
        overall behavior of the bzr application (rather than a unit test
107
101
 
108
102
        Much of the old code runs bzr by forking a new copy of Python, but
109
103
        that is slower, harder to debug, and generally not necessary.
110
 
 
111
 
        This runs bzr through the interface that catches and reports
112
 
        errors, and with logging set to something approximating the
113
 
        default, so that error reporting can be checked.
114
 
 
115
 
        argv -- arguments to invoke bzr
116
 
        retcode -- expected return code, or None for don't-care.
117
 
        """
118
 
        stdout = StringIO()
119
 
        stderr = StringIO()
120
 
        self.log('run bzr: %s', ' '.join(argv))
121
 
        handler = logging.StreamHandler(stderr)
122
 
        handler.setFormatter(bzrlib.trace.QuietFormatter())
123
 
        handler.setLevel(logging.INFO)
124
 
        logger = logging.getLogger('')
125
 
        logger.addHandler(handler)
126
 
        try:
127
 
            result = self.apply_redirected(None, stdout, stderr,
128
 
                                           bzrlib.commands.run_bzr_catch_errors,
129
 
                                           argv)
130
 
        finally:
131
 
            logger.removeHandler(handler)
132
 
        out = stdout.getvalue()
133
 
        err = stderr.getvalue()
134
 
        if out:
135
 
            self.log('output:\n%s', out)
136
 
        if err:
137
 
            self.log('errors:\n%s', err)
138
 
        if retcode is not None:
139
 
            self.assertEquals(result, retcode)
140
 
        return out, err
141
 
 
142
 
    def run_bzr(self, *args, **kwargs):
143
 
        """Invoke bzr, as if it were run from the command line.
144
 
 
145
 
        This should be the main method for tests that want to exercise the
146
 
        overall behavior of the bzr application (rather than a unit test
147
 
        or a functional test of the library.)
148
 
 
149
 
        This sends the stdout/stderr results into the test's log,
150
 
        where it may be useful for debugging.  See also run_captured.
151
 
        """
152
 
        retcode = kwargs.pop('retcode', 0)
153
 
        return self.run_bzr_captured(args, retcode)
154
 
 
 
104
        """
 
105
        retcode = kwargs.get('retcode', 0)
 
106
        result = self.apply_redirected(None, None, None,
 
107
                                       bzrlib.commands.run_bzr, args)
 
108
        self.assertEquals(result, retcode)
 
109
        
 
110
        
155
111
    def check_inventory_shape(self, inv, shape):
156
112
        """Compare an inventory to a list of expected names.
157
113
 
177
133
        """Call callable with redirected std io pipes.
178
134
 
179
135
        Returns the return code."""
 
136
        from StringIO import StringIO
180
137
        if not callable(a_callable):
181
138
            raise ValueError("a_callable must be callable.")
182
139
        if stdin is None:
183
140
            stdin = StringIO("")
184
141
        if stdout is None:
185
 
            if hasattr(self, "_log_file"):
186
 
                stdout = self._log_file
187
 
            else:
188
 
                stdout = StringIO()
 
142
            stdout = self._log_file
189
143
        if stderr is None:
190
 
            if hasattr(self, "_log_file"):
191
 
                stderr = self._log_file
192
 
            else:
193
 
                stderr = StringIO()
 
144
            stderr = self._log_file
194
145
        real_stdin = sys.stdin
195
146
        real_stdout = sys.stdout
196
147
        real_stderr = sys.stderr
231
182
        if contents != expect:
232
183
            self.log("expected: %r" % expect)
233
184
            self.log("actually: %r" % contents)
234
 
            self.fail("contents of %s not as expected" % filename)
 
185
            self.fail("contents of %s not as expected")
235
186
 
236
187
    def _make_test_root(self):
237
188
        if TestCaseInTempDir.TEST_ROOT is not None:
256
207
 
257
208
    def setUp(self):
258
209
        super(TestCaseInTempDir, self).setUp()
 
210
        import os
259
211
        self._make_test_root()
260
212
        self._currentdir = os.getcwdu()
261
213
        short_id = self.id().replace('bzrlib.selftest.', '') \
265
217
        os.chdir(self.test_dir)
266
218
        
267
219
    def tearDown(self):
 
220
        import os
268
221
        os.chdir(self._currentdir)
269
222
        super(TestCaseInTempDir, self).tearDown()
270
223
 
 
224
    def _formcmd(self, cmd):
 
225
        if isinstance(cmd, basestring):
 
226
            cmd = cmd.split()
 
227
        if cmd[0] == 'bzr':
 
228
            cmd[0] = self.BZRPATH
 
229
            if self.OVERRIDE_PYTHON:
 
230
                cmd.insert(0, self.OVERRIDE_PYTHON)
 
231
        self.log('$ %r' % cmd)
 
232
        return cmd
 
233
 
 
234
    def runcmd(self, cmd, retcode=0):
 
235
        """Run one command and check the return code.
 
236
 
 
237
        Returns a tuple of (stdout,stderr) strings.
 
238
 
 
239
        If a single string is based, it is split into words.
 
240
        For commands that are not simple space-separated words, please
 
241
        pass a list instead."""
 
242
        cmd = self._formcmd(cmd)
 
243
        self.log('$ ' + ' '.join(cmd))
 
244
        actual_retcode = subprocess.call(cmd, stdout=self._log_file,
 
245
                                         stderr=self._log_file)
 
246
        if retcode != actual_retcode:
 
247
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
248
                                % (cmd, actual_retcode, retcode))
 
249
 
 
250
    def backtick(self, cmd, retcode=0):
 
251
        """Run a command and return its output"""
 
252
        cmd = self._formcmd(cmd)
 
253
        child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._log_file)
 
254
        outd, errd = child.communicate()
 
255
        self.log(outd)
 
256
        actual_retcode = child.wait()
 
257
 
 
258
        outd = outd.replace('\r', '')
 
259
 
 
260
        if retcode != actual_retcode:
 
261
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
262
                                % (cmd, actual_retcode, retcode))
 
263
 
 
264
        return outd
 
265
 
 
266
 
 
267
 
271
268
    def build_tree(self, shape):
272
269
        """Build a test tree according to a pattern.
273
270
 
277
274
        This doesn't add anything to a branch.
278
275
        """
279
276
        # XXX: It's OK to just create them using forward slashes on windows?
 
277
        import os
280
278
        for name in shape:
281
279
            assert isinstance(name, basestring)
282
280
            if name[-1] == '/':
285
283
                f = file(name, 'wt')
286
284
                print >>f, "contents of", name
287
285
                f.close()
 
286
                
288
287
 
289
288
 
290
289
class MetaTestLog(TestCase):
307
306
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
308
307
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
309
308
    from doctest import DocTestSuite
 
309
    import os
 
310
    import shutil
 
311
    import time
 
312
    import sys
310
313
 
311
314
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
312
315
 
313
316
    testmod_names = \
314
317
                  ['bzrlib.selftest.MetaTestLog',
315
318
                   'bzrlib.selftest.testinv',
316
 
                   'bzrlib.selftest.test_ancestry',
317
319
                   'bzrlib.selftest.test_commit',
318
320
                   'bzrlib.selftest.test_commit_merge',
319
321
                   'bzrlib.selftest.versioning',
320
322
                   'bzrlib.selftest.testmerge3',
321
 
                   'bzrlib.selftest.testmerge',
322
323
                   'bzrlib.selftest.testhashcache',
323
324
                   'bzrlib.selftest.teststatus',
324
325
                   'bzrlib.selftest.testlog',
325
326
                   'bzrlib.selftest.testrevisionnamespaces',
326
327
                   'bzrlib.selftest.testbranch',
327
 
                   'bzrlib.selftest.testremotebranch',
328
328
                   'bzrlib.selftest.testrevision',
329
 
                   'bzrlib.selftest.test_revision_info',
330
329
                   'bzrlib.selftest.test_merge_core',
331
330
                   'bzrlib.selftest.test_smart_add',
332
 
                   'bzrlib.selftest.test_bad_files',
333
331
                   'bzrlib.selftest.testdiff',
334
332
                   'bzrlib.selftest.test_parent',
335
333
                   'bzrlib.selftest.test_xml',
338
336
                   'bzrlib.selftest.whitebox',
339
337
                   'bzrlib.selftest.teststore',
340
338
                   'bzrlib.selftest.blackbox',
341
 
                   'bzrlib.selftest.testgraph',
342
339
                   ]
343
340
 
344
341
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,