Dataset Viewer
Auto-converted to Parquet
repo
stringlengths
10
38
pull_number
int64
2
7.86k
instance_id
stringlengths
15
43
issue_numbers
stringlengths
5
18
base_commit
stringlengths
40
40
patch
stringlengths
337
805k
test_patch
stringlengths
379
52.3k
problem_statement
stringlengths
44
11.1k
hints_text
stringlengths
0
19.7k
created_at
stringdate
2013-01-13 16:37:56
2025-03-16 22:16:23
version
stringclasses
1 value
FAIL_TO_PASS
sequencelengths
1
103
PASS_TO_PASS
sequencelengths
0
13.5k
prodigyeducation/python-graphql-client
33
prodigyeducation__python-graphql-client-33
['32']
02492c7efe43b66f7c01bc54b4ea504b3dae5f6a
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7011cdd..6b173e9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,11 +1,11 @@ repos: - repo: https://github.com/psf/black - rev: stable + rev: 20.8b1 hooks: - id: black - language_version: python3.8 + language_version: python3 - repo: https://gitlab.com/pycqa/flake8 - rev: "" + rev: "3.8.4" hooks: - id: flake8 additional_dependencies: [flake8-docstrings, flake8-isort] diff --git a/README.md b/README.md index fecd4e5..948282a 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ pip install python-graphql-client - Query/Mutation -```python +```py from python_graphql_client import GraphqlClient # Instantiate the client with an endpoint. @@ -49,7 +49,7 @@ print(data) # => {'data': {'country': {'code': 'CA', 'name': 'Canada'}}} - Subscription -```python +```py from python_graphql_client import GraphqlClient # Instantiate the client with a websocket endpoint. @@ -72,6 +72,37 @@ asyncio.run(client.subscribe(query=query, handle=print)) # ... ``` +## Advanced Usage + +### Disable SSL verification + +Set the keyword argument `verify=False` ether when instantiating the `GraphqlClient` class. + +```py +from python_graphql_client import GraphqlClient + +client = GraphqlClient(endpoint="wss://www.your-api.com/graphql", verify=False) +``` + +Alternatively, you can set it when calling the `execute` method. + +```py +from python_graphql_client import GraphqlClient + +client = GraphqlClient(endpoint="wss://www.your-api.com/graphql" +client.execute(query="<Your Query>", verify=False) +``` + +### Custom Authentication + +```py +from requests.auth import HTTPBasicAuth +from python_graphql_client import GraphqlClient + +auth = HTTPBasicAuth('[email protected]', 'not_a_real_password') +client = GraphqlClient(endpoint="wss://www.your-api.com/graphql", auth=auth) +``` + ## Roadmap To start we'll try and use a Github project board for listing current work and updating priorities of upcoming features. diff --git a/python_graphql_client/graphql_client.py b/python_graphql_client/graphql_client.py index a6164a5..6a74440 100644 --- a/python_graphql_client/graphql_client.py +++ b/python_graphql_client/graphql_client.py @@ -1,7 +1,7 @@ """Module containing graphQL client.""" import json import logging -from typing import Callable +from typing import Any, Callable import aiohttp import requests @@ -13,10 +13,11 @@ class GraphqlClient: """Class which represents the interface to make graphQL requests through.""" - def __init__(self, endpoint: str, headers: dict = None): + def __init__(self, endpoint: str, headers: dict = {}, **kwargs: Any): """Insantiate the client.""" self.endpoint = endpoint - self.headers = headers or {} + self.headers = headers + self.options = kwargs def __request_body( self, query: str, variables: dict = None, operation_name: str = None @@ -31,15 +32,13 @@ def __request_body( return json - def __request_headers(self, headers: dict = None) -> dict: - return {**self.headers, **headers} if headers else self.headers - def execute( self, query: str, variables: dict = None, operation_name: str = None, - headers: dict = None, + headers: dict = {}, + **kwargs: Any, ): """Make synchronous request to graphQL server.""" request_body = self.__request_body( @@ -49,7 +48,8 @@ def execute( result = requests.post( self.endpoint, json=request_body, - headers=self.__request_headers(headers), + headers={**self.headers, **headers}, + **{**self.options, **kwargs}, ) result.raise_for_status() @@ -60,7 +60,7 @@ async def execute_async( query: str, variables: dict = None, operation_name: str = None, - headers: dict = None, + headers: dict = {}, ): """Make asynchronous request to graphQL server.""" request_body = self.__request_body( @@ -71,7 +71,7 @@ async def execute_async( async with session.post( self.endpoint, json=request_body, - headers=self.__request_headers(headers), + headers={**self.headers, **headers}, ) as response: return await response.json() @@ -81,7 +81,7 @@ async def subscribe( handle: Callable, variables: dict = None, operation_name: str = None, - headers: dict = None, + headers: dict = {}, ): """Make asynchronous request for GraphQL subscription.""" connection_init_message = json.dumps({"type": "connection_init", "payload": {}}) @@ -96,7 +96,7 @@ async def subscribe( async with websockets.connect( self.endpoint, subprotocols=["graphql-ws"], - extra_headers=self.__request_headers(headers), + extra_headers={**self.headers, **headers}, ) as websocket: await websocket.send(connection_init_message) await websocket.send(request_message)
diff --git a/tests/test_graphql_client.py b/tests/test_graphql_client.py index a3d408f..4e7b943 100644 --- a/tests/test_graphql_client.py +++ b/tests/test_graphql_client.py @@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMock, call, patch from aiohttp import web +from requests.auth import HTTPBasicAuth from requests.exceptions import HTTPError from python_graphql_client import GraphqlClient @@ -98,6 +99,25 @@ def test_execute_query_with_headers(self, post_mock): }, ) + @patch("python_graphql_client.graphql_client.requests.post") + def test_execute_query_with_options(self, post_mock): + """Sends a graphql POST request with headers.""" + auth = HTTPBasicAuth("[email protected]", "not_a_real_password") + client = GraphqlClient( + endpoint="http://www.test-api.com/", + auth=auth, + ) + query = "" + client.execute(query=query, verify=False) + + post_mock.assert_called_once_with( + "http://www.test-api.com/", + json={"query": query}, + headers={}, + auth=HTTPBasicAuth("[email protected]", "not_a_real_password"), + verify=False, + ) + @patch("python_graphql_client.graphql_client.requests.post") def test_execute_query_with_operation_name(self, post_mock): """Sends a graphql POST request with the operationName key set.""" @@ -302,8 +322,4 @@ async def test_headers_passed_to_websocket_connect(self, mock_connect): extra_headers=expected_headers, ) - mock_handle.assert_has_calls( - [ - call({"data": {"messageAdded": "one"}}), - ] - ) + mock_handle.assert_has_calls([call({"data": {"messageAdded": "one"}})])
Turning off SSL verification for API requests I am not sure if we have this already, however, I could not figure a way to turn off the SSL verification for the API requests using this library. I think we could pass an optional `**kwargs` while initializing the client so that we could pass those optional attributes while calling the APIs using `requests` library. The initialization could be the following. ```client = GraphqlClient("http://www.my.api.server.com/graphql", verify=False)```
2020-11-06T02:10:39.000
-1.0
[ "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_options" ]
[ "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_headers", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_headers", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_operation_name", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_basic_query", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_variables", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_subscribe", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_basic_query", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_headers_passed_to_websocket_connect", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_variables", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_no_endpoint", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_headers", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_raises_http_errors_as_exceptions", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_endpoint", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_operation_name", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_does_not_crash_with_keep_alive" ]
prodigyeducation/python-graphql-client
44
prodigyeducation__python-graphql-client-44
['43']
1e6df927963c12cb09f4843662177ca9a509e408
diff --git a/python_graphql_client/graphql_client.py b/python_graphql_client/graphql_client.py index 8d39676..1d3d104 100644 --- a/python_graphql_client/graphql_client.py +++ b/python_graphql_client/graphql_client.py @@ -7,14 +7,13 @@ import requests import websockets -logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s") - class GraphqlClient: """Class which represents the interface to make graphQL requests through.""" def __init__(self, endpoint: str, headers: dict = {}, **kwargs: Any): """Insantiate the client.""" + self.logger = logging.getLogger(__name__) self.endpoint = endpoint self.headers = headers self.options = kwargs @@ -106,8 +105,8 @@ async def subscribe( async for response_message in websocket: response_body = json.loads(response_message) if response_body["type"] == "connection_ack": - logging.info("the server accepted the connection") + self.logger.info("the server accepted the connection") elif response_body["type"] == "ka": - logging.info("the server sent a keep alive message") + self.logger.info("the server sent a keep alive message") else: handle(response_body["payload"])
diff --git a/tests/test_graphql_client.py b/tests/test_graphql_client.py index 8771d16..4a44207 100644 --- a/tests/test_graphql_client.py +++ b/tests/test_graphql_client.py @@ -269,9 +269,9 @@ async def test_subscribe(self, mock_connect): ] ) - @patch("logging.info") + @patch("logging.getLogger") @patch("websockets.connect") - async def test_does_not_crash_with_keep_alive(self, mock_connect, mock_info): + async def test_does_not_crash_with_keep_alive(self, mock_connect, mock_get_logger): """Subsribe a GraphQL subscription.""" mock_websocket = mock_connect.return_value.__aenter__.return_value mock_websocket.send = AsyncMock() @@ -288,7 +288,9 @@ async def test_does_not_crash_with_keep_alive(self, mock_connect, mock_info): await client.subscribe(query=query, handle=MagicMock()) - mock_info.assert_has_calls([call("the server sent a keep alive message")]) + mock_get_logger.return_value.info.assert_has_calls( + [call("the server sent a keep alive message")] + ) @patch("websockets.connect") async def test_headers_passed_to_websocket_connect(self, mock_connect):
Disable client logs Hi, is there a way to disable the logging produced by the client? If not, I think it's a good idea to add these feature. Thank you :)
Hi @nadavtsa, thank you for the issue. The following code is setting the logging level to `INFO` and I'm looking to make it configurable. Please feel free to let me know if you have any ideas on how to go about this. https://github.com/prodigyeducation/python-graphql-client/blob/1e6df927963c12cb09f4843662177ca9a509e408/python_graphql_client/graphql_client.py#L10
2021-02-28T23:04:15.000
-1.0
[ "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_does_not_crash_with_keep_alive" ]
[ "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_headers", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_headers", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_variables", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_basic_query", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_operation_name", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_subscribe", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_basic_query", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_init_payload_passed_in_init_message", "tests/test_graphql_client.py::TestGraphqlClientSubscriptions::test_headers_passed_to_websocket_connect", "tests/test_graphql_client.py::TestGraphqlClientExecuteAsync::test_execute_query_with_variables", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_no_endpoint", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_headers", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_options", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_raises_http_errors_as_exceptions", "tests/test_graphql_client.py::TestGraphqlClientConstructor::test_init_client_endpoint", "tests/test_graphql_client.py::TestGraphqlClientExecute::test_execute_query_with_operation_name" ]
python-openapi/openapi-spec-validator
75
python-openapi__openapi-spec-validator-75
['73']
827b49c7b3f3fb67b7022ab44b586bd67d28886c
diff --git a/openapi_spec_validator/__init__.py b/openapi_spec_validator/__init__.py index f7f4610..7c15d6e 100644 --- a/openapi_spec_validator/__init__.py +++ b/openapi_spec_validator/__init__.py @@ -2,7 +2,7 @@ from openapi_spec_validator.shortcuts import ( validate_spec_factory, validate_spec_url_factory, ) -from openapi_spec_validator.handlers import UrlHandler +from openapi_spec_validator.handlers import UrlHandler, FileObjectHandler from openapi_spec_validator.schemas import get_openapi_schema from openapi_spec_validator.factories import JSONSpecValidatorFactory from openapi_spec_validator.validators import SpecValidator @@ -19,8 +19,10 @@ 'validate_v2_spec_url', 'validate_v3_spec_url', 'validate_spec_url', ] +file_object_handler = FileObjectHandler() +all_urls_handler = UrlHandler('http', 'https', 'file') default_handlers = { - '<all_urls>': UrlHandler('http', 'https', 'file'), + '<all_urls>': all_urls_handler, 'http': UrlHandler('http'), 'https': UrlHandler('https'), 'file': UrlHandler('file'), diff --git a/openapi_spec_validator/__main__.py b/openapi_spec_validator/__main__.py index 3ee10e3..0c798fe 100644 --- a/openapi_spec_validator/__main__.py +++ b/openapi_spec_validator/__main__.py @@ -7,8 +7,10 @@ import pathlib2 as pathlib import sys - -from openapi_spec_validator import validate_spec_url, validate_v2_spec_url +from openapi_spec_validator import ( + openapi_v2_spec_validator, openapi_v3_spec_validator, all_urls_handler, + file_object_handler, +) from openapi_spec_validator.exceptions import ValidationError logger = logging.getLogger(__name__) @@ -18,6 +20,19 @@ ) +def read_from_stdin(filename): + return file_object_handler(sys.stdin), '' + + +def read_from_filename(filename): + if not os.path.isfile(filename): + raise SystemError("No such file {0}".format(filename)) + + filename = os.path.abspath(filename) + uri = pathlib.Path(filename).as_uri() + return all_urls_handler(uri), uri + + def main(args=None): parser = argparse.ArgumentParser() parser.add_argument('filename', help="Absolute or relative path to file") @@ -29,21 +44,34 @@ def main(args=None): default='3.0.0' ) args = parser.parse_args(args) - filename = args.filename - filename = os.path.abspath(filename) + + # choose source + reader = read_from_filename + if args.filename == '-': + reader = read_from_stdin + + # read source + try: + spec, spec_url = reader(args.filename) + except Exception as exc: + print(exc) + sys.exit(1) + # choose the validator - if args.schema == '2.0': - validate_url = validate_v2_spec_url - elif args.schema == '3.0.0': - validate_url = validate_spec_url + validators = { + '2.0': openapi_v2_spec_validator, + '3.0.0': openapi_v3_spec_validator, + } + validator = validators[args.schema] + # validate try: - validate_url(pathlib.Path(filename).as_uri()) - except ValidationError as e: - print(e) + validator.validate(spec, spec_url=spec_url) + except ValidationError as exc: + print(exc) sys.exit(1) - except Exception as e: - print(e) + except Exception as exc: + print(exc) sys.exit(2) else: print('OK') diff --git a/openapi_spec_validator/handlers.py b/openapi_spec_validator/handlers.py index f4db845..177c007 100644 --- a/openapi_spec_validator/handlers.py +++ b/openapi_spec_validator/handlers.py @@ -8,19 +8,30 @@ from openapi_spec_validator.loaders import ExtendedSafeLoader -class UrlHandler: - """OpenAPI spec validator URL scheme handler.""" +class FileObjectHandler(object): + """OpenAPI spec validator file-like object handler.""" - def __init__(self, *allowed_schemes, **options): - self.allowed_schemes = allowed_schemes + def __init__(self, **options): self.options = options @property def loader(self): return self.options.get('loader', ExtendedSafeLoader) + def __call__(self, f): + return load(f, self.loader) + + +class UrlHandler(FileObjectHandler): + """OpenAPI spec validator URL scheme handler.""" + + def __init__(self, *allowed_schemes, **options): + super(UrlHandler, self).__init__(**options) + self.allowed_schemes = allowed_schemes + def __call__(self, url, timeout=1): assert urlparse(url).scheme in self.allowed_schemes - with contextlib.closing(urlopen(url, timeout=timeout)) as fh: - return load(fh, self.loader) + f = urlopen(url, timeout=timeout) + with contextlib.closing(f) as fh: + return super(UrlHandler, self).__call__(fh)
diff --git a/tests/integration/test_main.py b/tests/integration/test_main.py index 6d890be..bbc1e1f 100644 --- a/tests/integration/test_main.py +++ b/tests/integration/test_main.py @@ -1,4 +1,7 @@ +import mock + import pytest +from six import StringIO from openapi_spec_validator.__main__ import main @@ -39,8 +42,32 @@ def test_validation_error(): main(testargs) [email protected]( + 'openapi_spec_validator.__main__.openapi_v3_spec_validator.validate', + side_effect=Exception, +) +def test_unknown_error(m_validate): + """SystemExit on running with unknown error.""" + testargs = ['--schema', '3.0.0', + './tests/integration/data/v2.0/petstore.yaml'] + with pytest.raises(SystemExit): + main(testargs) + + def test_nonexisting_file(): """Calling with non-existing file should sys.exit.""" testargs = ['i_dont_exist.yaml'] with pytest.raises(SystemExit): main(testargs) + + +def test_schema_stdin(): + """Test schema from STDIN""" + spes_path = './tests/integration/data/v3.0/petstore.yaml' + with open(spes_path, 'r') as spec_file: + spec_lines = spec_file.readlines() + spec_io = StringIO("".join(spec_lines)) + + testargs = ['-'] + with mock.patch('openapi_spec_validator.__main__.sys.stdin', spec_io): + main(testargs)
Support reading from STDIN It would be nice if the executable were able to read from STDIN instead of from a file. The default convention for this in *nix is to read from STDIN if `-` is specified as the filename. This is convenient when validating an automatically generated OpenAPI spec, because then it does not need to be saved as a file first. I think this "issue" can receive the `kind:enhancement` tag.
2019-05-20T15:36:02.000
-1.0
[ "tests/integration/test_main.py::test_schema_stdin", "tests/integration/test_main.py::test_unknown_error" ]
[ "tests/integration/test_main.py::test_schema_default", "tests/integration/test_main.py::test_validation_error", "tests/integration/test_main.py::test_schema_v3", "tests/integration/test_main.py::test_nonexisting_file", "tests/integration/test_main.py::test_schema_v2", "tests/integration/test_main.py::test_schema_unknown" ]
mkorpela/pabot
534
mkorpela__pabot-534
['533']
fadb9c4406044a626d669acf5cb10526b704f8d9
diff --git a/src/pabot/pabot.py b/src/pabot/pabot.py index c174b359..8738db20 100644 --- a/src/pabot/pabot.py +++ b/src/pabot/pabot.py @@ -1258,6 +1258,7 @@ def _options_for_rebot(options, start_time_string, end_time_string): "maxassignlength", "maxerrorlines", "monitorcolors", + "parser", "prerunmodifier", "quiet", "randomize", diff --git a/src/pabot/result_merger.py b/src/pabot/result_merger.py index 169d7a76..e7ab827d 100644 --- a/src/pabot/result_merger.py +++ b/src/pabot/result_merger.py @@ -56,7 +56,7 @@ def merge(self, merged): try: self._set_prefix(merged.source) merged.suite.visit(self) - self.root.metadata._add_initial(merged.suite.metadata) + self.root.metadata.update(merged.suite.metadata) if self.errors != merged.errors: self.errors.add(merged.errors) except:
diff --git a/tests/test_pabot.py b/tests/test_pabot.py index 703f7a9f..c60c7439 100644 --- a/tests/test_pabot.py +++ b/tests/test_pabot.py @@ -1045,6 +1045,7 @@ def test_rebot_conf(self): "prerunmodifier", "monitorcolors", "language", + "parser", ]: self.assertFalse(key in options, "%s should not be in options" % key) else:
pabot fails during merge restult with robot 6.1b1 A simple pabot execution fails with Robot 6.1b1 which was released yesterday. Robot 6.1a1 as well as 6.0.x works fine: ``` (v) $ cat /tmp/test.robot *** Test Cases *** simple test Should be True 1==1 (v)$ pabot /tmp/test.robot 2023-05-06 12:53:05.505201 [PID:46369] [0] [ID:0] EXECUTING Test 2023-05-06 12:53:06.032115 [PID:46369] [0] [ID:0] PASSED Test in 0.5 seconds Error while merging result ./pabot_results/0/output.xml [ERROR] EXCEPTION RAISED DURING PABOT EXECUTION [ERROR] PLEASE CONSIDER REPORTING THIS ISSUE TO https://github.com/mkorpela/pabot/issues Pabot: 2.15.0 Python: 3.9.6 (default, Mar 10 2023, 20:16:38) [Clang 14.0.3 (clang-1403.0.22.14.1)] Robot Framework: 6.1b1 Total testing: 0.50 seconds Elapsed time: 0.64 seconds Traceback (most recent call last): File "/tmp/v/bin/pabot", line 8, in <module> sys.exit(main()) File "/private/tmp/v/lib/python3.9/site-packages/pabot/pabot.py", line 1875, in main return sys.exit(main_program(args)) File "/private/tmp/v/lib/python3.9/site-packages/pabot/pabot.py", line 1926, in main_program result_code = _report_results( File "/private/tmp/v/lib/python3.9/site-packages/pabot/pabot.py", line 1420, in _report_results return _report_results_for_one_run( File "/private/tmp/v/lib/python3.9/site-packages/pabot/pabot.py", line 1451, in _report_results_for_one_run output_path = _merge_one_run( File "/private/tmp/v/lib/python3.9/site-packages/pabot/pabot.py", line 1488, in _merge_one_run resu = merge( File "/private/tmp/v/lib/python3.9/site-packages/pabot/result_merger.py", line 254, in merge merged = merge_groups( File "/private/tmp/v/lib/python3.9/site-packages/pabot/result_merger.py", line 233, in merge_groups merger.merge(out) File "/private/tmp/v/lib/python3.9/site-packages/pabot/result_merger.py", line 59, in merge self.root.metadata._add_initial(merged.suite.metadata) AttributeError: 'Metadata' object has no attribute '_add_initial' ``` This looks to be caused by the commit https://github.com/robotframework/robotframework/commit/afcbbffd41c479e262260e858f62c77772419d8b which removed the private `NormalizedDict._add_initial` method referenced by pabot.
`NormalizedDict._add_initial()` was removed in favor of going through initial values in `NormalizedDict.__init__`. Pabot should call `update()` instead. Looking at `NormalizedDict` code we should actually that in `__init__` as well. Although `_add_initial()` was a private method and removing them ought to be fine also in non-major releases (especially when there's a stable API available), we can add it back until RF 7 if needed. Based on investigation by @oboehmer on Slack, there is also some issue caused by the new `parser` option, so probably a new Pabot release is needed anyway.
2023-05-06T14:13:45.000
-1.0
[ "tests/test_pabot.py::PabotTests::test_rebot_conf" ]
[ "tests/test_pabot.py::PabotTests::test_fix_items_split_containig_suite_when_subsuite_before", "tests/test_pabot.py::PabotTests::test_suite_ordering_group_is_removed_if_no_items", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_wait_command_if_it_would_be_first_element", "tests/test_pabot.py::PabotTests::test_solve_suite_names_file_is_not_changed_when_invalid_cli_opts", "tests/test_pabot.py::PabotTests::test_start_and_stop_remote_library", "tests/test_pabot.py::PabotTests::test_fix_items_combines_to_suite_when_test_from_suite_after_suite", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_with_pabotsuitenames_file_with_wait_command", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_old_duplicate", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_after_suitesfrom_file_removed", "tests/test_pabot.py::PabotTests::test_fix_works_with_waits", "tests/test_pabot.py::PabotTests::test_suite_ordering_adds_new_suites_to_end", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_when_suitesfrom_file_added_and_directory", "tests/test_pabot.py::PabotTests::test_hash_of_command", "tests/test_pabot.py::PabotTests::test_suite_ordering_adds_new_suite", "tests/test_pabot.py::PabotTests::test_fix_items_removes_duplicates", "tests/test_pabot.py::PabotTests::test_solve_suite_names_ignores_testlevelsplit_if_suites_and_tests", "tests/test_pabot.py::PabotTests::test_hash_of_dirs", "tests/test_pabot.py::PabotTests::test_copy_output_artifacts_include_subfolders", "tests/test_pabot.py::PabotTests::test_solve_suite_names_with_corrupted_pabotsuitenames_file", "tests/test_pabot.py::PabotTests::test_greates_common_name", "tests/test_pabot.py::PabotTests::test_suite_ordering_preserves_directory_suites", "tests/test_pabot.py::PabotTests::test_suite_ordering_stores_two_wait_commands", "tests/test_pabot.py::PabotTests::test_solve_suite_names_with_testlevelsplit_option", "tests/test_pabot.py::PabotTests::test_solve_suite_names_leaves_suites_and_tests", "tests/test_pabot.py::PabotTests::test_replace_base_name", "tests/test_pabot.py::PabotTests::test_test_item_removes_rerunfailed_option", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_with_pabotsuitenames_file_with_wait_command_when_cli_change", "tests/test_pabot.py::PabotTests::test_parse_args", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_when_suitesfrom_file_added", "tests/test_pabot.py::PabotTests::test_solve_suite_names_transforms_old_suite_names_to_new_format", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_with_pabotsuitenames_file", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_directory_suite_subsuites_also_from_old_list_2", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_wait_command_if_it_would_be_last_element", "tests/test_pabot.py::PabotTests::test_start_and_stop_remote_library_without_resourcefile", "tests/test_pabot.py::PabotTests::test_suite_ordering_with_group", "tests/test_pabot.py::PabotTests::test_suite_ordering_with_group_ignores_new_and_preserves_old_grouping", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_old_suite", "tests/test_pabot.py::PabotTests::test_test_item_name_replaces_pattern_chars", "tests/test_pabot.py::PabotTests::test_fix_items_combines_subsuites_when_after_containing_suite", "tests/test_pabot.py::PabotTests::test_fix_items_splits_to_tests_when_suite_after_test_from_that_suite", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_with_directory_suite", "tests/test_pabot.py::PabotTests::test_suite_root_name", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_without_pabotsuitenames_file", "tests/test_pabot.py::PabotTests::test_solve_suite_names_with_ioerror_pabotsuitenames", "tests/test_pabot.py::PabotTests::test_suite_ordering_splits_directory_suite", "tests/test_pabot.py::PabotTests::test_suite_ordering_uses_old_order", "tests/test_pabot.py::PabotTests::test_copy_output_artifacts_direct_screenshots_only", "tests/test_pabot.py::PabotTests::test_solve_suite_names_works_with_suitesfrom_option", "tests/test_pabot.py::PabotTests::test_suite_ordering_preserves_wait_command", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_directory_suite_subsuites_also_from_old_list", "tests/test_pabot.py::PabotTests::test_suite_ordering_removes_double_wait_command", "tests/test_pabot.py::PabotTests::test_file_hash", "tests/test_pabot.py::PabotTests::test_solve_suite_names_with_testlevelsplit_option_added" ]
python-hyper/wsproto
29
python-hyper__wsproto-29
['25']
f74bd34194d496b690246dfa78dcf133b6f8be34
diff --git a/tox.ini b/tox.ini index c7a5b7e..cb7abad 100644 --- a/tox.ini +++ b/tox.ini @@ -3,7 +3,7 @@ envlist = py27, py35, py36, lint, docs [testenv] deps = -r{toxinidir}/test_requirements.txt -commands = pytest --cov {envsitepackagesdir}/wsproto --cov-config {toxinidir}/.coveragerc {toxinidir}/test/ +commands = pytest --cov {envsitepackagesdir}/wsproto --cov-report term-missing --cov-config {toxinidir}/.coveragerc {toxinidir}/test/ [testenv:lint] basepython = python3.6 diff --git a/wsproto/compat.py b/wsproto/compat.py index 9e8b7b0..267fa78 100644 --- a/wsproto/compat.py +++ b/wsproto/compat.py @@ -1,4 +1,17 @@ +# flake8: noqa + import sys + PY2 = sys.version_info.major == 2 PY3 = sys.version_info.major == 3 + + +if PY3: + unicode = str + + def Utf8Validator(): + return None +else: + unicode = unicode + from .utf8validator import Utf8Validator diff --git a/wsproto/frame_protocol.py b/wsproto/frame_protocol.py index 8c5e23f..9426826 100644 --- a/wsproto/frame_protocol.py +++ b/wsproto/frame_protocol.py @@ -14,8 +14,7 @@ from enum import Enum, IntEnum -from .compat import PY2, PY3 -from .utf8validator import Utf8Validator +from .compat import unicode, Utf8Validator try: from wsaccel.xormask import XorMaskerSimple @@ -34,10 +33,6 @@ def process(self, data): return data -if PY3: - unicode = str - - # RFC6455, Section 5.2 - Base Framing Protocol # Payload length constants @@ -202,8 +197,7 @@ def process_frame(self, frame): raise ParseFailed("expected CONTINUATION, got %r" % frame.opcode) if frame.opcode is Opcode.TEXT: - if PY2: - self.validator = Utf8Validator() + self.validator = Utf8Validator() self.decoder = getincrementaldecoder("utf-8")() finished = frame.frame_finished and frame.message_finished @@ -223,7 +217,7 @@ def process_frame(self, frame): def decode_payload(self, data, finished): if self.validator is not None: - results = self.validator.validate(str(data)) + results = self.validator.validate(bytes(data)) if not results[0] or (finished and not results[1]): raise ParseFailed(u'encountered invalid UTF-8 while processing' ' text message at payload octet index %d' % @@ -433,8 +427,9 @@ def _process_close(self, frame): code <= MAX_PROTOCOL_CLOSE_REASON: raise ParseFailed( "CLOSE with unknown reserved code") - if PY2: - results = Utf8Validator().validate(str(data[2:])) + validator = Utf8Validator() + if validator is not None: + results = validator.validate(bytes(data[2:])) if not (results[0] and results[1]): raise ParseFailed(u'encountered invalid UTF-8 while' ' processing close message at payload' @@ -497,7 +492,7 @@ def close(self, code=None, reason=None): return self._serialize_frame(Opcode.CLOSE, payload) - def pong(self, payload=None): + def pong(self, payload=b''): return self._serialize_frame(Opcode.PONG, payload) def send_data(self, payload=b'', fin=True): @@ -506,6 +501,8 @@ def send_data(self, payload=b'', fin=True): elif isinstance(payload, unicode): opcode = Opcode.TEXT payload = payload.encode('utf-8') + else: + raise ValueError('Must provide bytes or text') if self._outbound_opcode is None: self._outbound_opcode = opcode @@ -522,9 +519,6 @@ def send_data(self, payload=b'', fin=True): def _serialize_frame(self, opcode, payload=b'', fin=True): rsv = RsvBits(False, False, False) for extension in reversed(self.extensions): - if not extension.enabled(): - continue - rsv, payload = extension.frame_outbound(self, opcode, rsv, payload, fin)
diff --git a/test/test_frame_protocol.py b/test/test_frame_protocol.py index d4555af..0c25c07 100644 --- a/test/test_frame_protocol.py +++ b/test/test_frame_protocol.py @@ -1,14 +1,31 @@ # -*- coding: utf-8 -*- -import pytest +import itertools from binascii import unhexlify from codecs import getincrementaldecoder import struct +import pytest + import wsproto.frame_protocol as fp import wsproto.extensions as wpext +class FakeValidator(object): + def __init__(self): + self.validated = b'' + + self.valid = True + self.ends_on_complete = True + self.octet = 0 + self.code_point = 0 + + def validate(self, data): + self.validated += data + return (self.valid, self.ends_on_complete, self.octet, + self.code_point) + + class TestBuffer(object): def test_consume_at_most_zero_bytes(self): buf = fp.Buffer(b'xxyyy') @@ -320,6 +337,65 @@ def test_split_unicode_message(self): assert frame.message_finished is True assert frame.payload == text_payload[(split // 3):] + def send_frame_to_validator(self, payload, finished): + decoder = fp.MessageDecoder() + frame = fp.Frame( + opcode=fp.Opcode.TEXT, + payload=payload, + frame_finished=finished, + message_finished=True, + ) + frame = decoder.process_frame(frame) + + def test_text_message_hits_validator(self, monkeypatch): + validator = FakeValidator() + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + text_payload = u'fñör∂' + binary_payload = text_payload.encode('utf8') + self.send_frame_to_validator(binary_payload, True) + + assert validator.validated == binary_payload + + def test_message_validation_failure_fails_properly(self, monkeypatch): + validator = FakeValidator() + validator.valid = False + + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + with pytest.raises(fp.ParseFailed): + self.send_frame_to_validator(b'', True) + + def test_message_validation_finish_on_incomplete(self, monkeypatch): + validator = FakeValidator() + validator.valid = True + validator.ends_on_complete = False + + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + with pytest.raises(fp.ParseFailed): + self.send_frame_to_validator(b'', True) + + def test_message_validation_unfinished_on_incomplete(self, monkeypatch): + validator = FakeValidator() + validator.valid = True + validator.ends_on_complete = False + + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + self.send_frame_to_validator(b'', False) + + def test_message_no_validation_can_still_fail(self, monkeypatch): + validator = FakeValidator() + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + payload = u'fñörd' + payload = payload.encode('iso-8859-1') + + with pytest.raises(fp.ParseFailed) as exc: + self.send_frame_to_validator(payload, True) + assert exc.value.code == fp.CloseReason.INVALID_FRAME_PAYLOAD_DATA + class TestFrameDecoder(object): def _single_frame_test(self, client, frame_bytes, opcode, payload, @@ -552,6 +628,15 @@ def test_not_enough_for_very_long_length(self): split=7, ) + def test_eight_byte_length_with_msb_set(self): + frame_bytes = b'\x81\x7f\x80\x80\x80\x80\x80\x80\x80\x80' + + self._parse_failure_test( + client=True, + frame_bytes=frame_bytes, + close_reason=fp.CloseReason.PROTOCOL_ERROR, + ) + def test_not_enough_for_mask(self): payload = bytearray(b'xy') mask = bytearray(b'abcd') @@ -631,6 +716,17 @@ def test_long_message_sliced(self): split=65535, ) + def test_overly_long_control_frame(self): + payload = b'x' * 128 + payload_len = struct.pack('!H', len(payload)) + frame_bytes = b'\x89\x7e' + payload_len + payload + + self._parse_failure_test( + client=True, + frame_bytes=frame_bytes, + close_reason=fp.CloseReason.PROTOCOL_ERROR, + ) + class TestFrameDecoderExtensions(object): class FakeExtension(wpext.Extension): @@ -638,10 +734,11 @@ class FakeExtension(wpext.Extension): def __init__(self): self._inbound_header_called = False - self._rsv_bit_set = False + self._inbound_rsv_bit_set = False self._inbound_payload_data_called = False self._inbound_complete_called = False self._fail_inbound_complete = False + self._outbound_rsv_bit_set = False def enabled(self): return True @@ -650,7 +747,7 @@ def frame_inbound_header(self, proto, opcode, rsv, payload_length): self._inbound_header_called = True if opcode is fp.Opcode.PONG: return fp.CloseReason.MANDATORY_EXT - self._rsv_bit_set = rsv[2] + self._inbound_rsv_bit_set = rsv.rsv3 return fp.RsvBits(False, False, True) def frame_inbound_payload_data(self, proto, data): @@ -659,7 +756,7 @@ def frame_inbound_payload_data(self, proto, data): return fp.CloseReason.POLICY_VIOLATION elif data == b'ragequit': self._fail_inbound_complete = True - if self._rsv_bit_set: + if self._inbound_rsv_bit_set: data = data.decode('utf-8').upper().encode('utf-8') return data @@ -667,9 +764,18 @@ def frame_inbound_complete(self, proto, fin): self._inbound_complete_called = True if self._fail_inbound_complete: return fp.CloseReason.ABNORMAL_CLOSURE - if fin and self._rsv_bit_set: + if fin and self._inbound_rsv_bit_set: return u'™'.encode('utf-8') + def frame_outbound(self, proto, opcode, rsv, data, fin): + if opcode is fp.Opcode.TEXT: + rsv = fp.RsvBits(rsv.rsv1, rsv.rsv2, True) + self._outbound_rsv_bit_set = True + if fin and self._outbound_rsv_bit_set: + data += u'®'.encode('utf-8') + self._outbound_rsv_bit_set = False + return rsv, data + def test_rsv_bit(self): ext = self.FakeExtension() decoder = fp.FrameDecoder(client=True, extensions=[ext]) @@ -680,7 +786,7 @@ def test_rsv_bit(self): frame = decoder.process_buffer() assert frame is not None assert ext._inbound_header_called - assert ext._rsv_bit_set + assert ext._inbound_rsv_bit_set def test_wrong_rsv_bit(self): ext = self.FakeExtension() @@ -719,7 +825,7 @@ def test_payload_processing(self): frame = decoder.process_buffer() assert frame is not None assert ext._inbound_header_called - assert ext._rsv_bit_set + assert ext._inbound_rsv_bit_set assert ext._inbound_payload_data_called assert frame.payload == expected_payload @@ -736,7 +842,7 @@ def test_no_payload_processing_when_not_wanted(self): frame = decoder.process_buffer() assert frame is not None assert ext._inbound_header_called - assert not ext._rsv_bit_set + assert not ext._inbound_rsv_bit_set assert ext._inbound_payload_data_called assert frame.payload == expected_payload @@ -766,7 +872,7 @@ def test_frame_completion(self): frame = decoder.process_buffer() assert frame is not None assert ext._inbound_header_called - assert ext._rsv_bit_set + assert ext._inbound_rsv_bit_set assert ext._inbound_payload_data_called assert ext._inbound_complete_called assert frame.payload == expected_payload @@ -784,7 +890,7 @@ def test_no_frame_completion_when_not_wanted(self): frame = decoder.process_buffer() assert frame is not None assert ext._inbound_header_called - assert not ext._rsv_bit_set + assert not ext._inbound_rsv_bit_set assert ext._inbound_payload_data_called assert ext._inbound_complete_called assert frame.payload == expected_payload @@ -802,6 +908,27 @@ def test_completion_error_handling(self): decoder.process_buffer() assert excinfo.value.code is fp.CloseReason.ABNORMAL_CLOSURE + def test_outbound_handling_single_frame(self): + ext = self.FakeExtension() + proto = fp.FrameProtocol(client=False, extensions=[ext]) + payload = u'😃😄🙃😉' + data = proto.send_data(payload, fin=True) + payload = (payload + u'®').encode('utf8') + assert data == b'\x91' + bytearray([len(payload)]) + payload + + def test_outbound_handling_multiple_frames(self): + ext = self.FakeExtension() + proto = fp.FrameProtocol(client=False, extensions=[ext]) + payload = u'😃😄🙃😉' + data = proto.send_data(payload, fin=False) + payload = payload.encode('utf8') + assert data == b'\x11' + bytearray([len(payload)]) + payload + + payload = u'¯\_(ツ)_/¯' + data = proto.send_data(payload, fin=True) + payload = (payload + u'®').encode('utf8') + assert data == b'\x80' + bytearray([len(payload)]) + payload + class TestFrameProtocolReceive(object): def test_long_text_message(self): @@ -820,7 +947,9 @@ def test_long_text_message(self): assert frame.payload == payload def _close_test(self, code, reason=None, reason_bytes=None): - payload = struct.pack('!H', code) + payload = b'' + if code: + payload += struct.pack('!H', code) if reason: payload += reason.encode('utf8') elif reason_bytes: @@ -834,12 +963,39 @@ def _close_test(self, code, reason=None, reason_bytes=None): assert len(frames) == 1 frame = frames[0] assert frame.opcode == fp.Opcode.CLOSE - assert frame.payload[0] == code + assert frame.payload[0] == code or fp.CloseReason.NO_STATUS_RCVD if reason: assert frame.payload[1] == reason else: assert not frame.payload[1] + def test_close_no_code(self): + self._close_test(None) + + def test_close_one_byte_code(self): + frame_bytes = b'\x88\x01\x0e' + protocol = fp.FrameProtocol(client=True, extensions=[]) + + with pytest.raises(fp.ParseFailed) as exc: + protocol.receive_bytes(frame_bytes) + list(protocol.received_frames()) + assert exc.value.code == fp.CloseReason.PROTOCOL_ERROR + + def test_close_bad_code(self): + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(123) + assert exc.value.code == fp.CloseReason.PROTOCOL_ERROR + + def test_close_unknown_code(self): + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(2998) + assert exc.value.code == fp.CloseReason.PROTOCOL_ERROR + + def test_close_local_only_code(self): + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(fp.CloseReason.NO_STATUS_RCVD) + assert exc.value.code == fp.CloseReason.PROTOCOL_ERROR + def test_close_no_payload(self): self._close_test(fp.CloseReason.NORMAL_CLOSURE) @@ -863,66 +1019,240 @@ def test_close_incomplete_utf8_payload(self): reason_bytes=payload) assert exc.value.code == fp.CloseReason.INVALID_FRAME_PAYLOAD_DATA + def test_random_control_frame(self): + payload = b'give me one ping vasily' + frame_bytes = b'\x89' + bytearray([len(payload)]) + payload -def test_close_with_long_reason(): - # Long close reasons get silently truncated - proto = fp.FrameProtocol(client=False, extensions=[]) - data = proto.close(code=fp.CloseReason.NORMAL_CLOSURE, - reason="x" * 200) - assert data == bytearray(unhexlify("887d03e8")) + b"x" * 123 - - # While preserving valid utf-8 - proto = fp.FrameProtocol(client=False, extensions=[]) - # pound sign is 2 bytes in utf-8, so naive truncation to 123 bytes will - # cut it in half. Instead we truncate to 122 bytes. - data = proto.close(code=fp.CloseReason.NORMAL_CLOSURE, - reason=u"£" * 100) - assert data == unhexlify("887c03e8") + u"£".encode("utf-8") * 61 - - -def test_payload_length_decode(): - # "the minimal number of bytes MUST be used to encode the length, for - # example, the length of a 124-byte-long string can't be encoded as the - # sequence 126, 0, 124" -- RFC 6455 - - def make_header(encoding_bytes, payload_len): - if encoding_bytes == 1: - assert payload_len <= 125 - return unhexlify("81") + bytes([payload_len]) - elif encoding_bytes == 2: - assert payload_len < 2**16 - return unhexlify("81" "7e") + struct.pack("!H", payload_len) - elif encoding_bytes == 8: - return unhexlify("81" "7f") + struct.pack("!Q", payload_len) - else: - assert False + protocol = fp.FrameProtocol(client=True, extensions=[]) + protocol.receive_bytes(frame_bytes) + frames = list(protocol.received_frames()) + assert len(frames) == 1 + frame = frames[0] + assert frame.opcode == fp.Opcode.PING + assert len(frame.payload) == len(payload) + assert frame.payload == payload - def make_and_parse(encoding_bytes, payload_len): - proto = fp.FrameProtocol(client=True, extensions=[]) - proto.receive_bytes(make_header(encoding_bytes, payload_len)) - list(proto.received_frames()) - - # Valid lengths for 1 byte - for payload_len in [0, 1, 2, 123, 124, 125]: - make_and_parse(1, payload_len) - for encoding_bytes in [2, 8]: - with pytest.raises(fp.ParseFailed) as excinfo: - make_and_parse(encoding_bytes, payload_len) - assert "used {} bytes".format(encoding_bytes) in str(excinfo.value) - - # Valid lengths for 2 bytes - for payload_len in [126, 127, 1000, 2**16 - 1]: - make_and_parse(2, payload_len) - with pytest.raises(fp.ParseFailed) as excinfo: - make_and_parse(8, payload_len) - assert "used 8 bytes" in str(excinfo.value) + def test_close_reasons_get_utf8_validated(self, monkeypatch): + validator = FakeValidator() + reason = u'ƒñø®∂' + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) - # Valid lengths for 8 bytes - for payload_len in [2**16, 2**16 + 1, 2**32, 2**63 - 1]: - make_and_parse(8, payload_len) + self._close_test(fp.CloseReason.NORMAL_CLOSURE, reason=reason) - # Invalid lengths for 8 bytes - for payload_len in [2**63, 2**63 + 1]: - with pytest.raises(fp.ParseFailed) as excinfo: - make_and_parse(8, payload_len) - assert "non-zero MSB" in str(excinfo.value) + assert validator.validated == reason.encode('utf8') + + def test_close_reason_failing_validation_fails(self, monkeypatch): + validator = FakeValidator() + validator.valid = False + reason = u'ƒñø®∂' + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(fp.CloseReason.NORMAL_CLOSURE, reason=reason) + assert exc.value.code == fp.CloseReason.INVALID_FRAME_PAYLOAD_DATA + + def test_close_reason_with_incomplete_utf8_fails(self, monkeypatch): + validator = FakeValidator() + validator.ends_on_complete = False + reason = u'ƒñø®∂' + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(fp.CloseReason.NORMAL_CLOSURE, reason=reason) + assert exc.value.code == fp.CloseReason.INVALID_FRAME_PAYLOAD_DATA + + def test_close_no_validation(self, monkeypatch): + monkeypatch.setattr(fp, 'Utf8Validator', lambda: None) + reason = u'ƒñø®∂' + self._close_test(fp.CloseReason.NORMAL_CLOSURE, reason=reason) + + def test_close_no_validation_can_still_fail(self, monkeypatch): + validator = FakeValidator() + monkeypatch.setattr(fp, 'Utf8Validator', lambda: validator) + + reason = u'fñörd' + reason = reason.encode('iso-8859-1') + + with pytest.raises(fp.ParseFailed) as exc: + self._close_test(fp.CloseReason.NORMAL_CLOSURE, + reason_bytes=reason) + assert exc.value.code == fp.CloseReason.INVALID_FRAME_PAYLOAD_DATA + + +class TestFrameProtocolSend(object): + def test_simplest_possible_close(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + data = proto.close() + assert data == b'\x88\x00' + + def test_unreasoning_close(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + data = proto.close(code=fp.CloseReason.NORMAL_CLOSURE) + assert data == b'\x88\x02\x03\xe8' + + def test_reasoned_close(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + reason = u'¯\_(ツ)_/¯' + expected_payload = struct.pack('!H', fp.CloseReason.NORMAL_CLOSURE) + \ + reason.encode('utf8') + data = proto.close(code=fp.CloseReason.NORMAL_CLOSURE, reason=reason) + assert data == b'\x88' + bytearray([len(expected_payload)]) + \ + expected_payload + + def test_overly_reasoned_close(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + reason = u'¯\_(ツ)_/¯' * 10 + data = proto.close(code=fp.CloseReason.NORMAL_CLOSURE, reason=reason) + assert bytes(data[0:1]) == b'\x88' + assert len(data) <= 127 + assert data[4:].decode('utf8') + + def test_reasoned_but_uncoded_close(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + with pytest.raises(TypeError): + proto.close(reason='termites') + + def test_local_only_close_reason(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + data = proto.close(code=fp.CloseReason.NO_STATUS_RCVD) + assert data == b'\x88\x02\x03\xe8' + + def test_pong_without_payload(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + data = proto.pong() + assert data == b'\x8a\x00' + + def test_pong_with_payload(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = u'¯\_(ツ)_/¯'.encode('utf8') + data = proto.pong(payload) + assert data == b'\x8a' + bytearray([len(payload)]) + payload + + def test_single_short_binary_data(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b"it's all just ascii, right?" + data = proto.send_data(payload, fin=True) + assert data == b'\x82' + bytearray([len(payload)]) + payload + + def test_single_short_text_data(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = u'😃😄🙃😉' + data = proto.send_data(payload, fin=True) + payload = payload.encode('utf8') + assert data == b'\x81' + bytearray([len(payload)]) + payload + + def test_multiple_short_binary_data(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b"it's all just ascii, right?" + data = proto.send_data(payload, fin=False) + assert data == b'\x02' + bytearray([len(payload)]) + payload + + payload = b'sure no worries' + data = proto.send_data(payload, fin=True) + assert data == b'\x80' + bytearray([len(payload)]) + payload + + def test_multiple_short_text_data(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = u'😃😄🙃😉' + data = proto.send_data(payload, fin=False) + payload = payload.encode('utf8') + assert data == b'\x01' + bytearray([len(payload)]) + payload + + payload = u'🙈🙉🙊' + data = proto.send_data(payload, fin=True) + payload = payload.encode('utf8') + assert data == b'\x80' + bytearray([len(payload)]) + payload + + def test_mismatched_data_messages1(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = u'😃😄🙃😉' + data = proto.send_data(payload, fin=False) + payload = payload.encode('utf8') + assert data == b'\x01' + bytearray([len(payload)]) + payload + + payload = b'seriously, all ascii' + with pytest.raises(TypeError): + proto.send_data(payload) + + def test_mismatched_data_messages2(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b"it's all just ascii, right?" + data = proto.send_data(payload, fin=False) + assert data == b'\x02' + bytearray([len(payload)]) + payload + + payload = u'✔️☑️✅✔︎☑' + with pytest.raises(TypeError): + proto.send_data(payload) + + def test_message_length_max_short(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b'x' * 125 + data = proto.send_data(payload, fin=True) + assert data == b'\x82' + bytearray([len(payload)]) + payload + + def test_message_length_min_two_byte(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b'x' * 126 + data = proto.send_data(payload, fin=True) + assert data == b'\x82\x7e' + struct.pack('!H', len(payload)) + payload + + def test_message_length_max_two_byte(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b'x' * (2 ** 16 - 1) + data = proto.send_data(payload, fin=True) + assert data == b'\x82\x7e' + struct.pack('!H', len(payload)) + payload + + def test_message_length_min_eight_byte(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b'x' * (2 ** 16) + data = proto.send_data(payload, fin=True) + assert data == b'\x82\x7f' + struct.pack('!Q', len(payload)) + payload + + def test_client_side_masking_short_frame(self): + proto = fp.FrameProtocol(client=True, extensions=[]) + payload = b'x' * 125 + data = proto.send_data(payload, fin=True) + assert data[0] == 0x82 + assert struct.unpack('!B', data[1:2])[0] == len(payload) | 0x80 + masking_key = data[2:6] + maskbytes = itertools.cycle(masking_key) + assert data[6:] == \ + bytearray(b ^ next(maskbytes) for b in bytearray(payload)) + + def test_client_side_masking_two_byte_frame(self): + proto = fp.FrameProtocol(client=True, extensions=[]) + payload = b'x' * 126 + data = proto.send_data(payload, fin=True) + assert data[0] == 0x82 + assert data[1] == 0xfe + assert struct.unpack('!H', data[2:4])[0] == len(payload) + masking_key = data[4:8] + maskbytes = itertools.cycle(masking_key) + assert data[8:] == \ + bytearray(b ^ next(maskbytes) for b in bytearray(payload)) + + def test_client_side_masking_eight_byte_frame(self): + proto = fp.FrameProtocol(client=True, extensions=[]) + payload = b'x' * 65536 + data = proto.send_data(payload, fin=True) + assert data[0] == 0x82 + assert data[1] == 0xff + assert struct.unpack('!Q', data[2:10])[0] == len(payload) + masking_key = data[10:14] + maskbytes = itertools.cycle(masking_key) + assert data[14:] == \ + bytearray(b ^ next(maskbytes) for b in bytearray(payload)) + + def test_control_frame_with_overly_long_payload(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = b'x' * 126 + + with pytest.raises(ValueError): + proto.pong(payload) + + def test_data_we_have_no_idea_what_to_do_with(self): + proto = fp.FrameProtocol(client=False, extensions=[]) + payload = dict() + + with pytest.raises(ValueError): + proto.send_data(payload)
We need more send-side tests. With the recent rewrite we now have fairly good coverage on the receive side but we need a lot more coverage on the send side.
2017-06-02T05:17:37.000
-1.0
[ "test/test_frame_protocol.py::TestFrameProtocolSend::test_data_we_have_no_idea_what_to_do_with", "test/test_frame_protocol.py::TestMessageDecoder::test_message_validation_failure_fails_properly", "test/test_frame_protocol.py::TestMessageDecoder::test_text_message_hits_validator", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_reasons_get_utf8_validated", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_reason_with_incomplete_utf8_fails", "test/test_frame_protocol.py::TestFrameProtocolSend::test_pong_without_payload", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_reason_failing_validation_fails", "test/test_frame_protocol.py::TestMessageDecoder::test_message_validation_finish_on_incomplete" ]
[ "test/test_frame_protocol.py::TestBuffer::test_consume_at_most_with_no_data", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_outbound_handling_single_frame", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_no_payload_processing_when_not_wanted", "test/test_frame_protocol.py::TestFrameProtocolSend::test_local_only_close_reason", "test/test_frame_protocol.py::TestBuffer::test_consume_at_most_zero_bytes", "test/test_frame_protocol.py::TestFrameProtocolSend::test_single_short_binary_data", "test/test_frame_protocol.py::TestFrameProtocolSend::test_control_frame_with_overly_long_payload", "test/test_frame_protocol.py::TestMessageDecoder::test_bad_unicode", "test/test_frame_protocol.py::TestMessageDecoder::test_final_text_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_unknown_code", "test/test_frame_protocol.py::TestFrameDecoder::test_insufficiently_long_message_frame", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_rsv_bit", "test/test_frame_protocol.py::TestFrameProtocolSend::test_pong_with_payload", "test/test_frame_protocol.py::TestFrameDecoder::test_not_enough_for_mask", "test/test_frame_protocol.py::TestFrameDecoder::test_partial_control_frame", "test/test_frame_protocol.py::TestFrameDecoder::test_short_server_message_frame", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_outbound_handling_multiple_frames", "test/test_frame_protocol.py::TestFrameDecoder::test_insufficiently_very_long_message_frame", "test/test_frame_protocol.py::TestFrameDecoder::test_very_long_message_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_bad_code", "test/test_frame_protocol.py::TestFrameProtocolSend::test_simplest_possible_close", "test/test_frame_protocol.py::TestFrameDecoder::test_zero_length_message", "test/test_frame_protocol.py::TestMessageDecoder::test_start_with_continuation", "test/test_frame_protocol.py::TestFrameProtocolSend::test_client_side_masking_short_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_random_control_frame", "test/test_frame_protocol.py::TestFrameProtocolSend::test_message_length_min_eight_byte", "test/test_frame_protocol.py::TestFrameProtocolSend::test_client_side_masking_two_byte_frame", "test/test_frame_protocol.py::TestBuffer::test_consume_exactly_with_insufficient_data", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_no_validation_can_still_fail", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_payload_error_handling", "test/test_frame_protocol.py::TestFrameDecoder::test_reject_masked_server_frame", "test/test_frame_protocol.py::TestFrameProtocolSend::test_unreasoning_close", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_utf8_payload", "test/test_frame_protocol.py::TestBuffer::test_consume_exactly_with_more_than_sufficient_data", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_easy_payload", "test/test_frame_protocol.py::TestFrameProtocolSend::test_single_short_text_data", "test/test_frame_protocol.py::TestFrameProtocolSend::test_reasoned_close", "test/test_frame_protocol.py::TestFrameDecoder::test_not_enough_for_header", "test/test_frame_protocol.py::TestMessageDecoder::test_split_unicode_message", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_no_validation", "test/test_frame_protocol.py::TestFrameDecoder::test_long_message_sliced", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_bad_utf8_payload", "test/test_frame_protocol.py::TestFrameDecoder::test_reject_unfinished_control_frame", "test/test_frame_protocol.py::TestFrameDecoder::test_reject_unmasked_client_frame", "test/test_frame_protocol.py::TestFrameProtocolSend::test_mismatched_data_messages2", "test/test_frame_protocol.py::TestBuffer::test_consume_at_most_with_sufficient_data", "test/test_frame_protocol.py::TestFrameDecoder::test_very_insufficiently_very_long_message_frame", "test/test_frame_protocol.py::TestMessageDecoder::test_split_message", "test/test_frame_protocol.py::TestBuffer::test_consume_at_most_with_more_than_sufficient_data", "test/test_frame_protocol.py::TestFrameDecoder::test_not_enough_for_very_long_length", "test/test_frame_protocol.py::TestBuffer::test_feed", "test/test_frame_protocol.py::TestFrameProtocolSend::test_message_length_max_two_byte", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_no_frame_completion_when_not_wanted", "test/test_frame_protocol.py::TestBuffer::test_rollback", "test/test_frame_protocol.py::TestMessageDecoder::test_not_even_unicode", "test/test_frame_protocol.py::TestFrameDecoder::test_reject_reserved_bits", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_long_text_message", "test/test_frame_protocol.py::TestFrameDecoder::test_partial_message_frames", "test/test_frame_protocol.py::TestFrameProtocolSend::test_mismatched_data_messages1", "test/test_frame_protocol.py::TestFrameProtocolSend::test_overly_reasoned_close", "test/test_frame_protocol.py::TestFrameDecoder::test_long_message_frame", "test/test_frame_protocol.py::TestFrameDecoder::test_eight_byte_length_with_msb_set", "test/test_frame_protocol.py::TestFrameProtocolSend::test_client_side_masking_eight_byte_frame", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_completion_error_handling", "test/test_frame_protocol.py::TestFrameProtocolSend::test_message_length_max_short", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_one_byte_code", "test/test_frame_protocol.py::TestMessageDecoder::test_message_validation_unfinished_on_incomplete", "test/test_frame_protocol.py::TestBuffer::test_length", "test/test_frame_protocol.py::TestMessageDecoder::test_missing_continuation_1", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_header_error_handling", "test/test_frame_protocol.py::TestMessageDecoder::test_single_text_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_no_code", "test/test_frame_protocol.py::TestBuffer::test_consume_exactly_with_sufficient_data", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_wrong_rsv_bit", "test/test_frame_protocol.py::TestMessageDecoder::test_follow_on_binary_frame", "test/test_frame_protocol.py::TestBuffer::test_commit", "test/test_frame_protocol.py::TestFrameProtocolSend::test_message_length_min_two_byte", "test/test_frame_protocol.py::TestFrameDecoder::test_overly_long_control_frame", "test/test_frame_protocol.py::TestMessageDecoder::test_incomplete_unicode", "test/test_frame_protocol.py::TestMessageDecoder::test_follow_on_text_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_local_only_code", "test/test_frame_protocol.py::TestMessageDecoder::test_single_binary_frame", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_no_payload", "test/test_frame_protocol.py::TestMessageDecoder::test_missing_continuation_2", "test/test_frame_protocol.py::TestBuffer::test_consume_at_most_with_insufficient_data", "test/test_frame_protocol.py::TestFrameProtocolSend::test_multiple_short_text_data", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_frame_completion", "test/test_frame_protocol.py::TestFrameProtocolReceive::test_close_incomplete_utf8_payload", "test/test_frame_protocol.py::TestFrameDecoder::test_not_enough_for_long_length", "test/test_frame_protocol.py::TestFrameDecoder::test_short_client_message_frame", "test/test_frame_protocol.py::TestFrameDecoderExtensions::test_payload_processing", "test/test_frame_protocol.py::TestFrameDecoder::test_reject_bad_opcode", "test/test_frame_protocol.py::TestMessageDecoder::test_message_no_validation_can_still_fail", "test/test_frame_protocol.py::TestFrameProtocolSend::test_reasoned_but_uncoded_close", "test/test_frame_protocol.py::TestFrameProtocolSend::test_multiple_short_binary_data" ]
msoulier/tftpy
111
msoulier__tftpy-111
['110']
af2f2fe89a3bf45748b78703820efb0986a8207a
diff --git a/tftpy/TftpStates.py b/tftpy/TftpStates.py index 42bac1d..ef90bf0 100644 --- a/tftpy/TftpStates.py +++ b/tftpy/TftpStates.py @@ -279,7 +279,7 @@ def serverInitial(self, pkt, raddress, rport): # root directory self.full_path = os.path.abspath(full_path) log.debug("full_path is %s", full_path) - if self.full_path.startswith(self.context.root): + if self.full_path.startswith(os.path.normpath(self.context.root) + "/"): log.info("requested file is in the server root - good") else: log.warning("requested file is not within the server root - bad")
diff --git a/t/test.py b/t/test.py index df9d7a2..b0bf7fa 100644 --- a/t/test.py +++ b/t/test.py @@ -8,8 +8,11 @@ import os import time import threading +from contextlib import contextmanager from errno import EINTR from multiprocessing import Queue +from shutil import rmtree +from tempfile import mkdtemp log = logging.getLogger('tftpy') log.setLevel(logging.DEBUG) @@ -204,6 +207,19 @@ def clientServerDownloadOptions(self, options, output='/tmp/out'): else: server.listen('localhost', 20001) + @contextmanager + def dummyServerDir(self): + tmpdir = mkdtemp() + for dirname in ("foo", "foo-private", "other"): + os.mkdir(os.path.join(tmpdir, dirname)) + with open(os.path.join(tmpdir, dirname, "bar"), "w") as w: + w.write("baz") + + try: + yield tmpdir + finally: + rmtree(tmpdir) + def testClientServerNoOptions(self): self.clientServerDownloadOptions({}) @@ -335,42 +351,103 @@ def testServerNoOptionsSubdir(self): finalstate = serverstate.state.handle(ack, raddress, rport) self.assertTrue( finalstate is None ) - def testServerInsecurePath(self): + def testServerInsecurePathAbsolute(self): raddress = '127.0.0.2' rport = 10000 timeout = 5 - root = os.path.dirname(os.path.abspath(__file__)) - serverstate = tftpy.TftpContexts.TftpContextServer(raddress, - rport, - timeout, - root) - rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() - rrq.filename = '../setup.py' - rrq.mode = 'octet' - rrq.options = {} - - # Start the download. - self.assertRaises(tftpy.TftpException, - serverstate.start, rrq.encode().buffer) - - def testServerSecurePath(self): + with self.dummyServerDir() as d: + root = os.path.join(os.path.abspath(d), "foo") + serverstate = tftpy.TftpContexts.TftpContextServer(raddress, + rport, + timeout, + root) + rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() + rrq.filename = os.path.join(os.path.abspath(d), "other/bar") + rrq.mode = 'octet' + rrq.options = {} + + # Start the download. + self.assertRaises(tftpy.TftpException, + serverstate.start, rrq.encode().buffer) + + def testServerInsecurePathRelative(self): raddress = '127.0.0.2' rport = 10000 timeout = 5 - root = os.path.dirname(os.path.abspath(__file__)) - serverstate = tftpy.TftpContexts.TftpContextServer(raddress, - rport, - timeout, - root) - rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() - rrq.filename = '640KBFILE' - rrq.mode = 'octet' - rrq.options = {} + with self.dummyServerDir() as d: + root = os.path.join(os.path.abspath(d), "foo") + serverstate = tftpy.TftpContexts.TftpContextServer(raddress, + rport, + timeout, + root) + rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() + rrq.filename = '../other/bar' + rrq.mode = 'octet' + rrq.options = {} + + # Start the download. + self.assertRaises(tftpy.TftpException, + serverstate.start, rrq.encode().buffer) + + def testServerInsecurePathRootSibling(self): + raddress = '127.0.0.2' + rport = 10000 + timeout = 5 + with self.dummyServerDir() as d: + root = os.path.join(os.path.abspath(d), "foo") + serverstate = tftpy.TftpContexts.TftpContextServer(raddress, + rport, + timeout, + root) + rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() + rrq.filename = root + "-private/bar" + rrq.mode = 'octet' + rrq.options = {} + + # Start the download. + self.assertRaises(tftpy.TftpException, + serverstate.start, rrq.encode().buffer) + + def testServerSecurePathAbsolute(self): + raddress = '127.0.0.2' + rport = 10000 + timeout = 5 + with self.dummyServerDir() as d: + root = os.path.join(os.path.abspath(d), "foo") + serverstate = tftpy.TftpContexts.TftpContextServer(raddress, + rport, + timeout, + root) + rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() + rrq.filename = os.path.join(root, "bar") + rrq.mode = 'octet' + rrq.options = {} + + # Start the download. + serverstate.start(rrq.encode().buffer) + # Should be in expectack state. + self.assertTrue(isinstance(serverstate.state, + tftpy.TftpStates.TftpStateExpectACK)) - # Start the download. - serverstate.start(rrq.encode().buffer) - # Should be in expectack state. - self.assertTrue(isinstance(serverstate.state, + def testServerSecurePathRelative(self): + raddress = '127.0.0.2' + rport = 10000 + timeout = 5 + with self.dummyServerDir() as d: + root = os.path.join(os.path.abspath(d), "foo") + serverstate = tftpy.TftpContexts.TftpContextServer(raddress, + rport, + timeout, + root) + rrq = tftpy.TftpPacketTypes.TftpPacketRRQ() + rrq.filename = "bar" + rrq.mode = 'octet' + rrq.options = {} + + # Start the download. + serverstate.start(rrq.encode().buffer) + # Should be in expectack state. + self.assertTrue(isinstance(serverstate.state, tftpy.TftpStates.TftpStateExpectACK)) def testServerDownloadWithStopNow(self, output='/tmp/out'):
Directory traversal outside tftproot (previously sent to author privately, posting publicly at his request) When `tftpy` 0.8.0's `TftpServer` checks that the requested file lies within `tftproot` @ [TftpStates.py:272](https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L272), it does a simple string comparison to check the prefixes match. This will *not* catch a case where the `tftproot` directory has a sibling file/directory that shares `tftproot` as its prefix. Consider: ``` /var/data /var/data-private ``` Starting a` TftpServer` with `tftproot="/var/data"` will allow access to `/var/data-private` via `get /var/data-private/foo`. For a more contrived example imagine a user starting a `TftpServer` with `tftproot="/e"` - all of a sudden they're exposing /etc. Trying to mitigate this by specifying a `tftproot` with a trailing slash won't even work because the early call to `abspath` @ [TftpServer.py:45](https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpServer.py#L45) will strip any trailing slashes.
2020-08-29T00:22:52.000
-1.0
[ "t/test.py::TestTftpyState::testServerInsecurePathRootSibling" ]
[ "t/test.py::TestTftpyState::testClientServerNoOptions", "t/test.py::TestTftpyState::testClientServerUploadFileObj", "t/test.py::TestTftpyState::testServerInsecurePathAbsolute", "t/test.py::TestTftpyState::testClientServerUploadWithSubdirs", "t/test.py::TestTftpyClasses::testTftpPacketERR", "t/test.py::TestTftpyState::testClientServerUploadCustomOpenForbids", "t/test.py::TestTftpyClasses::testTftpPacketFactory", "t/test.py::TestTftpyClasses::testTftpPacketOACK", "t/test.py::TestTftpyState::testClientServerUploadCustomOpen", "t/test.py::TestTftpyState::testClientServerUploadNoOptions", "t/test.py::TestTftpyClasses::testTftpPacketWRQ", "t/test.py::TestTftpyState::testServerDownloadWithStopNotNow", "t/test.py::TestTftpyState::testServerInsecurePathRelative", "t/test.py::TestTftpyState::testClientServerUploadTsize", "t/test.py::TestTftpyState::testClientServerTsizeOptions", "t/test.py::TestTftpyState::testServerNoOptions", "t/test.py::TestTftpyClasses::testTftpPacketRRQ", "t/test.py::TestTftpyState::testClientServerUploadOptions", "t/test.py::TestTftpyState::testClientServerBlksize", "t/test.py::TestTftpyState::testServerSecurePathRelative", "t/test.py::TestTftpyState::testClientFileObject", "t/test.py::TestTftpyState::testClientServerUploadStartingSlash", "t/test.py::TestTftpyState::testServerSecurePathAbsolute", "t/test.py::TestTftpyState::testServerDownloadWithDynamicPort", "t/test.py::TestTftpyClasses::testTftpPacketACK", "t/test.py::TestTftpyClasses::testTftpPacketDAT", "t/test.py::TestTftpyState::testServerDownloadWithStopNow", "t/test.py::TestTftpyState::testClientServerNoOptionsDelay", "t/test.py::TestTftpyState::testServerNoOptionsSubdir" ]
pfmoore/editables
32
pfmoore__editables-32
['31']
38f210e51bfed679e54e579ed0101c034ad81ab4
diff --git a/src/editables/redirector.py b/src/editables/redirector.py index e898d81..7bdef59 100644 --- a/src/editables/redirector.py +++ b/src/editables/redirector.py @@ -37,3 +37,11 @@ def install(cls) -> None: break else: sys.meta_path.append(cls) + + @classmethod + def invalidate_caches(cls) -> None: + # importlib.invalidate_caches calls finders' invalidate_caches methods, + # and since we install this meta path finder as a class rather than an instance, + # we have to override the inherited invalidate_caches method (using self) + # as a classmethod instead + pass
diff --git a/tests/test_redirects.py b/tests/test_redirects.py index eead159..65a2059 100644 --- a/tests/test_redirects.py +++ b/tests/test_redirects.py @@ -1,4 +1,5 @@ import contextlib +import importlib import sys from editables.redirector import RedirectingFinder as F @@ -81,3 +82,10 @@ def test_redirects(tmp_path): import pkg.sub assert pkg.sub.val == 42 + + +def test_cache_invalidation(): + F.install() + # assert that the finder matches importlib's expectations + # see https://github.com/pfmoore/editables/issues/31 + importlib.invalidate_caches()
TypeError: MetaPathFinder.invalidate_caches() missing 1 required positional argument: 'self' When `editables` meta path finder is loaded and appears in `sys.meta_path`, running `importlib.invalidate_caches()` gives the following traceback: ```pycon >>> from importlib import invalidate_caches >>> invalidate_caches() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/pawamoy/.basher-packages/pyenv/pyenv/versions/3.11.4/lib/python3.11/importlib/__init__.py", line 70, in invalidate_caches finder.invalidate_caches() TypeError: MetaPathFinder.invalidate_caches() missing 1 required positional argument: 'self' ``` It seems to be because your meta path finder is added as a class to `sys.meta_path` rather than an instance (not sure if this is actually `editables` responsibility, or PDM which is the tool using `editables` in my environment): ```pycon >>> import sys >>> sys.meta_path [ <_distutils_hack.DistutilsMetaFinder object at 0x7f8af931a190>, <class '_frozen_importlib.BuiltinImporter'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib_external.PathFinder'>, <class 'editables.redirector.RedirectingFinder'>, ] ``` When `invalidate_caches` iterates and gets to `editables.redirector.RedirectingFinder`, it sees that it has an `invalidate_caches` attribute and calls it, but the `finder` is a class and therefore `self` is missing. For reference: ```python def invalidate_caches(): """Call the invalidate_caches() method on all meta path finders stored in sys.meta_path (where implemented).""" for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() # I guess finder is supposed to be an instance here, not a class ``` Possible solutions: - change things so that the finder is instantiated - or implement an `invalidate_caches()` **classmethod** in the finder class
2023-07-12T13:53:22.000
-1.0
[ "tests/test_redirects.py::test_double_install", "tests/test_redirects.py::test_cache_invalidation" ]
[ "tests/test_redirects.py::test_redirects", "tests/test_redirects.py::test_toplevel_only", "tests/test_redirects.py::test_no_map_returns_none", "tests/test_redirects.py::test_no_path" ]
robsdedude/flake8-picky-parentheses
34
robsdedude__flake8-picky-parentheses-34
['32']
00d64cfca48be197bb9b77431c3f9ef6e7523922
"diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex 814c3ca..86c3839 100644\n--- a/CHANGELOG.md\n+++ b/(...TRUNCATED)
"diff --git a/tests/test_redundant_parentheses.py b/tests/test_redundant_parentheses.py\nindex b5149(...TRUNCATED)
"Exempt concatenated string literals for `black --preview` compatibility\n[`black --preview`](https:(...TRUNCATED)
"Hi and thanks for bringing this up.\r\n\r\nI agree that these parenthesis are helpful and am inclin(...TRUNCATED)
2023-09-18T15:48:05.000
-1.0
["tests/test_redundant_parentheses.py::test_grouped_single_line_strings[\"-[\"a\",","tests/test_redu(...TRUNCATED)
["tests/test_redundant_parentheses.py::test_superfluous_but_helping_parentheses_around_bin_op[altera(...TRUNCATED)
robsdedude/flake8-picky-parentheses
30
robsdedude__flake8-picky-parentheses-30
['29']
6af76e9a4a799df343ea4436b116c95181ad8c12
"diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex b107031..052ee8f 100644\n--- a/CHANGELOG.md\n+++ b/(...TRUNCATED)
"diff --git a/tests/__init__.py b/tests/__init__.py\nnew file mode 100644\nindex 0000000..e69de29\nd(...TRUNCATED)
"PAR101 (only operators and comments are allowed)\nHi, thanks for writing this plugin! I really lik(...TRUNCATED)
"Hi and thanks for raising this. While I personally don't like this style I can totally see how othe(...TRUNCATED)
2023-04-10T01:16:33.000
-1.0
["tests/test_brackets_position.py::test_tuple_mismatch_line[False]","tests/test_brackets_position.py(...TRUNCATED)
["tests/test_redundant_parentheses.py::test_superfluous_but_helping_parentheses_around_bin_op[altera(...TRUNCATED)
py-pdf/pypdf
3,175
py-pdf__pypdf-3175
['3164']
ca9de10ef81f4593847efcede5177e4e71bc3db7
"diff --git a/pypdf/_reader.py b/pypdf/_reader.py\nindex 2ea21f5b2..df8564529 100644\n--- a/pypdf/_r(...TRUNCATED)
"diff --git a/tests/test_reader.py b/tests/test_reader.py\nindex 273729498..1ae965d16 100644\n--- a/(...TRUNCATED)
"Handling of root objects without a Type\nI am currently trying to handle some partially broken PDF (...TRUNCATED)
2025-03-12T10:17:06.000
-1.0
["tests/test_reader.py::test_outline_color","tests/test_reader.py::test_outline_font_format","tests/(...TRUNCATED)
["tests/test_reader.py::test_read_unknown_zero_pages","tests/test_reader.py::test_get_page_of_encryp(...TRUNCATED)
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
36