~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/selftest/__init__.py

  • Committer: Martin Pool
  • Date: 2005-06-22 08:07:30 UTC
  • Revision ID: mbp@sourcefrog.net-20050622080730-b5d1f2f51af71245
- new TestBase.build_tree helper method

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 testsweet import TestBase, run_suite, InTempDir
19
 
import bzrlib.commands
20
 
import bzrlib.fetch
21
 
 
22
 
MODULES_TO_TEST = []
23
 
MODULES_TO_DOCTEST = []
24
 
 
25
 
 
26
 
class BzrTestBase(InTempDir):
27
 
    """bzr-specific test base class"""
28
 
    def run_bzr(self, *args, **kwargs):
29
 
        retcode = kwargs.get('retcode', 0)
30
 
        self.assertEquals(bzrlib.commands.run_bzr(args), retcode)
 
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
 
 
47
    def formcmd(self, cmd):
 
48
        if isinstance(cmd, basestring):
 
49
            cmd = cmd.split()
 
50
 
 
51
        if cmd[0] == 'bzr':
 
52
            cmd[0] = self.BZRPATH
 
53
            if self.OVERRIDE_PYTHON:
 
54
                cmd.insert(0, self.OVERRIDE_PYTHON)
 
55
 
 
56
        self.log('$ %r' % cmd)
 
57
 
 
58
        return cmd
 
59
 
 
60
 
 
61
    def runcmd(self, cmd, retcode=0):
 
62
        """Run one command and check the return code.
 
63
 
 
64
        Returns a tuple of (stdout,stderr) strings.
 
65
 
 
66
        If a single string is based, it is split into words.
 
67
        For commands that are not simple space-separated words, please
 
68
        pass a list instead."""
 
69
        cmd = self.formcmd(cmd)
 
70
 
 
71
        self.log('$ ' + ' '.join(cmd))
 
72
        actual_retcode = call(cmd, stdout=self.TEST_LOG, stderr=self.TEST_LOG)
 
73
 
 
74
        if retcode != actual_retcode:
 
75
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
76
                                % (cmd, actual_retcode, retcode))
 
77
 
 
78
 
 
79
    def backtick(self, cmd, retcode=0):
 
80
        """Run a command and return its output"""
 
81
        cmd = self.formcmd(cmd)
 
82
        child = Popen(cmd, stdout=PIPE, stderr=self.TEST_LOG)
 
83
        outd, errd = child.communicate()
 
84
        self.log(outd)
 
85
        actual_retcode = child.wait()
 
86
 
 
87
        outd = outd.replace('\r', '')
 
88
 
 
89
        if retcode != actual_retcode:
 
90
            raise CommandFailed("test failed: %r returned %d, expected %d"
 
91
                                % (cmd, actual_retcode, retcode))
 
92
 
 
93
        return outd
 
94
 
 
95
 
 
96
 
 
97
    def build_tree(self, shape):
 
98
        """Build a test tree according to a pattern.
 
99
 
 
100
        shape is a sequence of file specifications.  If the final
 
101
        character is '/', a directory is created.
 
102
 
 
103
        This doesn't add anything to a branch.
 
104
        """
 
105
        # XXX: It's OK to just create them using forward slashes on windows?
 
106
        for name in shape:
 
107
            assert isinstance(name, basestring)
 
108
            if name[-1] == '/':
 
109
                os.mkdir(name[:-1])
 
110
            else:
 
111
                f = file(name, 'wt')
 
112
                print >>f, "contents of", name
 
113
                f.close()
 
114
 
 
115
 
 
116
    def log(self, msg):
 
117
        """Log a message to a progress file"""
 
118
        print >>self.TEST_LOG, msg
 
119
               
 
120
 
 
121
class InTempDir(TestBase):
 
122
    """Base class for tests run in a temporary branch."""
 
123
    def setUp(self):
 
124
        import os
 
125
        self.test_dir = os.path.join(self.TEST_ROOT, self.__class__.__name__)
 
126
        os.mkdir(self.test_dir)
 
127
        os.chdir(self.test_dir)
31
128
        
32
 
 
33
 
def selftest(verbose=False):
 
129
    def tearDown(self):
 
130
        import os
 
131
        os.chdir(self.TEST_ROOT)
 
132
 
 
133
 
 
134
 
 
135
 
 
136
 
 
137
class _MyResult(TestResult):
 
138
    """
 
139
    Custom TestResult.
 
140
 
 
141
    No special behaviour for now.
 
142
    """
 
143
    def __init__(self, out):
 
144
        self.out = out
 
145
        TestResult.__init__(self)
 
146
 
 
147
    def startTest(self, test):
 
148
        # TODO: Maybe show test.shortDescription somewhere?
 
149
        print >>self.out, '%-60.60s' % test.id(),
 
150
        TestResult.startTest(self, test)
 
151
 
 
152
    def stopTest(self, test):
 
153
        # print
 
154
        TestResult.stopTest(self, test)
 
155
 
 
156
 
 
157
    def addError(self, test, err):
 
158
        print >>self.out, 'ERROR'
 
159
        TestResult.addError(self, test, err)
 
160
 
 
161
    def addFailure(self, test, err):
 
162
        print >>self.out, 'FAILURE'
 
163
        TestResult.addFailure(self, test, err)
 
164
 
 
165
    def addSuccess(self, test):
 
166
        print >>self.out, 'OK'
 
167
        TestResult.addSuccess(self, test)
 
168
 
 
169
 
 
170
 
 
171
def selftest():
34
172
    from unittest import TestLoader, TestSuite
35
 
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
36
 
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
 
173
    import bzrlib
 
174
    import bzrlib.selftest.whitebox
 
175
    import bzrlib.selftest.blackbox
 
176
    import bzrlib.selftest.versioning
37
177
    from doctest import DocTestSuite
38
178
    import os
39
179
    import shutil
40
180
    import time
41
181
    import sys
42
 
    import unittest
43
 
 
44
 
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
45
 
 
46
 
    testmod_names = \
47
 
                  ['bzrlib.selftest.whitebox',
48
 
                   'bzrlib.selftest.versioning',
49
 
                   'bzrlib.selftest.testinv',
50
 
                   'bzrlib.selftest.testmerge3',
51
 
                   'bzrlib.selftest.testhashcache',
52
 
                   'bzrlib.selftest.teststatus',
53
 
                   'bzrlib.selftest.testlog',
54
 
                   'bzrlib.selftest.blackbox',
55
 
                   'bzrlib.selftest.testrevisionnamespaces',
56
 
                   'bzrlib.selftest.testbranch',
57
 
                   'bzrlib.selftest.testrevision',
58
 
                   'bzrlib.merge_core',
59
 
                   'bzrlib.selftest.testdiff',
60
 
                   'bzrlib.fetch'
61
 
                   ]
62
 
    testmod_names = ['bzrlib.fetch']
63
 
 
64
 
    # XXX: should also test bzrlib.merge_core, but they seem to be out
65
 
    # of date with the code.
66
 
 
67
 
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
68
 
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
69
 
        if m not in MODULES_TO_DOCTEST:
70
 
            MODULES_TO_DOCTEST.append(m)
71
 
 
72
 
    
73
 
    TestBase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
74
 
    print '%-30s %s' % ('bzr binary', TestBase.BZRPATH)
75
 
 
 
182
 
 
183
    _setup_test_log()
 
184
    _setup_test_dir()
76
185
    print
77
186
 
78
187
    suite = TestSuite()
79
 
 
80
 
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
81
 
 
82
 
    for m in MODULES_TO_TEST:
83
 
         suite.addTest(TestLoader().loadTestsFromModule(m))
84
 
 
85
 
    for m in (MODULES_TO_DOCTEST):
 
188
    tl = TestLoader()
 
189
 
 
190
    for m in bzrlib.selftest.whitebox, \
 
191
            bzrlib.selftest.versioning:
 
192
        suite.addTest(tl.loadTestsFromModule(m))
 
193
 
 
194
    suite.addTest(bzrlib.selftest.blackbox.suite())
 
195
 
 
196
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
 
197
            bzrlib.commands:
86
198
        suite.addTest(DocTestSuite(m))
87
199
 
88
 
    for p in bzrlib.plugin.all_plugins:
89
 
        if hasattr(p, 'test_suite'):
90
 
            suite.addTest(p.test_suite())
91
 
 
92
 
    import bzrlib.merge_core
93
 
    suite.addTest(unittest.makeSuite(bzrlib.merge_core.MergeTest, 'test_'))
94
 
 
95
 
    return run_suite(suite, 'testbzr', verbose=verbose)
96
 
 
97
 
 
98
 
 
 
200
    # save stdout & stderr so there's no leakage from code-under-test
 
201
    real_stdout = sys.stdout
 
202
    real_stderr = sys.stderr
 
203
    sys.stdout = sys.stderr = TestBase.TEST_LOG
 
204
    try:
 
205
        result = _MyResult(real_stdout)
 
206
        suite.run(result)
 
207
    finally:
 
208
        sys.stdout = real_stdout
 
209
        sys.stderr = real_stderr
 
210
 
 
211
    _show_results(result)
 
212
 
 
213
    return result.wasSuccessful()
 
214
 
 
215
 
 
216
 
 
217
 
 
218
def _setup_test_log():
 
219
    import time
 
220
    import os
 
221
    
 
222
    log_filename = os.path.abspath('testbzr.log')
 
223
    TestBase.TEST_LOG = open(log_filename, 'wt', buffering=1) # line buffered
 
224
 
 
225
    print >>TestBase.TEST_LOG, "bzr tests run at " + time.ctime()
 
226
    print '%-30s %s' % ('test log', log_filename)
 
227
 
 
228
 
 
229
def _setup_test_dir():
 
230
    import os
 
231
    import shutil
 
232
    
 
233
    TestBase.ORIG_DIR = os.getcwdu()
 
234
    TestBase.TEST_ROOT = os.path.abspath("testbzr.tmp")
 
235
 
 
236
    print '%-30s %s' % ('running tests in', TestBase.TEST_ROOT)
 
237
 
 
238
    if os.path.exists(TestBase.TEST_ROOT):
 
239
        shutil.rmtree(TestBase.TEST_ROOT)
 
240
    os.mkdir(TestBase.TEST_ROOT)
 
241
    os.chdir(TestBase.TEST_ROOT)
 
242
 
 
243
    # make a fake bzr directory there to prevent any tests propagating
 
244
    # up onto the source directory's real branch
 
245
    os.mkdir(os.path.join(TestBase.TEST_ROOT, '.bzr'))
 
246
 
 
247
    
 
248
 
 
249
def _show_results(result):
 
250
     for case, tb in result.errors:
 
251
         _show_test_failure('ERROR', case, tb)
 
252
 
 
253
     for case, tb in result.failures:
 
254
         _show_test_failure('FAILURE', case, tb)
 
255
         
 
256
     print
 
257
     print '%4d tests run' % result.testsRun
 
258
     print '%4d errors' % len(result.errors)
 
259
     print '%4d failures' % len(result.failures)
 
260
 
 
261
 
 
262
 
 
263
def _show_test_failure(kind, case, tb):
 
264
     print (kind + '! ').ljust(60, '-')
 
265
     print case
 
266
     desc = case.shortDescription()
 
267
     if desc:
 
268
         print '   (%s)' % desc
 
269
     print tb
 
270
     print ''.ljust(60, '-')
 
271