/brz/remove-bazaar

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