code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_putOverLongerFile(self):
"""
Check that 'put' uploads files correctly when overwriting a longer
file.
"""
# XXX - not actually a unit test
with self.testDir.child('shorterFile').open(mode='w') as f:
f.write(b"a")
with self.testDir.child('longerFile').open(mode='w') as f:
f.write(b"bb")
def _checkPut(result):
self.assertFilesEqual(self.testDir.child('shorterFile'),
self.testDir.child('longerFile'))
d = self.runCommand('put %s/shorterFile longerFile'
% (self.testDir.path,))
d.addCallback(_checkPut)
return d | Check that 'put' uploads files correctly when overwriting a longer
file. | test_putOverLongerFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def test_putMultipleOverLongerFile(self):
"""
Check that 'put' uploads files correctly when overwriting a longer
file and you use a wildcard to specify the files to upload.
"""
# XXX - not actually a unit test
someDir = self.testDir.child('dir')
someDir.createDirectory()
with someDir.child('file').open(mode='w') as f:
f.write(b"a")
with self.testDir.child('file').open(mode='w') as f:
f.write(b"bb")
def _checkPut(result):
self.assertFilesEqual(someDir.child('file'),
self.testDir.child('file'))
d = self.runCommand('put %s/dir/*'
% (self.testDir.path,))
d.addCallback(_checkPut)
return d | Check that 'put' uploads files correctly when overwriting a longer
file and you use a wildcard to specify the files to upload. | test_putMultipleOverLongerFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testWildcardPut(self):
"""
What happens if you issue a 'put' command and include a wildcard (i.e.
'*') in parameter? Check that all files matching the wildcard are
uploaded to the correct directory.
"""
def check(results):
self.assertEqual(results[0], b'')
self.assertEqual(results[2], b'')
self.assertFilesEqual(self.testDir.child('testRemoveFile'),
self.testDir.parent().child('testRemoveFile'),
'testRemoveFile get failed')
self.assertFilesEqual(self.testDir.child('testRenameFile'),
self.testDir.parent().child('testRenameFile'),
'testRenameFile get failed')
d = self.runScript('cd ..',
'put %s/testR*' % (self.testDir.path,),
'cd %s' % self.testDir.basename())
d.addCallback(check)
return d | What happens if you issue a 'put' command and include a wildcard (i.e.
'*') in parameter? Check that all files matching the wildcard are
uploaded to the correct directory. | testWildcardPut | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testLink(self):
"""
Test that 'ln' creates a file which appears as a link in the output of
'ls'. Check that removing the new file succeeds without output.
"""
def _check(results):
self.flushLoggedErrors()
self.assertEqual(results[0], b'')
self.assertTrue(results[1].startswith(b'l'), 'link failed')
return self.runCommand('rm testLink')
d = self.runScript('ln testLink testfile1', 'ls -l testLink')
d.addCallback(_check)
d.addCallback(self.assertEqual, b'')
return d | Test that 'ln' creates a file which appears as a link in the output of
'ls'. Check that removing the new file succeeds without output. | testLink | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testRemoteDirectory(self):
"""
Test that we can create and remove directories with the cftp client.
"""
def _check(results):
self.assertEqual(results[0], b'')
self.assertTrue(results[1].startswith(b'd'))
return self.runCommand('rmdir testMakeDirectory')
d = self.runScript('mkdir testMakeDirectory',
'ls -l testMakeDirector?')
d.addCallback(_check)
d.addCallback(self.assertEqual, b'')
return d | Test that we can create and remove directories with the cftp client. | testRemoteDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def test_existingRemoteDirectory(self):
"""
Test that a C{mkdir} on an existing directory fails with the
appropriate error, and doesn't log an useless error server side.
"""
def _check(results):
self.assertEqual(results[0], b'')
self.assertEqual(results[1],
b'remote error 11: mkdir failed')
d = self.runScript('mkdir testMakeDirectory',
'mkdir testMakeDirectory')
d.addCallback(_check)
return d | Test that a C{mkdir} on an existing directory fails with the
appropriate error, and doesn't log an useless error server side. | test_existingRemoteDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testLocalDirectory(self):
"""
Test that we can create a directory locally and remove it with the
cftp client. This test works because the 'remote' server is running
out of a local directory.
"""
d = self.runCommand('lmkdir %s/testLocalDirectory' % (self.testDir.path,))
d.addCallback(self.assertEqual, b'')
d.addCallback(lambda _: self.runCommand('rmdir testLocalDirectory'))
d.addCallback(self.assertEqual, b'')
return d | Test that we can create a directory locally and remove it with the
cftp client. This test works because the 'remote' server is running
out of a local directory. | testLocalDirectory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testRename(self):
"""
Test that we can rename a file.
"""
def _check(results):
self.assertEqual(results[0], b'')
self.assertEqual(results[1], b'testfile2')
return self.runCommand('rename testfile2 testfile1')
d = self.runScript('rename testfile1 testfile2', 'ls testfile?')
d.addCallback(_check)
d.addCallback(self.assertEqual, b'')
return d | Test that we can rename a file. | testRename | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testBatchFile(self):
"""
Test whether batch file function of cftp ('cftp -b batchfile').
This works by treating the file as a list of commands to be run.
"""
cmds = """pwd
ls
exit
"""
def _cbCheckResult(res):
res = res.split(b'\n')
log.msg('RES %s' % repr(res))
self.assertIn(self.testDir.asBytesMode().path, res[1])
self.assertEqual(res[3:-2], [b'testDirectory', b'testRemoveFile',
b'testRenameFile', b'testfile1'])
d = self._getBatchOutput(cmds)
d.addCallback(_cbCheckResult)
return d | Test whether batch file function of cftp ('cftp -b batchfile').
This works by treating the file as a list of commands to be run. | testBatchFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testError(self):
"""
Test that an error in the batch file stops running the batch.
"""
cmds = """chown 0 missingFile
pwd
exit
"""
def _cbCheckResult(res):
self.assertNotIn(self.testDir.asBytesMode().path, res)
d = self._getBatchOutput(cmds)
d.addCallback(_cbCheckResult)
return d | Test that an error in the batch file stops running the batch. | testError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def testIgnoredError(self):
"""
Test that a minus sign '-' at the front of a line ignores
any errors.
"""
cmds = """-chown 0 missingFile
pwd
exit
"""
def _cbCheckResult(res):
self.assertIn(self.testDir.asBytesMode().path, res)
d = self._getBatchOutput(cmds)
d.addCallback(_cbCheckResult)
return d | Test that a minus sign '-' at the front of a line ignores
any errors. | testIgnoredError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def test_extendedAttributes(self):
"""
Test the return of extended attributes by the server: the sftp client
should ignore them, but still be able to parse the response correctly.
This test is mainly here to check that
L{filetransfer.FILEXFER_ATTR_EXTENDED} has the correct value.
"""
fn = self.mktemp()
with open(fn, 'w') as f:
f.write("ls .\nexit")
port = self.server.getHost().port
oldGetAttr = FileTransferForTestAvatar._getAttrs
def _getAttrs(self, s):
attrs = oldGetAttr(self, s)
attrs["ext_foo"] = "bar"
return attrs
self.patch(FileTransferForTestAvatar, "_getAttrs", _getAttrs)
self.server.factory.expectedLoseConnection = True
# PubkeyAcceptedKeyTypes does not exist prior to OpenSSH 7.0 so we
# first need to check if we can set it. If we can, -V will just print
# the version without doing anything else; if we can't, we will get a
# configuration error.
d = getProcessValue(
'ssh', ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss', '-V'))
def hasPAKT(status):
if status == 0:
args = ('-o', 'PubkeyAcceptedKeyTypes=ssh-dss')
else:
args = ()
# Pass -F /dev/null to avoid the user's configuration file from
# being loaded, as it may contain settings that cause our tests to
# fail or hang.
args += ('-F', '/dev/null',
'-o', 'IdentityFile=dsa_test',
'-o', 'UserKnownHostsFile=kh_test',
'-o', 'HostKeyAlgorithms=ssh-rsa',
'-o', 'Port=%i' % (port,), '-b', fn, '[email protected]')
return args
def check(result):
self.assertEqual(result[2], 0)
for i in [b'testDirectory', b'testRemoveFile',
b'testRenameFile', b'testfile1']:
self.assertIn(i, result[0])
d.addCallback(hasPAKT)
d.addCallback(lambda args: getProcessOutputAndValue('sftp', args))
return d.addCallback(check) | Test the return of extended attributes by the server: the sftp client
should ignore them, but still be able to parse the response correctly.
This test is mainly here to check that
L{filetransfer.FILEXFER_ATTR_EXTENDED} has the correct value. | test_extendedAttributes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_cftp.py | MIT |
def abortConnection(self):
"""
Abort the connection in a fake manner.
This should really be implemented in the underlying module.
"""
self.aborted = True | Abort the connection in a fake manner.
This should really be implemented in the underlying module. | abortConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def request_exec(self, data):
"""
Fail all exec requests.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: C{0} to indicate failure
@rtype: L{int}
"""
return 0 | Fail all exec requests.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: C{0} to indicate failure
@rtype: L{int} | request_exec | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def request_exec(self, data):
"""
Succeed all exec requests.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: C{1} to indicate success
@rtype: L{int}
"""
return 1 | Succeed all exec requests.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: C{1} to indicate success
@rtype: L{int} | request_exec | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def request_exec(self, data):
"""
Delay all exec requests indefinitely.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: A L{Deferred} which will never fire.
@rtype: L{Deferred}
"""
return Deferred() | Delay all exec requests indefinitely.
@param data: Information about what is being executed.
@type data: L{bytes}
@return: A L{Deferred} which will never fire.
@rtype: L{Deferred} | request_exec | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def attemptsBeforeDisconnect(self):
"""
Use the C{attemptsBeforeDisconnect} value defined by the factory to make
it easier to override.
"""
return self.transport.factory.attemptsBeforeDisconnect | Use the C{attemptsBeforeDisconnect} value defined by the factory to make
it easier to override. | attemptsBeforeDisconnect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def clock(self):
"""
Use the reactor defined by the factory, rather than the default global
reactor, to simplify testing (by allowing an alternate implementation
to be supplied by tests).
"""
return self.transport.factory.reactor | Use the reactor defined by the factory, rather than the default global
reactor, to simplify testing (by allowing an alternate implementation
to be supplied by tests). | clock | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def __init__(self, server):
"""
@param server: An L{IProtocol} provider to which the client will be
connected.
@type server: L{IProtocol} provider
"""
self.pump = None
self._server = server | @param server: An L{IProtocol} provider to which the client will be
connected.
@type server: L{IProtocol} provider | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def create(self):
"""
Create and return a new L{SSHCommandClientEndpoint} to be tested.
Override this to implement creation in an interesting way the endpoint.
"""
raise NotImplementedError(
"%r did not implement create" % (self.__class__.__name__,)) | Create and return a new L{SSHCommandClientEndpoint} to be tested.
Override this to implement creation in an interesting way the endpoint. | create | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def assertClientTransportState(self, client, immediateClose):
"""
Make an assertion about the connectedness of the given protocol's
transport. Override this to implement either a check for the
connection still being open or having been closed as appropriate.
@param client: The client whose state is being checked.
@param immediateClose: Boolean indicating whether the connection was
closed immediately or not.
"""
raise NotImplementedError(
"%r did not implement assertClientTransportState" % (
self.__class__.__name__,)) | Make an assertion about the connectedness of the given protocol's
transport. Override this to implement either a check for the
connection still being open or having been closed as appropriate.
@param client: The client whose state is being checked.
@param immediateClose: Boolean indicating whether the connection was
closed immediately or not. | assertClientTransportState | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def finishConnection(self):
"""
Do any remaining work necessary to complete an in-memory connection
attempted initiated using C{self.reactor}.
"""
raise NotImplementedError(
"%r did not implement finishConnection" % (
self.__class__.__name__,)) | Do any remaining work necessary to complete an in-memory connection
attempted initiated using C{self.reactor}. | finishConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def connectedServerAndClient(self, serverFactory, clientFactory):
"""
Set up an in-memory connection between protocols created by
C{serverFactory} and C{clientFactory}.
@return: A three-tuple. The first element is the protocol created by
C{serverFactory}. The second element is the protocol created by
C{clientFactory}. The third element is the L{IOPump} connecting
them.
"""
clientProtocol = clientFactory.buildProtocol(None)
serverProtocol = serverFactory.buildProtocol(None)
clientTransport = AbortableFakeTransport(
clientProtocol, isServer=False, hostAddress=self.clientAddress,
peerAddress=self.serverAddress)
serverTransport = AbortableFakeTransport(
serverProtocol, isServer=True, hostAddress=self.serverAddress,
peerAddress=self.clientAddress)
pump = connect(
serverProtocol, serverTransport, clientProtocol, clientTransport)
return serverProtocol, clientProtocol, pump | Set up an in-memory connection between protocols created by
C{serverFactory} and C{clientFactory}.
@return: A three-tuple. The first element is the protocol created by
C{serverFactory}. The second element is the protocol created by
C{clientFactory}. The third element is the L{IOPump} connecting
them. | connectedServerAndClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_channelOpenFailure(self):
"""
If a channel cannot be opened on the authenticated SSH connection, the
L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
a L{Failure} wrapping the reason given by the server.
"""
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
# The server logs the channel open failure - this is expected.
errors = self.flushLoggedErrors(ConchError)
self.assertIn(
'unknown channel', (errors[0].value.data, errors[0].value.value))
self.assertEqual(1, len(errors))
# Now deal with the results on the endpoint side.
f = self.failureResultOf(connected)
f.trap(ConchError)
self.assertEqual(b'unknown channel', f.value.value)
self.assertClientTransportState(client, False) | If a channel cannot be opened on the authenticated SSH connection, the
L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
a L{Failure} wrapping the reason given by the server. | test_channelOpenFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_execFailure(self):
"""
If execution of the command fails, the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
the reason given by the server.
"""
self.realm.channelLookup[b'session'] = BrokenExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
f = self.failureResultOf(connected)
f.trap(ConchError)
self.assertEqual('channel request failed', f.value.value)
self.assertClientTransportState(client, False) | If execution of the command fails, the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
the reason given by the server. | test_execFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_execCancelled(self):
"""
If execution of the command is cancelled via the L{Deferred} returned
by L{SSHCommandClientEndpoint.connect}, the connection is closed
immediately.
"""
self.realm.channelLookup[b'session'] = UnsatisfiedExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
connected.cancel()
f = self.failureResultOf(connected)
f.trap(CancelledError)
self.assertClientTransportState(client, True) | If execution of the command is cancelled via the L{Deferred} returned
by L{SSHCommandClientEndpoint.connect}, the connection is closed
immediately. | test_execCancelled | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_buildProtocol(self):
"""
Once the necessary SSH actions have completed successfully,
L{SSHCommandClientEndpoint.connect} uses the factory passed to it to
construct a protocol instance by calling its C{buildProtocol} method
with an address object representing the SSH connection and command
executed.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = AddressSpyFactory()
factory.protocol = Protocol
endpoint.connect(factory)
server, client, pump = self.finishConnection()
self.assertIsInstance(factory.address, SSHCommandAddress)
self.assertEqual(server.transport.getHost(), factory.address.server)
self.assertEqual(self.user, factory.address.username)
self.assertEqual(b"/bin/ls -l", factory.address.command) | Once the necessary SSH actions have completed successfully,
L{SSHCommandClientEndpoint.connect} uses the factory passed to it to
construct a protocol instance by calling its C{buildProtocol} method
with an address object representing the SSH connection and command
executed. | test_buildProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_makeConnection(self):
"""
L{SSHCommandClientEndpoint} establishes an SSH connection, creates a
channel in it, runs a command in that channel, and uses the protocol's
C{makeConnection} to associate it with a protocol representing that
command's stdin and stdout.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
self.assertIsNotNone(protocol.transport) | L{SSHCommandClientEndpoint} establishes an SSH connection, creates a
channel in it, runs a command in that channel, and uses the protocol's
C{makeConnection} to associate it with a protocol representing that
command's stdin and stdout. | test_makeConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_dataReceived(self):
"""
After establishing the connection, when the command on the SSH server
produces output, it is delivered to the protocol's C{dataReceived}
method.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
dataReceived = []
protocol.dataReceived = dataReceived.append
# Figure out which channel on the connection this protocol is
# associated with so the test can do a write on it.
channelId = protocol.transport.id
server.service.channels[channelId].write(b"hello, world")
pump.pump()
self.assertEqual(b"hello, world", b"".join(dataReceived)) | After establishing the connection, when the command on the SSH server
produces output, it is delivered to the protocol's C{dataReceived}
method. | test_dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_connectionLost(self):
"""
When the command closes the channel, the protocol's C{connectionLost}
method is called.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
connectionLost = []
protocol.connectionLost = connectionLost.append
# Figure out which channel on the connection this protocol is
# associated with so the test can do a write on it.
channelId = protocol.transport.id
server.service.channels[channelId].loseConnection()
pump.pump()
connectionLost[0].trap(ConnectionDone)
self.assertClientTransportState(client, False) | When the command closes the channel, the protocol's C{connectionLost}
method is called. | test_connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def _exitStatusTest(self, request, requestArg):
"""
Test handling of non-zero exit statuses or exit signals.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
connectionLost = []
protocol.connectionLost = connectionLost.append
# Figure out which channel on the connection this protocol is
# associated with so the test can simulate command exit and
# channel close.
channelId = protocol.transport.id
channel = server.service.channels[channelId]
server.service.sendRequest(channel, request, requestArg)
channel.loseConnection()
pump.pump()
self.assertClientTransportState(client, False)
return connectionLost[0] | Test handling of non-zero exit statuses or exit signals. | _exitStatusTest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_zeroExitCode(self):
"""
When the command exits with a non-zero status, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status.
"""
exitCode = 0
exc = self._exitStatusTest(b'exit-status', pack('>L', exitCode))
exc.trap(ConnectionDone) | When the command exits with a non-zero status, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status. | test_zeroExitCode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_nonZeroExitStatus(self):
"""
When the command exits with a non-zero status, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status.
"""
exitCode = 123
signal = None
exc = self._exitStatusTest(b'exit-status', pack('>L', exitCode))
exc.trap(ProcessTerminated)
self.assertEqual(exitCode, exc.value.exitCode)
self.assertEqual(signal, exc.value.signal) | When the command exits with a non-zero status, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status. | test_nonZeroExitStatus | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_nonZeroExitSignal(self):
"""
When the command exits with a non-zero signal, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status.
Additional packet contents are logged at the C{info} level.
"""
logObserver = EventLoggingObserver()
globalLogPublisher.addObserver(logObserver)
self.addCleanup(globalLogPublisher.removeObserver, logObserver)
exitCode = None
signal = 15
# See https://tools.ietf.org/html/rfc4254#section-6.10
packet = b"".join([
common.NS(b'TERM'), # Signal name (without "SIG" prefix);
# string
b'\x01', # Core dumped; boolean
common.NS(b'message'), # Error message; string (UTF-8 encoded)
common.NS(b'en-US'), # Language tag; string
])
exc = self._exitStatusTest(b'exit-signal', packet)
exc.trap(ProcessTerminated)
self.assertEqual(exitCode, exc.value.exitCode)
self.assertEqual(signal, exc.value.signal)
logNamespace = "twisted.conch.endpoints._CommandChannel"
hamcrest.assert_that(
logObserver,
hamcrest.has_item(
hamcrest.has_entries(
{
"log_level": hamcrest.equal_to(LogLevel.info),
"log_namespace": logNamespace,
"shortSignalName": b"TERM",
"coreDumped": True,
"errorMessage": u"message",
"languageTag": b"en-US",
},
))) | When the command exits with a non-zero signal, the protocol's
C{connectionLost} method is called with a L{Failure} wrapping an
exception which encapsulates that status.
Additional packet contents are logged at the C{info} level. | test_nonZeroExitSignal | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def record(self, server, protocol, event, noArgs=False):
"""
Hook into and record events which happen to C{protocol}.
@param server: The SSH server protocol over which C{protocol} is
running.
@type server: L{IProtocol} provider
@param protocol:
@param event:
@param noArgs:
"""
# Figure out which channel the test is going to send data over
# so we can look for it to arrive at the right place on the server.
channelId = protocol.transport.id
recorder = []
if noArgs:
f = lambda: recorder.append(None)
else:
f = recorder.append
setattr(server.service.channels[channelId], event, f)
return recorder | Hook into and record events which happen to C{protocol}.
@param server: The SSH server protocol over which C{protocol} is
running.
@type server: L{IProtocol} provider
@param protocol:
@param event:
@param noArgs: | record | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_write(self):
"""
The transport connected to the protocol has a C{write} method which
sends bytes to the input of the command executing on the SSH server.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
dataReceived = self.record(server, protocol, 'dataReceived')
protocol.transport.write(b"hello, world")
pump.pump()
self.assertEqual(b"hello, world", b"".join(dataReceived)) | The transport connected to the protocol has a C{write} method which
sends bytes to the input of the command executing on the SSH server. | test_write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_writeSequence(self):
"""
The transport connected to the protocol has a C{writeSequence} method which
sends bytes to the input of the command executing on the SSH server.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
dataReceived = self.record(server, protocol, 'dataReceived')
protocol.transport.writeSequence([b"hello, world"])
pump.pump()
self.assertEqual(b"hello, world", b"".join(dataReceived)) | The transport connected to the protocol has a C{writeSequence} method which
sends bytes to the input of the command executing on the SSH server. | test_writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def setUp(self):
"""
Configure an SSH server with password authentication enabled for a
well-known (to the tests) account.
"""
SSHCommandClientEndpointTestsMixin.setUp(self)
# Make the server's host key available to be verified by the client.
self.hostKeyPath = FilePath(self.mktemp())
self.knownHosts = KnownHostsFile(self.hostKeyPath)
self.knownHosts.addHostKey(
self.hostname, self.factory.publicKeys[b'ssh-rsa'])
self.knownHosts.addHostKey(
networkString(self.serverAddress.host),
self.factory.publicKeys[b'ssh-rsa'])
self.knownHosts.save() | Configure an SSH server with password authentication enabled for a
well-known (to the tests) account. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def create(self):
"""
Create and return a new L{SSHCommandClientEndpoint} using the
C{newConnection} constructor.
"""
return SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
password=self.password, knownHosts=self.knownHosts,
ui=FixedResponseUI(False)) | Create and return a new L{SSHCommandClientEndpoint} using the
C{newConnection} constructor. | create | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def finishConnection(self):
"""
Establish the first attempted TCP connection using the SSH server which
C{self.factory} can create.
"""
return self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2]) | Establish the first attempted TCP connection using the SSH server which
C{self.factory} can create. | finishConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def loseConnectionToServer(self, server, client, protocol, pump):
"""
Lose the connection to a server and pump the L{IOPump} sufficiently for
the client to handle the lost connection. Asserts that the client
disconnects its transport.
@param server: The SSH server protocol over which C{protocol} is
running.
@type server: L{IProtocol} provider
@param client: The SSH client protocol over which C{protocol} is
running.
@type client: L{IProtocol} provider
@param protocol: The protocol created by calling connect on the ssh
endpoint under test.
@type protocol: L{IProtocol} provider
@param pump: The L{IOPump} connecting client to server.
@type pump: L{IOPump}
"""
closed = self.record(server, protocol, 'closed', noArgs=True)
protocol.transport.loseConnection()
pump.pump()
self.assertEqual([None], closed)
# Let the last bit of network traffic flow. This lets the server's
# close acknowledgement through, at which point the client can close
# the overall SSH connection.
pump.pump()
# Given that the client transport is disconnecting, report the
# disconnect from up to the ssh protocol.
client.transport.reportDisconnect() | Lose the connection to a server and pump the L{IOPump} sufficiently for
the client to handle the lost connection. Asserts that the client
disconnects its transport.
@param server: The SSH server protocol over which C{protocol} is
running.
@type server: L{IProtocol} provider
@param client: The SSH client protocol over which C{protocol} is
running.
@type client: L{IProtocol} provider
@param protocol: The protocol created by calling connect on the ssh
endpoint under test.
@type protocol: L{IProtocol} provider
@param pump: The L{IOPump} connecting client to server.
@type pump: L{IOPump} | loseConnectionToServer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def assertClientTransportState(self, client, immediateClose):
"""
Assert that the transport for the given protocol has been disconnected.
L{SSHCommandClientEndpoint.newConnection} creates a new dedicated SSH
connection and cleans it up after the command exits.
"""
# Nothing useful can be done with the connection at this point, so the
# endpoint should close it.
if immediateClose:
self.assertTrue(client.transport.aborted)
else:
self.assertTrue(client.transport.disconnecting) | Assert that the transport for the given protocol has been disconnected.
L{SSHCommandClientEndpoint.newConnection} creates a new dedicated SSH
connection and cleans it up after the command exits. | assertClientTransportState | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_interface(self):
"""
L{SSHCommandClientEndpoint} instances provide L{IStreamClientEndpoint}.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"dummy command", b"dummy user",
self.hostname, self.port)
self.assertTrue(verifyObject(IStreamClientEndpoint, endpoint)) | L{SSHCommandClientEndpoint} instances provide L{IStreamClientEndpoint}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_defaultPort(self):
"""
L{SSHCommandClientEndpoint} uses the default port number for SSH when
the C{port} argument is not specified.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"dummy command", b"dummy user", self.hostname)
self.assertEqual(22, endpoint._creator.port) | L{SSHCommandClientEndpoint} uses the default port number for SSH when
the C{port} argument is not specified. | test_defaultPort | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_specifiedPort(self):
"""
L{SSHCommandClientEndpoint} uses the C{port} argument if specified.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"dummy command", b"dummy user",
self.hostname, port=2222)
self.assertEqual(2222, endpoint._creator.port) | L{SSHCommandClientEndpoint} uses the C{port} argument if specified. | test_specifiedPort | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_destination(self):
"""
L{SSHCommandClientEndpoint} uses the L{IReactorTCP} passed to it to
attempt a connection to the host/port address also passed to it.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
password=self.password, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
endpoint.connect(factory)
host, port, factory, timeout, bindAddress = self.reactor.tcpClients[0]
self.assertEqual(self.hostname, networkString(host))
self.assertEqual(self.port, port)
self.assertEqual(1, len(self.reactor.tcpClients)) | L{SSHCommandClientEndpoint} uses the L{IReactorTCP} passed to it to
attempt a connection to the host/port address also passed to it. | test_destination | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_connectionFailed(self):
"""
If a connection cannot be established, the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure}
representing the reason for the connection setup failure.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
d = endpoint.connect(factory)
factory = self.reactor.tcpClients[0][2]
factory.clientConnectionFailed(None, Failure(ConnectionRefusedError()))
self.failureResultOf(d).trap(ConnectionRefusedError) | If a connection cannot be established, the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure}
representing the reason for the connection setup failure. | test_connectionFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_userRejectedHostKey(self):
"""
If the L{KnownHostsFile} instance used to construct
L{SSHCommandClientEndpoint} rejects the SSH public key presented by the
server, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect}
fires with a L{Failure} wrapping L{UserRejectedKey}.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, knownHosts=KnownHostsFile(self.mktemp()),
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
f = self.failureResultOf(connected)
f.trap(UserRejectedKey) | If the L{KnownHostsFile} instance used to construct
L{SSHCommandClientEndpoint} rejects the SSH public key presented by the
server, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect}
fires with a L{Failure} wrapping L{UserRejectedKey}. | test_userRejectedHostKey | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_mismatchedHostKey(self):
"""
If the SSH public key presented by the SSH server does not match the
previously remembered key, as reported by the L{KnownHostsFile}
instance use to construct the endpoint, for that server, the
L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
a L{Failure} wrapping L{HostKeyChanged}.
"""
firstKey = Key.fromString(privateRSA_openssh).public()
knownHosts = KnownHostsFile(FilePath(self.mktemp()))
knownHosts.addHostKey(
networkString(self.serverAddress.host), firstKey)
# Add a different RSA key with the same hostname
differentKey = Key.fromString(privateRSA_openssh_encrypted_aes,
passphrase=b'testxp').public()
knownHosts.addHostKey(self.hostname, differentKey)
# The UI may answer true to any questions asked of it; they should
# make no difference, since a *mismatched* key is not even optionally
# allowed to complete a connection.
ui = FixedResponseUI(True)
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, password=b"dummy password",
knownHosts=knownHosts, ui=ui)
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
f = self.failureResultOf(connected)
f.trap(HostKeyChanged) | If the SSH public key presented by the SSH server does not match the
previously remembered key, as reported by the L{KnownHostsFile}
instance use to construct the endpoint, for that server, the
L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
a L{Failure} wrapping L{HostKeyChanged}. | test_mismatchedHostKey | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_connectionClosedBeforeSecure(self):
"""
If the connection closes at any point before the SSH transport layer
has finished key exchange (ie, gotten to the point where we may attempt
to authenticate), the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
the reason for the lost connection.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
d = endpoint.connect(factory)
transport = StringTransport()
factory = self.reactor.tcpClients[0][2]
client = factory.buildProtocol(None)
client.makeConnection(transport)
client.connectionLost(Failure(ConnectionDone()))
self.failureResultOf(d).trap(ConnectionDone) | If the connection closes at any point before the SSH transport layer
has finished key exchange (ie, gotten to the point where we may attempt
to authenticate), the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
the reason for the lost connection. | test_connectionClosedBeforeSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_connectionCancelledBeforeSecure(self):
"""
If the connection is cancelled before the SSH transport layer has
finished key exchange (ie, gotten to the point where we may attempt to
authenticate), the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
L{CancelledError} and the connection is aborted.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
d = endpoint.connect(factory)
transport = AbortableFakeTransport(None, isServer=False)
factory = self.reactor.tcpClients[0][2]
client = factory.buildProtocol(None)
client.makeConnection(transport)
d.cancel()
self.failureResultOf(d).trap(CancelledError)
self.assertTrue(transport.aborted)
# Make sure the connection closing doesn't result in unexpected
# behavior when due to cancellation:
client.connectionLost(Failure(ConnectionDone())) | If the connection is cancelled before the SSH transport layer has
finished key exchange (ie, gotten to the point where we may attempt to
authenticate), the L{Deferred} returned by
L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
L{CancelledError} and the connection is aborted. | test_connectionCancelledBeforeSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_connectionCancelledBeforeConnected(self):
"""
If the connection is cancelled before it finishes connecting, the
connection attempt is stopped.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
d = endpoint.connect(factory)
d.cancel()
self.failureResultOf(d).trap(ConnectingCancelledError)
self.assertTrue(self.reactor.connectors[0].stoppedConnecting) | If the connection is cancelled before it finishes connecting, the
connection attempt is stopped. | test_connectionCancelledBeforeConnected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_passwordAuthenticationFailure(self):
"""
If the SSH server rejects the password presented during authentication,
the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
with a L{Failure} wrapping L{AuthenticationFailed}.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, password=b"dummy password",
knownHosts=self.knownHosts, ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
# For security, the server delays password authentication failure
# response. Advance the simulation clock so the client sees the
# failure.
self.reactor.advance(server.service.passwordDelay)
# Let the failure response traverse the "network"
pump.flush()
f = self.failureResultOf(connected)
f.trap(AuthenticationFailed)
# XXX Should assert something specific about the arguments of the
# exception
self.assertClientTransportState(client, False) | If the SSH server rejects the password presented during authentication,
the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
with a L{Failure} wrapping L{AuthenticationFailed}. | test_passwordAuthenticationFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def setupKeyChecker(self, portal, users):
"""
Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
to C{portal}.
@param portal: A L{Portal} to which to add the checker.
@type portal: L{Portal}
@param users: The users and their keys the checker will recognize. Keys
are byte strings giving user names. Values are byte strings giving
OpenSSH-formatted private keys.
@type users: L{dict}
"""
mapping = dict([(k,[Key.fromString(v).public()])
for k, v in iteritems(users)])
checker = SSHPublicKeyChecker(InMemorySSHKeyDB(mapping))
portal.registerChecker(checker) | Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
to C{portal}.
@param portal: A L{Portal} to which to add the checker.
@type portal: L{Portal}
@param users: The users and their keys the checker will recognize. Keys
are byte strings giving user names. Values are byte strings giving
OpenSSH-formatted private keys.
@type users: L{dict} | setupKeyChecker | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_publicKeyAuthenticationFailure(self):
"""
If the SSH server rejects the key pair presented during authentication,
the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
with a L{Failure} wrapping L{AuthenticationFailed}.
"""
badKey = Key.fromString(privateRSA_openssh)
self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user,
self.hostname, self.port, keys=[badKey],
knownHosts=self.knownHosts, ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
f = self.failureResultOf(connected)
f.trap(AuthenticationFailed)
# XXX Should assert something specific about the arguments of the
# exception
# Nothing useful can be done with the connection at this point, so the
# endpoint should close it.
self.assertTrue(client.transport.disconnecting) | If the SSH server rejects the key pair presented during authentication,
the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
with a L{Failure} wrapping L{AuthenticationFailed}. | test_publicKeyAuthenticationFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_authenticationFallback(self):
"""
If the SSH server does not accept any of the specified SSH keys, the
specified password is tried.
"""
badKey = Key.fromString(privateRSA_openssh)
self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
keys=[badKey], password=self.password, knownHosts=self.knownHosts,
ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
# Exercising fallback requires a failed authentication attempt. Allow
# one.
self.factory.attemptsBeforeDisconnect += 1
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
pump.pump()
# The server logs the channel open failure - this is expected.
errors = self.flushLoggedErrors(ConchError)
self.assertIn(
'unknown channel', (errors[0].value.data, errors[0].value.value))
self.assertEqual(1, len(errors))
# Now deal with the results on the endpoint side.
f = self.failureResultOf(connected)
f.trap(ConchError)
self.assertEqual(b'unknown channel', f.value.value)
# Nothing useful can be done with the connection at this point, so the
# endpoint should close it.
self.assertTrue(client.transport.disconnecting) | If the SSH server does not accept any of the specified SSH keys, the
specified password is tried. | test_authenticationFallback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_publicKeyAuthentication(self):
"""
If L{SSHCommandClientEndpoint} is initialized with any private keys, it
will try to use them to authenticate with the SSH server.
"""
key = Key.fromString(privateDSA_openssh)
self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
keys=[key], knownHosts=self.knownHosts, ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
protocol = self.successResultOf(connected)
self.assertIsNotNone(protocol.transport) | If L{SSHCommandClientEndpoint} is initialized with any private keys, it
will try to use them to authenticate with the SSH server. | test_publicKeyAuthentication | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_skipPasswordAuthentication(self):
"""
If the password is not specified, L{SSHCommandClientEndpoint} doesn't
try it as an authentication mechanism.
"""
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
knownHosts=self.knownHosts, ui=FixedResponseUI(False))
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
pump.pump()
# Now deal with the results on the endpoint side.
f = self.failureResultOf(connected)
f.trap(AuthenticationFailed)
# Nothing useful can be done with the connection at this point, so the
# endpoint should close it.
self.assertTrue(client.transport.disconnecting) | If the password is not specified, L{SSHCommandClientEndpoint} doesn't
try it as an authentication mechanism. | test_skipPasswordAuthentication | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_agentAuthentication(self):
"""
If L{SSHCommandClientEndpoint} is initialized with an
L{SSHAgentClient}, the agent is used to authenticate with the SSH
server. Once the connection with the SSH server has concluded, the
connection to the agent is disconnected.
"""
key = Key.fromString(privateRSA_openssh)
agentServer = SSHAgentServer()
agentServer.factory = Factory()
agentServer.factory.keys = {key.blob(): (key, b"")}
self.setupKeyChecker(self.portal, {self.user: privateRSA_openssh})
agentEndpoint = SingleUseMemoryEndpoint(agentServer)
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
knownHosts=self.knownHosts, ui=FixedResponseUI(False),
agentEndpoint=agentEndpoint)
self.realm.channelLookup[b'session'] = WorkingExecSession
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
# Let the agent client talk with the agent server and the ssh client
# talk with the ssh server.
for i in range(14):
agentEndpoint.pump.pump()
pump.pump()
protocol = self.successResultOf(connected)
self.assertIsNotNone(protocol.transport)
# Ensure the connection with the agent is cleaned up after the
# connection with the server is lost.
self.loseConnectionToServer(server, client, protocol, pump)
self.assertTrue(client.transport.disconnecting)
self.assertTrue(agentEndpoint.pump.clientIO.disconnecting) | If L{SSHCommandClientEndpoint} is initialized with an
L{SSHAgentClient}, the agent is used to authenticate with the SSH
server. Once the connection with the SSH server has concluded, the
connection to the agent is disconnected. | test_agentAuthentication | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_loseConnection(self):
"""
The transport connected to the protocol has a C{loseConnection} method
which causes the channel in which the command is running to close and
the overall connection to be closed.
"""
self.realm.channelLookup[b'session'] = WorkingExecSession
endpoint = self.create()
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.finishConnection()
protocol = self.successResultOf(connected)
self.loseConnectionToServer(server, client, protocol, pump)
# Nothing useful can be done with the connection at this point, so the
# endpoint should close it.
self.assertTrue(client.transport.disconnecting) | The transport connected to the protocol has a C{loseConnection} method
which causes the channel in which the command is running to close and
the overall connection to be closed. | test_loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def setUp(self):
"""
Configure an SSH server with password authentication enabled for a
well-known (to the tests) account.
"""
SSHCommandClientEndpointTestsMixin.setUp(self)
knownHosts = KnownHostsFile(FilePath(self.mktemp()))
knownHosts.addHostKey(
self.hostname, self.factory.publicKeys[b'ssh-rsa'])
knownHosts.addHostKey(
networkString(self.serverAddress.host),
self.factory.publicKeys[b'ssh-rsa'])
self.endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
password=self.password, knownHosts=knownHosts,
ui=FixedResponseUI(False)) | Configure an SSH server with password authentication enabled for a
well-known (to the tests) account. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def create(self):
"""
Create and return a new L{SSHCommandClientEndpoint} using the
C{existingConnection} constructor.
"""
factory = Factory()
factory.protocol = Protocol
connected = self.endpoint.connect(factory)
# Please, let me in. This kinda sucks.
channelLookup = self.realm.channelLookup.copy()
try:
self.realm.channelLookup[b'session'] = WorkingExecSession
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
finally:
self.realm.channelLookup.clear()
self.realm.channelLookup.update(channelLookup)
self._server = server
self._client = client
self._pump = pump
protocol = self.successResultOf(connected)
connection = protocol.transport.conn
return SSHCommandClientEndpoint.existingConnection(
connection, b"/bin/ls -l") | Create and return a new L{SSHCommandClientEndpoint} using the
C{existingConnection} constructor. | create | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def finishConnection(self):
"""
Give back the connection established in L{create} over which the new
command channel being tested will exchange data.
"""
# The connection was set up and the first command channel set up, but
# some more I/O needs to happen for the second command channel to be
# ready. Make that I/O happen before giving back the objects.
self._pump.pump()
self._pump.pump()
self._pump.pump()
self._pump.pump()
return self._server, self._client, self._pump | Give back the connection established in L{create} over which the new
command channel being tested will exchange data. | finishConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def assertClientTransportState(self, client, immediateClose):
"""
Assert that the transport for the given protocol is still connected.
L{SSHCommandClientEndpoint.existingConnection} re-uses an SSH connected
created by some other code, so other code is responsible for cleaning
it up.
"""
self.assertFalse(client.transport.disconnecting)
self.assertFalse(client.transport.aborted) | Assert that the transport for the given protocol is still connected.
L{SSHCommandClientEndpoint.existingConnection} re-uses an SSH connected
created by some other code, so other code is responsible for cleaning
it up. | assertClientTransportState | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_interface(self):
"""
L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator}.
"""
self.assertTrue(
verifyClass(_ISSHConnectionCreator, _ExistingConnectionHelper)) | L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_secureConnection(self):
"""
L{_ExistingConnectionHelper.secureConnection} returns a L{Deferred}
which fires with whatever object was fed to
L{_ExistingConnectionHelper.__init__}.
"""
result = object()
helper = _ExistingConnectionHelper(result)
self.assertIs(
result, self.successResultOf(helper.secureConnection())) | L{_ExistingConnectionHelper.secureConnection} returns a L{Deferred}
which fires with whatever object was fed to
L{_ExistingConnectionHelper.__init__}. | test_secureConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_cleanupConnectionNotImmediately(self):
"""
L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
existing connection if called with C{immediate} set to C{False}.
"""
helper = _ExistingConnectionHelper(object())
# Bit hard to test nothing happens. However, since object() has no
# relevant methods or attributes, if the code is incorrect we can
# expect an AttributeError.
helper.cleanupConnection(object(), False) | L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
existing connection if called with C{immediate} set to C{False}. | test_cleanupConnectionNotImmediately | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_cleanupConnectionImmediately(self):
"""
L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
existing connection if called with C{immediate} set to C{True}.
"""
helper = _ExistingConnectionHelper(object())
# Bit hard to test nothing happens. However, since object() has no
# relevant methods or attributes, if the code is incorrect we can
# expect an AttributeError.
helper.cleanupConnection(object(), True) | L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
existing connection if called with C{immediate} set to C{True}. | test_cleanupConnectionImmediately | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def __init__(self, contents):
"""
@param contents: L{bytes} which will be the contents of the
L{_ReadFile} this path can open.
"""
self.contents = contents | @param contents: L{bytes} which will be the contents of the
L{_ReadFile} this path can open. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def open(self, mode):
"""
If the mode is r+, return a L{_ReadFile} with the contents given to
this path's initializer.
@raise OSError: If the mode is unsupported.
@return: A L{_ReadFile} instance
"""
if mode == "rb+":
return _ReadFile(self.contents)
raise OSError(ENOSYS, "Function not implemented") | If the mode is r+, return a L{_ReadFile} with the contents given to
this path's initializer.
@raise OSError: If the mode is unsupported.
@return: A L{_ReadFile} instance | open | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_interface(self):
"""
L{_NewConnectionHelper} implements L{_ISSHConnectionCreator}.
"""
self.assertTrue(
verifyClass(_ISSHConnectionCreator, _NewConnectionHelper)) | L{_NewConnectionHelper} implements L{_ISSHConnectionCreator}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_defaultPath(self):
"""
The default I{known_hosts} path is I{~/.ssh/known_hosts}.
"""
self.assertEqual(
"~/.ssh/known_hosts", _NewConnectionHelper._KNOWN_HOSTS) | The default I{known_hosts} path is I{~/.ssh/known_hosts}. | test_defaultPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_defaultKnownHosts(self):
"""
L{_NewConnectionHelper._knownHosts} is used to create a
L{KnownHostsFile} if one is not passed to the initializer.
"""
result = object()
self.patch(_NewConnectionHelper, '_knownHosts', lambda cls: result)
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None)
self.assertIs(result, helper.knownHosts) | L{_NewConnectionHelper._knownHosts} is used to create a
L{KnownHostsFile} if one is not passed to the initializer. | test_defaultKnownHosts | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_readExisting(self):
"""
Existing entries in the I{known_hosts} file are reflected by the
L{KnownHostsFile} created by L{_NewConnectionHelper} when none is
supplied to it.
"""
key = CommandFactory().publicKeys[b'ssh-rsa']
path = FilePath(self.mktemp())
knownHosts = KnownHostsFile(path)
knownHosts.addHostKey(b"127.0.0.1", key)
knownHosts.save()
msg("Created known_hosts file at %r" % (path.path,))
# Unexpand ${HOME} to make sure ~ syntax is respected.
home = os.path.expanduser("~/")
default = path.path.replace(home, "~/")
self.patch(_NewConnectionHelper, "_KNOWN_HOSTS", default)
msg("Patched _KNOWN_HOSTS with %r" % (default,))
loaded = _NewConnectionHelper._knownHosts()
self.assertTrue(loaded.hasHostKey(b"127.0.0.1", key)) | Existing entries in the I{known_hosts} file are reflected by the
L{KnownHostsFile} created by L{_NewConnectionHelper} when none is
supplied to it. | test_readExisting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_defaultConsoleUI(self):
"""
If L{None} is passed for the C{ui} parameter to
L{_NewConnectionHelper}, a L{ConsoleUI} is used.
"""
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None)
self.assertIsInstance(helper.ui, ConsoleUI) | If L{None} is passed for the C{ui} parameter to
L{_NewConnectionHelper}, a L{ConsoleUI} is used. | test_defaultConsoleUI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_ttyConsoleUI(self):
"""
If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
and /dev/tty is available, the L{ConsoleUI} used is associated with
/dev/tty.
"""
tty = _PTYPath(b"yes")
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None, tty)
result = self.successResultOf(helper.ui.prompt(b"does this work?"))
self.assertTrue(result) | If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
and /dev/tty is available, the L{ConsoleUI} used is associated with
/dev/tty. | test_ttyConsoleUI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_nottyUI(self):
"""
If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
and /dev/tty is not available, the L{ConsoleUI} used is associated with
some file which always produces a C{b"no"} response.
"""
tty = FilePath(self.mktemp())
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None, tty)
result = self.successResultOf(helper.ui.prompt(b"did this break?"))
self.assertFalse(result) | If L{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
and /dev/tty is not available, the L{ConsoleUI} used is associated with
some file which always produces a C{b"no"} response. | test_nottyUI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_defaultTTYFilename(self):
"""
If not passed the name of a tty in the filesystem,
L{_NewConnectionHelper} uses C{b"/dev/tty"}.
"""
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None)
self.assertEqual(FilePath(b"/dev/tty"), helper.tty) | If not passed the name of a tty in the filesystem,
L{_NewConnectionHelper} uses C{b"/dev/tty"}. | test_defaultTTYFilename | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_cleanupConnectionNotImmediately(self):
"""
L{_NewConnectionHelper.cleanupConnection} closes the transport cleanly
if called with C{immediate} set to C{False}.
"""
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None)
connection = SSHConnection()
connection.transport = StringTransport()
helper.cleanupConnection(connection, False)
self.assertTrue(connection.transport.disconnecting) | L{_NewConnectionHelper.cleanupConnection} closes the transport cleanly
if called with C{immediate} set to C{False}. | test_cleanupConnectionNotImmediately | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def abortConnection(self):
"""
Abort the connection.
"""
self.aborted = True | Abort the connection. | test_cleanupConnectionImmediately.abortConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_cleanupConnectionImmediately(self):
"""
L{_NewConnectionHelper.cleanupConnection} closes the transport with
C{abortConnection} if called with C{immediate} set to C{True}.
"""
class Abortable:
aborted = False
def abortConnection(self):
"""
Abort the connection.
"""
self.aborted = True
helper = _NewConnectionHelper(
None, None, None, None, None, None, None, None, None, None)
connection = SSHConnection()
connection.transport = SSHClientTransport()
connection.transport.transport = Abortable()
helper.cleanupConnection(connection, True)
self.assertTrue(connection.transport.transport.aborted) | L{_NewConnectionHelper.cleanupConnection} closes the transport with
C{abortConnection} if called with C{immediate} set to C{True}. | test_cleanupConnectionImmediately | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_endpoints.py | MIT |
def test_getPublicKeys(self):
"""
L{OpenSSHFactory.getPublicKeys} should return the available public keys
in the data directory
"""
keys = self.factory.getPublicKeys()
self.assertEqual(len(keys), 1)
keyTypes = keys.keys()
self.assertEqual(list(keyTypes), [b'ssh-rsa']) | L{OpenSSHFactory.getPublicKeys} should return the available public keys
in the data directory | test_getPublicKeys | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | MIT |
def test_getPrivateKeys(self):
"""
Will return the available private keys in the data directory, ignoring
key files which failed to be loaded.
"""
keys = self.factory.getPrivateKeys()
self.assertEqual(len(keys), 2)
keyTypes = keys.keys()
self.assertEqual(set(keyTypes), set([b'ssh-rsa', b'ssh-dss']))
self.assertEqual(self.mockos.seteuidCalls, [])
self.assertEqual(self.mockos.setegidCalls, []) | Will return the available private keys in the data directory, ignoring
key files which failed to be loaded. | test_getPrivateKeys | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | MIT |
def test_getPrivateKeysAsRoot(self):
"""
L{OpenSSHFactory.getPrivateKeys} should switch to root if the keys
aren't readable by the current user.
"""
keyFile = self.keysDir.child("ssh_host_two_key")
# Fake permission error by changing the mode
keyFile.chmod(0000)
self.addCleanup(keyFile.chmod, 0o777)
# And restore the right mode when seteuid is called
savedSeteuid = os.seteuid
def seteuid(euid):
keyFile.chmod(0o777)
return savedSeteuid(euid)
self.patch(os, "seteuid", seteuid)
keys = self.factory.getPrivateKeys()
self.assertEqual(len(keys), 2)
keyTypes = keys.keys()
self.assertEqual(set(keyTypes), set([b'ssh-rsa', b'ssh-dss']))
self.assertEqual(self.mockos.seteuidCalls, [0, os.geteuid()])
self.assertEqual(self.mockos.setegidCalls, [0, os.getegid()]) | L{OpenSSHFactory.getPrivateKeys} should switch to root if the keys
aren't readable by the current user. | test_getPrivateKeysAsRoot | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | MIT |
def test_getPrimes(self):
"""
L{OpenSSHFactory.getPrimes} should return the available primes
in the moduli directory.
"""
primes = self.factory.getPrimes()
self.assertEqual(primes, {
2048: [getDHGeneratorAndPrime(b"diffie-hellman-group14-sha1")],
}) | L{OpenSSHFactory.getPrimes} should return the available primes
in the moduli directory. | test_getPrimes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_openssh_compat.py | MIT |
def lookupSubsystem(self, name, data):
"""
If the other side requests the 'subsystem' subsystem, allow it by
returning a MockProtocol to implement it. Otherwise raise an assertion.
"""
assert name == b'subsystem'
return MockProtocol() | If the other side requests the 'subsystem' subsystem, allow it by
returning a MockProtocol to implement it. Otherwise raise an assertion. | lookupSubsystem | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def lookupSubsystem(self, name, data):
"""
If the user requests the TestSubsystem subsystem, connect them to a
MockProtocol. If they request neither, then None is returned which is
interpreted by SSHSession as a failure.
"""
if name == b'TestSubsystem':
self.subsystem = MockProtocol()
self.subsystem.packetData = data
return self.subsystem | If the user requests the TestSubsystem subsystem, connect them to a
MockProtocol. If they request neither, then None is returned which is
interpreted by SSHSession as a failure. | lookupSubsystem | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def __init__(self, avatar):
"""
Store the avatar we're adapting.
"""
self.avatar = avatar
self.shellProtocol = None | Store the avatar we're adapting. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def getPty(self, terminal, window, modes):
"""
If the terminal is 'bad', fail. Otherwise, store the information in
the ptyRequest variable.
"""
if terminal != b'bad':
self.ptyRequest = (terminal, window, modes)
else:
raise RuntimeError('not getting a pty') | If the terminal is 'bad', fail. Otherwise, store the information in
the ptyRequest variable. | getPty | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def windowChanged(self, window):
"""
If all the window sizes are 0, fail. Otherwise, store the size in the
windowChange variable.
"""
if window == (0, 0, 0, 0):
raise RuntimeError('not changing the window size')
else:
self.windowChange = window | If all the window sizes are 0, fail. Otherwise, store the size in the
windowChange variable. | windowChanged | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def openShell(self, pp):
"""
If we have gotten a shell request before, fail. Otherwise, store the
process protocol in the shellProtocol variable, connect it to the
EchoTransport and store that as shellTransport.
"""
if self.shellProtocol is not None:
raise RuntimeError('not getting a shell this time')
else:
self.shellProtocol = pp
self.shellTransport = EchoTransport(pp) | If we have gotten a shell request before, fail. Otherwise, store the
process protocol in the shellProtocol variable, connect it to the
EchoTransport and store that as shellTransport. | openShell | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def execCommand(self, pp, command):
"""
If the command is 'true', store the command, the process protocol, and
the transport we connect to the process protocol. Otherwise, just
store the command and raise an error.
"""
self.execCommandLine = command
if command == b'success':
self.execProtocol = pp
elif command[:6] == b'repeat':
self.execProtocol = pp
self.execTransport = EchoTransport(pp)
pp.outReceived(command[7:])
else:
raise RuntimeError('not getting a command') | If the command is 'true', store the command, the process protocol, and
the transport we connect to the process protocol. Otherwise, just
store the command and raise an error. | execCommand | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def eofReceived(self):
"""
Note that EOF has been received.
"""
self.gotEOF = True | Note that EOF has been received. | eofReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def closed(self):
"""
Note that close has been received.
"""
self.gotClosed = True | Note that close has been received. | closed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def __init__(self, processProtocol):
"""
Initialize our instance variables.
@param processProtocol: a C{ProcessProtocol} to connect to ourself.
"""
self.proto = processProtocol
self.closed = False
self.data = b''
processProtocol.makeConnection(self) | Initialize our instance variables.
@param processProtocol: a C{ProcessProtocol} to connect to ourself. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def write(self, data):
"""
We got some data. Give it back to our C{ProcessProtocol} with
a newline attached. Disconnect if there's a null byte.
"""
self.data += data
self.proto.outReceived(data)
self.proto.outReceived(b'\r\n')
if b'\x00' in data: # mimic 'exit' for the shell test
self.loseConnection() | We got some data. Give it back to our C{ProcessProtocol} with
a newline attached. Disconnect if there's a null byte. | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def loseConnection(self):
"""
If we're asked to disconnect (and we haven't already) shut down
the C{ProcessProtocol} with a 0 exit code.
"""
if self.closed:
return
self.closed = 1
self.proto.inConnectionLost()
self.proto.outConnectionLost()
self.proto.errConnectionLost()
self.proto.processEnded(failure.Failure(
error.ProcessTerminated(0, None, None))) | If we're asked to disconnect (and we haven't already) shut down
the C{ProcessProtocol} with a 0 exit code. | loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def connectionMade(self):
"""
Set up the instance variables. If we have any packetData, send it
along.
"""
self.data = b''
self.open = True
self.reason = None
if self.packetData:
self.dataReceived(self.packetData) | Set up the instance variables. If we have any packetData, send it
along. | connectionMade | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def dataReceived(self, data):
"""
Store the received data and write it back with a tilde appended.
The tilde is appended so that the tests can verify that we processed
the data.
"""
self.data += data
self.transport.write(data + b'~') | Store the received data and write it back with a tilde appended.
The tilde is appended so that the tests can verify that we processed
the data. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
def connectionLost(self, reason):
"""
Close the protocol and store the reason.
"""
self.open = False
self.reason = reason | Close the protocol and store the reason. | connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_session.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.