~bzr-pqm/bzr/bzr.dev

5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2005-2011 Canonical Ltd
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
16
17
"""Tests for the bzrlib ui
18
"""
19
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
20
import time
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
21
4797.40.2 by Martin Pool
Add missing import
22
from StringIO import StringIO
23
5416.1.11 by Martin Pool
Add ConfirmationUserInterfacePolicy that lets specific confirmations be configured off.
24
from testtools.matchers import *
25
4488.1.1 by Vincent Ladeuil
(vila) Cleanup imports in some test files
26
from bzrlib import (
5230.1.3 by Martin Pool
Use configured output encoding for make_output_stream
27
    config,
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
28
    remote,
4488.1.1 by Vincent Ladeuil
(vila) Cleanup imports in some test files
29
    tests,
30
    ui as _mod_ui,
4449.3.4 by Martin Pool
ProgressTask now talks to ProgressView; easier to test
31
    )
5230.1.3 by Martin Pool
Use configured output encoding for make_output_stream
32
from bzrlib.tests import (
33
    fixtures,
34
    )
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
35
from bzrlib.ui import text as _mod_ui_text
5422.1.5 by Martin Pool
Move ProgressRecordingUIFactory to bzrlib.tests.testui
36
from bzrlib.tests.testui import (
5422.1.4 by Martin Pool
Rename CapturingUIFactory to ProgressRecordingUIFactory
37
    ProgressRecordingUIFactory,
5422.1.1 by Martin Pool
Move CapturingUIFactory out of per_workingtree tests into somewhere reusable
38
    )
1185.49.22 by John Arbash Meinel
Added get_password to the UIFactory, using it inside of sftp.py
39
1681.1.2 by Robert Collins
* bzrlib.ui.text.TextUIFactory now accepts a bar_type parameter which
40
6437.57.4 by Martin Packman
Test helper spelling changes suggested in review by vila
41
class TTYStringIO(StringIO):
6437.57.1 by Martin Packman
Move StringIO subclasses from bt.test_progress to bt.test_ui where they're actually used
42
    """A helper class which makes a StringIO look like a terminal"""
43
44
    def isatty(self):
45
        return True
46
47
6437.57.4 by Martin Packman
Test helper spelling changes suggested in review by vila
48
class NonTTYStringIO(StringIO):
6437.57.1 by Martin Packman
Move StringIO subclasses from bt.test_progress to bt.test_ui where they're actually used
49
    """Helper that implements isatty() but returns False"""
50
51
    def isatty(self):
52
        return False
53
54
5230.1.3 by Martin Pool
Use configured output encoding for make_output_stream
55
class TestUIConfiguration(tests.TestCaseWithTransport):
56
57
    def test_output_encoding_configuration(self):
5230.1.5 by Martin Pool
Merge updated test fixtures
58
        enc = fixtures.generate_unicode_encodings().next()
6499.3.8 by Vincent Ladeuil
Update some forgotten uses of GlobalConfig to GlobalStack.
59
        config.GlobalStack().set('output_encoding', enc)
5230.1.3 by Martin Pool
Use configured output encoding for make_output_stream
60
        ui = tests.TestUIFactory(stdin=None,
5230.1.5 by Martin Pool
Merge updated test fixtures
61
            stdout=tests.StringIOWrapper(),
62
            stderr=tests.StringIOWrapper())
5416.1.11 by Martin Pool
Add ConfirmationUserInterfacePolicy that lets specific confirmations be configured off.
63
        output = ui.make_output_stream()
64
        self.assertEquals(output.encoding, enc)
5230.1.3 by Martin Pool
Use configured output encoding for make_output_stream
65
66
4711.1.6 by Martin Pool
Separate TextUIFactory tests
67
class TestTextUIFactory(tests.TestCase):
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
68
5416.1.1 by Martin Pool
Use a structured ui_factory.confirm_action rather than just get_boolean
69
    def make_test_ui_factory(self, stdin_contents):
70
        ui = tests.TestUIFactory(stdin=stdin_contents,
71
                                 stdout=tests.StringIOWrapper(),
72
                                 stderr=tests.StringIOWrapper())
73
        return ui
74
75
    def test_text_factory_confirm(self):
76
        # turns into reading a regular boolean
77
        ui = self.make_test_ui_factory('n\n')
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
78
        self.assertEquals(ui.confirm_action(u'Should %(thing)s pass?',
5416.1.1 by Martin Pool
Use a structured ui_factory.confirm_action rather than just get_boolean
79
            'bzrlib.tests.test_ui.confirmation',
80
            {'thing': 'this'},),
81
            False)
82
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
83
    def test_text_factory_ascii_password(self):
5416.1.1 by Martin Pool
Use a structured ui_factory.confirm_action rather than just get_boolean
84
        ui = self.make_test_ui_factory('secret\n')
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
85
        pb = ui.nested_progress_bar()
86
        try:
87
            self.assertEqual('secret',
88
                             self.apply_redirected(ui.stdin, ui.stdout,
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
89
                                                   ui.stderr,
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
90
                                                   ui.get_password))
91
            # ': ' is appended to prompt
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
92
            self.assertEqual(': ', ui.stderr.getvalue())
93
            self.assertEqual('', ui.stdout.readline())
2363.4.3 by Vincent Ladeuil
Tidy-up tests.
94
            # stdin should be empty
2363.4.6 by Vincent Ladeuil
Fix tests around stdin emptyness.
95
            self.assertEqual('', ui.stdin.readline())
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
96
        finally:
97
            pb.finished()
98
99
    def test_text_factory_utf8_password(self):
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
100
        """Test an utf8 password."""
101
        ui = _mod_ui_text.TextUIFactory(None, None, None)
102
        ui.stdin = tests.StringIOWrapper(u'baz\u1234'.encode('utf8'))
103
        ui.stdout = tests.StringIOWrapper()
104
        ui.stderr = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
105
        ui.stderr.encoding = ui.stdout.encoding = ui.stdin.encoding = 'utf8'
2294.4.1 by Vincent Ladeuil
Add a UIFactory.get_login method, fix tests.
106
        pb = ui.nested_progress_bar()
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
107
        password = ui.get_password(u'Hello \u1234 %(user)s', user=u'some\u1234')
108
        self.assertEqual(u'baz\u1234', password)
109
        self.assertEqual(u'Hello \u1234 some\u1234: ',
110
                         ui.stderr.getvalue().decode('utf8'))
111
        # stdin and stdout should be empty
112
        self.assertEqual('', ui.stdin.readline())
113
        self.assertEqual('', ui.stdout.getvalue())
1534.5.6 by Robert Collins
split out converter logic into per-format objects.
114
4449.3.38 by Martin Pool
Cleanup get_boolean tests
115
    def test_text_ui_get_boolean(self):
4773.1.2 by Vincent Ladeuil
Cleanup imports in test_ui
116
        stdin = tests.StringIOWrapper("y\n" # True
117
                                      "n\n" # False
6182.2.4 by Benoît Pierre
Fix ui tests.
118
                                      " \n y \n" # True
119
                                      " no \n" # False
4773.1.2 by Vincent Ladeuil
Cleanup imports in test_ui
120
                                      "yes with garbage\nY\n" # True
121
                                      "not an answer\nno\n" # False
122
                                      "I'm sure!\nyes\n" # True
123
                                      "NO\n" # False
124
                                      "foo\n")
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
125
        stdout = tests.StringIOWrapper()
126
        stderr = tests.StringIOWrapper()
127
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
128
        self.assertEqual(True, factory.get_boolean(u""))
129
        self.assertEqual(False, factory.get_boolean(u""))
130
        self.assertEqual(True, factory.get_boolean(u""))
131
        self.assertEqual(False, factory.get_boolean(u""))
132
        self.assertEqual(True, factory.get_boolean(u""))
133
        self.assertEqual(False, factory.get_boolean(u""))
6182.2.4 by Benoît Pierre
Fix ui tests.
134
        self.assertEqual(True, factory.get_boolean(u""))
135
        self.assertEqual(False, factory.get_boolean(u""))
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
136
        self.assertEqual("foo\n", factory.stdin.read())
2363.4.4 by Vincent Ladeuil
More tidying-up.
137
        # stdin should be empty
2363.4.6 by Vincent Ladeuil
Fix tests around stdin emptyness.
138
        self.assertEqual('', factory.stdin.readline())
6182.2.4 by Benoît Pierre
Fix ui tests.
139
        # return false on EOF
140
        self.assertEqual(False, factory.get_boolean(u""))
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
141
6182.2.20 by Benoît Pierre
Add some more tests for TextUIFactory.choose.
142
    def test_text_ui_choose_bad_parameters(self):
143
        stdin = tests.StringIOWrapper()
144
        stdout = tests.StringIOWrapper()
145
        stderr = tests.StringIOWrapper()
146
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
147
        # invalid default index
148
        self.assertRaises(ValueError, factory.choose, u"", u"&Yes\n&No", 3)
149
        # duplicated choice
150
        self.assertRaises(ValueError, factory.choose, u"", u"&choice\n&ChOiCe")
151
        # duplicated shortcut
152
        self.assertRaises(ValueError, factory.choose, u"", u"&choice1\nchoi&ce2")
153
6182.2.22 by Benoît Pierre
More TextUIFactory.choose tests: check prompts.
154
    def test_text_ui_choose_prompt(self):
155
        stdin = tests.StringIOWrapper()
156
        stdout = tests.StringIOWrapper()
157
        stderr = tests.StringIOWrapper()
158
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
159
        # choices with explicit shortcuts
160
        factory.choose(u"prompt", u"&yes\n&No\nmore &info")
161
        self.assertEqual("prompt ([y]es, [N]o, more [i]nfo): \n", factory.stderr.getvalue())
162
        # automatic shortcuts
163
        factory.stderr.truncate(0)
164
        factory.choose(u"prompt", u"yes\nNo\nmore info")
165
        self.assertEqual("prompt ([y]es, [N]o, [m]ore info): \n", factory.stderr.getvalue())
166
6182.2.17 by Benoît Pierre
Add some tests for TextUIFactory.choose.
167
    def test_text_ui_choose_return_values(self):
168
        choose = lambda: factory.choose(u"", u"&Yes\n&No\nMaybe\nmore &info", 3)
169
        stdin = tests.StringIOWrapper("y\n" # 0
170
                                      "n\n" # 1
171
                                      " \n" # default: 3
172
                                      " no \n" # 1
6182.2.25 by Benoît Pierre
Tweak test_text_ui_choose_return_values a little.
173
                                      "b\na\nd \n" # bad shortcuts, all ignored
6182.2.17 by Benoît Pierre
Add some tests for TextUIFactory.choose.
174
                                      "yes with garbage\nY\n" # 0
175
                                      "not an answer\nno\n" # 1
176
                                      "info\nmore info\n" # 3
177
                                      "Maybe\n" # 2
178
                                      "foo\n")
179
        stdout = tests.StringIOWrapper()
180
        stderr = tests.StringIOWrapper()
181
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
182
        self.assertEqual(0, choose())
183
        self.assertEqual(1, choose())
184
        self.assertEqual(3, choose())
185
        self.assertEqual(1, choose())
186
        self.assertEqual(0, choose())
187
        self.assertEqual(1, choose())
188
        self.assertEqual(3, choose())
189
        self.assertEqual(2, choose())
190
        self.assertEqual("foo\n", factory.stdin.read())
191
        # stdin should be empty
192
        self.assertEqual('', factory.stdin.readline())
193
        # return None on EOF
194
        self.assertEqual(None, choose())
195
6182.2.19 by Benoît Pierre
Add more tests for TextUIFactory.choose.
196
    def test_text_ui_choose_no_default(self):
197
        stdin = tests.StringIOWrapper(" \n" # no default, invalid!
198
                                      " yes \n" # 0
199
                                      "foo\n")
200
        stdout = tests.StringIOWrapper()
201
        stderr = tests.StringIOWrapper()
202
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
203
        self.assertEqual(0, factory.choose(u"", u"&Yes\n&No"))
204
        self.assertEqual("foo\n", factory.stdin.read())
205
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
206
    def test_text_ui_get_integer(self):
207
        stdin = tests.StringIOWrapper(
208
            "1\n"
209
            "  -2  \n"
210
            "hmmm\nwhat else ?\nCome on\nok 42\n4.24\n42\n")
211
        stdout = tests.StringIOWrapper()
212
        stderr = tests.StringIOWrapper()
213
        factory = _mod_ui_text.TextUIFactory(stdin, stdout, stderr)
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
214
        self.assertEqual(1, factory.get_integer(u""))
215
        self.assertEqual(-2, factory.get_integer(u""))
216
        self.assertEqual(42, factory.get_integer(u""))
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
217
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
218
    def test_text_factory_prompt(self):
219
        # see <https://launchpad.net/bugs/365891>
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
220
        StringIO = tests.StringIOWrapper
221
        factory = _mod_ui_text.TextUIFactory(StringIO(), StringIO(), StringIO())
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
222
        factory.prompt(u'foo %2e')
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
223
        self.assertEqual('', factory.stdout.getvalue())
224
        self.assertEqual('foo %2e', factory.stderr.getvalue())
4300.3.1 by Martin Pool
Fix string expansion in TextUIFactory.prompt
225
1687.1.4 by Robert Collins
Add bzrlib.ui.ui_factory.get_boolean().
226
    def test_text_factory_prompts_and_clears(self):
227
        # a get_boolean call should clear the pb before prompting
6437.57.4 by Martin Packman
Test helper spelling changes suggested in review by vila
228
        out = TTYStringIO()
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
229
        self.overrideEnv('TERM', 'xterm')
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
230
        factory = _mod_ui_text.TextUIFactory(
231
            stdin=tests.StringIOWrapper("yada\ny\n"),
232
            stdout=out, stderr=out)
5339.2.6 by Martin Pool
One more UI test needs updates for spinner being at the front
233
        factory._avail_width = lambda: 79
3882.8.10 by Martin Pool
Fix up test_ui for new progress bars
234
        pb = factory.nested_progress_bar()
235
        pb.show_bar = False
236
        pb.show_spinner = False
237
        pb.show_count = False
238
        pb.update("foo", 0, 1)
2363.4.4 by Vincent Ladeuil
More tidying-up.
239
        self.assertEqual(True,
240
                         self.apply_redirected(None, factory.stdout,
241
                                               factory.stdout,
242
                                               factory.get_boolean,
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
243
                                               u"what do you want"))
3882.8.10 by Martin Pool
Fix up test_ui for new progress bars
244
        output = out.getvalue()
5339.2.6 by Martin Pool
One more UI test needs updates for spinner being at the front
245
        self.assertContainsRe(output,
246
            "| foo *\r\r  *\r*")
6182.2.4 by Benoît Pierre
Fix ui tests.
247
        self.assertContainsString(output,
248
            r"what do you want? ([y]es, [n]o): what do you want? ([y]es, [n]o): ")
3882.8.10 by Martin Pool
Fix up test_ui for new progress bars
249
        # stdin should have been totally consumed
2363.4.6 by Vincent Ladeuil
Fix tests around stdin emptyness.
250
        self.assertEqual('', factory.stdin.readline())
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
251
252
    def test_text_tick_after_update(self):
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
253
        ui_factory = _mod_ui_text.TextUIFactory(stdout=tests.StringIOWrapper(),
254
                                                stderr=tests.StringIOWrapper())
4017.1.1 by John Arbash Meinel
Get a pb.tick() to work after calling pb.update()
255
        pb = ui_factory.nested_progress_bar()
256
        try:
257
            pb.update('task', 0, 3)
258
            # Reset the clock, so that it actually tries to repaint itself
259
            ui_factory._progress_view._last_repaint = time.time() - 1.0
260
            pb.tick()
261
        finally:
262
            pb.finished()
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
263
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
264
    def test_text_ui_getusername(self):
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
265
        ui = _mod_ui_text.TextUIFactory(None, None, None)
266
        ui.stdin = tests.StringIOWrapper('someuser\n\n')
267
        ui.stdout = tests.StringIOWrapper()
268
        ui.stderr = tests.StringIOWrapper()
269
        ui.stdout.encoding = 'utf8'
270
        self.assertEqual('someuser',
271
                         ui.get_username(u'Hello %(host)s', host='some'))
272
        self.assertEquals('Hello some: ', ui.stderr.getvalue())
273
        self.assertEquals('', ui.stdout.getvalue())
274
        self.assertEqual('', ui.get_username(u"Gebruiker"))
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
275
        # stdin should be empty
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
276
        self.assertEqual('', ui.stdin.readline())
4222.2.1 by Jelmer Vernooij
Add get_username() call to the UIFactory.
277
4222.2.2 by Jelmer Vernooij
Review from vila: Deal with UTF8 strings in prompts, fix typo.
278
    def test_text_ui_getusername_utf8(self):
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
279
        ui = _mod_ui_text.TextUIFactory(None, None, None)
280
        ui.stdin = tests.StringIOWrapper(u'someuser\u1234'.encode('utf8'))
281
        ui.stdout = tests.StringIOWrapper()
282
        ui.stderr = tests.StringIOWrapper()
4368.3.1 by Vincent Ladeuil
Use stderr for UI prompt to address bug #376582.
283
        ui.stderr.encoding = ui.stdout.encoding = ui.stdin.encoding = "utf8"
6559.2.1 by Vincent Ladeuil
Makes AuthenticationConfig always return unicode user names and passwords.
284
        username = ui.get_username(u'Hello %(host)s', host=u'some\u1234')
285
        self.assertEquals(u"someuser\u1234", username)
286
        self.assertEquals(u"Hello some\u1234: ",
287
                          ui.stderr.getvalue().decode("utf8"))
288
        self.assertEquals('', ui.stdout.getvalue())
4222.2.2 by Jelmer Vernooij
Review from vila: Deal with UTF8 strings in prompts, fix typo.
289
4961.1.3 by Martin Pool
trace quietness now controls whether the progress bar appears
290
    def test_quietness(self):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
291
        self.overrideEnv('BZR_PROGRESS_BAR', 'text')
4961.1.3 by Martin Pool
trace quietness now controls whether the progress bar appears
292
        ui_factory = _mod_ui_text.TextUIFactory(None,
6437.57.4 by Martin Packman
Test helper spelling changes suggested in review by vila
293
            TTYStringIO(),
294
            TTYStringIO())
4961.1.3 by Martin Pool
trace quietness now controls whether the progress bar appears
295
        self.assertIsInstance(ui_factory._progress_view,
296
            _mod_ui_text.TextProgressView)
297
        ui_factory.be_quiet(True)
298
        self.assertIsInstance(ui_factory._progress_view,
299
            _mod_ui_text.NullProgressView)
300
4634.144.10 by Martin Pool
Update test_ui for warning suppression
301
    def test_text_ui_show_user_warning(self):
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
302
        from bzrlib.repofmt.groupcompress_repo import RepositoryFormat2a
5757.1.7 by Jelmer Vernooij
Fix more imports.
303
        from bzrlib.repofmt.knitpack_repo import RepositoryFormatKnitPack5
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
304
        err = StringIO()
305
        out = StringIO()
306
        ui = tests.TextUIFactory(stdin=None, stdout=out, stderr=err)
307
        remote_fmt = remote.RemoteRepositoryFormat()
308
        remote_fmt._network_name = RepositoryFormatKnitPack5().network_name()
4634.144.10 by Martin Pool
Update test_ui for warning suppression
309
        ui.show_user_warning('cross_format_fetch', from_format=RepositoryFormat2a(),
310
            to_format=remote_fmt)
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
311
        self.assertEquals('', out.getvalue())
312
        self.assertEquals("Doing on-the-fly conversion from RepositoryFormat2a() to "
313
            "RemoteRepositoryFormat(_network_name='Bazaar RepositoryFormatKnitPack5 "
314
            "(bzr 1.6)\\n').\nThis may take some time. Upgrade the repositories to "
315
            "the same format for better performance.\n",
316
            err.getvalue())
4634.144.10 by Martin Pool
Update test_ui for warning suppression
317
        # and now with it suppressed please
318
        err = StringIO()
319
        out = StringIO()
320
        ui = tests.TextUIFactory(stdin=None, stdout=out, stderr=err)
4634.144.11 by Martin Pool
Rename squelched to suppressed
321
        ui.suppressed_warnings.add('cross_format_fetch')
4634.144.10 by Martin Pool
Update test_ui for warning suppression
322
        ui.show_user_warning('cross_format_fetch', from_format=RepositoryFormat2a(),
323
            to_format=remote_fmt)
324
        self.assertEquals('', out.getvalue())
325
        self.assertEquals('', err.getvalue())
4634.144.5 by Martin Pool
Cleaner presentation and tests for warn_cross_format_fetch
326
4110.2.15 by Martin Pool
Fix bug in showing task progress and add a test
327
4884.1.1 by Vincent Ladeuil
Cleanup some test imports
328
class TestTextUIOutputStream(tests.TestCase):
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
329
    """Tests for output stream that synchronizes with progress bar."""
330
331
    def test_output_clears_terminal(self):
4884.1.1 by Vincent Ladeuil
Cleanup some test imports
332
        stdout = tests.StringIOWrapper()
333
        stderr = tests.StringIOWrapper()
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
334
        clear_calls = []
335
4884.1.1 by Vincent Ladeuil
Cleanup some test imports
336
        uif =  _mod_ui_text.TextUIFactory(None, stdout, stderr)
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
337
        uif.clear_term = lambda: clear_calls.append('clear')
338
4884.1.1 by Vincent Ladeuil
Cleanup some test imports
339
        stream = _mod_ui_text.TextUIOutputStream(uif, uif.stdout)
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
340
        stream.write("Hello world!\n")
341
        stream.write("there's more...\n")
4792.8.3 by Martin Pool
Add TextUIOutputStream.writelines
342
        stream.writelines(["1\n", "2\n", "3\n"])
4884.1.1 by Vincent Ladeuil
Cleanup some test imports
343
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
344
        self.assertEqual(stdout.getvalue(),
345
            "Hello world!\n"
4792.8.3 by Martin Pool
Add TextUIOutputStream.writelines
346
            "there's more...\n"
347
            "1\n2\n3\n")
348
        self.assertEqual(['clear', 'clear', 'clear'],
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
349
            clear_calls)
350
4792.8.8 by Martin Pool
Add TextUIOutputStream.flush
351
        stream.flush()
4792.8.1 by Martin Pool
Add TextUIOutputStream coordinated with progress view
352
353
4711.1.6 by Martin Pool
Separate TextUIFactory tests
354
class UITests(tests.TestCase):
355
356
    def test_progress_construction(self):
357
        """TextUIFactory constructs the right progress view.
358
        """
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
359
        FileStringIO = tests.StringIOWrapper
4711.1.6 by Martin Pool
Separate TextUIFactory tests
360
        for (file_class, term, pb, expected_pb_class) in (
361
            # on an xterm, either use them or not as the user requests,
362
            # otherwise default on
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
363
            (TTYStringIO, 'xterm', 'none', _mod_ui_text.NullProgressView),
364
            (TTYStringIO, 'xterm', 'text', _mod_ui_text.TextProgressView),
365
            (TTYStringIO, 'xterm', None, _mod_ui_text.TextProgressView),
4711.1.6 by Martin Pool
Separate TextUIFactory tests
366
            # on a dumb terminal, again if there's explicit configuration do
367
            # it, otherwise default off
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
368
            (TTYStringIO, 'dumb', 'none', _mod_ui_text.NullProgressView),
369
            (TTYStringIO, 'dumb', 'text', _mod_ui_text.TextProgressView),
370
            (TTYStringIO, 'dumb', None, _mod_ui_text.NullProgressView),
4711.1.6 by Martin Pool
Separate TextUIFactory tests
371
            # on a non-tty terminal, it's null regardless of $TERM
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
372
            (FileStringIO, 'xterm', None, _mod_ui_text.NullProgressView),
373
            (FileStringIO, 'dumb', None, _mod_ui_text.NullProgressView),
4711.1.6 by Martin Pool
Separate TextUIFactory tests
374
            # however, it can still be forced on
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
375
            (FileStringIO, 'dumb', 'text', _mod_ui_text.TextProgressView),
4711.1.6 by Martin Pool
Separate TextUIFactory tests
376
            ):
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
377
            self.overrideEnv('TERM', term)
378
            self.overrideEnv('BZR_PROGRESS_BAR', pb)
4711.1.6 by Martin Pool
Separate TextUIFactory tests
379
            stdin = file_class('')
380
            stderr = file_class()
381
            stdout = file_class()
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
382
            uif = _mod_ui.make_ui_for_terminal(stdin, stdout, stderr)
383
            self.assertIsInstance(uif, _mod_ui_text.TextUIFactory,
4711.1.6 by Martin Pool
Separate TextUIFactory tests
384
                "TERM=%s BZR_PROGRESS_BAR=%s uif=%r" % (term, pb, uif,))
385
            self.assertIsInstance(uif.make_progress_view(),
386
                expected_pb_class,
387
                "TERM=%s BZR_PROGRESS_BAR=%s uif=%r" % (term, pb, uif,))
388
389
    def test_text_ui_non_terminal(self):
390
        """Even on non-ttys, make_ui_for_terminal gives a text ui."""
6437.57.4 by Martin Packman
Test helper spelling changes suggested in review by vila
391
        stdin = NonTTYStringIO('')
392
        stderr = NonTTYStringIO()
393
        stdout = NonTTYStringIO()
4711.1.6 by Martin Pool
Separate TextUIFactory tests
394
        for term_type in ['dumb', None, 'xterm']:
5570.3.9 by Vincent Ladeuil
More use cases for overrideEnv, _cleanEnvironment *may* contain too much variables now.
395
            self.overrideEnv('TERM', term_type)
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
396
            uif = _mod_ui.make_ui_for_terminal(stdin, stdout, stderr)
397
            self.assertIsInstance(uif, _mod_ui_text.TextUIFactory,
4711.1.6 by Martin Pool
Separate TextUIFactory tests
398
                'TERM=%r' % (term_type,))
399
400
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
401
class SilentUITests(tests.TestCase):
4449.3.19 by Martin Pool
SilentUIFactory now always errors when asked for input
402
4449.3.36 by Martin Pool
Update tests: SilentUIFactory no longer does get_boolean or get_password
403
    def test_silent_factory_get_password(self):
404
        # A silent factory that can't do user interaction can't get a
405
        # password.  Possibly it should raise a more specific error but it
406
        # can't succeed.
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
407
        ui = _mod_ui.SilentUIFactory()
408
        stdout = tests.StringIOWrapper()
4449.3.19 by Martin Pool
SilentUIFactory now always errors when asked for input
409
        self.assertRaises(
410
            NotImplementedError,
411
            self.apply_redirected,
412
            None, stdout, stdout, ui.get_password)
413
        # and it didn't write anything out either
414
        self.assertEqual('', stdout.getvalue())
415
416
    def test_silent_ui_getbool(self):
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
417
        factory = _mod_ui.SilentUIFactory()
418
        stdout = tests.StringIOWrapper()
4449.3.19 by Martin Pool
SilentUIFactory now always errors when asked for input
419
        self.assertRaises(
420
            NotImplementedError,
421
            self.apply_redirected,
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
422
            None, stdout, stdout, factory.get_boolean, u"foo")
4449.3.42 by Martin Pool
Add basic test for CannedInputUIFactory
423
424
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
425
class TestUIFactoryTests(tests.TestCase):
4580.2.2 by Martin Pool
Add test for bug 408201
426
427
    def test_test_ui_factory_progress(self):
428
        # there's no output; we just want to make sure this doesn't crash -
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
429
        # see https://bugs.launchpad.net/bzr/+bug/408201
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
430
        ui = tests.TestUIFactory()
4580.2.2 by Martin Pool
Add test for bug 408201
431
        pb = ui.nested_progress_bar()
432
        pb.update('hello')
433
        pb.tick()
434
        pb.finished()
435
436
4597.3.36 by Vincent Ladeuil
Fix imports and various cleanups in test_ui.
437
class CannedInputUIFactoryTests(tests.TestCase):
438
4449.3.42 by Martin Pool
Add basic test for CannedInputUIFactory
439
    def test_canned_input_get_input(self):
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
440
        uif = _mod_ui.CannedInputUIFactory([True, 'mbp', 'password', 42])
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
441
        self.assertEqual(True, uif.get_boolean(u'Extra cheese?'))
442
        self.assertEqual('mbp', uif.get_username(u'Enter your user name'))
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
443
        self.assertEqual('password',
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
444
                         uif.get_password(u'Password for %(host)s',
4597.3.37 by Vincent Ladeuil
Allows ui factories to query users for an integer.
445
                                          host='example.com'))
5863.6.1 by Jelmer Vernooij
Require a unicode prompt to be passed into all methods that prompt.
446
        self.assertEqual(42, uif.get_integer(u'And all that jazz ?'))
4110.2.17 by Martin Pool
If one ProgressTask has no count, it passes through that of its child
447
4503.2.1 by Vincent Ladeuil
Get a bool from a string.
448
449
class TestBoolFromString(tests.TestCase):
450
451
    def assertIsTrue(self, s, accepted_values=None):
452
        res = _mod_ui.bool_from_string(s, accepted_values=accepted_values)
453
        self.assertEquals(True, res)
454
455
    def assertIsFalse(self, s, accepted_values=None):
456
        res = _mod_ui.bool_from_string(s, accepted_values=accepted_values)
457
        self.assertEquals(False, res)
458
459
    def assertIsNone(self, s, accepted_values=None):
460
        res = _mod_ui.bool_from_string(s, accepted_values=accepted_values)
461
        self.assertIs(None, res)
462
463
    def test_know_valid_values(self):
464
        self.assertIsTrue('true')
465
        self.assertIsFalse('false')
466
        self.assertIsTrue('1')
467
        self.assertIsFalse('0')
468
        self.assertIsTrue('on')
469
        self.assertIsFalse('off')
470
        self.assertIsTrue('yes')
471
        self.assertIsFalse('no')
472
        self.assertIsTrue('y')
473
        self.assertIsFalse('n')
474
        # Also try some case variations
475
        self.assertIsTrue('True')
476
        self.assertIsFalse('False')
477
        self.assertIsTrue('On')
478
        self.assertIsFalse('Off')
479
        self.assertIsTrue('ON')
480
        self.assertIsFalse('OFF')
481
        self.assertIsTrue('oN')
482
        self.assertIsFalse('oFf')
483
484
    def test_invalid_values(self):
485
        self.assertIsNone(None)
486
        self.assertIsNone('doubt')
487
        self.assertIsNone('frue')
488
        self.assertIsNone('talse')
489
        self.assertIsNone('42')
490
491
    def test_provided_values(self):
492
        av = dict(y=True, n=False, yes=True, no=False)
493
        self.assertIsTrue('y', av)
494
        self.assertIsTrue('Y', av)
495
        self.assertIsTrue('Yes', av)
496
        self.assertIsFalse('n', av)
497
        self.assertIsFalse('N', av)
498
        self.assertIsFalse('No', av)
499
        self.assertIsNone('1', av)
500
        self.assertIsNone('0', av)
501
        self.assertIsNone('on', av)
502
        self.assertIsNone('off', av)
5422.1.1 by Martin Pool
Move CapturingUIFactory out of per_workingtree tests into somewhere reusable
503
504
5416.1.11 by Martin Pool
Add ConfirmationUserInterfacePolicy that lets specific confirmations be configured off.
505
class TestConfirmationUserInterfacePolicy(tests.TestCase):
506
507
    def test_confirm_action_default(self):
508
        base_ui = _mod_ui.NoninteractiveUIFactory()
509
        for answer in [True, False]:
510
            self.assertEquals(
511
                _mod_ui.ConfirmationUserInterfacePolicy(base_ui, answer, {})
512
                .confirm_action("Do something?",
513
                    "bzrlib.tests.do_something", {}),
514
                answer)
515
516
    def test_confirm_action_specific(self):
517
        base_ui = _mod_ui.NoninteractiveUIFactory()
518
        for default_answer in [True, False]:
519
            for specific_answer in [True, False]:
520
                for conf_id in ['given_id', 'other_id']:
521
                    wrapper = _mod_ui.ConfirmationUserInterfacePolicy(
522
                        base_ui, default_answer, dict(given_id=specific_answer))
523
                    result = wrapper.confirm_action("Do something?", conf_id, {})
524
                    if conf_id == 'given_id':
525
                        self.assertEquals(result, specific_answer)
526
                    else:
527
                        self.assertEquals(result, default_answer)
528
529
    def test_repr(self):
530
        base_ui = _mod_ui.NoninteractiveUIFactory()
531
        wrapper = _mod_ui.ConfirmationUserInterfacePolicy(
532
            base_ui, True, dict(a=2))
533
        self.assertThat(repr(wrapper),
534
            Equals("ConfirmationUserInterfacePolicy("
535
                "NoninteractiveUIFactory(), True, {'a': 2})"))
5416.2.4 by Martin Pool
resolve against trunk
536
537
5422.1.4 by Martin Pool
Rename CapturingUIFactory to ProgressRecordingUIFactory
538
class TestProgressRecordingUI(tests.TestCase):
5422.1.1 by Martin Pool
Move CapturingUIFactory out of per_workingtree tests into somewhere reusable
539
    """Test test-oriented UIFactory that records progress updates"""
540
541
    def test_nested_ignore_depth_beyond_one(self):
542
        # we only want to capture the first level out progress, not
543
        # want sub-components might do. So we have nested bars ignored.
5422.1.4 by Martin Pool
Rename CapturingUIFactory to ProgressRecordingUIFactory
544
        factory = ProgressRecordingUIFactory()
5422.1.1 by Martin Pool
Move CapturingUIFactory out of per_workingtree tests into somewhere reusable
545
        pb1 = factory.nested_progress_bar()
546
        pb1.update('foo', 0, 1)
547
        pb2 = factory.nested_progress_bar()
548
        pb2.update('foo', 0, 1)
549
        pb2.finished()
550
        pb1.finished()
551
        self.assertEqual([("update", 0, 1, 'foo')], factory._calls)