1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
|
# Copyright (c) 2016-2020 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
# GNU General Public License, Version 2.0, or any later versions of
# that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""Unit tests for AsyncSSH stream API"""
import asyncio
import re
import asyncssh
from .server import Server, ServerTestCase
from .util import asynctest, echo
class _StreamServer(Server):
"""Server for testing the AsyncSSH stream API"""
async def _begin_session(self, stdin, stdout, stderr):
"""Begin processing a new session"""
# pylint: disable=no-self-use
action = stdin.channel.get_command()
if not action:
action = 'echo'
if action == 'echo':
await echo(stdin, stdout)
elif action == 'echo_stderr':
await echo(stdin, stdout, stderr)
elif action == 'close':
await stdin.read(1)
stdout.write('\n')
elif action == 'disconnect':
stdout.write(await stdin.read(1))
raise asyncssh.ConnectionLost('Connection lost')
elif action == 'custom_disconnect':
await stdin.read(1)
raise asyncssh.DisconnectError(99, 'Disconnect')
elif action == 'partial':
try:
await stdin.readexactly(10)
except asyncio.IncompleteReadError as exc:
stdout.write(exc.partial)
try:
await stdin.read()
except asyncssh.TerminalSizeChanged:
pass
stdout.write(await stdin.readexactly(5))
else:
stdin.channel.exit(255)
stdin.channel.close()
await stdin.channel.wait_closed()
def _begin_session_non_async(self, stdin, stdout, stderr):
"""Non-async version of session handler"""
self._conn.create_task(self._begin_session(stdin, stdout, stderr))
def begin_auth(self, username):
"""Handle client authentication request"""
return False
def session_requested(self):
"""Handle a request to create a new session"""
username = self._conn.get_extra_info('username')
if username == 'non_async':
return self._begin_session_non_async
elif username != 'no_channels':
return self._begin_session
else:
return False
class _UpstreamForwardingServer(Server):
"""Server for testing forwarding between SSH connections"""
def __init__(self, upstream_conn):
super().__init__()
self._upstream_conn = upstream_conn
def session_requested(self):
"""Handle a request to create a new session"""
return self._upstream_conn
class _TestStream(ServerTestCase):
"""Unit tests for AsyncSSH stream API"""
@classmethod
async def start_server(cls):
"""Start an SSH server for the tests to use"""
return await cls.create_server(_StreamServer)
async def _check_session(self, conn, large_block=False):
"""Open a session and test if an input line is echoed back"""
stdin, stdout, stderr = await conn.open_session('echo_stderr')
if large_block:
data = 4 * [1025*1024*'\0']
else:
data = [str(id(self))]
stdin.writelines(data)
await stdin.drain()
self.assertTrue(stdin.can_write_eof())
self.assertFalse(stdin.is_closing())
stdin.write_eof()
self.assertTrue(stdin.is_closing())
stdout_data, stderr_data = await asyncio.gather(stdout.read(),
stderr.read())
data = ''.join(data)
self.assertEqual(data, stdout_data)
self.assertEqual(data, stderr_data)
await stdin.drain()
stdin.close()
await stdin.channel.wait_closed()
@asynctest
async def test_shell(self):
"""Test starting a shell"""
async with self.connect() as conn:
await self._check_session(conn)
@asynctest
async def test_upstream_shell(self):
"""Test upstream forwarding of a shell request"""
def upstream_server():
"""Return a server capable of forwarding between SSH connections"""
return _UpstreamForwardingServer(upstream_conn)
async with self.connect() as upstream_conn:
upstream_listener = await self.create_server(upstream_server)
upstream_port = upstream_listener.get_port()
async with self.connect('127.0.0.1', upstream_port) as conn:
await self._check_session(conn)
upstream_listener.close()
@asynctest
async def test_shell_failure(self):
"""Test failure to start a shell"""
async with self.connect(username='no_channels') as conn:
with self.assertRaises(asyncssh.ChannelOpenError):
await conn.open_session()
@asynctest
async def test_shell_non_async(self):
"""Test starting a shell using non-async handler"""
async with self.connect(username='non_async') as conn:
await self._check_session(conn)
@asynctest
async def test_large_block(self):
"""Test sending and receiving a large block of data"""
async with self.connect() as conn:
await self._check_session(conn, large_block=True)
@asynctest
async def test_feed(self):
"""Test feeding data into an SSHReader"""
async with self.connect() as conn:
_, stdout, stderr = await conn.open_session()
stdout.feed_data('stdout')
stderr.feed_data('stderr')
stdout.feed_eof()
self.assertEqual(await stdout.read(), 'stdout')
self.assertEqual(await stderr.read(), 'stderr')
@asynctest
async def test_async_iterator(self):
"""Test reading lines by using SSHReader as an async iterator"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
data = ['Line 1\n', 'Line 2\n']
stdin.writelines(data)
stdin.write_eof()
async for line in stdout:
self.assertEqual(line, data.pop(0))
self.assertEqual(data, [])
@asynctest
async def test_write_broken_pipe(self):
"""Test close while we're writing"""
async with self.connect() as conn:
stdin, _, _ = await conn.open_session('close')
stdin.write(4*1024*1024*'\0')
with self.assertRaises((ConnectionError, asyncssh.ConnectionLost)):
await stdin.drain()
@asynctest
async def test_write_disconnect(self):
"""Test disconnect while we're writing"""
async with self.connect() as conn:
stdin, _, _ = await conn.open_session('disconnect')
stdin.write(6*1024*1024*'\0')
with self.assertRaises((ConnectionError, asyncssh.ConnectionLost)):
await stdin.drain()
@asynctest
async def test_read_exception(self):
"""Test read returning an exception"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session('disconnect')
stdin.write('\0')
self.assertEqual((await stdout.read()), '\0')
with self.assertRaises(asyncssh.ConnectionLost):
await stdout.read(1)
stdin.close()
@asynctest
async def test_readline_exception(self):
"""Test readline returning an exception"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session('disconnect')
stdin.write('\0')
self.assertEqual((await stdout.readline()), '\0')
with self.assertRaises(asyncssh.ConnectionLost):
await stdout.readline()
@asynctest
async def test_readexactly_partial_exception(self):
"""Test readexactly returning partial data before an exception"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session('partial')
stdin.write('abcde')
stdout.channel.change_terminal_size(80, 24)
stdin.write('fghij')
self.assertEqual((await stdout.read()), 'abcdefghij')
@asynctest
async def test_custom_disconnect(self):
"""Test receiving a custom disconnect message"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session('custom_disconnect')
stdin.write('\0')
with self.assertRaises(asyncssh.DisconnectError) as exc:
await stdout.read()
self.assertEqual(exc.exception.code, 99)
self.assertEqual(exc.exception.reason, 'Disconnect (error 99)')
@asynctest
async def test_readuntil_bigger_than_window(self):
"""Test readuntil getting data bigger than the receive window"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write(4*1024*1024*'\0')
with self.assertRaises(asyncio.IncompleteReadError) as exc:
await stdout.readuntil('\n')
self.assertEqual(exc.exception.partial,
stdin.channel.get_recv_window()*'\0')
stdin.close()
await conn.wait_closed()
@asynctest
async def test_readline_timeout(self):
"""Test receiving a timeout while calling readline"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write('ab')
try:
await asyncio.wait_for(stdout.readline(), timeout=0.1)
except asyncio.TimeoutError:
pass
stdin.write('c\n')
self.assertEqual((await stdout.readline()), 'abc\n')
stdin.close()
@asynctest
async def test_pause_read(self):
"""Test pause reading"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write(6*1024*1024*'\0')
await asyncio.sleep(0.01)
await stdout.read(1)
await asyncio.sleep(0.01)
await stdout.read(1)
@asynctest
async def test_readuntil(self):
"""Test readuntil with multi-character separator"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write('abc\r')
await asyncio.sleep(0.01)
stdin.write('\ndef')
await asyncio.sleep(0.01)
stdin.write('\r\n')
await asyncio.sleep(0.01)
stdin.write('ghi')
stdin.write_eof()
self.assertEqual((await stdout.readuntil('\r\n')), 'abc\r\n')
self.assertEqual((await stdout.readuntil('\r\n')), 'def\r\n')
with self.assertRaises(asyncio.IncompleteReadError) as exc:
await stdout.readuntil('\r\n')
self.assertEqual(exc.exception.partial, 'ghi')
stdin.close()
@asynctest
async def test_readuntil_separator_list(self):
"""Test readuntil with a list of separators"""
seps = ('+', '-', '\r\n')
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write('ab')
await asyncio.sleep(0.01)
stdin.write('c+d')
await asyncio.sleep(0.01)
stdin.write('ef-gh')
await asyncio.sleep(0.01)
stdin.write('i\r')
await asyncio.sleep(0.01)
stdin.write('\n')
stdin.write_eof()
self.assertEqual((await stdout.readuntil(seps)), 'abc+')
self.assertEqual((await stdout.readuntil(seps)), 'def-')
self.assertEqual((await stdout.readuntil(seps)), 'ghi\r\n')
stdin.close()
@asynctest
async def test_readuntil_empty_separator(self):
"""Test readuntil with empty separator"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
with self.assertRaises(ValueError):
await stdout.readuntil('')
stdin.close()
@asynctest
async def test_readuntil_regex(self):
"""Test readuntil with a regex pattern"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
stdin.write("hello world\nhello world")
output = await stdout.readuntil(
re.compile('hello world'), len('hello world')
)
self.assertEqual(output, "hello world")
output = await stdout.readuntil(
re.compile('hello world'), len('hello world')
)
self.assertEqual(output, "\nhello world")
stdin.close()
await conn.wait_closed()
@asynctest
async def test_abort(self):
"""Test abort on a channel"""
async with self.connect() as conn:
stdin, _, _ = await conn.open_session()
stdin.channel.abort()
@asynctest
async def test_abort_closed(self):
"""Test abort on an already-closed channel"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session('close')
stdin.write('\n')
await stdout.read()
stdin.channel.abort()
@asynctest
async def test_get_extra_info(self):
"""Test get_extra_info on streams"""
async with self.connect() as conn:
stdin, stdout, _ = await conn.open_session()
self.assertEqual(stdin.get_extra_info('connection'),
stdout.get_extra_info('connection'))
stdin.close()
@asynctest
async def test_unknown_action(self):
"""Test unknown action"""
async with self.connect() as conn:
stdin, _, _ = await conn.open_session('unknown')
await stdin.channel.wait_closed()
self.assertEqual(stdin.channel.get_exit_status(), 255)
|