Skip to content

Commit 1806fa8

Browse files
committed
Merge remote-tracking branch 'root/master' into blacken
2 parents 97fae8e + f5b2014 commit 1806fa8

File tree

12 files changed

+712
-391
lines changed

12 files changed

+712
-391
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ lint:
1515
$(PYTHON) -m pylint trio_websocket/ tests/ autobahn/ examples/
1616

1717
typecheck:
18-
$(PYTHON) -m mypy --explicit-package-bases trio_websocket tests autobahn examples
18+
$(PYTHON) -m mypy
1919

2020
publish:
2121
rm -fr build dist .egg trio_websocket.egg-info

autobahn/client.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,21 @@
1818
logger = logging.getLogger("client")
1919

2020

21-
async def get_case_count(url):
21+
async def get_case_count(url: str) -> int:
2222
url = url + "/getCaseCount"
2323
async with open_websocket_url(url) as conn:
2424
case_count = await conn.get_message()
2525
logger.info("Case count=%s", case_count)
2626
return int(case_count)
2727

2828

29-
async def get_case_info(url, case):
29+
async def get_case_info(url: str, case: str) -> object:
3030
url = f"{url}/getCaseInfo?case={case}"
3131
async with open_websocket_url(url) as conn:
3232
return json.loads(await conn.get_message())
3333

3434

35-
async def run_case(url, case):
35+
async def run_case(url: str, case: str) -> None:
3636
url = f"{url}/runCase?case={case}&agent={AGENT}"
3737
try:
3838
async with open_websocket_url(url, max_message_size=MAX_MESSAGE_SIZE) as conn:
@@ -43,15 +43,15 @@ async def run_case(url, case):
4343
pass
4444

4545

46-
async def update_reports(url):
46+
async def update_reports(url: str) -> None:
4747
url = f"{url}/updateReports?agent={AGENT}"
4848
async with open_websocket_url(url) as conn:
4949
# This command runs as soon as we connect to it, so we don't need to
5050
# send any messages.
5151
pass
5252

5353

54-
async def run_tests(args):
54+
async def run_tests(args: argparse.Namespace) -> None:
5555
logger = logging.getLogger("trio-websocket")
5656
if args.debug_cases:
5757
# Don't fetch case count when debugging a subset of test cases. It adds
@@ -63,7 +63,10 @@ async def run_tests(args):
6363
test_cases = list(range(1, case_count + 1))
6464
exception_cases = []
6565
for case in test_cases:
66-
case_id = (await get_case_info(args.url, case))["id"]
66+
result = await get_case_info(args.url, case)
67+
assert isinstance(result, dict)
68+
case_id = result["id"]
69+
assert isinstance(case_id, int)
6770
if case_count:
6871
logger.info("Running test case %s (%d of %d)", case_id, case, case_count)
6972
else:
@@ -89,7 +92,7 @@ async def run_tests(args):
8992
sys.exit(1)
9093

9194

92-
def parse_args():
95+
def parse_args() -> argparse.Namespace:
9396
"""Parse command line arguments."""
9497
parser = argparse.ArgumentParser(
9598
description="Autobahn client for" " trio-websocket"

autobahn/server.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@
2424
connection_count = 0
2525

2626

27-
async def main():
27+
async def main() -> None:
2828
"""Main entry point."""
2929
logger.info("Starting websocket server on ws://%s:%d", BIND_IP, BIND_PORT)
3030
await serve_websocket(
3131
handler, BIND_IP, BIND_PORT, ssl_context=None, max_message_size=MAX_MESSAGE_SIZE
3232
)
3333

3434

35-
async def handler(request: WebSocketRequest):
35+
async def handler(request: WebSocketRequest) -> None:
3636
"""Reverse incoming websocket messages and send them back."""
3737
global connection_count # pylint: disable=global-statement
3838
connection_count += 1
@@ -50,7 +50,7 @@ async def handler(request: WebSocketRequest):
5050
)
5151

5252

53-
def parse_args():
53+
def parse_args() -> argparse.Namespace:
5454
"""Parse command line arguments."""
5555
parser = argparse.ArgumentParser(
5656
description="Autobahn server for" " trio-websocket"

examples/client.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,23 @@
1212
import ssl
1313
import sys
1414
import urllib.parse
15+
from typing import NoReturn
1516

1617
import trio
17-
from trio_websocket import open_websocket_url, ConnectionClosed, HandshakeError
18+
from trio_websocket import (
19+
open_websocket_url,
20+
ConnectionClosed,
21+
HandshakeError,
22+
WebSocketConnection,
23+
CloseReason,
24+
)
1825

1926

2027
logging.basicConfig(level=logging.DEBUG)
2128
here = pathlib.Path(__file__).parent
2229

2330

24-
def commands():
31+
def commands() -> None:
2532
"""Print the supported commands."""
2633
print("Commands: ")
2734
print("send <MESSAGE> -> send message")
@@ -30,7 +37,7 @@ def commands():
3037
print()
3138

3239

33-
def parse_args():
40+
def parse_args() -> argparse.Namespace:
3441
"""Parse command line arguments."""
3542
parser = argparse.ArgumentParser(description="Example trio-websocket client")
3643
parser.add_argument(
@@ -40,7 +47,7 @@ def parse_args():
4047
return parser.parse_args()
4148

4249

43-
async def main(args):
50+
async def main(args: argparse.Namespace) -> bool:
4451
"""Main entry point, returning False in the case of logged error."""
4552
if urllib.parse.urlsplit(args.url).scheme == "wss":
4653
# Configure SSL context to handle our self-signed certificate. Most
@@ -62,9 +69,10 @@ async def main(args):
6269
except HandshakeError as e:
6370
logging.error("Connection attempt failed: %s", e)
6471
return False
72+
return True
6573

6674

67-
async def handle_connection(ws, use_heartbeat):
75+
async def handle_connection(ws: WebSocketConnection, use_heartbeat: bool) -> None:
6876
"""Handle the connection."""
6977
logging.debug("Connected!")
7078
try:
@@ -74,11 +82,14 @@ async def handle_connection(ws, use_heartbeat):
7482
nursery.start_soon(get_commands, ws)
7583
nursery.start_soon(get_messages, ws)
7684
except ConnectionClosed as cc:
85+
assert isinstance(cc.reason, CloseReason)
7786
reason = "<no reason>" if cc.reason.reason is None else f'"{cc.reason.reason}"'
7887
print(f"Closed: {cc.reason.code}/{cc.reason.name} {reason}")
7988

8089

81-
async def heartbeat(ws, timeout, interval):
90+
async def heartbeat(
91+
ws: WebSocketConnection, timeout: float, interval: float
92+
) -> NoReturn:
8293
"""
8394
Send periodic pings on WebSocket ``ws``.
8495
@@ -102,10 +113,10 @@ async def heartbeat(ws, timeout, interval):
102113
await trio.sleep(interval)
103114

104115

105-
async def get_commands(ws):
116+
async def get_commands(ws: WebSocketConnection) -> None:
106117
"""In a loop: get a command from the user and execute it."""
107118
while True:
108-
cmd = await trio.to_thread.run_sync(input, "cmd> ", cancellable=True)
119+
cmd = await trio.to_thread.run_sync(input, "cmd> ")
109120
if cmd.startswith("ping"):
110121
payload = cmd[5:].encode("utf8") or None
111122
await ws.ping(payload)
@@ -125,11 +136,11 @@ async def get_commands(ws):
125136
await trio.sleep(0.25)
126137

127138

128-
async def get_messages(ws):
139+
async def get_messages(ws: WebSocketConnection) -> None:
129140
"""In a loop: get a WebSocket message and print it out."""
130141
while True:
131142
message = await ws.get_message()
132-
print(f"message: {message}")
143+
print(f"message: {message!r}")
133144

134145

135146
if __name__ == "__main__":

examples/generate-cert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import trustme
55

66

7-
def main():
7+
def main() -> None:
88
here = pathlib.Path(__file__).parent
99
ca_path = here / "fake.ca.pem"
1010
server_path = here / "fake.server.pem"

examples/server.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@
1515
import ssl
1616

1717
import trio
18-
from trio_websocket import serve_websocket, ConnectionClosed
18+
from trio_websocket import serve_websocket, ConnectionClosed, WebSocketRequest
1919

2020

2121
logging.basicConfig(level=logging.DEBUG)
2222
logger = logging.getLogger()
2323
here = pathlib.Path(__file__).parent
2424

2525

26-
def parse_args():
26+
def parse_args() -> argparse.Namespace:
2727
"""Parse command line arguments."""
2828
parser = argparse.ArgumentParser(description="Example trio-websocket client")
2929
parser.add_argument("--ssl", action="store_true", help="Use SSL")
@@ -36,7 +36,7 @@ def parse_args():
3636
return parser.parse_args()
3737

3838

39-
async def main(args):
39+
async def main(args: argparse.Namespace) -> None:
4040
"""Main entry point."""
4141
logging.info("Starting websocket server…")
4242
if args.ssl:
@@ -54,7 +54,7 @@ async def main(args):
5454
await serve_websocket(handler, host, args.port, ssl_context)
5555

5656

57-
async def handler(request):
57+
async def handler(request: WebSocketRequest) -> None:
5858
"""Reverse incoming websocket messages and send them back."""
5959
logging.info('Handler starting on path "%s"', request.path)
6060
ws = await request.accept()

pyproject.toml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[tool.mypy]
2+
explicit_package_bases = true
3+
files = ["trio_websocket", "tests", "autobahn", "examples"]
4+
show_column_numbers = true
5+
show_error_codes = true
6+
show_traceback = true
7+
disallow_any_decorated = true
8+
disallow_any_unimported = true
9+
ignore_missing_imports = true
10+
local_partial_types = true
11+
no_implicit_optional = true
12+
strict = true
13+
warn_unreachable = true

setup.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
author_email="mehaase@gmail.com",
2525
classifiers=[
2626
# See https://pypi.org/classifiers/
27+
<<<<<<< HEAD
2728
"Development Status :: 3 - Alpha",
2829
"Intended Audience :: Developers",
2930
"Topic :: Software Development :: Libraries",
@@ -35,10 +36,45 @@
3536
"Programming Language :: Python :: 3.12",
3637
"Programming Language :: Python :: Implementation :: CPython",
3738
"Programming Language :: Python :: Implementation :: PyPy",
39+
||||||| e7706f4
40+
'Development Status :: 3 - Alpha',
41+
'Intended Audience :: Developers',
42+
'Topic :: Software Development :: Libraries',
43+
'License :: OSI Approved :: MIT License',
44+
'Programming Language :: Python :: 3.8',
45+
'Programming Language :: Python :: 3.9',
46+
'Programming Language :: Python :: 3.10',
47+
'Programming Language :: Python :: 3.11',
48+
'Programming Language :: Python :: 3.12',
49+
'Programming Language :: Python :: Implementation :: CPython',
50+
'Programming Language :: Python :: Implementation :: PyPy',
51+
=======
52+
'Development Status :: 3 - Alpha',
53+
'Intended Audience :: Developers',
54+
'Topic :: Software Development :: Libraries',
55+
'License :: OSI Approved :: MIT License',
56+
'Programming Language :: Python :: 3.8',
57+
'Programming Language :: Python :: 3.9',
58+
'Programming Language :: Python :: 3.10',
59+
'Programming Language :: Python :: 3.11',
60+
'Programming Language :: Python :: 3.12',
61+
'Programming Language :: Python :: Implementation :: CPython',
62+
'Programming Language :: Python :: Implementation :: PyPy',
63+
'Typing :: Typed',
64+
>>>>>>> root/master
3865
],
3966
python_requires=">=3.8",
67+
<<<<<<< HEAD
4068
keywords="websocket client server trio",
4169
packages=find_packages(exclude=["docs", "examples", "tests"]),
70+
||||||| e7706f4
71+
keywords='websocket client server trio',
72+
packages=find_packages(exclude=['docs', 'examples', 'tests']),
73+
=======
74+
keywords='websocket client server trio',
75+
packages=find_packages(exclude=['docs', 'examples', 'tests']),
76+
package_data={"trio-websocket": ["py.typed"]},
77+
>>>>>>> root/master
4278
install_requires=[
4379
'exceptiongroup; python_version<"3.11"',
4480
"trio>=0.11",

0 commit comments

Comments
 (0)