~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_trace.py

  • Committer: Ian Clatworthy
  • Date: 2007-12-11 02:07:30 UTC
  • mto: (3119.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3120.
  • Revision ID: ian.clatworthy@internode.on.net-20071211020730-sdj4kj794dw0628e
make help topics more discoverable

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
# "weren't nothing promised to you.  do i look like i got a promise face?"
18
18
 
21
21
from cStringIO import StringIO
22
22
import errno
23
23
import os
24
 
import re
25
24
import sys
26
 
import tempfile
27
25
 
28
26
from bzrlib import (
29
 
    debug,
30
27
    errors,
31
 
    trace,
32
28
    )
33
 
from bzrlib.tests import features, TestCaseInTempDir, TestCase
 
29
from bzrlib.tests import TestCaseInTempDir, TestCase
34
30
from bzrlib.trace import (
35
31
    mutter, mutter_callsite, report_exception,
36
32
    set_verbosity_level, get_verbosity_level, is_quiet, is_verbose, be_quiet,
37
 
    pop_log_file,
38
 
    push_log_file,
39
33
    _rollover_trace_maybe,
40
 
    show_error,
41
34
    )
42
35
 
43
36
 
51
44
class TestTrace(TestCase):
52
45
 
53
46
    def test_format_sys_exception(self):
54
 
        # Test handling of an internal/unexpected error that probably
55
 
        # indicates a bug in bzr.  The details of the message may vary
56
 
        # depending on whether apport is available or not.  See test_crash for
57
 
        # more.
58
47
        try:
59
48
            raise NotImplementedError, "time travel"
60
49
        except NotImplementedError:
63
52
        self.assertEqualDiff(err.splitlines()[0],
64
53
                'bzr: ERROR: exceptions.NotImplementedError: time travel')
65
54
        self.assertContainsRe(err,
66
 
            'Bazaar has encountered an internal error.')
 
55
                r'File.*test_trace.py')
67
56
 
68
57
    def test_format_interrupt_exception(self):
69
58
        try:
75
64
        self.assertTrue(len(msg) > 0)
76
65
        self.assertEqualDiff(msg, 'bzr: interrupted\n')
77
66
 
78
 
    def test_format_memory_error(self):
79
 
        try:
80
 
            raise MemoryError()
81
 
        except MemoryError:
82
 
            pass
83
 
        msg = _format_exception()
84
 
        self.assertEquals(msg,
85
 
            "bzr: out of memory\nUse -Dmem_dump to dump memory to a file.\n")
86
 
 
87
 
    def test_format_mem_dump(self):
88
 
        self.requireFeature(features.meliae)
89
 
        debug.debug_flags.add('mem_dump')
90
 
        try:
91
 
            raise MemoryError()
92
 
        except MemoryError:
93
 
            pass
94
 
        msg = _format_exception()
95
 
        self.assertStartsWith(msg,
96
 
            "bzr: out of memory\nMemory dumped to ")
97
 
 
98
67
    def test_format_os_error(self):
99
68
        try:
100
 
            os.rmdir('nosuchfile22222')
101
 
        except OSError, e:
102
 
            e_str = str(e)
103
 
        msg = _format_exception()
104
 
        # Linux seems to give "No such file" but Windows gives "The system
105
 
        # cannot find the file specified".
106
 
        self.assertEqual('bzr: ERROR: %s\n' % (e_str,), msg)
107
 
 
108
 
    def test_format_io_error(self):
109
 
        try:
110
69
            file('nosuchfile22222')
111
 
        except IOError:
112
 
            pass
113
 
        msg = _format_exception()
114
 
        # Even though Windows and Linux differ for 'os.rmdir', they both give
115
 
        # 'No such file' for open()
116
 
        self.assertContainsRe(msg,
117
 
            r'^bzr: ERROR: \[Errno .*\] No such file.*nosuchfile')
118
 
 
119
 
    def test_format_pywintypes_error(self):
120
 
        self.requireFeature(features.pywintypes)
121
 
        import pywintypes, win32file
122
 
        try:
123
 
            win32file.RemoveDirectory('nosuchfile22222')
124
 
        except pywintypes.error:
125
 
            pass
126
 
        msg = _format_exception()
127
 
        # GZ 2010-05-03: Formatting for pywintypes.error is basic, a 3-tuple
128
 
        #                with errno, function name, and locale error message
129
 
        self.assertContainsRe(msg,
130
 
            r"^bzr: ERROR: \(2, 'RemoveDirectory[AW]?', .*\)")
 
70
        except (OSError, IOError):
 
71
            pass
 
72
        msg = _format_exception()
 
73
        self.assertContainsRe(msg, r'^bzr: ERROR: \[Errno .*\] No such file.*nosuchfile')
131
74
 
132
75
    def test_format_unicode_error(self):
133
76
        try:
146
89
        self.assertTrue(len(msg) > 0)
147
90
        self.assertEqualDiff(msg, 'bzr: ERROR: Not a branch: \"wibble\".\n')
148
91
 
149
 
    def test_report_external_import_error(self):
150
 
        """Short friendly message for missing system modules."""
151
 
        try:
152
 
            import ImaginaryModule
153
 
        except ImportError, e:
154
 
            pass
155
 
        else:
156
 
            self.fail("somehow succeeded in importing %r" % ImaginaryModule)
157
 
        msg = _format_exception()
158
 
        self.assertEqual(msg,
159
 
            'bzr: ERROR: No module named ImaginaryModule\n'
160
 
            'You may need to install this Python library separately.\n')
161
 
 
162
 
    def test_report_import_syntax_error(self):
163
 
        try:
164
 
            raise ImportError("syntax error")
165
 
        except ImportError, e:
166
 
            pass
167
 
        msg = _format_exception()
168
 
        self.assertContainsRe(msg,
169
 
            r'Bazaar has encountered an internal error')
170
 
 
171
92
    def test_trace_unicode(self):
172
93
        """Write Unicode to trace log"""
173
94
        self.log(u'the unicode character for benzene is \N{BENZENE RING}')
174
 
        log = self.get_log()
175
 
        self.assertContainsRe(log, "the unicode character for benzene is")
176
 
 
 
95
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
96
                              "the unicode character for benzene is")
 
97
    
177
98
    def test_trace_argument_unicode(self):
178
99
        """Write a Unicode argument to the trace log"""
179
100
        mutter(u'the unicode character for benzene is %s', u'\N{BENZENE RING}')
180
 
        log = self.get_log()
181
 
        self.assertContainsRe(log, 'the unicode character')
 
101
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
102
                              'the unicode character')
182
103
 
183
104
    def test_trace_argument_utf8(self):
184
105
        """Write a Unicode argument to the trace log"""
185
106
        mutter(u'the unicode character for benzene is %s',
186
107
               u'\N{BENZENE RING}'.encode('utf-8'))
187
 
        log = self.get_log()
188
 
        self.assertContainsRe(log, 'the unicode character')
 
108
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
109
                              'the unicode character')
189
110
 
190
111
    def test_report_broken_pipe(self):
191
112
        try:
196
117
        else:
197
118
            self.fail("expected error not raised")
198
119
 
199
 
    def assertLogStartsWith(self, log, string):
200
 
        """Like assertStartsWith, but skips the log timestamp."""
201
 
        self.assertContainsRe(log,
202
 
            '^\\d+\\.\\d+  ' + re.escape(string))
203
 
 
204
120
    def test_mutter_callsite_1(self):
205
121
        """mutter_callsite can capture 1 level of stack frame."""
206
122
        mutter_callsite(1, "foo %s", "a string")
207
 
        log = self.get_log()
 
123
        log = self._get_log(keep_log_file=True)
208
124
        # begin with the message
209
 
        self.assertLogStartsWith(log, 'foo a string\nCalled from:\n')
 
125
        self.assertStartsWith(log, 'foo a string\nCalled from:\n')
210
126
        # should show two frame: this frame and the one above
211
127
        self.assertContainsRe(log,
212
 
            'test_trace\\.py", line \\d+, in test_mutter_callsite_1\n')
 
128
            'test_trace\.py", line \d+, in test_mutter_callsite_1\n')
213
129
        # this frame should be the final one
214
130
        self.assertEndsWith(log, ' "a string")\n')
215
131
 
216
132
    def test_mutter_callsite_2(self):
217
133
        """mutter_callsite can capture 2 levels of stack frame."""
218
134
        mutter_callsite(2, "foo %s", "a string")
219
 
        log = self.get_log()
 
135
        log = self._get_log(keep_log_file=True)
220
136
        # begin with the message
221
 
        self.assertLogStartsWith(log, 'foo a string\nCalled from:\n')
 
137
        self.assertStartsWith(log, 'foo a string\nCalled from:\n')
222
138
        # should show two frame: this frame and the one above
223
139
        self.assertContainsRe(log,
224
140
            'test_trace.py", line \d+, in test_mutter_callsite_2\n')
228
144
    def test_mutter_never_fails(self):
229
145
        # Even if the decode/encode stage fails, mutter should not
230
146
        # raise an exception
231
 
        # This test checks that mutter doesn't fail; the current behaviour
232
 
        # is that it doesn't fail *and writes non-utf8*.
233
147
        mutter(u'Writing a greek mu (\xb5) works in a unicode string')
234
148
        mutter('But fails in an ascii string \xb5')
235
149
        mutter('and in an ascii argument: %s', '\xb5')
236
 
        log = self.get_log()
 
150
        log = self._get_log(keep_log_file=True)
237
151
        self.assertContainsRe(log, 'Writing a greek mu')
238
152
        self.assertContainsRe(log, "But fails in an ascii string")
239
 
        # However, the log content object does unicode replacement on reading
240
 
        # to let it get unicode back where good data has been written. So we
241
 
        # have to do a replaceent here as well.
242
 
        self.assertContainsRe(log, "ascii argument: \xb5".decode('utf8',
243
 
            'replace'))
244
 
        
245
 
    def test_show_error(self):
246
 
        show_error('error1')
247
 
        show_error(u'error2 \xb5 blah')
248
 
        show_error('arg: %s', 'blah')
249
 
        show_error('arg2: %(key)s', {'key':'stuff'})
250
 
        try:
251
 
            raise Exception("oops")
252
 
        except:
253
 
            show_error('kwarg', exc_info=True)
254
 
        log = self.get_log()
255
 
        self.assertContainsRe(log, 'error1')
256
 
        self.assertContainsRe(log, u'error2 \xb5 blah')
257
 
        self.assertContainsRe(log, 'arg: blah')
258
 
        self.assertContainsRe(log, 'arg2: stuff')
259
 
        self.assertContainsRe(log, 'kwarg')
260
 
        self.assertContainsRe(log, 'Traceback \\(most recent call last\\):')
261
 
        self.assertContainsRe(log, 'File ".*test_trace.py", line .*, in test_show_error')
262
 
        self.assertContainsRe(log, 'raise Exception\\("oops"\\)')
263
 
        self.assertContainsRe(log, 'Exception: oops')
264
 
 
265
 
    def test_push_log_file(self):
266
 
        """Can push and pop log file, and this catches mutter messages.
267
 
 
268
 
        This is primarily for use in the test framework.
269
 
        """
270
 
        tmp1 = tempfile.NamedTemporaryFile()
271
 
        tmp2 = tempfile.NamedTemporaryFile()
272
 
        try:
273
 
            memento1 = push_log_file(tmp1)
274
 
            mutter("comment to file1")
275
 
            try:
276
 
                memento2 = push_log_file(tmp2)
277
 
                try:
278
 
                    mutter("comment to file2")
279
 
                finally:
280
 
                    pop_log_file(memento2)
281
 
                mutter("again to file1")
282
 
            finally:
283
 
                pop_log_file(memento1)
284
 
            # the files were opened in binary mode, so should have exactly
285
 
            # these bytes.  and removing the file as the log target should
286
 
            # have caused them to be flushed out.  need to match using regexps
287
 
            # as there's a timestamp at the front.
288
 
            tmp1.seek(0)
289
 
            self.assertContainsRe(tmp1.read(),
290
 
                r"\d+\.\d+  comment to file1\n\d+\.\d+  again to file1\n")
291
 
            tmp2.seek(0)
292
 
            self.assertContainsRe(tmp2.read(),
293
 
                r"\d+\.\d+  comment to file2\n")
294
 
        finally:
295
 
            tmp1.close()
296
 
            tmp2.close()
297
 
 
298
 
    def test__open_bzr_log_uses_stderr_for_failures(self):
299
 
        # If _open_bzr_log cannot open the file, then we should write the
300
 
        # warning to stderr. Since this is normally happening before logging is
301
 
        # set up.
302
 
        self.overrideAttr(sys, 'stderr', StringIO())
303
 
        # Set the log file to something that cannot exist
304
 
        self.overrideEnv('BZR_LOG', os.getcwd() + '/no-dir/bzr.log')
305
 
        self.overrideAttr(trace, '_bzr_log_filename')
306
 
        logf = trace._open_bzr_log()
307
 
        self.assertIs(None, logf)
308
 
        self.assertContainsRe(sys.stderr.getvalue(),
309
 
                              'failed to open trace file: .*/no-dir/bzr.log')
 
153
        self.assertContainsRe(log, u"ascii argument: \xb5")
310
154
 
311
155
 
312
156
class TestVerbosityLevel(TestCase):
338
182
    def test_log_rollover(self):
339
183
        temp_log_name = 'test-log'
340
184
        trace_file = open(temp_log_name, 'at')
341
 
        trace_file.writelines(['test_log_rollover padding\n'] * 200000)
 
185
        trace_file.write('test_log_rollover padding\n' * 1000000)
342
186
        trace_file.close()
343
187
        _rollover_trace_maybe(temp_log_name)
344
188
        # should have been rolled over
345
189
        self.assertFalse(os.access(temp_log_name, os.R_OK))
346
 
 
347
 
 
348
 
class TestTraceConfiguration(TestCaseInTempDir):
349
 
 
350
 
    def test_default_config(self):
351
 
        config = trace.DefaultConfig()
352
 
        self.overrideAttr(trace, "_bzr_log_filename", None)
353
 
        trace._bzr_log_filename = None
354
 
        expected_filename = trace._get_bzr_log_filename()
355
 
        self.assertEqual(None, trace._bzr_log_filename)
356
 
        config.__enter__()
357
 
        try:
358
 
            # Should have entered and setup a default filename.
359
 
            self.assertEqual(expected_filename, trace._bzr_log_filename)
360
 
        finally:
361
 
            config.__exit__(None, None, None)
362
 
            # Should have exited and cleaned up.
363
 
            self.assertEqual(None, trace._bzr_log_filename)