import inspect import logging import os import shutil import subprocess import time from datetime import timedelta, datetime from typing import Tuple, List import packaging.version
import pytest import websockets from pyhttpd.result import ExecResult from pyhttpd.ws_util import WsFrameReader, WsFrame
def ws_run(env: H2TestEnv, path, authority=None, do_input=None, inbytes=None,
send_close=True, timeout=5, scenario='ws-stdin',
wait_close: float = 0.0) -> Tuple[ExecResult, List[str], List[WsFrame]]: """ Run the h2ws test client in various scenarios with given input and
timings.
:param env: the test environment
:param path: the path on the Apache server to CONNECt to
:param authority: the host:port to use as
:param do_input: a Callable for sending input to h2ws
:param inbytes: fixed bytes to send to h2ws, unless do_input is given
:param send_close: send a CLOSE WebSockets frame at the end
:param timeout: timeout for waiting on h2ws to finish
:param scenario: name of scenario h2ws should run in
:param wait_close: time to wait before closing input
:return: ExecResult with exit_code/stdout/stderr of run """
h2ws = os.path.join(env.clients_dir, 'h2ws') ifnot os.path.exists(h2ws):
pytest.fail(f'test client not build: {h2ws}') if authority isNone:
authority = f'cgi.{env.http_tld}:{env.http_port}'
args = [
h2ws, '-vv', '-c', f'localhost:{env.http_port}',
f'ws://{authority}{path}',
scenario
] # we write all output to files, because we manipulate input timings # and would run in deadlock situations with h2ws blocking operations # because its output is not consumed
start = datetime.now() with open(f'{env.gen_dir}/h2ws.stdout', 'w') as fdout: with open(f'{env.gen_dir}/h2ws.stderr', 'w') as fderr:
proc = subprocess.Popen(args=args, stdin=subprocess.PIPE,
stdout=fdout, stderr=fderr) if do_input isnotNone:
do_input(proc) elif inbytes isnotNone:
proc.stdin.write(inbytes)
proc.stdin.flush()
if wait_close > 0:
time.sleep(wait_close) try:
inbytes = WsFrame.client_close(code=1000).to_network() if send_close elseNone
proc.communicate(input=inbytes, timeout=timeout) except subprocess.TimeoutExpired:
log.error(f'ws_run: timeout expired')
proc.kill()
proc.communicate(timeout=timeout)
end = datetime.now()
lines = open(f'{env.gen_dir}/h2ws.stdout').read().splitlines()
infos = [line for line in lines if line.startswith('[1] ')]
hex_content = ' '.join([line for line in lines ifnot line.startswith('[1] ')]) if len(infos) > 0 and infos[0] == '[1] :status: 200':
frames = WsFrameReader.parse(bytearray.fromhex(hex_content)) else:
frames = bytearray.fromhex(hex_content) return ExecResult(args=args, exit_code=proc.returncode,
stdout=b'', stderr=b'', duration=end - start), infos, frames
@pytest.mark.skipif(condition=H2TestEnv.is_unsupported, reason="mod_http2 not supported here")
@pytest.mark.skipif(condition=not H2TestEnv().httpd_is_at_least("2.4.60"),
reason=f'need at least httpd 2.4.60 for this')
@pytest.mark.skipif(condition=ws_version < ws_version_min,
reason=f'websockets is {ws_version}, need at least {ws_version_min}') class TestWebSockets:
@pytest.fixture(autouse=True, scope='class') def _class_scope(self, env): # Apache config that CONNECT proxies a WebSocket server for paths starting # with '/ws/' # The WebSocket server is started in pytest fixture 'ws_server' below.
conf = H2Conf(env, extras={ 'base': [ 'Timeout 1',
],
f'cgi.{env.http_tld}': [
f' H2WebSockets on',
f' ProxyPass /ws/ http://127.0.0.1:{env.ws_port}/ \\',
f' upgrade=websocket timeout=10',
f' ReadBufferSize 65535'
]
})
conf.add_vhost_cgi(proxy_self=True, h2proxy_self=True).install()
conf.add_vhost_test1(proxy_self=True, h2proxy_self=True).install() assert env.apache_restart() == 0
def ws_check_alive(self, env, timeout=5):
url = f'http://localhost:{env.ws_port}/'
end = datetime.now() + timedelta(seconds=timeout) while datetime.now() < end:
r = env.curl_get(url, 5) if r.exit_code == 0: returnTrue
time.sleep(.1) returnFalse
def _rmrf(self, path): if os.path.exists(path): return shutil.rmtree(path)
@pytest.fixture(autouse=True, scope='class') def ws_server(self, env): # Run our python websockets server that has some special behaviour # for the different path to CONNECT to.
run_dir = os.path.join(env.gen_dir, 'ws-server')
err_file = os.path.join(run_dir, 'stderr')
self._rmrf(run_dir)
self._mkpath(run_dir) with open(err_file, 'w') as cerr:
cmd = os.path.join(os.path.dirname(inspect.getfile(TestWebSockets)), 'ws_server.py')
args = ['python3', cmd, '--port', str(env.ws_port)]
p = subprocess.Popen(args=args, cwd=run_dir, stderr=cerr,
stdout=cerr) ifnot self.ws_check_alive(env):
p.kill()
p.wait()
pytest.fail(f'ws_server did not start. stderr={open(err_file).readlines()}') yield
p.terminate()
# CONNECT to a URL path that does not exist on the server def test_h2_800_03_not_found(self, env: H2TestEnv, ws_server):
r, infos, frames = ws_run(env, path='/does-not-exist') assert r.exit_code == 0, f'{r}' assert infos == ['[1] :status: 404', '[1] EOF'] or infos == ['[1] :status: 404', '[1] EOF', '[1] RST'], f'{r}'
# CONNECT to a URL path that is a normal HTTP file resource # we do not want to receive the body of that def test_h2_800_04_non_ws_resource(self, env: H2TestEnv, ws_server):
r, infos, frames = ws_run(env, path='/alive.json') assert r.exit_code == 0, f'{r}' assert infos == ['[1] :status: 502', '[1] EOF'] or infos == ['[1] :status: 502', '[1] EOF', '[1] RST'], f'{r}' assert frames == b''
# CONNECT to a URL path that sends a delayed HTTP response body # we do not want to receive the body of that def test_h2_800_05_non_ws_delay_resource(self, env: H2TestEnv, ws_server):
r, infos, frames = ws_run(env, path='/h2test/error?body_delay=100ms') assert r.exit_code == 0, f'{r}' assert infos == ['[1] :status: 502', '[1] EOF'] or infos == ['[1] :status: 502', '[1] EOF', '[1] RST'], f'{r}' assert frames == b''
# CONNECT and send several PINGs with a delay of 200ms def test_h2_800_11_ws_timed_pings(self, env: H2TestEnv, ws_server):
frame_count = 5
ping = WsFrame.client_ping(b'12345')
def do_send(proc): for _ in range(frame_count): try:
proc.stdin.write(ping.to_network())
proc.stdin.flush()
proc.wait(timeout=0.2) except subprocess.TimeoutExpired: pass
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.