Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blacken #177

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ test:
$(PYTHON) -m pytest --cov=trio_websocket --cov-report=term-missing --no-cov-on-fail

lint:
$(PYTHON) -m black trio_websocket/ tests/ autobahn/ examples/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @jakkdl

I was requested to add type hints to this repository

Would you share some context of that conversation? (gitter link etc.)

Please see the thread here before we discuss type annotation coverage.
#167 (comment)

Would it be reasonable to revisit if the project becomes more actively maintained?

is now relevant

To me, being off life-support maintenance would mean things like 1) there is at least another person that has some history on the project and I can trust to share the load on whatever comes up going forward, 2) there is activity like revising the API, rewriting the implementation or tests, etc. I wouldn't say that adding type annotations or auto formatting means that the project is out of the woods regarding stewardship, and there are aspects of full type annotations that make maintenance harder.

Regards,

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! We'll look into possible alternative libraries that are under more active support and reconsider whether to use trio-websockets. If we don't find any great alternatives, I could go with a more minimal approach and just write separate stub files that needn't touch the existing code at all, and if you don't want the extra maintenance burden of them we can just stick them in an entirely separate repo.

$(PYTHON) -m pylint trio_websocket/ tests/ autobahn/ examples/

typecheck:
Expand Down
56 changes: 34 additions & 22 deletions autobahn/client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'''
"""
This test client runs against the Autobahn test server. It is based on the
test_client.py in wsproto.
'''
"""

import argparse
import json
import logging
Expand All @@ -11,28 +12,28 @@
from trio_websocket import open_websocket_url, ConnectionClosed


AGENT = 'trio-websocket'
AGENT = "trio-websocket"
MAX_MESSAGE_SIZE = 16 * 1024 * 1024
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('client')
logger = logging.getLogger("client")


async def get_case_count(url):
url = url + '/getCaseCount'
url = url + "/getCaseCount"
async with open_websocket_url(url) as conn:
case_count = await conn.get_message()
logger.info('Case count=%s', case_count)
logger.info("Case count=%s", case_count)
return int(case_count)


async def get_case_info(url, case):
url = f'{url}/getCaseInfo?case={case}'
url = f"{url}/getCaseInfo?case={case}"
async with open_websocket_url(url) as conn:
return json.loads(await conn.get_message())


async def run_case(url, case):
url = f'{url}/runCase?case={case}&agent={AGENT}'
url = f"{url}/runCase?case={case}&agent={AGENT}"
try:
async with open_websocket_url(url, max_message_size=MAX_MESSAGE_SIZE) as conn:
while True:
Expand All @@ -43,15 +44,15 @@ async def run_case(url, case):


async def update_reports(url):
url = f'{url}/updateReports?agent={AGENT}'
url = f"{url}/updateReports?agent={AGENT}"
async with open_websocket_url(url) as conn:
# This command runs as soon as we connect to it, so we don't need to
# send any messages.
pass


async def run_tests(args):
logger = logging.getLogger('trio-websocket')
logger = logging.getLogger("trio-websocket")
if args.debug_cases:
# Don't fetch case count when debugging a subset of test cases. It adds
# noise to the debug logging.
Expand All @@ -62,7 +63,7 @@ async def run_tests(args):
test_cases = list(range(1, case_count + 1))
exception_cases = []
for case in test_cases:
case_id = (await get_case_info(args.url, case))['id']
case_id = (await get_case_info(args.url, case))["id"]
if case_count:
logger.info("Running test case %s (%d of %d)", case_id, case, case_count)
else:
Expand All @@ -71,28 +72,39 @@ async def run_tests(args):
try:
await run_case(args.url, case)
except Exception: # pylint: disable=broad-exception-caught
logger.exception(' runtime exception during test case %s (%d)', case_id, case)
logger.exception(
" runtime exception during test case %s (%d)", case_id, case
)
exception_cases.append(case_id)
logger.setLevel(logging.INFO)
logger.info('Updating report')
logger.info("Updating report")
await update_reports(args.url)
if exception_cases:
logger.error('Runtime exception in %d of %d test cases: %s',
len(exception_cases), len(test_cases), exception_cases)
logger.error(
"Runtime exception in %d of %d test cases: %s",
len(exception_cases),
len(test_cases),
exception_cases,
)
sys.exit(1)


def parse_args():
''' Parse command line arguments. '''
parser = argparse.ArgumentParser(description='Autobahn client for'
' trio-websocket')
parser.add_argument('url', help='WebSocket URL for server')
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Autobahn client for" " trio-websocket"
)
parser.add_argument("url", help="WebSocket URL for server")
# TODO: accept case ID's rather than indices
parser.add_argument('debug_cases', type=int, nargs='*', help='Run'
' individual test cases with debug logging (optional)')
parser.add_argument(
"debug_cases",
type=int,
nargs="*",
help="Run" " individual test cases with debug logging (optional)",
)
return parser.parse_args()


if __name__ == '__main__':
if __name__ == "__main__":
args = parse_args()
trio.run(run_tests, args)
42 changes: 24 additions & 18 deletions autobahn/server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'''
"""
This simple WebSocket server responds to text messages by reversing each
message string and sending it back.

Expand All @@ -7,34 +7,36 @@

To use SSL/TLS: install the `trustme` package from PyPI and run the
`generate-cert.py` script in this directory.
'''
"""

import argparse
import logging

import trio
from trio_websocket import serve_websocket, ConnectionClosed, WebSocketRequest

BIND_IP = '0.0.0.0'
BIND_IP = "0.0.0.0"
BIND_PORT = 9000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024
logging.basicConfig()
logger = logging.getLogger('client')
logger = logging.getLogger("client")
logger.setLevel(logging.INFO)
connection_count = 0


async def main():
''' Main entry point. '''
logger.info('Starting websocket server on ws://%s:%d', BIND_IP, BIND_PORT)
await serve_websocket(handler, BIND_IP, BIND_PORT, ssl_context=None,
max_message_size=MAX_MESSAGE_SIZE)
"""Main entry point."""
logger.info("Starting websocket server on ws://%s:%d", BIND_IP, BIND_PORT)
await serve_websocket(
handler, BIND_IP, BIND_PORT, ssl_context=None, max_message_size=MAX_MESSAGE_SIZE
)


async def handler(request: WebSocketRequest):
''' Reverse incoming websocket messages and send them back. '''
"""Reverse incoming websocket messages and send them back."""
global connection_count # pylint: disable=global-statement
connection_count += 1
logger.info('Connection #%d', connection_count)
logger.info("Connection #%d", connection_count)
ws = await request.accept()
while True:
try:
Expand All @@ -43,20 +45,24 @@ async def handler(request: WebSocketRequest):
except ConnectionClosed:
break
except Exception: # pylint: disable=broad-exception-caught
logger.exception(' runtime exception handling connection #%d', connection_count)
logger.exception(
" runtime exception handling connection #%d", connection_count
)


def parse_args():
''' Parse command line arguments. '''
parser = argparse.ArgumentParser(description='Autobahn server for'
' trio-websocket')
parser.add_argument('-d', '--debug', action='store_true',
help='WebSocket URL for server')
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Autobahn server for" " trio-websocket"
)
parser.add_argument(
"-d", "--debug", action="store_true", help="WebSocket URL for server"
)
return parser.parse_args()


if __name__ == '__main__':
if __name__ == "__main__":
args = parse_args()
if args.debug:
logging.getLogger('trio-websocket').setLevel(logging.DEBUG)
logging.getLogger("trio-websocket").setLevel(logging.DEBUG)
trio.run(main)
67 changes: 36 additions & 31 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@

# -- Project information -----------------------------------------------------

project = 'Trio WebSocket'
copyright = '2018, Hyperion Gray'
author = 'Hyperion Gray'
project = "Trio WebSocket"
copyright = "2018, Hyperion Gray"
author = "Hyperion Gray"

from trio_websocket._version import __version__ as version

release = version


Expand All @@ -37,22 +38,22 @@
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinxcontrib_trio',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinxcontrib_trio",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -64,7 +65,7 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
Expand All @@ -75,7 +76,7 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
Expand All @@ -86,7 +87,7 @@
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
Expand All @@ -102,46 +103,44 @@
# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'TrioWebSocketdoc'
htmlhelp_basename = "TrioWebSocketdoc"


# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# Additional stuff for the LaTeX preamble.
# 'preamble': '',

# Latex figure (float) alignment
#
# Latex figure (float) alignment
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'TrioWebSocket.tex', 'Trio WebSocket Documentation',
'Hyperion Gray', 'manual'),
(
master_doc,
"TrioWebSocket.tex",
"Trio WebSocket Documentation",
"Hyperion Gray",
"manual",
),
]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'triowebsocket', 'Trio WebSocket Documentation',
[author], 1)
]
man_pages = [(master_doc, "triowebsocket", "Trio WebSocket Documentation", [author], 1)]


# -- Options for Texinfo output ----------------------------------------------
Expand All @@ -150,9 +149,15 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'TrioWebSocket', 'Trio WebSocket Documentation',
author, 'TrioWebSocket', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"TrioWebSocket",
"Trio WebSocket Documentation",
author,
"TrioWebSocket",
"One line description of project.",
"Miscellaneous",
),
]


Expand All @@ -171,10 +176,10 @@
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
epub_exclude_files = ["search.html"]


# -- Extension configuration -------------------------------------------------
intersphinx_mapping = {
'trio': ('https://trio.readthedocs.io/en/stable/', None),
"trio": ("https://trio.readthedocs.io/en/stable/", None),
}
Loading
Loading