/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1
# Copyright (C) 2005-2012, 2016 Robey Pointer <robey@lag.net>
2221.5.1 by Dmitry Vasiliev
Added support for Putty's SSH implementation
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
3
#
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
8
#
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
13
#
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
17
18
import os
19
import socket
2321.3.7 by Alexander Belchenko
fixes for passing test_sftp_transport on win32 (thankyou John)
20
import sys
1871.1.3 by Robert Collins
proof of concept slowsocket wrapper.
21
import time
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
22
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
23
from breezy import (
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
24
    config,
6472.2.2 by Jelmer Vernooij
Use controldir rather than bzrdir in a couple more places.
25
    controldir,
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
26
    errors,
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
27
    tests,
28
    transport as _mod_transport,
4222.3.13 by Jelmer Vernooij
Add tests to ensure sftp and ftp don't prompt for usernames.
29
    ui,
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
30
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
31
from breezy.osutils import (
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
32
    lexists,
33
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
34
from breezy.tests import (
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
35
    features,
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
36
    TestCaseWithTransport,
37
    TestCase,
38
    TestSkipped,
39
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
40
from breezy.tests.http_server import HttpServer
2822.1.1 by v.ladeuil+lp at free
Fix #59150 (again) by handling paramiko availability for transport_util.py.
41
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
42
if features.paramiko.available():
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
43
    from breezy.transport import sftp as _mod_sftp
44
    from breezy.tests import stub_sftp
2822.1.1 by v.ladeuil+lp at free
Fix #59150 (again) by handling paramiko availability for transport_util.py.
45
1874.1.12 by Carl Friedrich Bolz
More fixes according to John's comments.
46
1874.1.14 by Carl Friedrich Bolz
Rename setup method to make its intent clearer. Some PEP 8 issues.
47
def set_test_transport_to_sftp(testcase):
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
48
    """A helper to set transports on test case instances."""
1874.1.6 by holger krekel
(cfbolz, hpk) Factor out common set_transport code.
49
    if getattr(testcase, '_get_remote_is_absolute', None) is None:
50
        testcase._get_remote_is_absolute = True
51
    if testcase._get_remote_is_absolute:
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
52
        testcase.transport_server = stub_sftp.SFTPAbsoluteServer
1874.1.6 by holger krekel
(cfbolz, hpk) Factor out common set_transport code.
53
    else:
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
54
        testcase.transport_server = stub_sftp.SFTPHomeDirServer
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
55
    testcase.transport_readonly_server = HttpServer
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
56
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
57
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
58
class TestCaseWithSFTPServer(TestCaseWithTransport):
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
59
    """A test case base class that provides a sftp server on localhost."""
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
60
61
    def setUp(self):
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
62
        super(TestCaseWithSFTPServer, self).setUp()
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
63
        self.requireFeature(features.paramiko)
2381.1.1 by Robert Collins
Split out hpss test fixes which dont depend on new or altered API's.
64
        set_test_transport_to_sftp(self)
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
65
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
66
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
67
class SFTPLockTests(TestCaseWithSFTPServer):
1185.16.127 by Martin Pool
[patch] paramiko sftp tests (robey)
68
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
69
    def test_sftp_locks(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
70
        from breezy.errors import LockError
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
71
        t = self.get_transport()
72
73
        l = t.lock_write('bogus')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
74
        self.assertPathExists('bogus.write-lock')
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
75
76
        # Don't wait for the lock, locking an already locked
77
        # file should raise an assert
78
        self.assertRaises(LockError, t.lock_write, 'bogus')
79
80
        l.unlock()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
81
        self.assertFalse(lexists('bogus.write-lock'))
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
82
6973.6.1 by Jelmer Vernooij
More bees.
83
        with open('something.write-lock', 'wb') as f:
84
            f.write(b'fake lock\n')
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
85
        self.assertRaises(LockError, t.lock_write, 'something')
86
        os.remove('something.write-lock')
87
88
        l = t.lock_write('something')
89
90
        l2 = t.lock_write('bogus')
91
92
        l.unlock()
93
        l2.unlock()
94
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
95
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
96
class SFTPTransportTestRelative(TestCaseWithSFTPServer):
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
97
    """Test the SFTP transport with homedir based relative paths."""
98
99
    def test__remote_path(self):
2823.1.4 by Vincent Ladeuil
Use assertIsSameRealPath to avoid OSX aliasing (specifically /tmp
100
        if sys.platform == 'darwin':
2823.1.11 by Vincent Ladeuil
Review feedback.
101
            # This test is about sftp absolute path handling. There is already
102
            # (in this test) a TODO about windows needing an absolute path
103
            # without drive letter. To me, using self.test_dir is a trick to
104
            # get an absolute path for comparison purposes.  That fails for OSX
105
            # because the sftp server doesn't resolve the links (and it doesn't
106
            # have to). --vila 20070924
2823.1.8 by Vincent Ladeuil
Rewrite expected failure message
107
            self.knownFailure('Mac OSX symlinks /tmp to /private/tmp,'
108
                              ' testing against self.test_dir'
109
                              ' is not appropriate')
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
110
        t = self.get_transport()
2321.3.7 by Alexander Belchenko
fixes for passing test_sftp_transport on win32 (thankyou John)
111
        # This test require unix-like absolute path
112
        test_dir = self.test_dir
113
        if sys.platform == 'win32':
114
            # using hack suggested by John Meinel.
115
            # TODO: write another mock server for this test
116
            #       and use absolute path without drive letter
117
            test_dir = '/' + test_dir
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
118
        # try what is currently used:
119
        # remote path = self._abspath(relpath)
2823.1.14 by Vincent Ladeuil
Fix 141382 by comparing real paths.
120
        self.assertIsSameRealPath(test_dir + '/relative',
121
                                  t._remote_path('relative'))
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
122
        # we dont os.path.join because windows gives us the wrong path
2321.3.7 by Alexander Belchenko
fixes for passing test_sftp_transport on win32 (thankyou John)
123
        root_segments = test_dir.split('/')
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
124
        root_parent = '/'.join(root_segments[:-1])
125
        # .. should be honoured
2823.1.14 by Vincent Ladeuil
Fix 141382 by comparing real paths.
126
        self.assertIsSameRealPath(root_parent + '/sibling',
127
                                  t._remote_path('../sibling'))
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
128
        # /  should be illegal ?
7143.15.2 by Jelmer Vernooij
Run autopep8.
129
        # FIXME decide and then test for all transports. RBC20051208
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
130
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
131
1986.1.10 by Robert Collins
Merge from bzr.dev, fixing found bugs handling 'has('/')' in MemoryTransport and SFTP transports.
132
class SFTPTransportTestRelativeRoot(TestCaseWithSFTPServer):
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
133
    """Test the SFTP transport with homedir based relative paths."""
134
135
    def setUp(self):
2485.8.43 by Vincent Ladeuil
Cleaning.
136
        # Only SFTPHomeDirServer is tested here
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
137
        self._get_remote_is_absolute = False
1986.1.10 by Robert Collins
Merge from bzr.dev, fixing found bugs handling 'has('/')' in MemoryTransport and SFTP transports.
138
        super(SFTPTransportTestRelativeRoot, self).setUp()
1530.1.6 by Robert Collins
Trim duplicate sftp tests.
139
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
140
    def test__remote_path_relative_root(self):
141
        # relative paths are preserved
142
        t = self.get_transport('')
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
143
        self.assertEqual('/~/', t._parsed_url.path)
2485.8.27 by Vincent Ladeuil
Hearing jam saying "vila, you're trying too hard", I simplified again.
144
        # the remote path should be relative to home dir
145
        # (i.e. not begining with a '/')
1524.1.1 by Robert Collins
Test sftp with relative, absolute-in-homedir and absolute-not-in-homedir
146
        self.assertEqual('a', t._remote_path('a'))
147
148
1185.49.14 by John Arbash Meinel
[merge] bzr.dev
149
class SFTPNonServerTest(TestCase):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
150
1185.58.12 by John Arbash Meinel
Changing so that sftp tests are skipped rather than hidden when paramiko isn't present
151
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
152
        super(SFTPNonServerTest, self).setUp()
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
153
        self.requireFeature(features.paramiko)
1185.58.12 by John Arbash Meinel
Changing so that sftp tests are skipped rather than hidden when paramiko isn't present
154
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
155
    def test_parse_url_with_home_dir(self):
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
156
        s = _mod_sftp.SFTPTransport(
157
            'sftp://ro%62ey:h%40t@example.com:2222/~/relative')
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
158
        self.assertEqual(s._parsed_url.host, 'example.com')
159
        self.assertEqual(s._parsed_url.port, 2222)
160
        self.assertEqual(s._parsed_url.user, 'robey')
161
        self.assertEqual(s._parsed_url.password, 'h@t')
162
        self.assertEqual(s._parsed_url.path, '/~/relative/')
1185.49.23 by John Arbash Meinel
bugreport from Matthieu Moy: relpath was failing, but throwing an unhelpful exception.
163
164
    def test_relpath(self):
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
165
        s = _mod_sftp.SFTPTransport('sftp://user@host.com/abs/path')
2485.8.20 by Vincent Ladeuil
Refactor SFTPTransport. Test suite passes.
166
        self.assertRaises(errors.PathNotChild, s.relpath,
167
                          'sftp://user@host.com/~/rel/path/sub')
1185.33.58 by Martin Pool
[patch] Better error when sftp urls are given with invalid port numbers (Matthieu Moy)
168
2013.1.2 by John Arbash Meinel
Add a test that we can always fall back to the paramiko vendor
169
    def test_get_paramiko_vendor(self):
170
        """Test that if no 'ssh' is available we get builtin paramiko"""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
171
        from breezy.transport import ssh
2013.1.2 by John Arbash Meinel
Add a test that we can always fall back to the paramiko vendor
172
        # set '.' as the only location in the path, forcing no 'ssh' to exist
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
173
        self.overrideAttr(ssh, '_ssh_vendor_manager')
5570.3.13 by Vincent Ladeuil
Fix typo.
174
        self.overrideEnv('PATH', '.')
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
175
        ssh._ssh_vendor_manager.clear_cache()
176
        vendor = ssh._get_ssh_vendor()
177
        self.assertIsInstance(vendor, ssh.ParamikoVendor)
2013.1.2 by John Arbash Meinel
Add a test that we can always fall back to the paramiko vendor
178
1986.1.10 by Robert Collins
Merge from bzr.dev, fixing found bugs handling 'has('/')' in MemoryTransport and SFTP transports.
179
    def test_abspath_root_sibling_server(self):
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
180
        server = stub_sftp.SFTPSiblingAbsoluteServer()
4934.3.3 by Martin Pool
Rename Server.setUp to Server.start_server
181
        server.start_server()
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
182
        self.addCleanup(server.stop_server)
183
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
184
        transport = _mod_transport.get_transport_from_url(server.get_url())
5570.3.12 by Vincent Ladeuil
Replace osutils.set_or_unset_env calls with self.overrideEnv.
185
        self.assertFalse(transport.abspath('/').endswith('/~/'))
186
        self.assertTrue(transport.abspath('/').endswith('/'))
187
        del transport
1986.1.10 by Robert Collins
Merge from bzr.dev, fixing found bugs handling 'has('/')' in MemoryTransport and SFTP transports.
188
1185.40.4 by Robey Pointer
fix sftp urls to support the ietf draft url spec wrt relative vs absolute sftp urls (this will break existing branch urls); fix username/password parsing in sftp urls; add unit tests to make sure sftp url parsing is working
189
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
190
class SFTPBranchTest(TestCaseWithSFTPServer):
191
    """Test some stuff when accessing a bzr Branch over sftp"""
192
1185.49.26 by John Arbash Meinel
Adding tests for remote sftp branches without working trees, plus a bugfix to allow push to still work with a warning.
193
    def test_push_support(self):
194
        self.build_tree(['a/', 'a/foo'])
6472.2.2 by Jelmer Vernooij
Use controldir rather than bzrdir in a couple more places.
195
        t = controldir.ControlDir.create_standalone_workingtree('a')
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
196
        b = t.branch
1185.49.26 by John Arbash Meinel
Adding tests for remote sftp branches without working trees, plus a bugfix to allow push to still work with a warning.
197
        t.add('foo')
6855.4.1 by Jelmer Vernooij
Yet more bees.
198
        t.commit('foo', rev_id=b'a1')
1185.49.26 by John Arbash Meinel
Adding tests for remote sftp branches without working trees, plus a bugfix to allow push to still work with a warning.
199
6472.2.2 by Jelmer Vernooij
Use controldir rather than bzrdir in a couple more places.
200
        b2 = controldir.ControlDir.create_branch_and_repo(self.get_url('/b'))
1185.49.26 by John Arbash Meinel
Adding tests for remote sftp branches without working trees, plus a bugfix to allow push to still work with a warning.
201
        b2.pull(b)
202
6973.6.1 by Jelmer Vernooij
More bees.
203
        self.assertEqual(b2.last_revision(), b'a1')
1185.49.26 by John Arbash Meinel
Adding tests for remote sftp branches without working trees, plus a bugfix to allow push to still work with a warning.
204
7143.15.2 by Jelmer Vernooij
Run autopep8.
205
        with open('a/foo', 'wt') as f:
206
            f.write('something new in foo\n')
6855.4.1 by Jelmer Vernooij
Yet more bees.
207
        t.commit('new', rev_id=b'a2')
1185.31.48 by John Arbash Meinel
Added a small test to sftp to make sure some replacing was going on in the remote side.
208
        b2.pull(b)
209
6973.6.1 by Jelmer Vernooij
More bees.
210
        self.assertEqual(b2.last_revision(), b'a2')
1185.31.48 by John Arbash Meinel
Added a small test to sftp to make sure some replacing was going on in the remote side.
211
1185.49.3 by John Arbash Meinel
Added a form of locking to sftp branches. Refactored _sftp_open_exclusive to take a relative path
212
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
213
class SSHVendorConnection(TestCaseWithSFTPServer):
214
    """Test that the ssh vendors can all connect.
215
216
    Verify that a full-handshake (SSH over loopback TCP) sftp connection works.
217
218
    We have 3 sftp implementations in the test suite:
219
      'loopback': Doesn't use ssh, just uses a local socket. Most tests are
220
                  done this way to save the handshaking time, so it is not
221
                  tested again here
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
222
      'none':     This uses paramiko's built-in ssh client and server, and
223
                  layers sftp on top of it.
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
224
      None:       If 'ssh' exists on the machine, then it will be spawned as a
225
                  child process.
226
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
227
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
228
    def setUp(self):
229
        super(SSHVendorConnection, self).setUp()
230
231
        def create_server():
232
            """Just a wrapper so that when created, it will set _vendor"""
233
            # SFTPFullAbsoluteServer can handle any vendor,
234
            # it just needs to be set between the time it is instantiated
235
            # and the time .setUp() is called
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
236
            server = stub_sftp.SFTPFullAbsoluteServer()
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
237
            server._vendor = self._test_vendor
238
            return server
239
        self._test_vendor = 'loopback'
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
240
        self.vfs_transport_server = create_server
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
241
        f = open('a_file', 'wb')
242
        try:
6855.2.6 by Jelmer Vernooij
Fix recent regressions.
243
            f.write(b'foobar\n')
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
244
        finally:
245
            f.close()
246
247
    def set_vendor(self, vendor):
248
        self._test_vendor = vendor
249
250
    def test_connection_paramiko(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
251
        from breezy.transport import ssh
1951.1.8 by Andrew Bennetts
Make _get_ssh_vendor return the vendor object, rather than just a string.
252
        self.set_vendor(ssh.ParamikoVendor())
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
253
        t = self.get_transport()
6973.6.1 by Jelmer Vernooij
More bees.
254
        self.assertEqual(b'foobar\n', t.get('a_file').read())
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
255
256
    def test_connection_vendor(self):
257
        raise TestSkipped("We don't test spawning real ssh,"
258
                          " because it prompts for a password."
259
                          " Enable this test if we figure out"
260
                          " how to prevent this.")
261
        self.set_vendor(None)
262
        t = self.get_transport()
6973.6.1 by Jelmer Vernooij
More bees.
263
        self.assertEqual(b'foobar\n', t.get('a_file').read())
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
264
265
266
class SSHVendorBadConnection(TestCaseWithTransport):
267
    """Test that the ssh vendors handle bad connection properly
268
269
    We don't subclass TestCaseWithSFTPServer, because we don't actually
270
    need an SFTP connection.
271
    """
272
273
    def setUp(self):
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
274
        self.requireFeature(features.paramiko)
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
275
        super(SSHVendorBadConnection, self).setUp()
276
1185.49.35 by John Arbash Meinel
Update tests to use a truly unused port
277
        # open a random port, so we know nobody else is using it
278
        # but don't actually listen on the port.
279
        s = socket.socket()
280
        s.bind(('localhost', 0))
4985.2.1 by Vincent Ladeuil
Deploy addAttrCleanup on the whole test suite.
281
        self.addCleanup(s.close)
1185.49.35 by John Arbash Meinel
Update tests to use a truly unused port
282
        self.bogus_url = 'sftp://%s:%s/' % s.getsockname()
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
283
6331.5.1 by Martin Packman
Stop requiring a bzr subprocess in bt.test_sftp_transport for ssh connection error test
284
    def set_vendor(self, vendor, subprocess_stderr=None):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
285
        from breezy.transport import ssh
7143.15.2 by Jelmer Vernooij
Run autopep8.
286
        self.overrideAttr(ssh._ssh_vendor_manager,
287
                          '_cached_ssh_vendor', vendor)
6331.5.1 by Martin Packman
Stop requiring a bzr subprocess in bt.test_sftp_transport for ssh connection error test
288
        if subprocess_stderr is not None:
289
            self.overrideAttr(ssh.SubprocessVendor, "_stderr_target",
7143.15.2 by Jelmer Vernooij
Run autopep8.
290
                              subprocess_stderr)
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
291
292
    def test_bad_connection_paramiko(self):
293
        """Test that a real connection attempt raises the right error"""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
294
        from breezy.transport import ssh
1951.1.8 by Andrew Bennetts
Make _get_ssh_vendor return the vendor object, rather than just a string.
295
        self.set_vendor(ssh.ParamikoVendor())
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
296
        t = _mod_transport.get_transport_from_url(self.bogus_url)
2485.8.38 by Vincent Ladeuil
Finish sftp refactoring. Test suite passing.
297
        self.assertRaises(errors.ConnectionError, t.get, 'foobar')
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
298
299
    def test_bad_connection_ssh(self):
300
        """None => auto-detect vendor"""
6855.4.8 by Jelmer Vernooij
Fix some more tests.
301
        f = open(os.devnull, "wb")
6331.5.2 by Martin Packman
Close the devnull file on test cleanup
302
        self.addCleanup(f.close)
303
        self.set_vendor(None, f)
6331.5.1 by Martin Packman
Stop requiring a bzr subprocess in bt.test_sftp_transport for ssh connection error test
304
        t = _mod_transport.get_transport_from_url(self.bogus_url)
305
        try:
6331.5.3 by Martin Packman
Make the test more in the same style as its sibling as pointed out by vila in review
306
            self.assertRaises(errors.ConnectionError, t.get, 'foobar')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
307
        except NameError as e:
6331.5.1 by Martin Packman
Stop requiring a bzr subprocess in bt.test_sftp_transport for ssh connection error test
308
            if "global name 'SSHException'" in str(e):
6331.5.3 by Martin Packman
Make the test more in the same style as its sibling as pointed out by vila in review
309
                self.knownFailure('Known NameError bug in paramiko 1.6.1')
6331.5.1 by Martin Packman
Stop requiring a bzr subprocess in bt.test_sftp_transport for ssh connection error test
310
            raise
1185.49.32 by John Arbash Meinel
Update tests to show that all ssh vendor failed connections work correctly, has some stipple from real ssh
311
1871.1.3 by Robert Collins
proof of concept slowsocket wrapper.
312
313
class SFTPLatencyKnob(TestCaseWithSFTPServer):
314
    """Test that the testing SFTPServer's latency knob works."""
315
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
316
    def test_latency_knob_slows_transport(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
317
        # change the latency knob to 500ms. We take about 40ms for a
1871.1.3 by Robert Collins
proof of concept slowsocket wrapper.
318
        # loopback connection ordinarily.
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
319
        start_time = time.time()
320
        self.get_server().add_latency = 0.5
321
        transport = self.get_transport()
7143.15.2 by Jelmer Vernooij
Run autopep8.
322
        transport.has('not me')  # Force connection by issuing a request
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
323
        with_latency_knob_time = time.time() - start_time
324
        self.assertTrue(with_latency_knob_time > 0.4)
325
326
    def test_default(self):
327
        # This test is potentially brittle: under extremely high machine load
328
        # it could fail, but that is quite unlikely
2631.1.1 by Aaron Bentley
Disable timing-sensitive test
329
        raise TestSkipped('Timing-sensitive test')
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
330
        start_time = time.time()
331
        transport = self.get_transport()
7143.15.2 by Jelmer Vernooij
Run autopep8.
332
        transport.has('not me')  # Force connection by issuing a request
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
333
        regular_time = time.time() - start_time
334
        self.assertTrue(regular_time < 0.5)
335
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
336
337
class FakeSocket(object):
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
338
    """Fake socket object used to test the SocketDelay wrapper without
339
    using a real socket.
340
    """
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
341
342
    def __init__(self):
343
        self._data = ""
344
345
    def send(self, data, flags=0):
346
        self._data += data
347
        return len(data)
348
349
    def sendall(self, data, flags=0):
350
        self._data += data
351
        return len(data)
352
353
    def recv(self, size, flags=0):
354
        if size < len(self._data):
355
            result = self._data[:size]
356
            self._data = self._data[size:]
357
            return result
358
        else:
359
            result = self._data
360
            self._data = ""
361
            return result
362
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
363
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
364
class TestSocketDelay(TestCase):
1874.1.9 by Carl Friedrich Bolz
Try to fix all the issues outline by john and Robert.
365
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
366
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
367
        super(TestSocketDelay, self).setUp()
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
368
        self.requireFeature(features.paramiko)
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
369
370
    def test_delay(self):
371
        sending = FakeSocket()
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
372
        receiving = stub_sftp.SocketDelay(sending, 0.1, bandwidth=1000000,
373
                                          really_sleep=False)
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
374
        # check that simulated time is charged only per round-trip:
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
375
        t1 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
376
        receiving.send("connect1")
377
        self.assertEqual(sending.recv(1024), "connect1")
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
378
        t2 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
379
        self.assertAlmostEqual(t2 - t1, 0.1)
380
        receiving.send("connect2")
381
        self.assertEqual(sending.recv(1024), "connect2")
382
        sending.send("hello")
383
        self.assertEqual(receiving.recv(1024), "hello")
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
384
        t3 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
385
        self.assertAlmostEqual(t3 - t2, 0.1)
386
        sending.send("hello")
387
        self.assertEqual(receiving.recv(1024), "hello")
388
        sending.send("hello")
389
        self.assertEqual(receiving.recv(1024), "hello")
390
        sending.send("hello")
391
        self.assertEqual(receiving.recv(1024), "hello")
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
392
        t4 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
393
        self.assertAlmostEqual(t4, t3)
394
395
    def test_bandwidth(self):
396
        sending = FakeSocket()
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
397
        receiving = stub_sftp.SocketDelay(
398
            sending, 0, bandwidth=8.0 / (1024 * 1024), really_sleep=False)
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
399
        # check that simulated time is charged only per round-trip:
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
400
        t1 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
401
        receiving.send("connect")
402
        self.assertEqual(sending.recv(1024), "connect")
403
        sending.send("a" * 100)
404
        self.assertEqual(receiving.recv(1024), "a" * 100)
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
405
        t2 = stub_sftp.SocketDelay.simulated_time
1874.1.2 by Carl Friedrich Bolz
Refined the SocketDelay to charge latency only once per round-trip and to
406
        self.assertAlmostEqual(t2 - t1, 100 + 7)
407
1874.1.3 by Carl Friedrich Bolz
Merge bzr.dev.
408
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
409
class ReadvFile(object):
5807.5.5 by Martin
Add close method to ReadvFile test object to fix failure
410
    """An object that acts like Paramiko's SFTPFile when readv() is used"""
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
411
412
    def __init__(self, data):
413
        self._data = data
414
415
    def readv(self, requests):
416
        for start, length in requests:
7143.15.2 by Jelmer Vernooij
Run autopep8.
417
            yield self._data[start:start + length]
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
418
5807.5.5 by Martin
Add close method to ReadvFile test object to fix failure
419
    def close(self):
420
        pass
421
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
422
3882.7.16 by Martin Pool
Update SFTP tests to accommodate progress reporting
423
def _null_report_activity(*a, **k):
424
    pass
425
426
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
427
class Test_SFTPReadvHelper(tests.TestCase):
428
3686.1.6 by John Arbash Meinel
Respond to Martin's review comments.
429
    def checkGetRequests(self, expected_requests, offsets):
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
430
        self.requireFeature(features.paramiko)
3882.7.16 by Martin Pool
Update SFTP tests to accommodate progress reporting
431
        helper = _mod_sftp._SFTPReadvHelper(offsets, 'artificial_test',
7143.15.2 by Jelmer Vernooij
Run autopep8.
432
                                            _null_report_activity)
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
433
        self.assertEqual(expected_requests, helper._get_requests())
434
435
    def test__get_requests(self):
436
        # Small single requests become a single readv request
3686.1.6 by John Arbash Meinel
Respond to Martin's review comments.
437
        self.checkGetRequests([(0, 100)],
438
                              [(0, 20), (30, 50), (20, 10), (80, 20)])
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
439
        # Non-contiguous ranges are given as multiple requests
3686.1.6 by John Arbash Meinel
Respond to Martin's review comments.
440
        self.checkGetRequests([(0, 20), (30, 50)],
441
                              [(10, 10), (30, 20), (0, 10), (50, 30)])
3686.1.2 by John Arbash Meinel
Start moving the readv code into a helper.
442
        # Ranges larger than _max_request_size (32kB) are broken up into
443
        # multiple requests, even if it actually spans multiple logical
444
        # requests
3686.1.6 by John Arbash Meinel
Respond to Martin's review comments.
445
        self.checkGetRequests([(0, 32768), (32768, 32768), (65536, 464)],
446
                              [(0, 40000), (40000, 100), (40100, 1900),
447
                               (42000, 24000)])
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
448
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
449
    def checkRequestAndYield(self, expected, data, offsets):
4913.2.16 by John Arbash Meinel
Move bzrlib.tests.ParamikoFeature to bzrlib.tests.features.paramiko
450
        self.requireFeature(features.paramiko)
3882.7.16 by Martin Pool
Update SFTP tests to accommodate progress reporting
451
        helper = _mod_sftp._SFTPReadvHelper(offsets, 'artificial_test',
7143.15.2 by Jelmer Vernooij
Run autopep8.
452
                                            _null_report_activity)
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
453
        data_f = ReadvFile(data)
454
        result = list(helper.request_and_yield_offsets(data_f))
455
        self.assertEqual(expected, result)
456
457
    def test_request_and_yield_offsets(self):
6973.6.1 by Jelmer Vernooij
More bees.
458
        data = b'abcdefghijklmnopqrstuvwxyz'
459
        self.checkRequestAndYield([(0, b'a'), (5, b'f'), (10, b'klm')], data,
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
460
                                  [(0, 1), (5, 1), (10, 3)])
461
        # Should combine requests, and split them again
6973.6.1 by Jelmer Vernooij
More bees.
462
        self.checkRequestAndYield([(0, b'a'), (1, b'b'), (10, b'klm')], data,
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
463
                                  [(0, 1), (1, 1), (10, 3)])
464
        # Out of order requests. The requests should get combined, but then be
465
        # yielded out-of-order. We also need one that is at the end of a
466
        # previous range. See bug #293746
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
467
        self.checkRequestAndYield(
468
            [(0, b'a'), (10, b'k'), (4, b'efg'), (1, b'bcd')],
469
            data, [(0, 1), (10, 1), (4, 3), (1, 3)])
3815.2.4 by Martin Pool
merge fix for out-of-order SFTP readv
470
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
471
472
class TestUsesAuthConfig(TestCaseWithSFTPServer):
3777.1.4 by Aaron Bentley
bzr+ssh and sftp both use ssh scheme.
473
    """Test that AuthenticationConfig can supply default usernames."""
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
474
3777.1.2 by Aaron Bentley
Make testing more thorough
475
    def get_transport_for_connection(self, set_config):
5247.4.18 by Vincent Ladeuil
Replace SocketListener by TestingTCPServerInAThread and fallouts,
476
        port = self.get_server().port
3777.1.2 by Aaron Bentley
Make testing more thorough
477
        if set_config:
478
            conf = config.AuthenticationConfig()
479
            conf._get_config().update(
3777.1.4 by Aaron Bentley
bzr+ssh and sftp both use ssh scheme.
480
                {'sftptest': {'scheme': 'ssh', 'port': port, 'user': 'bar'}})
3777.1.2 by Aaron Bentley
Make testing more thorough
481
            conf._save()
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
482
        t = _mod_transport.get_transport_from_url(
483
            'sftp://localhost:%d' % port)
3777.1.2 by Aaron Bentley
Make testing more thorough
484
        # force a connection to be performed.
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
485
        t.has('foo')
3777.1.2 by Aaron Bentley
Make testing more thorough
486
        return t
487
488
    def test_sftp_uses_config(self):
489
        t = self.get_transport_for_connection(set_config=True)
3777.1.1 by Aaron Bentley
Use auth.conf for sftp
490
        self.assertEqual('bar', t._get_credentials()[0])
3777.1.2 by Aaron Bentley
Make testing more thorough
491
492
    def test_sftp_is_none_if_no_config(self):
493
        t = self.get_transport_for_connection(set_config=False)
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
494
        self.assertIs(None, t._get_credentials()[0])
4222.3.13 by Jelmer Vernooij
Add tests to ensure sftp and ftp don't prompt for usernames.
495
496
    def test_sftp_doesnt_prompt_username(self):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
497
        ui.ui_factory = tests.TestUIFactory(stdin='joe\nfoo\n')
4222.3.13 by Jelmer Vernooij
Add tests to ensure sftp and ftp don't prompt for usernames.
498
        t = self.get_transport_for_connection(set_config=False)
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
499
        self.assertIs(None, t._get_credentials()[0])
4222.3.13 by Jelmer Vernooij
Add tests to ensure sftp and ftp don't prompt for usernames.
500
        # No prompts should've been printed, stdin shouldn't have been read
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
501
        self.assertEqual("", ui.ui_factory.stdout.getvalue())
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
502
        self.assertEqual(0, ui.ui_factory.stdin.tell())