13
12
# You should have received a copy of the GNU General Public License
14
13
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
14
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
16
"""Tests for the test framework."""
19
from cStringIO import StringIO
20
from doctest import ELLIPSIS
20
from StringIO import StringIO
28
from testtools import MultiTestResult
29
from testtools.content_type import ContentType
30
from testtools.matchers import (
34
import testtools.tests.helpers
26
from bzrlib import osutils, memorytree
53
from bzrlib.repofmt import (
58
from bzrlib.symbol_versioning import (
28
from bzrlib.progress import _BaseProgressBar
63
29
from bzrlib.tests import (
33
TestCaseWithMemoryTransport,
34
TestCaseWithTransport,
39
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
40
from bzrlib.tests.TestUtil import _load_module_by_name
41
import bzrlib.errors as errors
42
from bzrlib import symbol_versioning
43
from bzrlib.symbol_versioning import zero_ten, zero_eleven
70
44
from bzrlib.trace import note
71
from bzrlib.transport import memory
45
from bzrlib.transport.memory import MemoryServer, MemoryTransport
72
46
from bzrlib.version import _get_bzr_source_tree
75
def _test_ids(test_suite):
76
"""Get the ids for the tests in a test suite."""
77
return [t.id() for t in tests.iter_suite_tests(test_suite)]
80
class SelftestTests(tests.TestCase):
49
class SelftestTests(TestCase):
82
51
def test_import_tests(self):
83
mod = TestUtil._load_module_by_name('bzrlib.tests.test_selftest')
52
mod = _load_module_by_name('bzrlib.tests.test_selftest')
84
53
self.assertEqual(mod.SelftestTests, SelftestTests)
86
55
def test_import_test_failure(self):
87
56
self.assertRaises(ImportError,
88
TestUtil._load_module_by_name,
89
58
'bzrlib.no-name-yet')
92
class MetaTestLog(tests.TestCase):
61
class MetaTestLog(TestCase):
94
63
def test_logging(self):
95
64
"""Test logs are captured when a test fails."""
96
65
self.log('a test message')
97
details = self.getDetails()
99
self.assertThat(log.content_type, Equals(ContentType(
100
"text", "plain", {"charset": "utf8"})))
101
self.assertThat(u"".join(log.iter_text()), Equals(self.get_log()))
102
self.assertThat(self.get_log(),
103
DocTestMatches(u"...a test message\n", ELLIPSIS))
106
class TestUnicodeFilename(tests.TestCase):
108
def test_probe_passes(self):
109
"""UnicodeFilename._probe passes."""
110
# We can't test much more than that because the behaviour depends
112
tests.UnicodeFilename._probe()
115
class TestTreeShape(tests.TestCaseInTempDir):
66
self._log_file.flush()
67
self.assertContainsRe(self._get_log(keep_log_file=True),
71
class TestTreeShape(TestCaseInTempDir):
117
73
def test_unicode_paths(self):
118
self.requireFeature(tests.UnicodeFilename)
120
74
filename = u'hell\u00d8'
121
self.build_tree_contents([(filename, 'contents of hello')])
76
self.build_tree_contents([(filename, 'contents of hello')])
77
except UnicodeEncodeError:
78
raise TestSkipped("can't build unicode working tree in "
79
"filesystem encoding %s" % sys.getfilesystemencoding())
122
80
self.failUnlessExists(filename)
125
class TestTransportScenarios(tests.TestCase):
83
class TestTransportProviderAdapter(TestCase):
126
84
"""A group of tests that test the transport implementation adaption core.
128
This is a meta test that the tests are applied to all available
86
This is a meta test that the tests are applied to all available
131
This will be generalised in the future which is why it is in this
89
This will be generalised in the future which is why it is in this
132
90
test file even though it is specific to transport tests at the moment.
135
93
def test_get_transport_permutations(self):
136
# this checks that get_test_permutations defined by the module is
137
# called by the get_transport_test_permutations function.
94
# this checks that we the module get_test_permutations call
95
# is made by the adapter get_transport_test_permitations method.
138
96
class MockModule(object):
139
97
def get_test_permutations(self):
140
98
return sample_permutation
141
99
sample_permutation = [(1,2), (3,4)]
142
from bzrlib.tests.per_transport import get_transport_test_permutations
100
from bzrlib.transport import TransportTestProviderAdapter
101
adapter = TransportTestProviderAdapter()
143
102
self.assertEqual(sample_permutation,
144
get_transport_test_permutations(MockModule()))
103
adapter.get_transport_test_permutations(MockModule()))
146
def test_scenarios_include_all_modules(self):
147
# this checks that the scenario generator returns as many permutations
148
# as there are in all the registered transport modules - we assume if
149
# this matches its probably doing the right thing especially in
150
# combination with the tests for setting the right classes below.
151
from bzrlib.tests.per_transport import transport_test_permutations
152
from bzrlib.transport import _get_transport_modules
105
def test_adapter_checks_all_modules(self):
106
# this checks that the adapter returns as many permurtations as
107
# there are in all the registered# transport modules for there
108
# - we assume if this matches its probably doing the right thing
109
# especially in combination with the tests for setting the right
111
from bzrlib.transport import (TransportTestProviderAdapter,
112
_get_transport_modules
153
114
modules = _get_transport_modules()
154
115
permutation_count = 0
155
116
for module in modules:
157
permutation_count += len(reduce(getattr,
118
permutation_count += len(reduce(getattr,
158
119
(module + ".get_test_permutations").split('.')[1:],
159
120
__import__(module))())
160
121
except errors.DependencyNotPresent:
162
scenarios = transport_test_permutations()
163
self.assertEqual(permutation_count, len(scenarios))
123
input_test = TestTransportProviderAdapter(
124
"test_adapter_sets_transport_class")
125
adapter = TransportTestProviderAdapter()
126
self.assertEqual(permutation_count,
127
len(list(iter(adapter.adapt(input_test)))))
165
def test_scenarios_include_transport_class(self):
129
def test_adapter_sets_transport_class(self):
130
# Check that the test adapter inserts a transport and server into the
166
133
# This test used to know about all the possible transports and the
167
134
# order they were returned but that seems overly brittle (mbp
169
from bzrlib.tests.per_transport import transport_test_permutations
170
scenarios = transport_test_permutations()
136
input_test = TestTransportProviderAdapter(
137
"test_adapter_sets_transport_class")
138
from bzrlib.transport import TransportTestProviderAdapter
139
suite = TransportTestProviderAdapter().adapt(input_test)
140
tests = list(iter(suite))
141
self.assertTrue(len(tests) > 6)
171
142
# there are at least that many builtin transports
172
self.assertTrue(len(scenarios) > 6)
173
one_scenario = scenarios[0]
174
self.assertIsInstance(one_scenario[0], str)
175
self.assertTrue(issubclass(one_scenario[1]["transport_class"],
144
self.assertTrue(issubclass(one_test.transport_class,
176
145
bzrlib.transport.Transport))
177
self.assertTrue(issubclass(one_scenario[1]["transport_server"],
146
self.assertTrue(issubclass(one_test.transport_server,
178
147
bzrlib.transport.Server))
181
class TestBranchScenarios(tests.TestCase):
150
class TestBranchProviderAdapter(TestCase):
151
"""A group of tests that test the branch implementation test adapter."""
183
def test_scenarios(self):
153
def test_adapted_tests(self):
184
154
# check that constructor parameters are passed through to the adapted
186
from bzrlib.tests.per_branch import make_scenarios
156
from bzrlib.branch import BranchTestProviderAdapter
157
input_test = TestBranchProviderAdapter(
158
"test_adapted_tests")
189
161
formats = [("c", "C"), ("d", "D")]
190
scenarios = make_scenarios(server1, server2, formats)
191
self.assertEqual(2, len(scenarios))
194
{'branch_format': 'c',
195
'bzrdir_format': 'C',
196
'transport_readonly_server': 'b',
197
'transport_server': 'a'}),
199
{'branch_format': 'd',
200
'bzrdir_format': 'D',
201
'transport_readonly_server': 'b',
202
'transport_server': 'a'})],
206
class TestBzrDirScenarios(tests.TestCase):
208
def test_scenarios(self):
162
adapter = BranchTestProviderAdapter(server1, server2, formats)
163
suite = adapter.adapt(input_test)
164
tests = list(iter(suite))
165
self.assertEqual(2, len(tests))
166
self.assertEqual(tests[0].branch_format, formats[0][0])
167
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
168
self.assertEqual(tests[0].transport_server, server1)
169
self.assertEqual(tests[0].transport_readonly_server, server2)
170
self.assertEqual(tests[1].branch_format, formats[1][0])
171
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
172
self.assertEqual(tests[1].transport_server, server1)
173
self.assertEqual(tests[1].transport_readonly_server, server2)
176
class TestBzrDirProviderAdapter(TestCase):
177
"""A group of tests that test the bzr dir implementation test adapter."""
179
def test_adapted_tests(self):
209
180
# check that constructor parameters are passed through to the adapted
211
from bzrlib.tests.per_bzrdir import make_scenarios
182
from bzrlib.bzrdir import BzrDirTestProviderAdapter
183
input_test = TestBzrDirProviderAdapter(
184
"test_adapted_tests")
215
187
formats = ["c", "d"]
216
scenarios = make_scenarios(vfs_factory, server1, server2, formats)
219
{'bzrdir_format': 'c',
220
'transport_readonly_server': 'b',
221
'transport_server': 'a',
222
'vfs_transport_factory': 'v'}),
224
{'bzrdir_format': 'd',
225
'transport_readonly_server': 'b',
226
'transport_server': 'a',
227
'vfs_transport_factory': 'v'})],
231
class TestRepositoryScenarios(tests.TestCase):
233
def test_formats_to_scenarios(self):
234
from bzrlib.tests.per_repository import formats_to_scenarios
235
formats = [("(c)", remote.RemoteRepositoryFormat()),
236
("(d)", repository.format_registry.get(
237
'Bazaar repository format 2a (needs bzr 1.16 or later)\n'))]
238
no_vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
240
vfs_scenarios = formats_to_scenarios(formats, "server", "readonly",
241
vfs_transport_factory="vfs")
242
# no_vfs generate scenarios without vfs_transport_factory
244
('RemoteRepositoryFormat(c)',
245
{'bzrdir_format': remote.RemoteBzrDirFormat(),
246
'repository_format': remote.RemoteRepositoryFormat(),
247
'transport_readonly_server': 'readonly',
248
'transport_server': 'server'}),
249
('RepositoryFormat2a(d)',
250
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
251
'repository_format': groupcompress_repo.RepositoryFormat2a(),
252
'transport_readonly_server': 'readonly',
253
'transport_server': 'server'})]
254
self.assertEqual(expected, no_vfs_scenarios)
256
('RemoteRepositoryFormat(c)',
257
{'bzrdir_format': remote.RemoteBzrDirFormat(),
258
'repository_format': remote.RemoteRepositoryFormat(),
259
'transport_readonly_server': 'readonly',
260
'transport_server': 'server',
261
'vfs_transport_factory': 'vfs'}),
262
('RepositoryFormat2a(d)',
263
{'bzrdir_format': bzrdir.BzrDirMetaFormat1(),
264
'repository_format': groupcompress_repo.RepositoryFormat2a(),
265
'transport_readonly_server': 'readonly',
266
'transport_server': 'server',
267
'vfs_transport_factory': 'vfs'})],
271
class TestTestScenarioApplication(tests.TestCase):
272
"""Tests for the test adaption facilities."""
274
def test_apply_scenario(self):
275
from bzrlib.tests import apply_scenario
276
input_test = TestTestScenarioApplication("test_apply_scenario")
277
# setup two adapted tests
278
adapted_test1 = apply_scenario(input_test,
280
{"bzrdir_format":"bzr_format",
281
"repository_format":"repo_fmt",
282
"transport_server":"transport_server",
283
"transport_readonly_server":"readonly-server"}))
284
adapted_test2 = apply_scenario(input_test,
285
("new id 2", {"bzrdir_format":None}))
286
# input_test should have been altered.
287
self.assertRaises(AttributeError, getattr, input_test, "bzrdir_format")
288
# the new tests are mutually incompatible, ensuring it has
289
# made new ones, and unspecified elements in the scenario
290
# should not have been altered.
291
self.assertEqual("bzr_format", adapted_test1.bzrdir_format)
292
self.assertEqual("repo_fmt", adapted_test1.repository_format)
293
self.assertEqual("transport_server", adapted_test1.transport_server)
294
self.assertEqual("readonly-server",
295
adapted_test1.transport_readonly_server)
297
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
298
"test_apply_scenario(new id)",
300
self.assertEqual(None, adapted_test2.bzrdir_format)
302
"bzrlib.tests.test_selftest.TestTestScenarioApplication."
303
"test_apply_scenario(new id 2)",
307
class TestInterRepositoryScenarios(tests.TestCase):
309
def test_scenarios(self):
310
# check that constructor parameters are passed through to the adapted
312
from bzrlib.tests.per_interrepository import make_scenarios
315
formats = [("C0", "C1", "C2"), ("D0", "D1", "D2")]
316
scenarios = make_scenarios(server1, server2, formats)
319
{'repository_format': 'C1',
320
'repository_format_to': 'C2',
321
'transport_readonly_server': 'b',
322
'transport_server': 'a'}),
324
{'repository_format': 'D1',
325
'repository_format_to': 'D2',
326
'transport_readonly_server': 'b',
327
'transport_server': 'a'})],
331
class TestWorkingTreeScenarios(tests.TestCase):
333
def test_scenarios(self):
334
# check that constructor parameters are passed through to the adapted
336
from bzrlib.tests.per_workingtree import make_scenarios
339
formats = [workingtree.WorkingTreeFormat2(),
340
workingtree.WorkingTreeFormat3(),]
341
scenarios = make_scenarios(server1, server2, formats)
343
('WorkingTreeFormat2',
344
{'bzrdir_format': formats[0]._matchingbzrdir,
345
'transport_readonly_server': 'b',
346
'transport_server': 'a',
347
'workingtree_format': formats[0]}),
348
('WorkingTreeFormat3',
349
{'bzrdir_format': formats[1]._matchingbzrdir,
350
'transport_readonly_server': 'b',
351
'transport_server': 'a',
352
'workingtree_format': formats[1]})],
356
class TestTreeScenarios(tests.TestCase):
358
def test_scenarios(self):
359
# the tree implementation scenario generator is meant to setup one
360
# instance for each working tree format, and one additional instance
361
# that will use the default wt format, but create a revision tree for
362
# the tests. this means that the wt ones should have the
363
# workingtree_to_test_tree attribute set to 'return_parameter' and the
364
# revision one set to revision_tree_from_workingtree.
366
from bzrlib.tests.per_tree import (
367
_dirstate_tree_from_workingtree,
188
adapter = BzrDirTestProviderAdapter(server1, server2, formats)
189
suite = adapter.adapt(input_test)
190
tests = list(iter(suite))
191
self.assertEqual(2, len(tests))
192
self.assertEqual(tests[0].bzrdir_format, formats[0])
193
self.assertEqual(tests[0].transport_server, server1)
194
self.assertEqual(tests[0].transport_readonly_server, server2)
195
self.assertEqual(tests[1].bzrdir_format, formats[1])
196
self.assertEqual(tests[1].transport_server, server1)
197
self.assertEqual(tests[1].transport_readonly_server, server2)
200
class TestRepositoryProviderAdapter(TestCase):
201
"""A group of tests that test the repository implementation test adapter."""
203
def test_adapted_tests(self):
204
# check that constructor parameters are passed through to the adapted
206
from bzrlib.repository import RepositoryTestProviderAdapter
207
input_test = TestRepositoryProviderAdapter(
208
"test_adapted_tests")
211
formats = [("c", "C"), ("d", "D")]
212
adapter = RepositoryTestProviderAdapter(server1, server2, formats)
213
suite = adapter.adapt(input_test)
214
tests = list(iter(suite))
215
self.assertEqual(2, len(tests))
216
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
217
self.assertEqual(tests[0].repository_format, formats[0][0])
218
self.assertEqual(tests[0].transport_server, server1)
219
self.assertEqual(tests[0].transport_readonly_server, server2)
220
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
221
self.assertEqual(tests[1].repository_format, formats[1][0])
222
self.assertEqual(tests[1].transport_server, server1)
223
self.assertEqual(tests[1].transport_readonly_server, server2)
226
class TestInterRepositoryProviderAdapter(TestCase):
227
"""A group of tests that test the InterRepository test adapter."""
229
def test_adapted_tests(self):
230
# check that constructor parameters are passed through to the adapted
232
from bzrlib.repository import InterRepositoryTestProviderAdapter
233
input_test = TestInterRepositoryProviderAdapter(
234
"test_adapted_tests")
237
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
238
adapter = InterRepositoryTestProviderAdapter(server1, server2, formats)
239
suite = adapter.adapt(input_test)
240
tests = list(iter(suite))
241
self.assertEqual(2, len(tests))
242
self.assertEqual(tests[0].interrepo_class, formats[0][0])
243
self.assertEqual(tests[0].repository_format, formats[0][1])
244
self.assertEqual(tests[0].repository_format_to, formats[0][2])
245
self.assertEqual(tests[0].transport_server, server1)
246
self.assertEqual(tests[0].transport_readonly_server, server2)
247
self.assertEqual(tests[1].interrepo_class, formats[1][0])
248
self.assertEqual(tests[1].repository_format, formats[1][1])
249
self.assertEqual(tests[1].repository_format_to, formats[1][2])
250
self.assertEqual(tests[1].transport_server, server1)
251
self.assertEqual(tests[1].transport_readonly_server, server2)
254
class TestInterVersionedFileProviderAdapter(TestCase):
255
"""A group of tests that test the InterVersionedFile test adapter."""
257
def test_adapted_tests(self):
258
# check that constructor parameters are passed through to the adapted
260
from bzrlib.versionedfile import InterVersionedFileTestProviderAdapter
261
input_test = TestInterRepositoryProviderAdapter(
262
"test_adapted_tests")
265
formats = [(str, "C1", "C2"), (int, "D1", "D2")]
266
adapter = InterVersionedFileTestProviderAdapter(server1, server2, formats)
267
suite = adapter.adapt(input_test)
268
tests = list(iter(suite))
269
self.assertEqual(2, len(tests))
270
self.assertEqual(tests[0].interversionedfile_class, formats[0][0])
271
self.assertEqual(tests[0].versionedfile_factory, formats[0][1])
272
self.assertEqual(tests[0].versionedfile_factory_to, formats[0][2])
273
self.assertEqual(tests[0].transport_server, server1)
274
self.assertEqual(tests[0].transport_readonly_server, server2)
275
self.assertEqual(tests[1].interversionedfile_class, formats[1][0])
276
self.assertEqual(tests[1].versionedfile_factory, formats[1][1])
277
self.assertEqual(tests[1].versionedfile_factory_to, formats[1][2])
278
self.assertEqual(tests[1].transport_server, server1)
279
self.assertEqual(tests[1].transport_readonly_server, server2)
282
class TestRevisionStoreProviderAdapter(TestCase):
283
"""A group of tests that test the RevisionStore test adapter."""
285
def test_adapted_tests(self):
286
# check that constructor parameters are passed through to the adapted
288
from bzrlib.store.revision import RevisionStoreTestProviderAdapter
289
input_test = TestRevisionStoreProviderAdapter(
290
"test_adapted_tests")
291
# revision stores need a store factory - i.e. RevisionKnit
292
#, a readonly and rw transport
296
store_factories = ["c", "d"]
297
adapter = RevisionStoreTestProviderAdapter(server1, server2, store_factories)
298
suite = adapter.adapt(input_test)
299
tests = list(iter(suite))
300
self.assertEqual(2, len(tests))
301
self.assertEqual(tests[0].store_factory, store_factories[0][0])
302
self.assertEqual(tests[0].transport_server, server1)
303
self.assertEqual(tests[0].transport_readonly_server, server2)
304
self.assertEqual(tests[1].store_factory, store_factories[1][0])
305
self.assertEqual(tests[1].transport_server, server1)
306
self.assertEqual(tests[1].transport_readonly_server, server2)
309
class TestWorkingTreeProviderAdapter(TestCase):
310
"""A group of tests that test the workingtree implementation test adapter."""
312
def test_adapted_tests(self):
313
# check that constructor parameters are passed through to the adapted
315
from bzrlib.workingtree import WorkingTreeTestProviderAdapter
316
input_test = TestWorkingTreeProviderAdapter(
317
"test_adapted_tests")
320
formats = [("c", "C"), ("d", "D")]
321
adapter = WorkingTreeTestProviderAdapter(server1, server2, formats)
322
suite = adapter.adapt(input_test)
323
tests = list(iter(suite))
324
self.assertEqual(2, len(tests))
325
self.assertEqual(tests[0].workingtree_format, formats[0][0])
326
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
327
self.assertEqual(tests[0].transport_server, server1)
328
self.assertEqual(tests[0].transport_readonly_server, server2)
329
self.assertEqual(tests[1].workingtree_format, formats[1][0])
330
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
331
self.assertEqual(tests[1].transport_server, server1)
332
self.assertEqual(tests[1].transport_readonly_server, server2)
335
class TestTreeProviderAdapter(TestCase):
336
"""Test the setup of tree_implementation tests."""
338
def test_adapted_tests(self):
339
# the tree implementation adapter is meant to setup one instance for
340
# each working tree format, and one additional instance that will
341
# use the default wt format, but create a revision tree for the tests.
342
# this means that the wt ones should have the workingtree_to_test_tree
343
# attribute set to 'return_parameter' and the revision one set to
344
# revision_tree_from_workingtree.
346
from bzrlib.tests.tree_implementations import (
347
TreeTestProviderAdapter,
371
348
return_parameter,
372
349
revision_tree_from_workingtree
351
from bzrlib.workingtree import WorkingTreeFormat
352
input_test = TestTreeProviderAdapter(
353
"test_adapted_tests")
376
formats = [workingtree.WorkingTreeFormat2(),
377
workingtree.WorkingTreeFormat3(),]
378
scenarios = make_scenarios(server1, server2, formats)
379
self.assertEqual(7, len(scenarios))
380
default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
wt4_format = workingtree.WorkingTreeFormat4()
382
wt5_format = workingtree.WorkingTreeFormat5()
383
expected_scenarios = [
384
('WorkingTreeFormat2',
385
{'bzrdir_format': formats[0]._matchingbzrdir,
386
'transport_readonly_server': 'b',
387
'transport_server': 'a',
388
'workingtree_format': formats[0],
389
'_workingtree_to_test_tree': return_parameter,
391
('WorkingTreeFormat3',
392
{'bzrdir_format': formats[1]._matchingbzrdir,
393
'transport_readonly_server': 'b',
394
'transport_server': 'a',
395
'workingtree_format': formats[1],
396
'_workingtree_to_test_tree': return_parameter,
399
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
400
'bzrdir_format': default_wt_format._matchingbzrdir,
401
'transport_readonly_server': 'b',
402
'transport_server': 'a',
403
'workingtree_format': default_wt_format,
405
('DirStateRevisionTree,WT4',
406
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
407
'bzrdir_format': wt4_format._matchingbzrdir,
408
'transport_readonly_server': 'b',
409
'transport_server': 'a',
410
'workingtree_format': wt4_format,
412
('DirStateRevisionTree,WT5',
413
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
414
'bzrdir_format': wt5_format._matchingbzrdir,
415
'transport_readonly_server': 'b',
416
'transport_server': 'a',
417
'workingtree_format': wt5_format,
420
{'_workingtree_to_test_tree': preview_tree_pre,
421
'bzrdir_format': default_wt_format._matchingbzrdir,
422
'transport_readonly_server': 'b',
423
'transport_server': 'a',
424
'workingtree_format': default_wt_format}),
426
{'_workingtree_to_test_tree': preview_tree_post,
427
'bzrdir_format': default_wt_format._matchingbzrdir,
428
'transport_readonly_server': 'b',
429
'transport_server': 'a',
430
'workingtree_format': default_wt_format}),
432
self.assertEqual(expected_scenarios, scenarios)
435
class TestInterTreeScenarios(tests.TestCase):
356
formats = [("c", "C"), ("d", "D")]
357
adapter = TreeTestProviderAdapter(server1, server2, formats)
358
suite = adapter.adapt(input_test)
359
tests = list(iter(suite))
360
self.assertEqual(3, len(tests))
361
default_format = WorkingTreeFormat.get_default_format()
362
self.assertEqual(tests[0].workingtree_format, formats[0][0])
363
self.assertEqual(tests[0].bzrdir_format, formats[0][1])
364
self.assertEqual(tests[0].transport_server, server1)
365
self.assertEqual(tests[0].transport_readonly_server, server2)
366
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
367
self.assertEqual(tests[1].workingtree_format, formats[1][0])
368
self.assertEqual(tests[1].bzrdir_format, formats[1][1])
369
self.assertEqual(tests[1].transport_server, server1)
370
self.assertEqual(tests[1].transport_readonly_server, server2)
371
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
372
self.assertEqual(tests[2].workingtree_format, default_format)
373
self.assertEqual(tests[2].bzrdir_format, default_format._matchingbzrdir)
374
self.assertEqual(tests[2].transport_server, server1)
375
self.assertEqual(tests[2].transport_readonly_server, server2)
376
self.assertEqual(tests[2].workingtree_to_test_tree,
377
revision_tree_from_workingtree)
380
class TestInterTreeProviderAdapter(TestCase):
436
381
"""A group of tests that test the InterTreeTestAdapter."""
438
def test_scenarios(self):
383
def test_adapted_tests(self):
439
384
# check that constructor parameters are passed through to the adapted
441
386
# for InterTree tests we want the machinery to bring up two trees in
1015
733
This current saves and restores:
1016
734
TestCaseInTempDir.TEST_ROOT
1018
There should be no tests in this file that use
1019
bzrlib.tests.TextTestRunner without using this convenience method,
1020
because of our use of global state.
736
There should be no tests in this file that use bzrlib.tests.TextTestRunner
737
without using this convenience method, because of our use of global state.
1022
old_root = tests.TestCaseInTempDir.TEST_ROOT
1023
old_leak = tests.TestCase._first_thread_leaker_id
739
old_root = TestCaseInTempDir.TEST_ROOT
1025
tests.TestCaseInTempDir.TEST_ROOT = None
1026
tests.TestCase._first_thread_leaker_id = None
741
TestCaseInTempDir.TEST_ROOT = None
1027
742
return testrunner.run(test)
1029
tests.TestCaseInTempDir.TEST_ROOT = old_root
1030
tests.TestCase._first_thread_leaker_id = old_leak
1032
def test_known_failure_failed_run(self):
1033
# run a test that generates a known failure which should be printed in
1034
# the final output when real failures occur.
1035
class Test(tests.TestCase):
1036
def known_failure_test(self):
1037
self.expectFailure('failed', self.assertTrue, False)
1038
test = unittest.TestSuite()
1039
test.addTest(Test("known_failure_test"))
1042
test.addTest(unittest.FunctionTestCase(failing_test))
1044
runner = tests.TextTestRunner(stream=stream)
1045
result = self.run_test_runner(runner, test)
1046
lines = stream.getvalue().splitlines()
1047
self.assertContainsRe(stream.getvalue(),
1048
'(?sm)^bzr selftest.*$'
1050
'^======================================================================\n'
1051
'^FAIL: failing_test\n'
1052
'^----------------------------------------------------------------------\n'
1053
'Traceback \\(most recent call last\\):\n'
1054
' .*' # File .*, line .*, in failing_test' - but maybe not from .pyc
1055
' self.fail\\(\'foo\'\\)\n'
1057
'^----------------------------------------------------------------------\n'
1059
'FAILED \\(failures=1, known_failure_count=1\\)'
1062
def test_known_failure_ok_run(self):
1063
# run a test that generates a known failure which should be printed in
1065
class Test(tests.TestCase):
1066
def known_failure_test(self):
1067
self.expectFailure('failed', self.assertTrue, False)
1068
test = Test("known_failure_test")
1070
runner = tests.TextTestRunner(stream=stream)
1071
result = self.run_test_runner(runner, test)
1072
self.assertContainsRe(stream.getvalue(),
1075
'Ran 1 test in .*\n'
1077
'OK \\(known_failures=1\\)\n')
1079
def test_result_decorator(self):
1082
class LoggingDecorator(tests.ForwardingResult):
1083
def startTest(self, test):
1084
tests.ForwardingResult.startTest(self, test)
1085
calls.append('start')
1086
test = unittest.FunctionTestCase(lambda:None)
1088
runner = tests.TextTestRunner(stream=stream,
1089
result_decorators=[LoggingDecorator])
1090
result = self.run_test_runner(runner, test)
1091
self.assertLength(1, calls)
744
TestCaseInTempDir.TEST_ROOT = old_root
746
def test_accepts_and_uses_pb_parameter(self):
747
test = TestRunner('dummy_test')
748
mypb = MockProgress()
749
self.assertEqual([], mypb.calls)
750
runner = TextTestRunner(stream=self._log_file, pb=mypb)
751
result = self.run_test_runner(runner, test)
752
self.assertEqual(1, result.testsRun)
753
self.assertEqual(('update', 'Running tests', 0, 1), mypb.calls[0])
754
self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
755
self.assertEqual(('update', 'OK ', 1, None), mypb.calls[2])
756
self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
757
self.assertEqual(('clear',), mypb.calls[4])
758
self.assertEqual(5, len(mypb.calls))
1093
760
def test_skipped_test(self):
1094
761
# run a test that is skipped, and check the suite as a whole still
1096
763
# skipping_test must be hidden in here so it's not run as a real test
1097
class SkippingTest(tests.TestCase):
1098
def skipping_test(self):
1099
raise tests.TestSkipped('test intentionally skipped')
1100
runner = tests.TextTestRunner(stream=self._log_file)
1101
test = SkippingTest("skipping_test")
1102
result = self.run_test_runner(runner, test)
1103
self.assertTrue(result.wasSuccessful())
1105
def test_skipped_from_setup(self):
1107
class SkippedSetupTest(tests.TestCase):
1110
calls.append('setUp')
1111
self.addCleanup(self.cleanup)
1112
raise tests.TestSkipped('skipped setup')
1114
def test_skip(self):
1115
self.fail('test reached')
1118
calls.append('cleanup')
1120
runner = tests.TextTestRunner(stream=self._log_file)
1121
test = SkippedSetupTest('test_skip')
1122
result = self.run_test_runner(runner, test)
1123
self.assertTrue(result.wasSuccessful())
1124
# Check if cleanup was called the right number of times.
1125
self.assertEqual(['setUp', 'cleanup'], calls)
1127
def test_skipped_from_test(self):
1129
class SkippedTest(tests.TestCase):
1132
tests.TestCase.setUp(self)
1133
calls.append('setUp')
1134
self.addCleanup(self.cleanup)
1136
def test_skip(self):
1137
raise tests.TestSkipped('skipped test')
1140
calls.append('cleanup')
1142
runner = tests.TextTestRunner(stream=self._log_file)
1143
test = SkippedTest('test_skip')
1144
result = self.run_test_runner(runner, test)
1145
self.assertTrue(result.wasSuccessful())
1146
# Check if cleanup was called the right number of times.
1147
self.assertEqual(['setUp', 'cleanup'], calls)
1149
def test_not_applicable(self):
1150
# run a test that is skipped because it's not applicable
1151
class Test(tests.TestCase):
1152
def not_applicable_test(self):
1153
raise tests.TestNotApplicable('this test never runs')
1155
runner = tests.TextTestRunner(stream=out, verbosity=2)
1156
test = Test("not_applicable_test")
1157
result = self.run_test_runner(runner, test)
1158
self._log_file.write(out.getvalue())
1159
self.assertTrue(result.wasSuccessful())
1160
self.assertTrue(result.wasStrictlySuccessful())
1161
self.assertContainsRe(out.getvalue(),
1162
r'(?m)not_applicable_test * N/A')
1163
self.assertContainsRe(out.getvalue(),
1164
r'(?m)^ this test never runs')
1166
def test_unsupported_features_listed(self):
1167
"""When unsupported features are encountered they are detailed."""
1168
class Feature1(tests.Feature):
1169
def _probe(self): return False
1170
class Feature2(tests.Feature):
1171
def _probe(self): return False
1172
# create sample tests
1173
test1 = SampleTestCase('_test_pass')
1174
test1._test_needs_features = [Feature1()]
1175
test2 = SampleTestCase('_test_pass')
1176
test2._test_needs_features = [Feature2()]
1177
test = unittest.TestSuite()
1181
runner = tests.TextTestRunner(stream=stream)
1182
result = self.run_test_runner(runner, test)
1183
lines = stream.getvalue().splitlines()
1186
"Missing feature 'Feature1' skipped 1 tests.",
1187
"Missing feature 'Feature2' skipped 1 tests.",
1191
def _patch_get_bzr_source_tree(self):
1192
# Reading from the actual source tree breaks isolation, but we don't
1193
# want to assume that thats *all* that would happen.
1194
self._get_source_tree_calls = []
1196
self._get_source_tree_calls.append("called")
1198
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', new_get)
765
raise TestSkipped('test intentionally skipped')
766
runner = TextTestRunner(stream=self._log_file, keep_output=True)
767
test = unittest.FunctionTestCase(skipping_test)
768
result = self.run_test_runner(runner, test)
769
self.assertTrue(result.wasSuccessful())
1200
771
def test_bench_history(self):
1201
# tests that the running the benchmark passes bench_history into
1202
# the test result object. We can tell that happens if
1203
# _get_bzr_source_tree is called.
1204
self._patch_get_bzr_source_tree()
772
# tests that the running the benchmark produces a history file
773
# containing a timestamp and the revision id of the bzrlib source which
775
workingtree = _get_bzr_source_tree()
1205
776
test = TestRunner('dummy_test')
1206
777
output = StringIO()
1207
runner = tests.TextTestRunner(stream=self._log_file,
1208
bench_history=output)
778
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1209
779
result = self.run_test_runner(runner, test)
1210
780
output_string = output.getvalue()
1211
781
self.assertContainsRe(output_string, "--date [0-9.]+")
1212
self.assertLength(1, self._get_source_tree_calls)
1214
def test_startTestRun(self):
1215
"""run should call result.startTestRun()"""
1217
class LoggingDecorator(tests.ForwardingResult):
1218
def startTestRun(self):
1219
tests.ForwardingResult.startTestRun(self)
1220
calls.append('startTestRun')
1221
test = unittest.FunctionTestCase(lambda:None)
1223
runner = tests.TextTestRunner(stream=stream,
1224
result_decorators=[LoggingDecorator])
1225
result = self.run_test_runner(runner, test)
1226
self.assertLength(1, calls)
1228
def test_stopTestRun(self):
1229
"""run should call result.stopTestRun()"""
1231
class LoggingDecorator(tests.ForwardingResult):
1232
def stopTestRun(self):
1233
tests.ForwardingResult.stopTestRun(self)
1234
calls.append('stopTestRun')
1235
test = unittest.FunctionTestCase(lambda:None)
1237
runner = tests.TextTestRunner(stream=stream,
1238
result_decorators=[LoggingDecorator])
1239
result = self.run_test_runner(runner, test)
1240
self.assertLength(1, calls)
1243
class SampleTestCase(tests.TestCase):
1245
def _test_pass(self):
1248
class _TestException(Exception):
1252
class TestTestCase(tests.TestCase):
782
if workingtree is not None:
783
revision_id = workingtree.get_parent_ids()[0]
784
self.assertEndsWith(output_string.rstrip(), revision_id)
786
def test_success_log_deleted(self):
787
"""Successful tests have their log deleted"""
789
class LogTester(TestCase):
791
def test_success(self):
792
self.log('this will be removed\n')
794
sio = cStringIO.StringIO()
795
runner = TextTestRunner(stream=sio)
796
test = LogTester('test_success')
797
result = self.run_test_runner(runner, test)
799
log = test._get_log()
800
self.assertEqual("DELETED log file to reduce memory footprint", log)
801
self.assertEqual('', test._log_contents)
802
self.assertIs(None, test._log_file_name)
804
def test_fail_log_kept(self):
805
"""Failed tests have their log kept"""
807
class LogTester(TestCase):
810
self.log('this will be kept\n')
811
self.fail('this test fails')
813
sio = cStringIO.StringIO()
814
runner = TextTestRunner(stream=sio)
815
test = LogTester('test_fail')
816
result = self.run_test_runner(runner, test)
818
text = sio.getvalue()
819
self.assertContainsRe(text, 'this will be kept')
820
self.assertContainsRe(text, 'this test fails')
822
log = test._get_log()
823
self.assertContainsRe(log, 'this will be kept')
824
self.assertEqual(log, test._log_contents)
826
def test_error_log_kept(self):
827
"""Tests with errors have their log kept"""
829
class LogTester(TestCase):
831
def test_error(self):
832
self.log('this will be kept\n')
833
raise ValueError('random exception raised')
835
sio = cStringIO.StringIO()
836
runner = TextTestRunner(stream=sio)
837
test = LogTester('test_error')
838
result = self.run_test_runner(runner, test)
840
text = sio.getvalue()
841
self.assertContainsRe(text, 'this will be kept')
842
self.assertContainsRe(text, 'random exception raised')
844
log = test._get_log()
845
self.assertContainsRe(log, 'this will be kept')
846
self.assertEqual(log, test._log_contents)
849
class TestTestCase(TestCase):
1253
850
"""Tests that test the core bzrlib TestCase."""
1255
def test_assertLength_matches_empty(self):
1257
self.assertLength(0, a_list)
1259
def test_assertLength_matches_nonempty(self):
1261
self.assertLength(3, a_list)
1263
def test_assertLength_fails_different(self):
1265
self.assertRaises(AssertionError, self.assertLength, 1, a_list)
1267
def test_assertLength_shows_sequence_in_failure(self):
1269
exception = self.assertRaises(AssertionError, self.assertLength, 2,
1271
self.assertEqual('Incorrect length: wanted 2, got 3 for [1, 2, 3]',
1274
def test_base_setUp_not_called_causes_failure(self):
1275
class TestCaseWithBrokenSetUp(tests.TestCase):
1277
pass # does not call TestCase.setUp
1280
test = TestCaseWithBrokenSetUp('test_foo')
1281
result = unittest.TestResult()
1283
self.assertFalse(result.wasSuccessful())
1284
self.assertEqual(1, result.testsRun)
1286
def test_base_tearDown_not_called_causes_failure(self):
1287
class TestCaseWithBrokenTearDown(tests.TestCase):
1289
pass # does not call TestCase.tearDown
1292
test = TestCaseWithBrokenTearDown('test_foo')
1293
result = unittest.TestResult()
1295
self.assertFalse(result.wasSuccessful())
1296
self.assertEqual(1, result.testsRun)
1298
def test_debug_flags_sanitised(self):
1299
"""The bzrlib debug flags should be sanitised by setUp."""
1300
if 'allow_debug' in tests.selftest_debug_flags:
1301
raise tests.TestNotApplicable(
1302
'-Eallow_debug option prevents debug flag sanitisation')
1303
# we could set something and run a test that will check
1304
# it gets santised, but this is probably sufficient for now:
1305
# if someone runs the test with -Dsomething it will error.
1307
if self._lock_check_thorough:
1308
flags.add('strict_locks')
1309
self.assertEqual(flags, bzrlib.debug.debug_flags)
1311
def change_selftest_debug_flags(self, new_flags):
1312
self.overrideAttr(tests, 'selftest_debug_flags', set(new_flags))
1314
def test_allow_debug_flag(self):
1315
"""The -Eallow_debug flag prevents bzrlib.debug.debug_flags from being
1316
sanitised (i.e. cleared) before running a test.
1318
self.change_selftest_debug_flags(set(['allow_debug']))
1319
bzrlib.debug.debug_flags = set(['a-flag'])
1320
class TestThatRecordsFlags(tests.TestCase):
1321
def test_foo(nested_self):
1322
self.flags = set(bzrlib.debug.debug_flags)
1323
test = TestThatRecordsFlags('test_foo')
1324
test.run(self.make_test_result())
1325
flags = set(['a-flag'])
1326
if 'disable_lock_checks' not in tests.selftest_debug_flags:
1327
flags.add('strict_locks')
1328
self.assertEqual(flags, self.flags)
1330
def test_disable_lock_checks(self):
1331
"""The -Edisable_lock_checks flag disables thorough checks."""
1332
class TestThatRecordsFlags(tests.TestCase):
1333
def test_foo(nested_self):
1334
self.flags = set(bzrlib.debug.debug_flags)
1335
self.test_lock_check_thorough = nested_self._lock_check_thorough
1336
self.change_selftest_debug_flags(set())
1337
test = TestThatRecordsFlags('test_foo')
1338
test.run(self.make_test_result())
1339
# By default we do strict lock checking and thorough lock/unlock
1341
self.assertTrue(self.test_lock_check_thorough)
1342
self.assertEqual(set(['strict_locks']), self.flags)
1343
# Now set the disable_lock_checks flag, and show that this changed.
1344
self.change_selftest_debug_flags(set(['disable_lock_checks']))
1345
test = TestThatRecordsFlags('test_foo')
1346
test.run(self.make_test_result())
1347
self.assertFalse(self.test_lock_check_thorough)
1348
self.assertEqual(set(), self.flags)
1350
def test_this_fails_strict_lock_check(self):
1351
class TestThatRecordsFlags(tests.TestCase):
1352
def test_foo(nested_self):
1353
self.flags1 = set(bzrlib.debug.debug_flags)
1354
self.thisFailsStrictLockCheck()
1355
self.flags2 = set(bzrlib.debug.debug_flags)
1356
# Make sure lock checking is active
1357
self.change_selftest_debug_flags(set())
1358
test = TestThatRecordsFlags('test_foo')
1359
test.run(self.make_test_result())
1360
self.assertEqual(set(['strict_locks']), self.flags1)
1361
self.assertEqual(set(), self.flags2)
1363
def test_debug_flags_restored(self):
1364
"""The bzrlib debug flags should be restored to their original state
1365
after the test was run, even if allow_debug is set.
1367
self.change_selftest_debug_flags(set(['allow_debug']))
1368
# Now run a test that modifies debug.debug_flags.
1369
bzrlib.debug.debug_flags = set(['original-state'])
1370
class TestThatModifiesFlags(tests.TestCase):
1372
bzrlib.debug.debug_flags = set(['modified'])
1373
test = TestThatModifiesFlags('test_foo')
1374
test.run(self.make_test_result())
1375
self.assertEqual(set(['original-state']), bzrlib.debug.debug_flags)
1377
def make_test_result(self):
1378
"""Get a test result that writes to the test log file."""
1379
return tests.TextTestResult(self._log_file, descriptions=0, verbosity=1)
1381
852
def inner_test(self):
1382
853
# the inner child test
1383
854
note("inner_test")
1797
1022
tree = self.make_branch_and_memory_tree('a')
1798
1023
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1800
def test_make_tree_for_local_vfs_backed_transport(self):
1801
# make_branch_and_tree has to use local branch and repositories
1802
# when the vfs transport and local disk are colocated, even if
1803
# a different transport is in use for url generation.
1804
self.transport_server = test_server.FakeVFATServer
1805
self.assertFalse(self.get_url('t1').startswith('file://'))
1026
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1028
def test_make_tree_for_sftp_branch(self):
1029
"""Transports backed by local directories create local trees."""
1806
1031
tree = self.make_branch_and_tree('t1')
1807
1032
base = tree.bzrdir.root_transport.base
1808
self.assertStartsWith(base, 'file://')
1033
self.failIf(base.startswith('sftp'),
1034
'base %r is on sftp but should be local' % base)
1809
1035
self.assertEquals(tree.bzrdir.root_transport,
1810
1036
tree.branch.bzrdir.root_transport)
1811
1037
self.assertEquals(tree.bzrdir.root_transport,
1812
1038
tree.branch.repository.bzrdir.root_transport)
1815
class SelfTestHelper:
1817
def run_selftest(self, **kwargs):
1818
"""Run selftest returning its output."""
1820
old_transport = bzrlib.tests.default_transport
1821
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1822
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1824
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1826
bzrlib.tests.default_transport = old_transport
1827
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1832
class TestSelftest(tests.TestCase, SelfTestHelper):
1041
class TestSelftest(TestCase):
1833
1042
"""Tests of bzrlib.tests.selftest."""
1835
1044
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1836
1045
factory_called = []
1838
1047
factory_called.append(True)
1839
return TestUtil.TestSuite()
1840
1049
out = StringIO()
1841
1050
err = StringIO()
1842
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1051
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1843
1052
test_suite_factory=factory)
1844
1053
self.assertEqual([True], factory_called)
1847
"""A test suite factory."""
1848
class Test(tests.TestCase):
1855
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1857
def test_list_only(self):
1858
output = self.run_selftest(test_suite_factory=self.factory,
1860
self.assertEqual(3, len(output.readlines()))
1862
def test_list_only_filtered(self):
1863
output = self.run_selftest(test_suite_factory=self.factory,
1864
list_only=True, pattern="Test.b")
1865
self.assertEndsWith(output.getvalue(), "Test.b\n")
1866
self.assertLength(1, output.readlines())
1868
def test_list_only_excludes(self):
1869
output = self.run_selftest(test_suite_factory=self.factory,
1870
list_only=True, exclude_pattern="Test.b")
1871
self.assertNotContainsRe("Test.b", output.getvalue())
1872
self.assertLength(2, output.readlines())
1874
def test_lsprof_tests(self):
1875
self.requireFeature(test_lsprof.LSProfFeature)
1878
def __call__(test, result):
1880
def run(test, result):
1881
self.assertIsInstance(result, tests.ForwardingResult)
1882
calls.append("called")
1883
def countTestCases(self):
1885
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1886
self.assertLength(1, calls)
1888
def test_random(self):
1889
# test randomising by listing a number of tests.
1890
output_123 = self.run_selftest(test_suite_factory=self.factory,
1891
list_only=True, random_seed="123")
1892
output_234 = self.run_selftest(test_suite_factory=self.factory,
1893
list_only=True, random_seed="234")
1894
self.assertNotEqual(output_123, output_234)
1895
# "Randominzing test order..\n\n
1896
self.assertLength(5, output_123.readlines())
1897
self.assertLength(5, output_234.readlines())
1899
def test_random_reuse_is_same_order(self):
1900
# test randomising by listing a number of tests.
1901
expected = self.run_selftest(test_suite_factory=self.factory,
1902
list_only=True, random_seed="123")
1903
repeated = self.run_selftest(test_suite_factory=self.factory,
1904
list_only=True, random_seed="123")
1905
self.assertEqual(expected.getvalue(), repeated.getvalue())
1907
def test_runner_class(self):
1908
self.requireFeature(features.subunit)
1909
from subunit import ProtocolTestCase
1910
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1911
test_suite_factory=self.factory)
1912
test = ProtocolTestCase(stream)
1913
result = unittest.TestResult()
1915
self.assertEqual(3, result.testsRun)
1917
def test_starting_with_single_argument(self):
1918
output = self.run_selftest(test_suite_factory=self.factory,
1919
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1921
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1924
def test_starting_with_multiple_argument(self):
1925
output = self.run_selftest(test_suite_factory=self.factory,
1926
starting_with=['bzrlib.tests.test_selftest.Test.a',
1927
'bzrlib.tests.test_selftest.Test.b'],
1929
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1930
'bzrlib.tests.test_selftest.Test.b\n',
1933
def check_transport_set(self, transport_server):
1934
captured_transport = []
1935
def seen_transport(a_transport):
1936
captured_transport.append(a_transport)
1937
class Capture(tests.TestCase):
1939
seen_transport(bzrlib.tests.default_transport)
1941
return TestUtil.TestSuite([Capture("a")])
1942
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1943
self.assertEqual(transport_server, captured_transport[0])
1945
def test_transport_sftp(self):
1946
self.requireFeature(features.paramiko)
1947
from bzrlib.tests import stub_sftp
1948
self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
1950
def test_transport_memory(self):
1951
self.check_transport_set(memory.MemoryServer)
1954
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1955
# Does IO: reads test.list
1957
def test_load_list(self):
1958
# Provide a list with one test - this test.
1959
test_id_line = '%s\n' % self.id()
1960
self.build_tree_contents([('test.list', test_id_line)])
1961
# And generate a list of the tests in the suite.
1962
stream = self.run_selftest(load_list='test.list', list_only=True)
1963
self.assertEqual(test_id_line, stream.getvalue())
1965
def test_load_unknown(self):
1966
# Provide a list with one test - this test.
1967
# And generate a list of the tests in the suite.
1968
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1969
load_list='missing file name', list_only=True)
1972
class TestRunBzr(tests.TestCase):
1977
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
1979
"""Override _run_bzr_core to test how it is invoked by run_bzr.
1981
Attempts to run bzr from inside this class don't actually run it.
1983
We test how run_bzr actually invokes bzr in another location. Here we
1984
only need to test that it passes the right parameters to run_bzr.
1986
self.argv = list(argv)
1987
self.retcode = retcode
1988
self.encoding = encoding
1990
self.working_dir = working_dir
1991
return self.retcode, self.out, self.err
1993
def test_run_bzr_error(self):
1994
self.out = "It sure does!\n"
1995
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1996
self.assertEqual(['rocks'], self.argv)
1997
self.assertEqual(34, self.retcode)
1998
self.assertEqual('It sure does!\n', out)
1999
self.assertEquals(out, self.out)
2000
self.assertEqual('', err)
2001
self.assertEquals(err, self.err)
2003
def test_run_bzr_error_regexes(self):
2005
self.err = "bzr: ERROR: foobarbaz is not versioned"
2006
out, err = self.run_bzr_error(
2007
["bzr: ERROR: foobarbaz is not versioned"],
2008
['file-id', 'foobarbaz'])
2010
def test_encoding(self):
2011
"""Test that run_bzr passes encoding to _run_bzr_core"""
2012
self.run_bzr('foo bar')
2013
self.assertEqual(None, self.encoding)
2014
self.assertEqual(['foo', 'bar'], self.argv)
2016
self.run_bzr('foo bar', encoding='baz')
2017
self.assertEqual('baz', self.encoding)
2018
self.assertEqual(['foo', 'bar'], self.argv)
2020
def test_retcode(self):
2021
"""Test that run_bzr passes retcode to _run_bzr_core"""
2022
# Default is retcode == 0
2023
self.run_bzr('foo bar')
2024
self.assertEqual(0, self.retcode)
2025
self.assertEqual(['foo', 'bar'], self.argv)
2027
self.run_bzr('foo bar', retcode=1)
2028
self.assertEqual(1, self.retcode)
2029
self.assertEqual(['foo', 'bar'], self.argv)
2031
self.run_bzr('foo bar', retcode=None)
2032
self.assertEqual(None, self.retcode)
2033
self.assertEqual(['foo', 'bar'], self.argv)
2035
self.run_bzr(['foo', 'bar'], retcode=3)
2036
self.assertEqual(3, self.retcode)
2037
self.assertEqual(['foo', 'bar'], self.argv)
2039
def test_stdin(self):
2040
# test that the stdin keyword to run_bzr is passed through to
2041
# _run_bzr_core as-is. We do this by overriding
2042
# _run_bzr_core in this class, and then calling run_bzr,
2043
# which is a convenience function for _run_bzr_core, so
2045
self.run_bzr('foo bar', stdin='gam')
2046
self.assertEqual('gam', self.stdin)
2047
self.assertEqual(['foo', 'bar'], self.argv)
2049
self.run_bzr('foo bar', stdin='zippy')
2050
self.assertEqual('zippy', self.stdin)
2051
self.assertEqual(['foo', 'bar'], self.argv)
2053
def test_working_dir(self):
2054
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2055
self.run_bzr('foo bar')
2056
self.assertEqual(None, self.working_dir)
2057
self.assertEqual(['foo', 'bar'], self.argv)
2059
self.run_bzr('foo bar', working_dir='baz')
2060
self.assertEqual('baz', self.working_dir)
2061
self.assertEqual(['foo', 'bar'], self.argv)
2063
def test_reject_extra_keyword_arguments(self):
2064
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2065
error_regex=['error message'])
2068
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2069
# Does IO when testing the working_dir parameter.
2071
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2072
a_callable=None, *args, **kwargs):
2074
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2075
self.factory = bzrlib.ui.ui_factory
2076
self.working_dir = osutils.getcwd()
2077
stdout.write('foo\n')
2078
stderr.write('bar\n')
2081
def test_stdin(self):
2082
# test that the stdin keyword to _run_bzr_core is passed through to
2083
# apply_redirected as a StringIO. We do this by overriding
2084
# apply_redirected in this class, and then calling _run_bzr_core,
2085
# which calls apply_redirected.
2086
self.run_bzr(['foo', 'bar'], stdin='gam')
2087
self.assertEqual('gam', self.stdin.read())
2088
self.assertTrue(self.stdin is self.factory_stdin)
2089
self.run_bzr(['foo', 'bar'], stdin='zippy')
2090
self.assertEqual('zippy', self.stdin.read())
2091
self.assertTrue(self.stdin is self.factory_stdin)
2093
def test_ui_factory(self):
2094
# each invocation of self.run_bzr should get its
2095
# own UI factory, which is an instance of TestUIFactory,
2096
# with stdin, stdout and stderr attached to the stdin,
2097
# stdout and stderr of the invoked run_bzr
2098
current_factory = bzrlib.ui.ui_factory
2099
self.run_bzr(['foo'])
2100
self.failIf(current_factory is self.factory)
2101
self.assertNotEqual(sys.stdout, self.factory.stdout)
2102
self.assertNotEqual(sys.stderr, self.factory.stderr)
2103
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2104
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2105
self.assertIsInstance(self.factory, tests.TestUIFactory)
2107
def test_working_dir(self):
2108
self.build_tree(['one/', 'two/'])
2109
cwd = osutils.getcwd()
2111
# Default is to work in the current directory
2112
self.run_bzr(['foo', 'bar'])
2113
self.assertEqual(cwd, self.working_dir)
2115
self.run_bzr(['foo', 'bar'], working_dir=None)
2116
self.assertEqual(cwd, self.working_dir)
2118
# The function should be run in the alternative directory
2119
# but afterwards the current working dir shouldn't be changed
2120
self.run_bzr(['foo', 'bar'], working_dir='one')
2121
self.assertNotEqual(cwd, self.working_dir)
2122
self.assertEndsWith(self.working_dir, 'one')
2123
self.assertEqual(cwd, osutils.getcwd())
2125
self.run_bzr(['foo', 'bar'], working_dir='two')
2126
self.assertNotEqual(cwd, self.working_dir)
2127
self.assertEndsWith(self.working_dir, 'two')
2128
self.assertEqual(cwd, osutils.getcwd())
2131
class StubProcess(object):
2132
"""A stub process for testing run_bzr_subprocess."""
2134
def __init__(self, out="", err="", retcode=0):
2137
self.returncode = retcode
2139
def communicate(self):
2140
return self.out, self.err
2143
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2144
"""Base class for tests testing how we might run bzr."""
2147
tests.TestCaseWithTransport.setUp(self)
2148
self.subprocess_calls = []
2150
def start_bzr_subprocess(self, process_args, env_changes=None,
2151
skip_if_plan_to_signal=False,
2153
allow_plugins=False):
2154
"""capture what run_bzr_subprocess tries to do."""
2155
self.subprocess_calls.append({'process_args':process_args,
2156
'env_changes':env_changes,
2157
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2158
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2159
return self.next_subprocess
2162
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2164
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2165
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2167
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2168
that will return static results. This assertion method populates those
2169
results and also checks the arguments run_bzr_subprocess generates.
2171
self.next_subprocess = process
2173
result = self.run_bzr_subprocess(*args, **kwargs)
2175
self.next_subprocess = None
2176
for key, expected in expected_args.iteritems():
2177
self.assertEqual(expected, self.subprocess_calls[-1][key])
2180
self.next_subprocess = None
2181
for key, expected in expected_args.iteritems():
2182
self.assertEqual(expected, self.subprocess_calls[-1][key])
2185
def test_run_bzr_subprocess(self):
2186
"""The run_bzr_helper_external command behaves nicely."""
2187
self.assertRunBzrSubprocess({'process_args':['--version']},
2188
StubProcess(), '--version')
2189
self.assertRunBzrSubprocess({'process_args':['--version']},
2190
StubProcess(), ['--version'])
2191
# retcode=None disables retcode checking
2192
result = self.assertRunBzrSubprocess({},
2193
StubProcess(retcode=3), '--version', retcode=None)
2194
result = self.assertRunBzrSubprocess({},
2195
StubProcess(out="is free software"), '--version')
2196
self.assertContainsRe(result[0], 'is free software')
2197
# Running a subcommand that is missing errors
2198
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2199
{'process_args':['--versionn']}, StubProcess(retcode=3),
2201
# Unless it is told to expect the error from the subprocess
2202
result = self.assertRunBzrSubprocess({},
2203
StubProcess(retcode=3), '--versionn', retcode=3)
2204
# Or to ignore retcode checking
2205
result = self.assertRunBzrSubprocess({},
2206
StubProcess(err="unknown command", retcode=3), '--versionn',
2208
self.assertContainsRe(result[1], 'unknown command')
2210
def test_env_change_passes_through(self):
2211
self.assertRunBzrSubprocess(
2212
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2214
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2216
def test_no_working_dir_passed_as_None(self):
2217
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2219
def test_no_working_dir_passed_through(self):
2220
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2223
def test_run_bzr_subprocess_no_plugins(self):
2224
self.assertRunBzrSubprocess({'allow_plugins': False},
2227
def test_allow_plugins(self):
2228
self.assertRunBzrSubprocess({'allow_plugins': True},
2229
StubProcess(), '', allow_plugins=True)
2232
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2234
def test_finish_bzr_subprocess_with_error(self):
2235
"""finish_bzr_subprocess allows specification of the desired exit code.
2237
process = StubProcess(err="unknown command", retcode=3)
2238
result = self.finish_bzr_subprocess(process, retcode=3)
2239
self.assertEqual('', result[0])
2240
self.assertContainsRe(result[1], 'unknown command')
2242
def test_finish_bzr_subprocess_ignoring_retcode(self):
2243
"""finish_bzr_subprocess allows the exit code to be ignored."""
2244
process = StubProcess(err="unknown command", retcode=3)
2245
result = self.finish_bzr_subprocess(process, retcode=None)
2246
self.assertEqual('', result[0])
2247
self.assertContainsRe(result[1], 'unknown command')
2249
def test_finish_subprocess_with_unexpected_retcode(self):
2250
"""finish_bzr_subprocess raises self.failureException if the retcode is
2251
not the expected one.
2253
process = StubProcess(err="unknown command", retcode=3)
2254
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2258
class _DontSpawnProcess(Exception):
2259
"""A simple exception which just allows us to skip unnecessary steps"""
2262
class TestStartBzrSubProcess(tests.TestCase):
2264
def check_popen_state(self):
2265
"""Replace to make assertions when popen is called."""
2267
def _popen(self, *args, **kwargs):
2268
"""Record the command that is run, so that we can ensure it is correct"""
2269
self.check_popen_state()
2270
self._popen_args = args
2271
self._popen_kwargs = kwargs
2272
raise _DontSpawnProcess()
2274
def test_run_bzr_subprocess_no_plugins(self):
2275
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2276
command = self._popen_args[0]
2277
self.assertEqual(sys.executable, command[0])
2278
self.assertEqual(self.get_bzr_path(), command[1])
2279
self.assertEqual(['--no-plugins'], command[2:])
2281
def test_allow_plugins(self):
2282
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2284
command = self._popen_args[0]
2285
self.assertEqual([], command[2:])
2287
def test_set_env(self):
2288
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2290
def check_environment():
2291
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2292
self.check_popen_state = check_environment
2293
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2294
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2295
# not set in theparent
2296
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2298
def test_run_bzr_subprocess_env_del(self):
2299
"""run_bzr_subprocess can remove environment variables too."""
2300
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2301
def check_environment():
2302
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2303
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2304
self.check_popen_state = check_environment
2305
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2306
env_changes={'EXISTANT_ENV_VAR':None})
2307
# Still set in parent
2308
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2309
del os.environ['EXISTANT_ENV_VAR']
2311
def test_env_del_missing(self):
2312
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2313
def check_environment():
2314
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2315
self.check_popen_state = check_environment
2316
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2317
env_changes={'NON_EXISTANT_ENV_VAR':None})
2319
def test_working_dir(self):
2320
"""Test that we can specify the working dir for the child"""
2321
orig_getcwd = osutils.getcwd
2322
orig_chdir = os.chdir
2330
osutils.getcwd = getcwd
2332
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2335
osutils.getcwd = orig_getcwd
2337
os.chdir = orig_chdir
2338
self.assertEqual(['foo', 'current'], chdirs)
2341
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2342
"""Tests that really need to do things with an external bzr."""
2344
def test_start_and_stop_bzr_subprocess_send_signal(self):
2345
"""finish_bzr_subprocess raises self.failureException if the retcode is
2346
not the expected one.
2348
self.disable_missing_extensions_warning()
2349
process = self.start_bzr_subprocess(['wait-until-signalled'],
2350
skip_if_plan_to_signal=True)
2351
self.assertEqual('running\n', process.stdout.readline())
2352
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2354
self.assertEqual('', result[0])
2355
self.assertEqual('bzr: interrupted\n', result[1])
2358
class TestFeature(tests.TestCase):
2360
def test_caching(self):
2361
"""Feature._probe is called by the feature at most once."""
2362
class InstrumentedFeature(tests.Feature):
2364
super(InstrumentedFeature, self).__init__()
2367
self.calls.append('_probe')
2369
feature = InstrumentedFeature()
2371
self.assertEqual(['_probe'], feature.calls)
2373
self.assertEqual(['_probe'], feature.calls)
2375
def test_named_str(self):
2376
"""Feature.__str__ should thunk to feature_name()."""
2377
class NamedFeature(tests.Feature):
2378
def feature_name(self):
2380
feature = NamedFeature()
2381
self.assertEqual('symlinks', str(feature))
2383
def test_default_str(self):
2384
"""Feature.__str__ should default to __class__.__name__."""
2385
class NamedFeature(tests.Feature):
2387
feature = NamedFeature()
2388
self.assertEqual('NamedFeature', str(feature))
2391
class TestUnavailableFeature(tests.TestCase):
2393
def test_access_feature(self):
2394
feature = tests.Feature()
2395
exception = tests.UnavailableFeature(feature)
2396
self.assertIs(feature, exception.args[0])
2399
simple_thunk_feature = tests._CompatabilityThunkFeature(
2400
deprecated_in((2, 1, 0)),
2401
'bzrlib.tests.test_selftest',
2402
'simple_thunk_feature','UnicodeFilename',
2403
replacement_module='bzrlib.tests'
2406
class Test_CompatibilityFeature(tests.TestCase):
2408
def test_does_thunk(self):
2409
res = self.callDeprecated(
2410
['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2411
' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2412
simple_thunk_feature.available)
2413
self.assertEqual(tests.UnicodeFilename.available(), res)
2416
class TestModuleAvailableFeature(tests.TestCase):
2418
def test_available_module(self):
2419
feature = tests.ModuleAvailableFeature('bzrlib.tests')
2420
self.assertEqual('bzrlib.tests', feature.module_name)
2421
self.assertEqual('bzrlib.tests', str(feature))
2422
self.assertTrue(feature.available())
2423
self.assertIs(tests, feature.module)
2425
def test_unavailable_module(self):
2426
feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2427
self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2428
self.assertFalse(feature.available())
2429
self.assertIs(None, feature.module)
2432
class TestSelftestFiltering(tests.TestCase):
2435
tests.TestCase.setUp(self)
2436
self.suite = TestUtil.TestSuite()
2437
self.loader = TestUtil.TestLoader()
2438
self.suite.addTest(self.loader.loadTestsFromModule(
2439
sys.modules['bzrlib.tests.test_selftest']))
2440
self.all_names = _test_ids(self.suite)
2442
def test_condition_id_re(self):
2443
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2444
'test_condition_id_re')
2445
filtered_suite = tests.filter_suite_by_condition(
2446
self.suite, tests.condition_id_re('test_condition_id_re'))
2447
self.assertEqual([test_name], _test_ids(filtered_suite))
2449
def test_condition_id_in_list(self):
2450
test_names = ['bzrlib.tests.test_selftest.TestSelftestFiltering.'
2451
'test_condition_id_in_list']
2452
id_list = tests.TestIdList(test_names)
2453
filtered_suite = tests.filter_suite_by_condition(
2454
self.suite, tests.condition_id_in_list(id_list))
2455
my_pattern = 'TestSelftestFiltering.*test_condition_id_in_list'
2456
re_filtered = tests.filter_suite_by_re(self.suite, my_pattern)
2457
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2459
def test_condition_id_startswith(self):
2460
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2461
start1 = klass + 'test_condition_id_starts'
2462
start2 = klass + 'test_condition_id_in'
2463
test_names = [ klass + 'test_condition_id_in_list',
2464
klass + 'test_condition_id_startswith',
2466
filtered_suite = tests.filter_suite_by_condition(
2467
self.suite, tests.condition_id_startswith([start1, start2]))
2468
self.assertEqual(test_names, _test_ids(filtered_suite))
2470
def test_condition_isinstance(self):
2471
filtered_suite = tests.filter_suite_by_condition(
2472
self.suite, tests.condition_isinstance(self.__class__))
2473
class_pattern = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2474
re_filtered = tests.filter_suite_by_re(self.suite, class_pattern)
2475
self.assertEqual(_test_ids(re_filtered), _test_ids(filtered_suite))
2477
def test_exclude_tests_by_condition(self):
2478
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2479
'test_exclude_tests_by_condition')
2480
filtered_suite = tests.exclude_tests_by_condition(self.suite,
2481
lambda x:x.id() == excluded_name)
2482
self.assertEqual(len(self.all_names) - 1,
2483
filtered_suite.countTestCases())
2484
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2485
remaining_names = list(self.all_names)
2486
remaining_names.remove(excluded_name)
2487
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2489
def test_exclude_tests_by_re(self):
2490
self.all_names = _test_ids(self.suite)
2491
filtered_suite = tests.exclude_tests_by_re(self.suite,
2492
'exclude_tests_by_re')
2493
excluded_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2494
'test_exclude_tests_by_re')
2495
self.assertEqual(len(self.all_names) - 1,
2496
filtered_suite.countTestCases())
2497
self.assertFalse(excluded_name in _test_ids(filtered_suite))
2498
remaining_names = list(self.all_names)
2499
remaining_names.remove(excluded_name)
2500
self.assertEqual(remaining_names, _test_ids(filtered_suite))
2502
def test_filter_suite_by_condition(self):
2503
test_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2504
'test_filter_suite_by_condition')
2505
filtered_suite = tests.filter_suite_by_condition(self.suite,
2506
lambda x:x.id() == test_name)
2507
self.assertEqual([test_name], _test_ids(filtered_suite))
2509
def test_filter_suite_by_re(self):
2510
filtered_suite = tests.filter_suite_by_re(self.suite,
2511
'test_filter_suite_by_r')
2512
filtered_names = _test_ids(filtered_suite)
2513
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
2514
'TestSelftestFiltering.test_filter_suite_by_re'])
2516
def test_filter_suite_by_id_list(self):
2517
test_list = ['bzrlib.tests.test_selftest.'
2518
'TestSelftestFiltering.test_filter_suite_by_id_list']
2519
filtered_suite = tests.filter_suite_by_id_list(
2520
self.suite, tests.TestIdList(test_list))
2521
filtered_names = _test_ids(filtered_suite)
2524
['bzrlib.tests.test_selftest.'
2525
'TestSelftestFiltering.test_filter_suite_by_id_list'])
2527
def test_filter_suite_by_id_startswith(self):
2528
# By design this test may fail if another test is added whose name also
2529
# begins with one of the start value used.
2530
klass = 'bzrlib.tests.test_selftest.TestSelftestFiltering.'
2531
start1 = klass + 'test_filter_suite_by_id_starts'
2532
start2 = klass + 'test_filter_suite_by_id_li'
2533
test_list = [klass + 'test_filter_suite_by_id_list',
2534
klass + 'test_filter_suite_by_id_startswith',
2536
filtered_suite = tests.filter_suite_by_id_startswith(
2537
self.suite, [start1, start2])
2540
_test_ids(filtered_suite),
2543
def test_preserve_input(self):
2544
# NB: Surely this is something in the stdlib to do this?
2545
self.assertTrue(self.suite is tests.preserve_input(self.suite))
2546
self.assertTrue("@#$" is tests.preserve_input("@#$"))
2548
def test_randomize_suite(self):
2549
randomized_suite = tests.randomize_suite(self.suite)
2550
# randomizing should not add or remove test names.
2551
self.assertEqual(set(_test_ids(self.suite)),
2552
set(_test_ids(randomized_suite)))
2553
# Technically, this *can* fail, because random.shuffle(list) can be
2554
# equal to list. Trying multiple times just pushes the frequency back.
2555
# As its len(self.all_names)!:1, the failure frequency should be low
2556
# enough to ignore. RBC 20071021.
2557
# It should change the order.
2558
self.assertNotEqual(self.all_names, _test_ids(randomized_suite))
2559
# But not the length. (Possibly redundant with the set test, but not
2561
self.assertEqual(len(self.all_names), len(_test_ids(randomized_suite)))
2563
def test_split_suit_by_condition(self):
2564
self.all_names = _test_ids(self.suite)
2565
condition = tests.condition_id_re('test_filter_suite_by_r')
2566
split_suite = tests.split_suite_by_condition(self.suite, condition)
2567
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2568
'test_filter_suite_by_re')
2569
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2570
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2571
remaining_names = list(self.all_names)
2572
remaining_names.remove(filtered_name)
2573
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2575
def test_split_suit_by_re(self):
2576
self.all_names = _test_ids(self.suite)
2577
split_suite = tests.split_suite_by_re(self.suite,
2578
'test_filter_suite_by_r')
2579
filtered_name = ('bzrlib.tests.test_selftest.TestSelftestFiltering.'
2580
'test_filter_suite_by_re')
2581
self.assertEqual([filtered_name], _test_ids(split_suite[0]))
2582
self.assertFalse(filtered_name in _test_ids(split_suite[1]))
2583
remaining_names = list(self.all_names)
2584
remaining_names.remove(filtered_name)
2585
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2588
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2590
def test_check_inventory_shape(self):
2591
files = ['a', 'b/', 'b/c']
2592
tree = self.make_branch_and_tree('.')
2593
self.build_tree(files)
2597
self.check_inventory_shape(tree.inventory, files)
2602
class TestBlackboxSupport(tests.TestCase):
2603
"""Tests for testsuite blackbox features."""
2605
def test_run_bzr_failure_not_caught(self):
2606
# When we run bzr in blackbox mode, we want any unexpected errors to
2607
# propagate up to the test suite so that it can show the error in the
2608
# usual way, and we won't get a double traceback.
2609
e = self.assertRaises(
2611
self.run_bzr, ['assert-fail'])
2612
# make sure we got the real thing, not an error from somewhere else in
2613
# the test framework
2614
self.assertEquals('always fails', str(e))
2615
# check that there's no traceback in the test log
2616
self.assertNotContainsRe(self.get_log(), r'Traceback')
2618
def test_run_bzr_user_error_caught(self):
2619
# Running bzr in blackbox mode, normal/expected/user errors should be
2620
# caught in the regular way and turned into an error message plus exit
2622
transport_server = memory.MemoryServer()
2623
transport_server.start_server()
2624
self.addCleanup(transport_server.stop_server)
2625
url = transport_server.get_url()
2626
self.permit_url(url)
2627
out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2628
self.assertEqual(out, '')
2629
self.assertContainsRe(err,
2630
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2633
class TestTestLoader(tests.TestCase):
2634
"""Tests for the test loader."""
2636
def _get_loader_and_module(self):
2637
"""Gets a TestLoader and a module with one test in it."""
2638
loader = TestUtil.TestLoader()
2640
class Stub(tests.TestCase):
2643
class MyModule(object):
2645
MyModule.a_class = Stub
2647
return loader, module
2649
def test_module_no_load_tests_attribute_loads_classes(self):
2650
loader, module = self._get_loader_and_module()
2651
self.assertEqual(1, loader.loadTestsFromModule(module).countTestCases())
2653
def test_module_load_tests_attribute_gets_called(self):
2654
loader, module = self._get_loader_and_module()
2655
# 'self' is here because we're faking the module with a class. Regular
2656
# load_tests do not need that :)
2657
def load_tests(self, standard_tests, module, loader):
2658
result = loader.suiteClass()
2659
for test in tests.iter_suite_tests(standard_tests):
2660
result.addTests([test, test])
2662
# add a load_tests() method which multiplies the tests from the module.
2663
module.__class__.load_tests = load_tests
2664
self.assertEqual(2, loader.loadTestsFromModule(module).countTestCases())
2666
def test_load_tests_from_module_name_smoke_test(self):
2667
loader = TestUtil.TestLoader()
2668
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2669
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2672
def test_load_tests_from_module_name_with_bogus_module_name(self):
2673
loader = TestUtil.TestLoader()
2674
self.assertRaises(ImportError, loader.loadTestsFromModuleName, 'bogus')
2677
class TestTestIdList(tests.TestCase):
2679
def _create_id_list(self, test_list):
2680
return tests.TestIdList(test_list)
2682
def _create_suite(self, test_id_list):
2684
class Stub(tests.TestCase):
2688
def _create_test_id(id):
2691
suite = TestUtil.TestSuite()
2692
for id in test_id_list:
2693
t = Stub('test_foo')
2694
t.id = _create_test_id(id)
2698
def _test_ids(self, test_suite):
2699
"""Get the ids for the tests in a test suite."""
2700
return [t.id() for t in tests.iter_suite_tests(test_suite)]
2702
def test_empty_list(self):
2703
id_list = self._create_id_list([])
2704
self.assertEquals({}, id_list.tests)
2705
self.assertEquals({}, id_list.modules)
2707
def test_valid_list(self):
2708
id_list = self._create_id_list(
2709
['mod1.cl1.meth1', 'mod1.cl1.meth2',
2710
'mod1.func1', 'mod1.cl2.meth2',
2712
'mod1.submod2.cl1.meth1', 'mod1.submod2.cl2.meth2',
2714
self.assertTrue(id_list.refers_to('mod1'))
2715
self.assertTrue(id_list.refers_to('mod1.submod1'))
2716
self.assertTrue(id_list.refers_to('mod1.submod2'))
2717
self.assertTrue(id_list.includes('mod1.cl1.meth1'))
2718
self.assertTrue(id_list.includes('mod1.submod1'))
2719
self.assertTrue(id_list.includes('mod1.func1'))
2721
def test_bad_chars_in_params(self):
2722
id_list = self._create_id_list(['mod1.cl1.meth1(xx.yy)'])
2723
self.assertTrue(id_list.refers_to('mod1'))
2724
self.assertTrue(id_list.includes('mod1.cl1.meth1(xx.yy)'))
2726
def test_module_used(self):
2727
id_list = self._create_id_list(['mod.class.meth'])
2728
self.assertTrue(id_list.refers_to('mod'))
2729
self.assertTrue(id_list.refers_to('mod.class'))
2730
self.assertTrue(id_list.refers_to('mod.class.meth'))
2732
def test_test_suite_matches_id_list_with_unknown(self):
2733
loader = TestUtil.TestLoader()
2734
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2735
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',
2737
not_found, duplicates = tests.suite_matches_id_list(suite, test_list)
2738
self.assertEquals(['bogus'], not_found)
2739
self.assertEquals([], duplicates)
2741
def test_suite_matches_id_list_with_duplicates(self):
2742
loader = TestUtil.TestLoader()
2743
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2744
dupes = loader.suiteClass()
2745
for test in tests.iter_suite_tests(suite):
2747
dupes.addTest(test) # Add it again
2749
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing',]
2750
not_found, duplicates = tests.suite_matches_id_list(
2752
self.assertEquals([], not_found)
2753
self.assertEquals(['bzrlib.tests.test_sampler.DemoTest.test_nothing'],
2757
class TestTestSuite(tests.TestCase):
2759
def test__test_suite_testmod_names(self):
2760
# Test that a plausible list of test module names are returned
2761
# by _test_suite_testmod_names.
2762
test_list = tests._test_suite_testmod_names()
2764
'bzrlib.tests.blackbox',
2765
'bzrlib.tests.per_transport',
2766
'bzrlib.tests.test_selftest',
2770
def test__test_suite_modules_to_doctest(self):
2771
# Test that a plausible list of modules to doctest is returned
2772
# by _test_suite_modules_to_doctest.
2773
test_list = tests._test_suite_modules_to_doctest()
2775
# When docstrings are stripped, there are no modules to doctest
2776
self.assertEqual([], test_list)
2783
def test_test_suite(self):
2784
# test_suite() loads the entire test suite to operate. To avoid this
2785
# overhead, and yet still be confident that things are happening,
2786
# we temporarily replace two functions used by test_suite with
2787
# test doubles that supply a few sample tests to load, and check they
2790
def testmod_names():
2791
calls.append("testmod_names")
2793
'bzrlib.tests.blackbox.test_branch',
2794
'bzrlib.tests.per_transport',
2795
'bzrlib.tests.test_selftest',
2797
self.overrideAttr(tests, '_test_suite_testmod_names', testmod_names)
2799
calls.append("modules_to_doctest")
2802
return ['bzrlib.timestamp']
2803
self.overrideAttr(tests, '_test_suite_modules_to_doctest', doctests)
2804
expected_test_list = [
2806
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2807
('bzrlib.tests.per_transport.TransportTests'
2808
'.test_abspath(LocalTransport,LocalURLServer)'),
2809
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2810
# plugins can't be tested that way since selftest may be run with
2813
if __doc__ is not None:
2814
expected_test_list.extend([
2815
# modules_to_doctest
2816
'bzrlib.timestamp.format_highres_date',
2818
suite = tests.test_suite()
2819
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2821
self.assertSubset(expected_test_list, _test_ids(suite))
2823
def test_test_suite_list_and_start(self):
2824
# We cannot test this at the same time as the main load, because we want
2825
# to know that starting_with == None works. So a second load is
2826
# incurred - note that the starting_with parameter causes a partial load
2827
# rather than a full load so this test should be pretty quick.
2828
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2829
suite = tests.test_suite(test_list,
2830
['bzrlib.tests.test_selftest.TestTestSuite'])
2831
# test_test_suite_list_and_start is not included
2832
self.assertEquals(test_list, _test_ids(suite))
2835
class TestLoadTestIdList(tests.TestCaseInTempDir):
2837
def _create_test_list_file(self, file_name, content):
2838
fl = open(file_name, 'wt')
2842
def test_load_unknown(self):
2843
self.assertRaises(errors.NoSuchFile,
2844
tests.load_test_id_list, 'i_do_not_exist')
2846
def test_load_test_list(self):
2847
test_list_fname = 'test.list'
2848
self._create_test_list_file(test_list_fname,
2849
'mod1.cl1.meth1\nmod2.cl2.meth2\n')
2850
tlist = tests.load_test_id_list(test_list_fname)
2851
self.assertEquals(2, len(tlist))
2852
self.assertEquals('mod1.cl1.meth1', tlist[0])
2853
self.assertEquals('mod2.cl2.meth2', tlist[1])
2855
def test_load_dirty_file(self):
2856
test_list_fname = 'test.list'
2857
self._create_test_list_file(test_list_fname,
2858
' mod1.cl1.meth1\n\nmod2.cl2.meth2 \n'
2860
tlist = tests.load_test_id_list(test_list_fname)
2861
self.assertEquals(4, len(tlist))
2862
self.assertEquals('mod1.cl1.meth1', tlist[0])
2863
self.assertEquals('', tlist[1])
2864
self.assertEquals('mod2.cl2.meth2', tlist[2])
2865
self.assertEquals('bar baz', tlist[3])
2868
class TestFilteredByModuleTestLoader(tests.TestCase):
2870
def _create_loader(self, test_list):
2871
id_filter = tests.TestIdList(test_list)
2872
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
2875
def test_load_tests(self):
2876
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2877
loader = self._create_loader(test_list)
2878
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2879
self.assertEquals(test_list, _test_ids(suite))
2881
def test_exclude_tests(self):
2882
test_list = ['bogus']
2883
loader = self._create_loader(test_list)
2884
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2885
self.assertEquals([], _test_ids(suite))
2888
class TestFilteredByNameStartTestLoader(tests.TestCase):
2890
def _create_loader(self, name_start):
2891
def needs_module(name):
2892
return name.startswith(name_start) or name_start.startswith(name)
2893
loader = TestUtil.FilteredByModuleTestLoader(needs_module)
2896
def test_load_tests(self):
2897
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2898
loader = self._create_loader('bzrlib.tests.test_samp')
2900
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2901
self.assertEquals(test_list, _test_ids(suite))
2903
def test_load_tests_inside_module(self):
2904
test_list = ['bzrlib.tests.test_sampler.DemoTest.test_nothing']
2905
loader = self._create_loader('bzrlib.tests.test_sampler.Demo')
2907
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2908
self.assertEquals(test_list, _test_ids(suite))
2910
def test_exclude_tests(self):
2911
test_list = ['bogus']
2912
loader = self._create_loader('bogus')
2914
suite = loader.loadTestsFromModuleName('bzrlib.tests.test_sampler')
2915
self.assertEquals([], _test_ids(suite))
2918
class TestTestPrefixRegistry(tests.TestCase):
2920
def _get_registry(self):
2921
tp_registry = tests.TestPrefixAliasRegistry()
2924
def test_register_new_prefix(self):
2925
tpr = self._get_registry()
2926
tpr.register('foo', 'fff.ooo.ooo')
2927
self.assertEquals('fff.ooo.ooo', tpr.get('foo'))
2929
def test_register_existing_prefix(self):
2930
tpr = self._get_registry()
2931
tpr.register('bar', 'bbb.aaa.rrr')
2932
tpr.register('bar', 'bBB.aAA.rRR')
2933
self.assertEquals('bbb.aaa.rrr', tpr.get('bar'))
2934
self.assertThat(self.get_log(),
2935
DocTestMatches("...bar...bbb.aaa.rrr...BB.aAA.rRR", ELLIPSIS))
2937
def test_get_unknown_prefix(self):
2938
tpr = self._get_registry()
2939
self.assertRaises(KeyError, tpr.get, 'I am not a prefix')
2941
def test_resolve_prefix(self):
2942
tpr = self._get_registry()
2943
tpr.register('bar', 'bb.aa.rr')
2944
self.assertEquals('bb.aa.rr', tpr.resolve_alias('bar'))
2946
def test_resolve_unknown_alias(self):
2947
tpr = self._get_registry()
2948
self.assertRaises(errors.BzrCommandError,
2949
tpr.resolve_alias, 'I am not a prefix')
2951
def test_predefined_prefixes(self):
2952
tpr = tests.test_prefix_alias_registry
2953
self.assertEquals('bzrlib', tpr.resolve_alias('bzrlib'))
2954
self.assertEquals('bzrlib.doc', tpr.resolve_alias('bd'))
2955
self.assertEquals('bzrlib.utils', tpr.resolve_alias('bu'))
2956
self.assertEquals('bzrlib.tests', tpr.resolve_alias('bt'))
2957
self.assertEquals('bzrlib.tests.blackbox', tpr.resolve_alias('bb'))
2958
self.assertEquals('bzrlib.plugins', tpr.resolve_alias('bp'))
2961
class TestRunSuite(tests.TestCase):
2963
def test_runner_class(self):
2964
"""run_suite accepts and uses a runner_class keyword argument."""
2965
class Stub(tests.TestCase):
2968
suite = Stub("test_foo")
2970
class MyRunner(tests.TextTestRunner):
2971
def run(self, test):
2973
return tests.ExtendedTestResult(self.stream, self.descriptions,
2975
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2976
self.assertLength(1, calls)