instance_id
stringlengths
12
53
patch
stringlengths
278
33.9k
repo
stringlengths
7
48
base_commit
stringlengths
40
40
hints_text
stringclasses
189 values
test_patch
stringlengths
212
264k
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
FAIL_TO_PASS
sequencelengths
1
902
PASS_TO_PASS
sequencelengths
0
7.6k
created_at
stringlengths
25
25
__index_level_0__
int64
1.89k
4.13k
elastic__elasticsearch-py-1157
diff --git a/elasticsearch/client/tasks.py b/elasticsearch/client/tasks.py index 0f253ca1..4c4f6d1f 100644 --- a/elasticsearch/client/tasks.py +++ b/elasticsearch/client/tasks.py @@ -1,3 +1,4 @@ +import warnings from .utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH @@ -58,7 +59,7 @@ class TasksClient(NamespacedClient): ) @query_params("timeout", "wait_for_completion") - def get(self, task_id, params=None, headers=None): + def get(self, task_id=None, params=None, headers=None): """ Returns information about a task. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/tasks.html>`_ @@ -70,7 +71,11 @@ class TasksClient(NamespacedClient): complete (default: false) """ if task_id in SKIP_IN_PATH: - raise ValueError("Empty value passed for a required argument 'task_id'.") + warnings.warn( + "Calling client.tasks.get() without a task_id is deprecated " + "and will be removed in v8.0. Use client.tasks.list() instead.", + DeprecationWarning, + ) return self.transport.perform_request( "GET", _make_path("_tasks", task_id), params=params, headers=headers diff --git a/utils/generate_api.py b/utils/generate_api.py index 0e76617d..183934e4 100644 --- a/utils/generate_api.py +++ b/utils/generate_api.py @@ -146,6 +146,13 @@ class API: p in url.get("parts", {}) for url in self._def["url"]["paths"] ) + # This piece of logic corresponds to calling + # client.tasks.get() w/o a task_id which was erroneously + # allowed in the 7.1 client library. This functionality + # is deprecated and will be removed in 8.x. + if self.namespace == "tasks" and self.name == "get": + parts["task_id"]["required"] = False + for k, sub in SUBSTITUTIONS.items(): if k in parts: parts[sub] = parts.pop(k) diff --git a/utils/templates/overrides/tasks/get b/utils/templates/overrides/tasks/get new file mode 100644 index 00000000..ca855ab9 --- /dev/null +++ b/utils/templates/overrides/tasks/get @@ -0,0 +1,12 @@ +{% extends "base" %} +{% block request %} + if task_id in SKIP_IN_PATH: + warnings.warn( + "Calling client.tasks.get() without a task_id is deprecated " + "and will be removed in v8.0. Use client.tasks.list() instead.", + DeprecationWarning, + ) + + {{ super()|trim }} +{% endblock %} +
elastic/elasticsearch-py
883287551ab37f8197e6a02459c647cb08f9ba84
diff --git a/test_elasticsearch/test_client/__init__.py b/test_elasticsearch/test_client/__init__.py index b7fa18ad..5fa01f76 100644 --- a/test_elasticsearch/test_client/__init__.py +++ b/test_elasticsearch/test_client/__init__.py @@ -1,4 +1,5 @@ from __future__ import unicode_literals +import warnings from elasticsearch.client import _normalize_hosts, Elasticsearch @@ -110,3 +111,27 @@ class TestClient(ElasticsearchTestCase): self.client.index(index="my-index", id=0, body={}) self.assert_url_called("PUT", "/my-index/_doc/0") + + def test_tasks_get_without_task_id_deprecated(self): + warnings.simplefilter("always", DeprecationWarning) + with warnings.catch_warnings(record=True) as w: + self.client.tasks.get() + + self.assert_url_called("GET", "/_tasks") + self.assertEquals(len(w), 1) + self.assertIs(w[0].category, DeprecationWarning) + self.assertEquals( + str(w[0].message), + "Calling client.tasks.get() without a task_id is deprecated " + "and will be removed in v8.0. Use client.tasks.list() instead.", + ) + + def test_tasks_get_with_task_id_not_deprecated(self): + warnings.simplefilter("always", DeprecationWarning) + with warnings.catch_warnings(record=True) as w: + self.client.tasks.get("task-1") + self.client.tasks.get(task_id="task-2") + + self.assert_url_called("GET", "/_tasks/task-1") + self.assert_url_called("GET", "/_tasks/task-2") + self.assertEquals(len(w), 0)
TasksClient.get() requiring an argument on v7.5.1 <!-- ** Please read the guidelines below. ** 1. GitHub is reserved for bug reports and feature requests. The best place to ask a general question is at the Elastic [forums](https://discuss.elastic.co). GitHub is not the place for general questions. 2. Please fill out EITHER the feature request block or the bug report block below, and delete the other block. 3. For issues with API definition please note that the API is [auto generated](https://github.com/elastic/elasticsearch-py/blob/master/CONTRIBUTING.md#api-code-generation) so any problems should be checked and reported against [the Elasticsearch repo](https://github.com/elastic/elasticsearch) instead. Thank you! --> <!-- Bug report --> **Elasticsearch version** (`bin/elasticsearch --version`): 7.1.1, 7.5.1 **`elasticsearch-py` version (`elasticsearch.__versionstr__`)**: 7.5.1 Please make sure the major version matches the Elasticsearch server you are running. **Description of the problem including expected versus actual behavior**: Elasticsearch().tasks.get() fails using elasticsearch-py 7.5.1, whereas it succeeds using 7.1.1. ``` >>> import elasticsearch >>> elasticsearch.__versionstr__ '7.5.1' >>> elasticsearch.Elasticsearch().tasks.get() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/nfox/myenv-7.5.1/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 84, in _wrapped return func(*args, params=params, **kwargs) TypeError: get() missing 1 required positional argument: 'task_id' ``` ``` >>> import elasticsearch >>> elasticsearch.__versionstr__ '7.1.0' >>> elasticsearch.Elasticsearch().tasks.get() {'nodes': {'GkSSDiZPTBq4Tlv5xV9wtg': {'name': 'e6a01a4d549f', 'transport_address': '172.17.0.3:9300', 'host': '172.17.0.3', 'ip': '172.17.0.3:9300', 'roles': ['ingest', 'master', 'data', 'ml'], 'attributes': {'ml.machine_memory': '4129972224', 'xpack.installed': 'true', 'ml.max_open_jobs': '20'}, 'tasks': {'GkSSDiZPTBq4Tlv5xV9wtg:56': {'node': 'GkSSDiZPTBq4Tlv5xV9wtg', 'id': 56, 'type': 'direct', 'action': 'cluster:monitor/tasks/lists[n]', 'start_time_in_millis': 1582238526445, 'running_time_in_nanos': 8142200, 'cancellable': False, 'parent_task_id': 'GkSSDiZPTBq4Tlv5xV9wtg:55', 'headers': {}}, 'GkSSDiZPTBq4Tlv5xV9wtg:55': {'node': 'GkSSDiZPTBq4Tlv5xV9wtg', 'id': 55, 'type': 'transport', 'action': 'cluster:monitor/tasks/lists', 'start_time_in_millis': 1582238526442, 'running_time_in_nanos': 11192200, 'cancellable': False, 'headers': {}}}}}} ``` I've verified this against running both ES 7.5.1 and ES 7.1.1 (via docker on localhost) **Steps to reproduce**: run `elasticsearch.Elasticsearch().tasks.get()` while using elasticsearch-py 7.5.1 Ultimately, this is breaking curator's DeleteSnapshot as it checks for tasks.
0.0
[ "test_elasticsearch/test_client/__init__.py::TestClient::test_tasks_get_without_task_id_deprecated" ]
[ "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_dicts_are_left_unchanged", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_none_uses_defaults", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_single_string_is_wrapped_in_list", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_parsed_for_port_and_user", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_parsed_for_scheme", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_used_as_hostnames", "test_elasticsearch/test_client/__init__.py::TestClient::test_from_in_search", "test_elasticsearch/test_client/__init__.py::TestClient::test_headers_is_copied_when", "test_elasticsearch/test_client/__init__.py::TestClient::test_index_uses_post_if_id_is_empty", "test_elasticsearch/test_client/__init__.py::TestClient::test_index_uses_put_if_id_is_not_empty", "test_elasticsearch/test_client/__init__.py::TestClient::test_params_is_copied_when", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_contains_hosts", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_contains_hosts_passed_in", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_subclass", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_truncates_host_to_5", "test_elasticsearch/test_client/__init__.py::TestClient::test_request_timeout_is_passed_through_unescaped", "test_elasticsearch/test_client/__init__.py::TestClient::test_tasks_get_with_task_id_not_deprecated" ]
2020-03-13 17:57:57+00:00
2,093
elastic__elasticsearch-py-2030
diff --git a/elasticsearch/_async/client/__init__.py b/elasticsearch/_async/client/__init__.py index aae2173e..9ec82bf2 100644 --- a/elasticsearch/_async/client/__init__.py +++ b/elasticsearch/_async/client/__init__.py @@ -519,26 +519,36 @@ class AsyncElasticsearch(BaseClient): if request_timeout is not DEFAULT: client._request_timeout = request_timeout + else: + client._request_timeout = self._request_timeout if ignore_status is not DEFAULT: if isinstance(ignore_status, int): ignore_status = (ignore_status,) client._ignore_status = ignore_status + else: + client._ignore_status = self._ignore_status if max_retries is not DEFAULT: if not isinstance(max_retries, int): raise TypeError("'max_retries' must be of type 'int'") client._max_retries = max_retries + else: + client._max_retries = self._max_retries if retry_on_status is not DEFAULT: if isinstance(retry_on_status, int): retry_on_status = (retry_on_status,) client._retry_on_status = retry_on_status + else: + client._retry_on_status = self._retry_on_status if retry_on_timeout is not DEFAULT: if not isinstance(retry_on_timeout, bool): raise TypeError("'retry_on_timeout' must be of type 'bool'") client._retry_on_timeout = retry_on_timeout + else: + client._retry_on_timeout = self._retry_on_timeout return client diff --git a/elasticsearch/_sync/client/__init__.py b/elasticsearch/_sync/client/__init__.py index c1860766..af10f2db 100644 --- a/elasticsearch/_sync/client/__init__.py +++ b/elasticsearch/_sync/client/__init__.py @@ -519,26 +519,36 @@ class Elasticsearch(BaseClient): if request_timeout is not DEFAULT: client._request_timeout = request_timeout + else: + client._request_timeout = self._request_timeout if ignore_status is not DEFAULT: if isinstance(ignore_status, int): ignore_status = (ignore_status,) client._ignore_status = ignore_status + else: + client._ignore_status = self._ignore_status if max_retries is not DEFAULT: if not isinstance(max_retries, int): raise TypeError("'max_retries' must be of type 'int'") client._max_retries = max_retries + else: + client._max_retries = self._max_retries if retry_on_status is not DEFAULT: if isinstance(retry_on_status, int): retry_on_status = (retry_on_status,) client._retry_on_status = retry_on_status + else: + client._retry_on_status = self._retry_on_status if retry_on_timeout is not DEFAULT: if not isinstance(retry_on_timeout, bool): raise TypeError("'retry_on_timeout' must be of type 'bool'") client._retry_on_timeout = retry_on_timeout + else: + client._retry_on_timeout = self._retry_on_timeout return client
elastic/elasticsearch-py
2f64b0ccbaf71ac1f1dc7ab498bd0ccafd1777f4
diff --git a/test_elasticsearch/test_client/test_options.py b/test_elasticsearch/test_client/test_options.py index 16e89af5..72d5edf4 100644 --- a/test_elasticsearch/test_client/test_options.py +++ b/test_elasticsearch/test_client/test_options.py @@ -368,3 +368,104 @@ class TestOptions(DummyTransportTestCase): "user-agent": "custom4", "accept": "application/vnd.elasticsearch+json; compatible-with=8", } + + def test_options_timeout_parameters(self): + client = Elasticsearch( + "http://localhost:9200", + transport_class=DummyTransport, + request_timeout=1, + max_retries=2, + retry_on_status=(404,), + retry_on_timeout=True, + ) + + # timeout parameters are preserved with .options() + client.options().indices.get(index="test") + + calls = client.transport.calls + call = calls[("GET", "/test")][0] + assert call.pop("client_meta") is DEFAULT + assert call == { + "headers": { + "accept": "application/vnd.elasticsearch+json; compatible-with=8", + }, + "body": None, + "request_timeout": 1, + "max_retries": 2, + "retry_on_status": (404,), + "retry_on_timeout": True, + } + + client = Elasticsearch( + "http://localhost:9200", + transport_class=DummyTransport, + request_timeout=1, + max_retries=2, + retry_on_status=(404,), + retry_on_timeout=True, + ) + client.options( + request_timeout=2, + max_retries=3, + retry_on_status=(400,), + retry_on_timeout=False, + ).indices.get(index="test") + + calls = client.transport.calls + call = calls[("GET", "/test")][0] + assert call.pop("client_meta") is DEFAULT + assert call == { + "headers": { + "accept": "application/vnd.elasticsearch+json; compatible-with=8", + }, + "body": None, + "request_timeout": 2, + "max_retries": 3, + "retry_on_status": (400,), + "retry_on_timeout": False, + } + + client = Elasticsearch( + "http://localhost:9200", + transport_class=DummyTransport, + ) + client.options().indices.get(index="test") + + calls = client.transport.calls + call = calls[("GET", "/test")][0] + assert call.pop("request_timeout") is DEFAULT + assert call.pop("max_retries") is DEFAULT + assert call.pop("retry_on_timeout") is DEFAULT + assert call.pop("retry_on_status") is DEFAULT + assert call.pop("client_meta") is DEFAULT + assert call == { + "headers": { + "accept": "application/vnd.elasticsearch+json; compatible-with=8", + }, + "body": None, + } + + client = Elasticsearch( + "http://localhost:9200", + transport_class=DummyTransport, + ) + client.options( + request_timeout=1, + max_retries=2, + retry_on_status=(404,), + retry_on_timeout=True, + ).indices.get(index="test") + + calls = client.transport.calls + call = calls[("GET", "/test")][0] + assert call.pop("client_meta") is DEFAULT + assert call == { + "headers": { + "accept": "application/vnd.elasticsearch+json; compatible-with=8", + }, + "body": None, + "request_timeout": 1, + "max_retries": 2, + "retry_on_status": (404,), + "retry_on_timeout": True, + }
Calling options() on a client resets timeout related attributes <!-- Bug report --> **Elasticsearch version** (8.1.1): **`elasticsearch-py` version (`8.1.1`)**: Please make sure the major version matches the Elasticsearch server you are running. **Description of the problem including expected versus actual behavior**: When the `options()` method is called for an existing `ElasticSearch` client instance, the timeout related parameters are not preserved. These parameters are: - `self._request_timeout` - `self._max_retries` - `self._retry_on_timeout` - `self._retry_on_status` This is problematic in the `helpers` module, particularly `scan()` because that method calls the `options` and resets any timeout related settings we may have made on the client. We can re-specify the `request_timeout` there but retries parameters cannot be replicated **Steps to reproduce**: ``` >>> import elasticsearch as ES >>> es=ES.Elasticsearch("http://esmasters:9200", sniff_on_connection_fail=True, sniff_on_start=True, min_delay_between_sniffing=600, request_timeout=600, sniff_timeout=300, max_retries=5, retry_on_timeout=True) >>> es._retry_on_timeout True >>> es2=es.options() >>> es2._retry_on_timeout <DEFAULT> >>> es._max_retries 5 >>> es2._max_retries <DEFAULT> >>> es2._retry_on_status <DEFAULT> >>> es._retry_on_status <DEFAULT> >>> es._request_timeout 600 >>> es2._request_timeout <DEFAULT> ```
0.0
[ "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_timeout_parameters" ]
[ "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options0-headers0]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options1-headers1]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options2-headers2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options3-headers3]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options4-headers4]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options5-headers5]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options6-headers6]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_to_headers[options7-headers7]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-None-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-None-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-user:pass-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-user:pass-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-user:pass-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-user:pass-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-user:pass-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-basic_auth2-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-basic_auth2-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-basic_auth2-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-basic_auth2-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[None-basic_auth2-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-None-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-None-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-None-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-None-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-None-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-None-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-user:pass-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-None-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers1-basic_auth2-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-None-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-None-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-None-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-None-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-None-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-None-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-user:pass-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-None-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-None-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-None-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-bearer-None]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-bearer-api-key]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_auth_conflicts[headers2-basic_auth2-bearer-api_key2]", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_passed_to_perform_request", "test_elasticsearch/test_client/test_options.py::TestOptions::test_options_passed_to_async_perform_request", "test_elasticsearch/test_client/test_options.py::TestOptions::test_default_node_configs", "test_elasticsearch/test_client/test_options.py::TestOptions::test_http_headers_overrides", "test_elasticsearch/test_client/test_options.py::TestOptions::test_user_agent_override" ]
2022-07-14 11:09:50+00:00
2,094
elastic__elasticsearch-py-2427
diff --git a/elasticsearch/_sync/client/utils.py b/elasticsearch/_sync/client/utils.py index 4febb035..1d1a983a 100644 --- a/elasticsearch/_sync/client/utils.py +++ b/elasticsearch/_sync/client/utils.py @@ -298,7 +298,8 @@ def _merge_kwargs_no_duplicates(kwargs: Dict[str, Any], values: Dict[str, Any]) def _merge_body_fields_no_duplicates( body: _TYPE_BODY, kwargs: Dict[str, Any], body_fields: Tuple[str, ...] -) -> None: +) -> bool: + mixed_body_and_params = False for key in list(kwargs.keys()): if key in body_fields: if isinstance(body, (str, bytes)): @@ -315,11 +316,13 @@ def _merge_body_fields_no_duplicates( warnings.warn( f"Received '{key}' via a specific parameter in the presence of a " "'body' parameter, which is deprecated and will be removed in a future " - "version. Instead, use only 'body' or only specific paremeters.", + "version. Instead, use only 'body' or only specific parameters.", category=DeprecationWarning, stacklevel=warn_stacklevel(), ) body[key] = kwargs.pop(key) + mixed_body_and_params = True + return mixed_body_and_params def _rewrite_parameters( @@ -401,6 +404,7 @@ def _rewrite_parameters( not ignore_deprecated_options or "body" not in ignore_deprecated_options ): body: Optional[_TYPE_BODY] = kwargs.pop("body") + mixed_body_and_params = False if body is not None: if body_name: if body_name in kwargs: @@ -411,11 +415,27 @@ def _rewrite_parameters( "issues/1698 for more information" ) kwargs[body_name] = body - elif body_fields is not None: - _merge_body_fields_no_duplicates(body, kwargs, body_fields) + mixed_body_and_params = _merge_body_fields_no_duplicates( + body, kwargs, body_fields + ) kwargs["body"] = body + if parameter_aliases and not isinstance(body, (str, bytes)): + for alias, rename_to in parameter_aliases.items(): + if rename_to in body: + body[alias] = body.pop(rename_to) + # If body and params are mixed, the alias may come from a param, + # in which case the warning below will not make sense. + if not mixed_body_and_params: + warnings.warn( + f"Using '{rename_to}' alias in 'body' is deprecated and will be removed " + f"in a future version of elasticsearch-py. Use '{alias}' directly instead. " + "See https://github.com/elastic/elasticsearch-py/issues/1698 for more information", + category=DeprecationWarning, + stacklevel=2, + ) + if parameter_aliases: for alias, rename_to in parameter_aliases.items(): try:
elastic/elasticsearch-py
7d4a34b6e3ceceb82396be62682b7e8623c72665
diff --git a/test_elasticsearch/test_client/test_rewrite_parameters.py b/test_elasticsearch/test_client/test_rewrite_parameters.py index 26218040..50a23256 100644 --- a/test_elasticsearch/test_client/test_rewrite_parameters.py +++ b/test_elasticsearch/test_client/test_rewrite_parameters.py @@ -191,7 +191,7 @@ class TestRewriteParameters: assert str(w[0].message) == ( "Received 'source' via a specific parameter in the presence of a " "'body' parameter, which is deprecated and will be removed in a future " - "version. Instead, use only 'body' or only specific paremeters." + "version. Instead, use only 'body' or only specific parameters." ) def test_body_fields_conflict(self): @@ -238,6 +238,41 @@ class TestRewriteParameters: self.wrapped_func_aliases(source=["key3"]) assert self.calls[-1] == ((), {"source": ["key3"]}) + def test_parameter_aliases_body(self): + with pytest.warns( + DeprecationWarning, + match=( + "Using 'source' alias in 'body' is deprecated and will be removed in a future version of elasticsearch-py. " + "Use '_source' directly instead." + ), + ): + self.wrapped_func_aliases(body={"source": ["key4"]}) + + # using the correct name does not warn + with warnings.catch_warnings(): + warnings.simplefilter("error") + self.wrapped_func_aliases(body={"_source": ["key4"]}) + + def test_parameter_aliases_body_param(self): + with pytest.warns( + DeprecationWarning, + match=( + "Received 'source' via a specific parameter in the presence of a " + "'body' parameter, which is deprecated and will be removed in a future " + "version. Instead, use only 'body' or only specific parameters." + ), + ): + self.wrapped_func_aliases( + source=["key4"], body={"query": {"match_all": {}}} + ) + + # using the correct name does not warn + with warnings.catch_warnings(): + warnings.simplefilter("error") + self.wrapped_func_aliases( + body={"query": {"match_all": {}}, "_source": ["key4"]} + ) + @pytest.mark.parametrize("client_cls", [Elasticsearch, AsyncElasticsearch]) def test_positional_argument_error(self, client_cls): client = client_cls("https://localhost:9200")
elasticsearch-py 8.12 breaks the use of `from_` in body parameters This bug was initially reported in the [Elastic Community Slack](https://www.elastic.co/blog/join-our-elastic-stack-workspace-on-slack). But first, come context. ## Context Since the early days of the Elasticsearch Python client, [back in July 2013](https://github.com/elastic/elasticsearch-py/commit/48ec1ab4bbc0b49ac5dfcdd39fb341d93c7f4538), the `body` parameter is the way to specify the request body for requests that accept it. API calls using body look like this: ```python es.search(index="bonsais", body={"query": {"match_all": {}}, "size": 50}) ``` However, this parameter is an untyped Python dictionary which is not validated by the client. That said, thanks to the [Elasticsearch specification](https://github.com/elastic/elasticsearch-specification/) which provides the full types of each Elasticsearch API, we can provide a better experience. elasticsearch-py 8.0 did just that, introducing this new way of calling APIs, where the first level of body keys can be specified using Python parameters: ```python es.search(index="bonsais", query={"match_all": {}}, size=50) ``` This has various advantages, including better autocompletion and type checks. For example, mypy will raise an error if size is not an integer. And since we realized we could [unpack](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) body to typed parameters like this: ```python es.search(index="bonsais", **{"query": {"match_all": {}}, "size": 50}) ``` We decided to deprecate the body API altogether. However, deprecating body has the following downsides: * A lot of code written in the past decade was now triggering a deprecation warning * Unknown parameters such as `sub_searches` or unintentional omissions from the Elasticsearch specification were rejected, causing queries to outright fail, unnecessarily forcing the use of raw requests. * Optimizations such as passing an already encoded body to avoid paying the cost of serializing JSON were no longer possible. The original author of the client, Honza KrΓ‘l, [pointed out those issues](https://github.com/elastic/elasticsearch-py/issues/2181), and we decided to allow `body` to work as before, without any warnings, [alongside the new API](https://github.com/elastic/elasticsearch-py/pull/2383). This is available elasticsearch-py 8.12.0. ## The case of Python keywords, like `from` One subtlety with the above is that some identifiers are [reserved by Python](https://docs.python.org/3/reference/lexical_analysis.html#keywords) and can't be used as parameters. This is the case of `from`, for example. As such, `es.search(index="bonsais", query={"match_all": {}}, from=100, size=50)`, is invalid Python code. For this reason, parameter aliases were introduced, and the correct way to write that query was to use `from_`, eg. `es.search(index="bonsais", query={"match_all": {}}, from_=100, size=50)`. And then, under the hood, `from` is actually sent to Elasticsearch: https://github.com/elastic/elasticsearch-py/blob/5014ce5337594f66040c81a2610220b1e8c0527e/elasticsearch/_sync/client/__init__.py#L1280-L1281 However, when the `body` parameter was deprecated in elasticsearch-py 8.12, it was deprecated by converting all `body` subfields to Python parameters internally, and *then* updated parameter aliases like `from_` to `from`. This means it was possible to write: ```python es.search(index="bonsais", body={"query": {"match_all": {}}, "from_": 100, "size": 50}) ``` which was then converted as if we had called: ```python es.search(index="bonsais", query={"match_all": {}, from_=100, size=50) ``` to finally send `{"query": {"match_all": {}}, "from": 100, "size": 50}` as the body to Elasticsearch. This no longer works with elasticsearch-py 8.12.0. The body is used as is, without any inspection, and the correct way to use `from` with the `body` parameter is the one that always worked: ```python es.search( index="*", body={ "query": {"match_all": {}}, "from": 10, "size": 10, }, ) ``` I'm still not sure what the solution is here.
0.0
[ "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_parameter_aliases_body", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_parameter_aliases_body_param" ]
[ "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_default_params_conflict", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_body_name_duplicate", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_error_on_body_merge[{\"query\":", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_error_on_params_merge[{\"query\":", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_body_fields_conflict", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_parameter_aliases", "test_elasticsearch/test_client/test_rewrite_parameters.py::TestRewriteParameters::test_positional_argument_error[Elasticsearch]" ]
2024-01-31 12:21:36+00:00
2,095
elastic__elasticsearch-py-569
diff --git a/elasticsearch/client/__init__.py b/elasticsearch/client/__init__.py index c735b70a..488cf8be 100644 --- a/elasticsearch/client/__init__.py +++ b/elasticsearch/client/__init__.py @@ -3,7 +3,7 @@ import logging from ..transport import Transport from ..exceptions import TransportError -from ..compat import string_types, urlparse +from ..compat import string_types, urlparse, unquote from .indices import IndicesClient from .ingest import IngestClient from .cluster import ClusterClient @@ -49,7 +49,8 @@ def _normalize_hosts(hosts): h['scheme'] = parsed_url.scheme if parsed_url.username or parsed_url.password: - h['http_auth'] = '%s:%s' % (parsed_url.username, parsed_url.password) + h['http_auth'] = '%s:%s' % (unquote(parsed_url.username), + unquote(parsed_url.password)) if parsed_url.path and parsed_url.path != '/': h['url_prefix'] = parsed_url.path diff --git a/elasticsearch/compat.py b/elasticsearch/compat.py index deee3c52..a5b615d2 100644 --- a/elasticsearch/compat.py +++ b/elasticsearch/compat.py @@ -4,10 +4,10 @@ PY2 = sys.version_info[0] == 2 if PY2: string_types = basestring, - from urllib import quote_plus, urlencode + from urllib import quote_plus, urlencode, unquote from urlparse import urlparse from itertools import imap as map else: string_types = str, bytes - from urllib.parse import quote_plus, urlencode, urlparse + from urllib.parse import quote_plus, urlencode, urlparse, unquote map = map
elastic/elasticsearch-py
fe897ebe0d2167e91ea19fa9a81f448a861d58d1
diff --git a/test_elasticsearch/test_client/__init__.py b/test_elasticsearch/test_client/__init__.py index 4bf2978c..ec01145e 100644 --- a/test_elasticsearch/test_client/__init__.py +++ b/test_elasticsearch/test_client/__init__.py @@ -13,8 +13,8 @@ class TestNormalizeHosts(TestCase): def test_strings_are_parsed_for_port_and_user(self): self.assertEquals( - [{"host": "elastic.co", "port": 42}, {"host": "elastic.co", "http_auth": "user:secret"}], - _normalize_hosts(["elastic.co:42", "user:[email protected]"]) + [{"host": "elastic.co", "port": 42}, {"host": "elastic.co", "http_auth": "user:secre]"}], + _normalize_hosts(["elastic.co:42", "user:secre%[email protected]"]) ) def test_strings_are_parsed_for_scheme(self):
user:password in hosts are not url decoded Hello, If I have a character like "]" in my username or password I must urlencode it or `urlparse` will interpret the host as IPv6. Unfortunately, `urlparse` does not urldecode fragments : ``` The components are not broken up in smaller parts (for example, the network location is a single string), and % escapes are not expanded. ``` (https://docs.python.org/3/library/urllib.parse.html) `_normalize_hosts` should urldecode explicitely, which I will propose in a PR.
0.0
[ "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_parsed_for_port_and_user" ]
[ "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_dicts_are_left_unchanged", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_none_uses_defaults", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_single_string_is_wrapped_in_list", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_parsed_for_scheme", "test_elasticsearch/test_client/__init__.py::TestNormalizeHosts::test_strings_are_used_as_hostnames", "test_elasticsearch/test_client/__init__.py::TestClient::test_from_in_search", "test_elasticsearch/test_client/__init__.py::TestClient::test_index_uses_post_if_id_is_empty", "test_elasticsearch/test_client/__init__.py::TestClient::test_index_uses_put_if_id_is_not_empty", "test_elasticsearch/test_client/__init__.py::TestClient::test_params_is_copied_when", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_contains_hosts", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_contains_hosts_passed_in", "test_elasticsearch/test_client/__init__.py::TestClient::test_repr_truncates_host_to_10", "test_elasticsearch/test_client/__init__.py::TestClient::test_request_timeout_is_passed_through_unescaped" ]
2017-04-13 11:28:46+00:00
2,096
elastic__elasticsearch-py-618
diff --git a/elasticsearch/client/__init__.py b/elasticsearch/client/__init__.py index 59858549..834f1d86 100644 --- a/elasticsearch/client/__init__.py +++ b/elasticsearch/client/__init__.py @@ -1127,7 +1127,8 @@ class Elasticsearch(object): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request('POST', _make_path(index, - doc_type, '_bulk'), params=params, body=self._bulk_body(body)) + doc_type, '_bulk'), params=params, body=self._bulk_body(body), + headers={'content-type': 'application/x-ndjson'}) @query_params('max_concurrent_searches', 'pre_filter_shard_size', 'search_type', 'typed_keys') @@ -1159,7 +1160,8 @@ class Elasticsearch(object): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request('GET', _make_path(index, - doc_type, '_msearch'), params=params, body=self._bulk_body(body)) + doc_type, '_msearch'), params=params, body=self._bulk_body(body), + headers={'content-type': 'application/x-ndjson'}) @query_params('field_statistics', 'fields', 'offsets', 'parent', 'payloads', 'positions', 'preference', 'realtime', 'routing', 'term_statistics', @@ -1363,7 +1365,8 @@ class Elasticsearch(object): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") return self.transport.perform_request('GET', _make_path(index, doc_type, - '_msearch', 'template'), params=params, body=self._bulk_body(body)) + '_msearch', 'template'), params=params, body=self._bulk_body(body), + headers={'content-type': 'application/x-ndjson'}) @query_params('allow_no_indices', 'expand_wildcards', 'fields', 'ignore_unavailable') @@ -1387,3 +1390,4 @@ class Elasticsearch(object): """ return self.transport.perform_request('GET', _make_path(index, '_field_caps'), params=params, body=body) + diff --git a/elasticsearch/connection/http_requests.py b/elasticsearch/connection/http_requests.py index 59dd381c..b98e7772 100644 --- a/elasticsearch/connection/http_requests.py +++ b/elasticsearch/connection/http_requests.py @@ -61,13 +61,13 @@ class RequestsHttpConnection(Connection): warnings.warn( 'Connecting to %s using SSL with verify_certs=False is insecure.' % self.base_url) - def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()): + def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=(), headers=None): url = self.base_url + url if params: url = '%s?%s' % (url, urlencode(params or {})) start = time.time() - request = requests.Request(method=method, url=url, data=body) + request = requests.Request(method=method, headers=headers, url=url, data=body) prepared_request = self.session.prepare_request(request) settings = self.session.merge_environment_settings(prepared_request.url, {}, None, None, None) send_kwargs = {'timeout': timeout or self.timeout} diff --git a/elasticsearch/connection/http_urllib3.py b/elasticsearch/connection/http_urllib3.py index 7b4e6c79..62957ed2 100644 --- a/elasticsearch/connection/http_urllib3.py +++ b/elasticsearch/connection/http_urllib3.py @@ -91,7 +91,7 @@ class Urllib3HttpConnection(Connection): self.pool = pool_class(host, port=port, timeout=self.timeout, maxsize=maxsize, **kw) - def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=()): + def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=(), headers=None): url = self.url_prefix + url if params: url = '%s?%s' % (url, urlencode(params)) @@ -111,6 +111,9 @@ class Urllib3HttpConnection(Connection): if not isinstance(method, str): method = method.encode('utf-8') + if headers: + request_headers = dict(self.headers) + request_headers.update(headers or {}) response = self.pool.urlopen(method, url, body, retries=False, headers=self.headers, **kw) duration = time.time() - start raw_data = response.data.decode('utf-8') diff --git a/elasticsearch/transport.py b/elasticsearch/transport.py index dc8cd891..f876a945 100644 --- a/elasticsearch/transport.py +++ b/elasticsearch/transport.py @@ -255,7 +255,7 @@ class Transport(object): if self.sniff_on_connection_fail: self.sniff_hosts() - def perform_request(self, method, url, params=None, body=None): + def perform_request(self, method, url, headers=None, params=None, body=None): """ Perform the actual request. Retrieve a connection from the connection pool, pass all the information to it's perform_request method and @@ -269,6 +269,8 @@ class Transport(object): :arg method: HTTP method to use :arg url: absolute url (without host) to target + :arg headers: dictionary of headers, will be handed over to the + underlying :class:`~elasticsearch.Connection` class :arg params: dictionary of query parameters, will be handed over to the underlying :class:`~elasticsearch.Connection` class for serialization :arg body: body of the request, will be serializes using serializer and @@ -309,7 +311,7 @@ class Transport(object): connection = self.get_connection() try: - status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) + status, headers, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout) except TransportError as e: if method == 'HEAD' and e.status_code == 404:
elastic/elasticsearch-py
0397527d12bcb43274ce9054111c5f7f673a7ad6
diff --git a/test_elasticsearch/test_connection.py b/test_elasticsearch/test_connection.py index b2d84996..e4e0ae63 100644 --- a/test_elasticsearch/test_connection.py +++ b/test_elasticsearch/test_connection.py @@ -104,6 +104,13 @@ class TestRequestsConnection(TestCase): self.assertEquals('GET', request.method) self.assertEquals(None, request.body) + def test_merge_headers(self): + con = self._get_mock_connection(connection_params={'headers': {'h1': 'v1', 'h2': 'v2'}}) + req = self._get_request(con, 'GET', '/', headers={'h2': 'v2p', 'h3': 'v3'}) + self.assertEquals(req.headers['h1'], 'v1') + self.assertEquals(req.headers['h2'], 'v2p') + self.assertEquals(req.headers['h3'], 'v3') + def test_http_auth(self): con = RequestsHttpConnection(http_auth='username:secret') self.assertEquals(('username', 'secret'), con.session.auth) diff --git a/test_elasticsearch/test_transport.py b/test_elasticsearch/test_transport.py index 328325c1..50acb7fa 100644 --- a/test_elasticsearch/test_transport.py +++ b/test_elasticsearch/test_transport.py @@ -74,7 +74,7 @@ class TestTransport(TestCase): t.perform_request('GET', '/', params={'request_timeout': 42}) self.assertEquals(1, len(t.get_connection().calls)) self.assertEquals(('GET', '/', {}, None), t.get_connection().calls[0][0]) - self.assertEquals({'timeout': 42, 'ignore': ()}, t.get_connection().calls[0][1]) + self.assertEquals({'timeout': 42, 'ignore': (), 'headers': None}, t.get_connection().calls[0][1]) def test_send_get_body_as_source(self): t = Transport([{}], send_get_body_as='source', connection_class=DummyConnection)
Set `application/x-ndjson` content type on bulk requests As of elastic 5.x, requests to `/_bulk` should set `Content-Type` to `application/x-ndjson`. If not, elastic logs a warning. It looks like this library defaults to `application/json`. To fix, I'm thinking we should accept an optional dict of headers at `https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/connection/http_urllib3.py#L94`. If that sounds reasonable, I'd be happy to submit a patch. cc @cnelson @wjwoodson
0.0
[ "test_elasticsearch/test_connection.py::TestRequestsConnection::test_merge_headers", "test_elasticsearch/test_transport.py::TestTransport::test_request_timeout_extracted_from_params_and_passed" ]
[ "test_elasticsearch/test_connection.py::TestRequestsConnection::test_url_prefix", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_repr", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_body_attached", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_head_with_404_doesnt_get_logged", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_failed_request_logs_and_traces", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_conflict_error_is_returned_on_409", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_defaults", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_http_auth_list", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_not_found_error_is_returned_on_404", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_uses_https_if_verify_certs_is_off", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_timeout_set", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_params_properly_encoded", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_custom_http_auth_is_allowed", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_request_error_is_returned_on_400", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_http_auth_tuple", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_http_auth", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_http_auth_attached", "test_elasticsearch/test_connection.py::TestRequestsConnection::test_success_logs_and_traces", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_doesnt_use_https_if_not_specified", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_http_auth_list", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_http_auth", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_http_auth_tuple", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_uses_https_if_verify_certs_is_off", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_keep_alive_is_on_by_default", "test_elasticsearch/test_connection.py::TestUrllib3Connection::test_timeout_set", "test_elasticsearch/test_transport.py::TestHostsInfoCallback::test_master_only_nodes_are_ignored", "test_elasticsearch/test_transport.py::TestTransport::test_custom_connection_class", "test_elasticsearch/test_transport.py::TestTransport::test_add_connection", "test_elasticsearch/test_transport.py::TestTransport::test_kwargs_passed_on_to_connections", "test_elasticsearch/test_transport.py::TestTransport::test_body_bytes_get_passed_untouched", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_after_n_seconds", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_on_start_ignores_sniff_timeout", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_uses_sniff_timeout", "test_elasticsearch/test_transport.py::TestTransport::test_body_gets_encoded_into_bytes", "test_elasticsearch/test_transport.py::TestTransport::test_request_will_fail_after_X_retries", "test_elasticsearch/test_transport.py::TestTransport::test_resurrected_connection_will_be_marked_as_live_on_success", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_reuses_connection_instances_if_possible", "test_elasticsearch/test_transport.py::TestTransport::test_kwargs_passed_on_to_connection_pool", "test_elasticsearch/test_transport.py::TestTransport::test_send_get_body_as_post", "test_elasticsearch/test_transport.py::TestTransport::test_send_get_body_as_source", "test_elasticsearch/test_transport.py::TestTransport::test_body_surrogates_replaced_encoded_into_bytes", "test_elasticsearch/test_transport.py::TestTransport::test_failed_connection_will_be_marked_as_dead", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_on_start_fetches_and_uses_nodes_list", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_on_fail_triggers_sniffing_on_fail", "test_elasticsearch/test_transport.py::TestTransport::test_sniff_will_use_seed_connections", "test_elasticsearch/test_transport.py::TestTransport::test_single_connection_uses_dummy_connection_pool" ]
2017-07-13 02:52:29+00:00
2,097
elastic__elasticsearch-py-628
diff --git a/elasticsearch/client/utils.py b/elasticsearch/client/utils.py index 78b005cd..120b4abe 100644 --- a/elasticsearch/client/utils.py +++ b/elasticsearch/client/utils.py @@ -26,13 +26,13 @@ def _escape(value): elif isinstance(value, bool): value = str(value).lower() + # don't decode bytestrings + elif isinstance(value, bytes): + return value + # encode strings to utf-8 if isinstance(value, string_types): - try: - return value.encode('utf-8') - except UnicodeDecodeError: - # Python 2 and str, no need to re-encode - pass + return value.encode('utf-8') return str(value)
elastic/elasticsearch-py
4e6f63571105545914c07fa4846f996d6049f44b
diff --git a/test_elasticsearch/test_client/test_utils.py b/test_elasticsearch/test_client/test_utils.py index 9fd6df4f..66a83293 100644 --- a/test_elasticsearch/test_client/test_utils.py +++ b/test_elasticsearch/test_client/test_utils.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from elasticsearch.client.utils import _make_path +from elasticsearch.client.utils import _make_path, _escape from elasticsearch.compat import PY2 from ..test_cases import TestCase, SkipTest @@ -17,3 +17,24 @@ class TestMakePath(TestCase): id = "δΈ­ζ–‡".encode('utf-8') self.assertEquals('/some-index/type/%E4%B8%AD%E6%96%87', _make_path('some-index', 'type', id)) + +class TestEscape(TestCase): + def test_handles_ascii(self): + string = "abc123" + self.assertEquals( + b'abc123', + _escape(string) + ) + def test_handles_unicode(self): + string = "δΈ­ζ–‡" + self.assertEquals( + b'\xe4\xb8\xad\xe6\x96\x87', + _escape(string) + ) + + def test_handles_bytestring(self): + string = b'celery-task-meta-c4f1201f-eb7b-41d5-9318-a75a8cfbdaa0' + self.assertEquals( + string, + _escape(string) + )
'bytes' object has no attribute 'encode' File "/root/.local/share/virtualenvs/celery-jR7fJ1bi/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 32, in _escape return value.encode('utf-8') AttributeError: 'bytes' object has no attribute 'encode' It appears that when _escape receives value, which in my case is b'celery-task-meta-c4f1201f-eb7b-41d5-9318-a75a8cfbdaa0', it gets checked against (<class 'str'>, <class 'bytes'>), and therefore passes the test but <class 'bytes'> does not have the **encode** method. try does not catch as error is AttributeError: 'bytes' object has no attribute 'encode' def _escape(value): """ Escape a single value of a URL string or a query parameter. If it is a list or tuple, turn it into a comma-separated string first. """ # make sequences into comma-separated stings if isinstance(value, (list, tuple)): value = ','.join(value) # dates and datetimes into isoformat elif isinstance(value, (date, datetime)): value = value.isoformat() # make bools into true/false strings elif isinstance(value, bool): value = str(value).lower() # encode strings to utf-8 if isinstance(value, string_types): try: return value.encode('utf-8') except UnicodeDecodeError: # Python 2 and str, no need to re-encode pass return str(value)
0.0
[ "test_elasticsearch/test_client/test_utils.py::TestEscape::test_handles_bytestring" ]
[ "test_elasticsearch/test_client/test_utils.py::TestMakePath::test_handles_unicode", "test_elasticsearch/test_client/test_utils.py::TestEscape::test_handles_ascii", "test_elasticsearch/test_client/test_utils.py::TestEscape::test_handles_unicode" ]
2017-08-07 21:39:19+00:00
2,098
elcaminoreal__elcaminoreal-10
diff --git a/src/elcaminoreal/_gather.py b/src/elcaminoreal/_gather.py index 63f85a9..cbe7637 100644 --- a/src/elcaminoreal/_gather.py +++ b/src/elcaminoreal/_gather.py @@ -24,12 +24,13 @@ class Commands(object): def command(self, name=None, parser=caparg.command(''), - dependencies=pyrsistent.v()): + dependencies=pyrsistent.v(), + regular=False): """ Register as a command. """ - transform = gather.Wrapper.glue((dependencies, parser)) + transform = gather.Wrapper.glue((dependencies, parser, regular)) ret = self._command_collector.register(name, transform=transform) return ret @@ -47,20 +48,27 @@ class Commands(object): parsed = command.parse(args) subcommand = ' '.join(parsed['__caparg_subcommand__']) func = collection[subcommand].original - dependencies, _ignored = collection[subcommand].extra + dependencies, _ignored, regular = collection[subcommand].extra graph = self.mkgraph(dependencies) graph.update(override_dependencies) - return func(parsed, graph) + if not regular: + return func(parsed, graph) + args = {dependency: graph[dependency] + for dependency in dependencies} + args.update(parsed) + del args['__caparg_subcommand__'] + return func(**args) def dependency(self, name=None, dependencies=pyrsistent.v(), - possible_dependencies=pyrsistent.v()): + possible_dependencies=pyrsistent.v(), + regular=False): """ Register as a dependency. """ - glue = (dependencies, possible_dependencies) + glue = (dependencies, possible_dependencies, regular) transform = gather.Wrapper.glue(glue) ret = self._collector.register(name, transform=transform) return ret @@ -83,14 +91,20 @@ class Commands(object): on_route = on_route.add(thing) plugin = collection[thing] func = plugin.original - dependencies, possible_dependencies = plugin.extra + dependencies, possible_dependencies, regular = plugin.extra my_dependencies, my_possible_dependencies = {}, {} for other_thing in dependencies: my_dependencies[other_thing] = _build(other_thing, on_route) for other_thing in possible_dependencies: builder = functools.partial(_build, other_thing, on_route) my_possible_dependencies[other_thing] = builder - ret[thing] = func(my_dependencies, my_possible_dependencies) + if regular: + args = {'build_' + key: value + for key, value in my_possible_dependencies.items()} + args.update(my_dependencies) + ret[thing] = func(**args) + else: + ret[thing] = func(my_dependencies, my_possible_dependencies) return ret[thing] for thing in things: _build(thing) diff --git a/tox.ini b/tox.ini index 0ef3c06..297cc23 100644 --- a/tox.ini +++ b/tox.ini @@ -30,7 +30,7 @@ commands = # E0704 -- bare raise outside except (rare, when it's done I mean it) # R0201 -- unused self in methods (methods can be used for polymorphism) # R0903 -- too few public methods (attrs-based classes have implicit ones) - py27-lint: pylint --disable=unsupported-assignment-operation --disable=no-member --disable=not-callable --disable=unsubscriptable-object --disable=E0704 --disable=R0903 --disable=R0201 src/elcaminoreal + py27-lint: pylint --disable=blacklisted-name --disable=unsupported-assignment-operation --disable=no-member --disable=not-callable --disable=unsubscriptable-object --disable=E0704 --disable=R0903 --disable=R0201 src/elcaminoreal py27-lint: flake8 src/elcaminoreal #{py27,pypy,py36,py35}-func: python -m elcaminoreal.example selftest #{py27,pypy,py35}-func: python -m elcaminoreal.example selftest
elcaminoreal/elcaminoreal
a76600014ed645b6f92b98bf491f2b49e5625d6d
diff --git a/src/elcaminoreal/test/some_plugins.py b/src/elcaminoreal/test/some_plugins.py index a885594..9507b74 100644 --- a/src/elcaminoreal/test/some_plugins.py +++ b/src/elcaminoreal/test/some_plugins.py @@ -21,6 +21,18 @@ def a_foo(dependencies, _possible_dependencies): return dict(bar=dependencies['bar']) [email protected](dependencies=["bar", "quux"], + possible_dependencies=["foo"], + regular=True) +def regular(bar, quux, build_foo): + """ + Depend on bar, maybe on foo + + Use regular arguments. + """ + return dict(bar=bar, quux=quux, foo=build_foo()) + + @COMMANDS.dependency(possible_dependencies=["bar"]) def foo_2(_dependencies, possible_dependencies): """ @@ -37,6 +49,14 @@ def a_bar(_dependencies, _possible_dependencies): return "I'm a bar" [email protected](name="quux") +def a_quux(_dependencies, _possible_dependencies): + """ + Return a quux-like object. + """ + return "I'm a quux" + + @COMMANDS.dependency() def rand(_dependencies, _possible_dependencies): """ @@ -83,6 +103,28 @@ def _print(_dependencies, _possible_dependencies): return print [email protected](name='output') +def dummy_output(_dependencies, _possible_dependencies): + """ + Literally do nothing. + + This is designed for being overridden. + """ + + [email protected](dependencies=['foo', 'output'], + parser=ca.command('', + ca.positional('lili', type=str)), + regular=True) +def regular_command(foo, lili, output): + """ + Use regular arguments + + Output results + """ + output(foo, lili) + + @COMMANDS.command(dependencies=['foo', 'print'], parser=ca.command('', ca.positional('lala', type=str))) diff --git a/src/elcaminoreal/test/test_gathering.py b/src/elcaminoreal/test/test_gathering.py index 8049cd1..7ec2028 100644 --- a/src/elcaminoreal/test/test_gathering.py +++ b/src/elcaminoreal/test/test_gathering.py @@ -46,6 +46,15 @@ class DependencyResolverTester(unittest.TestCase): result = some_plugins.COMMANDS.mkgraph(['foo_2']) self.assertEquals(result['foo_2'], dict(bar="I'm a bar")) + def test_mkgraph_regular(self): + """ + mkgraph regular functions work + """ + result = some_plugins.COMMANDS.mkgraph(['regular']) + self.assertEquals(result['regular']['bar'], result['bar']) + self.assertEquals(result['regular']['quux'], result['quux']) + self.assertEquals(result['regular']['foo'], result['foo']) + class RunnerResolverTester(unittest.TestCase): @@ -100,3 +109,18 @@ class RunnerResolverTester(unittest.TestCase): some_plugins.COMMANDS.run(['no-such-command']) error_message = filep.getvalue().splitlines() self.assertEquals(error_message.pop(0), 'Usage:') + + def test_regular(self): + """ + Asking for regular arguments calls functions with argument names + """ + output = [] + + def _my_output(*args): + output.append(args) + dependencies = dict(output=_my_output) + some_plugins.COMMANDS.run(['regular-command', 'thing'], + override_dependencies=dependencies) + self.assertEquals(len(output), 1) + self.assertEquals(output[0][0]['bar'], "I'm a bar") + self.assertEquals(output[0][1], 'thing')
Allow regular arguments to commands and dependencies The following should work: ``` @COMMANDS.dependency( dependencies=['foo', 'bar'], possible_dependencies=['baz'], regular=True) def thing(foo , bar, build_baz): val = foo() if val > 5: val -= build_baz() return val + bar() @COMMANDS.command( dependencies=['thing'], parser=ca.command('', ca.positional('lala', type=str)), regular=True) def do_stuff(thing, lala): return str(thing) + lala ```
0.0
[ "src/elcaminoreal/test/test_gathering.py::RunnerResolverTester::test_required" ]
[]
2018-04-12 03:32:11+00:00
2,099
eliben__pycparser-236
diff --git a/pycparser/c_parser.py b/pycparser/c_parser.py index f01f67f..47d958f 100644 --- a/pycparser/c_parser.py +++ b/pycparser/c_parser.py @@ -616,6 +616,59 @@ class CParser(PLYParser): """ p[0] = p[1] + # A pragma is generally considered a decorator rather than an actual statement. + # Still, for the purposes of analyzing an abstract syntax tree of C code, + # pragma's should not be ignored and were previously treated as a statement. + # This presents a problem for constructs that take a statement such as labeled_statements, + # selection_statements, and iteration_statements, causing a misleading structure + # in the AST. For example, consider the following C code. + # + # for (int i = 0; i < 3; i++) + # #pragma omp critical + # sum += 1; + # + # This code will compile and execute "sum += 1;" as the body of the for loop. + # Previous implementations of PyCParser would render the AST for this + # block of code as follows: + # + # For: + # DeclList: + # Decl: i, [], [], [] + # TypeDecl: i, [] + # IdentifierType: ['int'] + # Constant: int, 0 + # BinaryOp: < + # ID: i + # Constant: int, 3 + # UnaryOp: p++ + # ID: i + # Pragma: omp critical + # Assignment: += + # ID: sum + # Constant: int, 1 + # + # This AST misleadingly takes the Pragma as the body of the loop and the + # assignment then becomes a sibling of the loop. + # + # To solve edge cases like these, the pragmacomp_or_statement rule groups + # a pragma and its following statement (which would otherwise be orphaned) + # using a compound block, effectively turning the above code into: + # + # for (int i = 0; i < 3; i++) { + # #pragma omp critical + # sum += 1; + # } + def p_pragmacomp_or_statement(self, p): + """ pragmacomp_or_statement : pppragma_directive statement + | statement + """ + if isinstance(p[1], c_ast.Pragma) and len(p) == 3: + p[0] = c_ast.Compound( + block_items=[p[1], p[2]], + coord=self._token_coord(p, 1)) + else: + p[0] = p[1] + # In C, declarations can come several in a line: # int x, *px, romulo = 5; # @@ -1410,44 +1463,44 @@ class CParser(PLYParser): coord=self._token_coord(p, 1)) def p_labeled_statement_1(self, p): - """ labeled_statement : ID COLON statement """ + """ labeled_statement : ID COLON pragmacomp_or_statement """ p[0] = c_ast.Label(p[1], p[3], self._token_coord(p, 1)) def p_labeled_statement_2(self, p): - """ labeled_statement : CASE constant_expression COLON statement """ + """ labeled_statement : CASE constant_expression COLON pragmacomp_or_statement """ p[0] = c_ast.Case(p[2], [p[4]], self._token_coord(p, 1)) def p_labeled_statement_3(self, p): - """ labeled_statement : DEFAULT COLON statement """ + """ labeled_statement : DEFAULT COLON pragmacomp_or_statement """ p[0] = c_ast.Default([p[3]], self._token_coord(p, 1)) def p_selection_statement_1(self, p): - """ selection_statement : IF LPAREN expression RPAREN statement """ + """ selection_statement : IF LPAREN expression RPAREN pragmacomp_or_statement """ p[0] = c_ast.If(p[3], p[5], None, self._token_coord(p, 1)) def p_selection_statement_2(self, p): - """ selection_statement : IF LPAREN expression RPAREN statement ELSE statement """ + """ selection_statement : IF LPAREN expression RPAREN statement ELSE pragmacomp_or_statement """ p[0] = c_ast.If(p[3], p[5], p[7], self._token_coord(p, 1)) def p_selection_statement_3(self, p): - """ selection_statement : SWITCH LPAREN expression RPAREN statement """ + """ selection_statement : SWITCH LPAREN expression RPAREN pragmacomp_or_statement """ p[0] = fix_switch_cases( c_ast.Switch(p[3], p[5], self._token_coord(p, 1))) def p_iteration_statement_1(self, p): - """ iteration_statement : WHILE LPAREN expression RPAREN statement """ + """ iteration_statement : WHILE LPAREN expression RPAREN pragmacomp_or_statement """ p[0] = c_ast.While(p[3], p[5], self._token_coord(p, 1)) def p_iteration_statement_2(self, p): - """ iteration_statement : DO statement WHILE LPAREN expression RPAREN SEMI """ + """ iteration_statement : DO pragmacomp_or_statement WHILE LPAREN expression RPAREN SEMI """ p[0] = c_ast.DoWhile(p[5], p[2], self._token_coord(p, 1)) def p_iteration_statement_3(self, p): - """ iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN statement """ + """ iteration_statement : FOR LPAREN expression_opt SEMI expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement """ p[0] = c_ast.For(p[3], p[5], p[7], p[9], self._token_coord(p, 1)) def p_iteration_statement_4(self, p): - """ iteration_statement : FOR LPAREN declaration expression_opt SEMI expression_opt RPAREN statement """ + """ iteration_statement : FOR LPAREN declaration expression_opt SEMI expression_opt RPAREN pragmacomp_or_statement """ p[0] = c_ast.For(c_ast.DeclList(p[3], self._token_coord(p, 1)), p[4], p[6], p[8], self._token_coord(p, 1))
eliben/pycparser
4992410bf8c2d6d7eb94703d0f6f94b5a9acaa0a
diff --git a/tests/test_c_parser.py b/tests/test_c_parser.py index ab6143f..3b336bf 100755 --- a/tests/test_c_parser.py +++ b/tests/test_c_parser.py @@ -1369,6 +1369,54 @@ class TestCParser_fundamentals(TestCParser_base): self.assertEqual(s1_ast.ext[2].type.type.decls[0].string, 'baz') self.assertEqual(s1_ast.ext[2].type.type.decls[0].coord.line, 9) + def test_pragmacomp_or_statement(self): + s1 = r''' + void main() { + int sum = 0; + for (int i; i < 3; i++) + #pragma omp critical + sum += 1; + + while(sum < 10) + #pragma omp critical + sum += 1; + + mylabel: + #pragma foo + sum += 10; + + if (sum > 10) + #pragma bar + sum = 10; + + switch (sum) + case 10: + #pragma foo + sum = 20; + } + ''' + s1_ast = self.parse(s1) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[1], For)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Pragma)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Assignment)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[2], While)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[2].stmt, Compound)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[0], Pragma)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[1], Assignment)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[3], Label)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[3].stmt, Compound)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[0], Pragma)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[1], Assignment)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[4], If)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[4].iftrue, Compound)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[0], Pragma)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[1], Assignment)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[5], Switch)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0], Compound)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[0], Pragma)) + self.assertTrue(isinstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[1], Assignment)) + class TestCParser_whole_code(TestCParser_base): """ Testing of parsing whole chunks of code.
Incorrect AST Structure when #pragma follows For loop. Consider the following code snippet: ```c for(int i = 0; i < 3; i++) #pragma omp critical sum += 1; ``` When compiled without Open MP, the #pragma should be ignored completely, so that the statement ``sum += 1`` should be a descendent of the for loop. However, in the current implementation of pycparser, it is parsed a _sibling_ of the for loop, instead of as a descendant. ``` For: DeclList: Decl: i, [], [], [] TypeDecl: i, [] IdentifierType: ['int'] Constant: int, 0 BinaryOp: < ID: i Constant: int, 3 UnaryOp: p++ ID: i Pragma: omp critical Assignment: += ID: sum Constant: int, 1 ``` The same problem applies to other loops, Labels, and If statements, as in the following: ```c for(int i = 0; i < 3; i++) myLabel: #pragma omp critical sum += 1; ``` ```c while(sum < 100) #pragma omp critical sum += 1; ``` ```c if (sum < 100) #pragma omp critical sum += 1; ``` The following will not even parse, but it should: ```c do #pragma omp critical sum += 1; while(sum < 100) ```
0.0
[ "tests/test_c_parser.py::TestCParser_fundamentals::test_pragmacomp_or_statement" ]
[ "tests/test_c_parser.py::TestCParser_fundamentals::test_FileAST", "tests/test_c_parser.py::TestCParser_fundamentals::test_anonymous_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_statement", "tests/test_c_parser.py::TestCParser_fundamentals::test_coords", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_named_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_duplicate_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_empty_toplevel_decl", "tests/test_c_parser.py::TestCParser_fundamentals::test_enums", "tests/test_c_parser.py::TestCParser_fundamentals::test_forloop_coord", "tests/test_c_parser.py::TestCParser_fundamentals::test_func_decls_with_array_dim_qualifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_function_definitions", "tests/test_c_parser.py::TestCParser_fundamentals::test_inline_specifier", "tests/test_c_parser.py::TestCParser_fundamentals::test_int128", "tests/test_c_parser.py::TestCParser_fundamentals::test_invalid_multiple_types_error", "tests/test_c_parser.py::TestCParser_fundamentals::test_multi_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_nested_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_offsetof", "tests/test_c_parser.py::TestCParser_fundamentals::test_pragma", "tests/test_c_parser.py::TestCParser_fundamentals::test_qualifiers_storage_specifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_simple_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_sizeof", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_bitfields", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_members_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_with_extra_semis_inside", "tests/test_c_parser.py::TestCParser_fundamentals::test_tags_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_string_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_wstring_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_vla", "tests/test_c_parser.py::TestCParser_whole_code::test_empty_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_expressions", "tests/test_c_parser.py::TestCParser_whole_code::test_for_statement", "tests/test_c_parser.py::TestCParser_whole_code::test_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_switch_statement", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file_with_stdio", "tests/test_c_parser.py::TestCParser_typenames::test_ambiguous_parameters", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_typedef", "tests/test_c_parser.py::TestCParser_typenames::test_nested_function_decls", "tests/test_c_parser.py::TestCParser_typenames::test_parameter_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_samescope_reuse_name" ]
2018-03-01 22:45:54+00:00
2,100
eliben__pycparser-255
diff --git a/pycparser/c_generator.py b/pycparser/c_generator.py index 0575b8b..4c86f84 100644 --- a/pycparser/c_generator.py +++ b/pycparser/c_generator.py @@ -283,8 +283,8 @@ class CGenerator(object): for name in n.name: if isinstance(name, c_ast.ID): s += '.' + name.name - elif isinstance(name, c_ast.Constant): - s += '[' + name.value + ']' + else: + s += '[' + self.visit(name) + ']' s += ' = ' + self._visit_expr(n.expr) return s
eliben/pycparser
168f54c3ae324c3827d22fb90e456653e6fe584a
diff --git a/tests/test_c_generator.py b/tests/test_c_generator.py index 9385e80..4e38f28 100644 --- a/tests/test_c_generator.py +++ b/tests/test_c_generator.py @@ -228,6 +228,11 @@ class TestCtoC(unittest.TestCase): } ''') + def test_issue246(self): + self._assert_ctoc_correct(r''' + int array[3] = {[0] = 0, [1] = 1, [1+1] = 2}; + ''') + def test_exprlist_with_semi(self): self._assert_ctoc_correct(r''' void x() {
Constant expressions in designated initializers are not generated back to C While pycparser correctly parses a constant-expression in a designated initializer (the AST is correct), it fails to write it back when generating C code. Consider the following code: ```C void myFunction(void) { int array[3] = {[0] = 0, [1] = 1, [1+1] = 2}; } ``` Parsing it, then using `CGenerator` to generate the source produces: ```C void myFunction(void) { int array[3] = {[0] = 0, [1] = 1, = 2}; } ``` The C99 grammar describes the designator part of designated initializers as: ```ebnf designator: [ constant-expression ] . identifier ``` (See Β§6.7.8 in http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf) The ```CGenerator.visit_NamedInitializer``` currently only considers the `ID` and `Constant` types. The `Constant` branch should either be extended to other types or be an `else:` branch.
0.0
[ "tests/test_c_generator.py::TestCtoC::test_issue246" ]
[ "tests/test_c_generator.py::TestFunctionDeclGeneration::test_partial_funcdecl_generation", "tests/test_c_generator.py::TestCtoC::test_casts", "tests/test_c_generator.py::TestCtoC::test_comma_op_assignment", "tests/test_c_generator.py::TestCtoC::test_comma_op_in_ternary", "tests/test_c_generator.py::TestCtoC::test_comma_operator_funcarg", "tests/test_c_generator.py::TestCtoC::test_complex_decls", "tests/test_c_generator.py::TestCtoC::test_compound_literal", "tests/test_c_generator.py::TestCtoC::test_enum", "tests/test_c_generator.py::TestCtoC::test_enum_typedef", "tests/test_c_generator.py::TestCtoC::test_expr_list_in_initializer_list", "tests/test_c_generator.py::TestCtoC::test_exprlist_with_semi", "tests/test_c_generator.py::TestCtoC::test_exprlist_with_subexprlist", "tests/test_c_generator.py::TestCtoC::test_exprs", "tests/test_c_generator.py::TestCtoC::test_generate_struct_union_enum_exception", "tests/test_c_generator.py::TestCtoC::test_initlist", "tests/test_c_generator.py::TestCtoC::test_issue36", "tests/test_c_generator.py::TestCtoC::test_issue37", "tests/test_c_generator.py::TestCtoC::test_issue83", "tests/test_c_generator.py::TestCtoC::test_issue84", "tests/test_c_generator.py::TestCtoC::test_krstyle", "tests/test_c_generator.py::TestCtoC::test_nest_initializer_list", "tests/test_c_generator.py::TestCtoC::test_nest_named_initializer", "tests/test_c_generator.py::TestCtoC::test_pragma", "tests/test_c_generator.py::TestCtoC::test_statements", "tests/test_c_generator.py::TestCtoC::test_struct_decl", "tests/test_c_generator.py::TestCtoC::test_switchcase", "tests/test_c_generator.py::TestCtoC::test_ternary", "tests/test_c_generator.py::TestCtoC::test_trivial_decls" ]
2018-04-26 10:13:25+00:00
2,101
eliben__pycparser-346
diff --git a/pycparser/ast_transforms.py b/pycparser/ast_transforms.py index ba50966..0aeb88f 100644 --- a/pycparser/ast_transforms.py +++ b/pycparser/ast_transforms.py @@ -74,7 +74,8 @@ def fix_switch_cases(switch_node): # Goes over the children of the Compound below the Switch, adding them # either directly below new_compound or below the last Case as appropriate - for child in switch_node.stmt.block_items: + # (for `switch(cond) {}`, block_items would have been None) + for child in (switch_node.stmt.block_items or []): if isinstance(child, (c_ast.Case, c_ast.Default)): # If it's a Case/Default: # 1. Add it to the Compound and mark as "last case"
eliben/pycparser
bc2010aea92535cb1d70be9fc1bebeb6eff229d8
diff --git a/tests/test_c_parser.py b/tests/test_c_parser.py index ad9a218..49cada3 100755 --- a/tests/test_c_parser.py +++ b/tests/test_c_parser.py @@ -1792,6 +1792,7 @@ class TestCParser_whole_code(TestCParser_base): switch = ps1.ext[0].body.block_items[0] block = switch.stmt.block_items + self.assertEqual(len(block), 4) assert_case_node(block[0], '10') self.assertEqual(len(block[0].stmts), 3) assert_case_node(block[1], '20') @@ -1819,6 +1820,7 @@ class TestCParser_whole_code(TestCParser_base): switch = ps2.ext[0].body.block_items[0] block = switch.stmt.block_items + self.assertEqual(len(block), 5) assert_default_node(block[0]) self.assertEqual(len(block[0].stmts), 2) assert_case_node(block[1], '10') @@ -1830,6 +1832,18 @@ class TestCParser_whole_code(TestCParser_base): assert_case_node(block[4], '40') self.assertEqual(len(block[4].stmts), 1) + s3 = r''' + int foo(void) { + switch (myvar) { + } + return 0; + } + ''' + ps3 = self.parse(s3) + switch = ps3.ext[0].body.block_items[0] + + self.assertEqual(switch.stmt.block_items, []) + def test_for_statement(self): s2 = r''' void x(void)
"'NoneType' object is not iterable" seen for switch statement without cases Seen calling parse_file on a file containing the below snippet (similar code was generated by a preprocessor). This compiles with `gcc`. I think checking if block_items is None may be sufficient. ```c int main() { int type = 2; switch(type) {} } ``` ``` /usr/local/lib/python3.7/site-packages/pycparser/ply/yacc.py in parseopt_notrack(self, input, lexer, debug, tracking, tokenfunc) 1116 del symstack[-plen:] 1117 self.state = state -> 1118 p.callable(pslice) 1119 del statestack[-plen:] 1120 symstack.append(sym) /usr/local/lib/python3.7/site-packages/pycparser/c_parser.py in p_selection_statement_3(self, p) 1505 """ selection_statement : SWITCH LPAREN expression RPAREN pragmacomp_or_statement """ 1506 p[0] = fix_switch_cases( -> 1507 c_ast.Switch(p[3], p[5], self._token_coord(p, 1))) 1508 1509 def p_iteration_statement_1(self, p): /usr/local/lib/python3.7/site-packages/pycparser/ast_transforms.py in fix_switch_cases(switch_node) 75 # Goes over the children of the Compound below the Switch, adding them 76 # either directly below new_compound or below the last Case as appropriate ---> 77 for child in switch_node.stmt.block_items: 78 if isinstance(child, (c_ast.Case, c_ast.Default)): 79 # If it's a Case/Default: TypeError: 'NoneType' object is not iterable ```
0.0
[ "tests/test_c_parser.py::TestCParser_whole_code::test_switch_statement" ]
[ "tests/test_c_parser.py::TestCParser_fundamentals::test_FileAST", "tests/test_c_parser.py::TestCParser_fundamentals::test_anonymous_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_statement", "tests/test_c_parser.py::TestCParser_fundamentals::test_coords", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_named_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_duplicate_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_empty_toplevel_decl", "tests/test_c_parser.py::TestCParser_fundamentals::test_enums", "tests/test_c_parser.py::TestCParser_fundamentals::test_forloop_coord", "tests/test_c_parser.py::TestCParser_fundamentals::test_func_decls_with_array_dim_qualifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_function_definitions", "tests/test_c_parser.py::TestCParser_fundamentals::test_initial_semi", "tests/test_c_parser.py::TestCParser_fundamentals::test_inline_specifier", "tests/test_c_parser.py::TestCParser_fundamentals::test_int128", "tests/test_c_parser.py::TestCParser_fundamentals::test_invalid_multiple_types_error", "tests/test_c_parser.py::TestCParser_fundamentals::test_multi_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_nested_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_offsetof", "tests/test_c_parser.py::TestCParser_fundamentals::test_pragma", "tests/test_c_parser.py::TestCParser_fundamentals::test_pragmacomp_or_statement", "tests/test_c_parser.py::TestCParser_fundamentals::test_qualifiers_storage_specifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_simple_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_sizeof", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_bitfields", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_empty", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_members_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_with_extra_semis_inside", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_with_initial_semi", "tests/test_c_parser.py::TestCParser_fundamentals::test_tags_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_string_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_wstring_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_vla", "tests/test_c_parser.py::TestCParser_whole_code::test_empty_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_expressions", "tests/test_c_parser.py::TestCParser_whole_code::test_for_statement", "tests/test_c_parser.py::TestCParser_whole_code::test_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file_with_stdio", "tests/test_c_parser.py::TestCParser_typenames::test_ambiguous_parameters", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_typedef", "tests/test_c_parser.py::TestCParser_typenames::test_nested_function_decls", "tests/test_c_parser.py::TestCParser_typenames::test_parameter_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_samescope_reuse_name" ]
2019-08-21 00:12:44+00:00
2,102
eliben__pycparser-364
diff --git a/README.rst b/README.rst index df9025c..682abf7 100644 --- a/README.rst +++ b/README.rst @@ -161,6 +161,9 @@ See `this blog post <https://eli.thegreenplace.net/2015/on-parsing-c-type-declarations-and-fake-headers>`_ for more details. +Note that the fake headers are not included in the ``pip`` package nor installed +via ``setup.py`` (`#224 <https://github.com/eliben/pycparser/issues/224>`_). + Basic usage ----------- diff --git a/pycparser/c_parser.py b/pycparser/c_parser.py index 4cf96fa..744ede8 100644 --- a/pycparser/c_parser.py +++ b/pycparser/c_parser.py @@ -1740,8 +1740,7 @@ class CParser(PLYParser): if len(p) == 2: p[0] = p[1] elif len(p) == 4: - field = c_ast.ID(p[3], self._token_coord(p, 3)) - p[0] = c_ast.StructRef(p[1], p[2], field, p[1].coord) + p[0] = c_ast.StructRef(p[1], p[2], p[3], p[1].coord) elif len(p) == 5: p[0] = c_ast.ArrayRef(p[1], p[3], p[1].coord) else:
eliben/pycparser
1166ea11785ce12cdfd5e8bf8b3a69b5e6b76f9c
diff --git a/tests/test_c_parser.py b/tests/test_c_parser.py index 49cada3..b6ecdd5 100755 --- a/tests/test_c_parser.py +++ b/tests/test_c_parser.py @@ -529,6 +529,18 @@ class TestCParser_fundamentals(TestCParser_base): ['IdentifierType', ['int']]]]]]) def test_offsetof(self): + def expand_ref(n): + if isinstance(n, StructRef): + return ['StructRef', expand_ref(n.name), expand_ref(n.field)] + elif isinstance(n, ArrayRef): + return ['ArrayRef', expand_ref(n.name), expand_ref(n.subscript)] + elif isinstance(n, ID): + return ['ID', n.name] + elif isinstance(n, Constant): + return ['Constant', n.type, n.value] + else: + raise TypeError("Unexpected type " + n.__class__.__name__) + e = """ void foo() { int a = offsetof(struct S, p); @@ -546,8 +558,20 @@ class TestCParser_fundamentals(TestCParser_base): self.assertIsInstance(s1.args.exprs[1], ID) s3 = compound.block_items[2].init self.assertIsInstance(s3.args.exprs[1], StructRef) + self.assertEqual(expand_ref(s3.args.exprs[1]), + ['StructRef', + ['StructRef', ['ID', 'p'], ['ID', 'q']], + ['ID', 'r']]) s4 = compound.block_items[3].init self.assertIsInstance(s4.args.exprs[1], ArrayRef) + self.assertEqual(expand_ref(s4.args.exprs[1]), + ['ArrayRef', + ['ArrayRef', + ['StructRef', + ['ArrayRef', ['ID', 'p'], ['Constant', 'int', '5']], + ['ID', 'q']], + ['Constant', 'int', '4']], + ['Constant', 'int', '5']]) def test_compound_statement(self): e = """
Incorrect AST structure when parsing `offsetof` expressions. I am using the latest commit on `master` branch (`1166ea1`). Take the following code as example: ```c int x = offsetof(struct A, a.b); ``` The generated parse tree is: ```python FileAST(ext=[Decl(name='x', quals=[], storage=[], funcspec=[], type=TypeDecl(declname='x', quals=[], type=IdentifierType(names=['int'])), init=FuncCall(name=ID(name='offsetof'), args=ExprList(exprs=[Typename(name=None, quals=[], type=TypeDecl(declname=None, quals=[], type=Struct(name='A', decls=None))), StructRef(name=ID(name='a'), type='.', field=ID(name=ID(name='b')))])), bitsize=None)]) ``` where the `field` attribute of `StructRef` has a value of `ID(name=ID(name='b'))` instead of just `ID(name='b')`. I think the issue is with the production rules of `offsetof_member_designator` that was introduced in #145, namely: https://github.com/eliben/pycparser/blob/1166ea11785ce12cdfd5e8bf8b3a69b5e6b76f9c/pycparser/c_parser.py#L1735-L1748 In the `len(p) == 4` case, `StructRef` should be created using `p[3]` directly, instead of constructing an `ID` first. If you agree with my analysis, I'd be happy to create a patch.
0.0
[ "tests/test_c_parser.py::TestCParser_fundamentals::test_offsetof" ]
[ "tests/test_c_parser.py::TestCParser_fundamentals::test_FileAST", "tests/test_c_parser.py::TestCParser_fundamentals::test_anonymous_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_compound_statement", "tests/test_c_parser.py::TestCParser_fundamentals::test_coords", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_decl_named_inits", "tests/test_c_parser.py::TestCParser_fundamentals::test_duplicate_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_empty_toplevel_decl", "tests/test_c_parser.py::TestCParser_fundamentals::test_enums", "tests/test_c_parser.py::TestCParser_fundamentals::test_forloop_coord", "tests/test_c_parser.py::TestCParser_fundamentals::test_func_decls_with_array_dim_qualifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_function_definitions", "tests/test_c_parser.py::TestCParser_fundamentals::test_initial_semi", "tests/test_c_parser.py::TestCParser_fundamentals::test_inline_specifier", "tests/test_c_parser.py::TestCParser_fundamentals::test_int128", "tests/test_c_parser.py::TestCParser_fundamentals::test_invalid_multiple_types_error", "tests/test_c_parser.py::TestCParser_fundamentals::test_multi_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_nested_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_pragma", "tests/test_c_parser.py::TestCParser_fundamentals::test_pragmacomp_or_statement", "tests/test_c_parser.py::TestCParser_fundamentals::test_qualifiers_storage_specifiers", "tests/test_c_parser.py::TestCParser_fundamentals::test_simple_decls", "tests/test_c_parser.py::TestCParser_fundamentals::test_sizeof", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_bitfields", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_empty", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_members_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_union", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_with_extra_semis_inside", "tests/test_c_parser.py::TestCParser_fundamentals::test_struct_with_initial_semi", "tests/test_c_parser.py::TestCParser_fundamentals::test_tags_namespace", "tests/test_c_parser.py::TestCParser_fundamentals::test_typedef", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_string_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_unified_wstring_literals", "tests/test_c_parser.py::TestCParser_fundamentals::test_vla", "tests/test_c_parser.py::TestCParser_whole_code::test_empty_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_expressions", "tests/test_c_parser.py::TestCParser_whole_code::test_for_statement", "tests/test_c_parser.py::TestCParser_whole_code::test_statements", "tests/test_c_parser.py::TestCParser_whole_code::test_switch_statement", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file", "tests/test_c_parser.py::TestCParser_whole_code::test_whole_file_with_stdio", "tests/test_c_parser.py::TestCParser_typenames::test_ambiguous_parameters", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_innerscope_typedef", "tests/test_c_parser.py::TestCParser_typenames::test_nested_function_decls", "tests/test_c_parser.py::TestCParser_typenames::test_parameter_reuse_typedef_name", "tests/test_c_parser.py::TestCParser_typenames::test_samescope_reuse_name" ]
2020-02-25 16:22:57+00:00
2,103
eliben__pycparser-394
diff --git a/pycparser/c_generator.py b/pycparser/c_generator.py index 53c26fd..c494176 100644 --- a/pycparser/c_generator.py +++ b/pycparser/c_generator.py @@ -14,11 +14,17 @@ class CGenerator(object): return a value from each visit method, using string accumulation in generic_visit. """ - def __init__(self): + def __init__(self, reduce_parentheses=False): + """ Constructs C-code generator + + reduce_parentheses: + if True, eliminates needless parentheses on binary operators + """ # Statements start with indentation of self.indent_level spaces, using # the _make_indent method # self.indent_level = 0 + self.reduce_parentheses = reduce_parentheses def _make_indent(self): return ' ' * self.indent_level @@ -72,11 +78,49 @@ class CGenerator(object): else: return '%s%s' % (n.op, operand) + # Precedence map of binary operators: + precedence_map = { + # Some what of a duplicate of c_paarser.CParser.precedence + # Higher numbers are stronger binding + '||': 0, # weakest binding + '&&': 1, + '|': 2, + '^': 3, + '&': 4, + '==': 5, '!=': 5, + '>': 6, '>=': 6, '<': 6, '<=': 6, + '>>': 7, '<<': 7, + '+': 8, '-': 8, + '*': 9, '/': 9, '%': 9 # strongest binding + } + def visit_BinaryOp(self, n): - lval_str = self._parenthesize_if(n.left, - lambda d: not self._is_simple_node(d)) - rval_str = self._parenthesize_if(n.right, - lambda d: not self._is_simple_node(d)) + # Note: all binary operators are left-to-right associative + # + # If `n.left.op` has a stronger or equally binding precedence in + # comparison to `n.op`, no parenthesis are needed for the left: + # e.g., `(a*b) + c` is equivelent to `a*b + c`, as well as + # `(a+b) - c` is equivelent to `a+b - c` (same precedence). + # If the left operator is weaker binding than the current, then + # parentheses are necessary: + # e.g., `(a+b) * c` is NOT equivelent to `a+b * c`. + lval_str = self._parenthesize_if( + n.left, + lambda d: not (self._is_simple_node(d) or + self.reduce_parentheses and isinstance(d, c_ast.BinaryOp) and + self.precedence_map[d.op] >= self.precedence_map[n.op])) + # If `n.right.op` has a stronger -but not equal- binding precedence, + # parenthesis can be omitted on the right: + # e.g., `a + (b*c)` is equivelent to `a + b*c`. + # If the right operator is weaker or equally binding, then parentheses + # are necessary: + # e.g., `a * (b+c)` is NOT equivelent to `a * b+c` and + # `a - (b+c)` is NOT equivelent to `a - b+c` (same precedence). + rval_str = self._parenthesize_if( + n.right, + lambda d: not (self._is_simple_node(d) or + self.reduce_parentheses and isinstance(d, c_ast.BinaryOp) and + self.precedence_map[d.op] > self.precedence_map[n.op])) return '%s %s %s' % (lval_str, n.op, rval_str) def visit_Assignment(self, n): diff --git a/pycparser/c_parser.py b/pycparser/c_parser.py index c2d82f7..0536e58 100644 --- a/pycparser/c_parser.py +++ b/pycparser/c_parser.py @@ -491,6 +491,7 @@ class CParser(PLYParser): ## ## Precedence and associativity of operators ## + # If this changes, c_generator.CGenerator.precedence_map needs to change as well precedence = ( ('left', 'LOR'), ('left', 'LAND'),
eliben/pycparser
ba80794f1460a87eed2f8f918e47868878f3a5ad
diff --git a/tests/test_c_generator.py b/tests/test_c_generator.py index 159c763..7937525 100644 --- a/tests/test_c_generator.py +++ b/tests/test_c_generator.py @@ -61,19 +61,22 @@ class TestFunctionDeclGeneration(unittest.TestCase): class TestCtoC(unittest.TestCase): - def _run_c_to_c(self, src): + def _run_c_to_c(self, src, *args, **kwargs): ast = parse_to_ast(src) - generator = c_generator.CGenerator() + generator = c_generator.CGenerator(*args, **kwargs) return generator.visit(ast) - def _assert_ctoc_correct(self, src): + def _assert_ctoc_correct(self, src, *args, **kwargs): """ Checks that the c2c translation was correct by parsing the code generated by c2c for src and comparing the AST with the original AST. + + Additional arguments are passed to CGenerator.__init__. """ - src2 = self._run_c_to_c(src) + src2 = self._run_c_to_c(src, *args, **kwargs) self.assertTrue(compare_asts(parse_to_ast(src), parse_to_ast(src2)), - src2) + "{!r} != {!r}".format(src, src2)) + return src2 def test_trivial_decls(self): self._assert_ctoc_correct('int a;') @@ -361,6 +364,26 @@ class TestCtoC(unittest.TestCase): src = 'int x = ' + src + ';' self._assert_ctoc_correct(src) + def test_flattened_binaryops(self): + # codes with minimum number of (necessary) parenthesis: + test_snippets = [ + 'int x = a*b*c*d;', + 'int x = a+b*c*d;', + 'int x = a*b+c*d;', + 'int x = a*b*c+d;', + 'int x = (a+b)*c*d;', + 'int x = (a+b)*(c+d);', + 'int x = (a+b)/(c-d);', + 'int x = a+b-c-d;', + 'int x = a+(b-c)-d;' + ] + for src in test_snippets: + src2 = self._assert_ctoc_correct(src, reduce_parentheses=True) + self.assertTrue( + src2.count('(') == src.count('('), + msg="{!r} did not have minimum number of parenthesis, should be like {!r}.".format( + src2, src)) + class TestCasttoC(unittest.TestCase): def _find_file(self, name):
Precedence-aware CGenerator I ran into the issue that in a code more than 256 variables are summed up. The `CGenerator` turned this into >256 nested BinaryOperators with that many parenthesis, that in turn was something clang did not like (be default). I wrote a small generator which takes precedence into account for binary operators: ```python class LessParanthesizingCGenerator(CGenerator): def get_BinaryOp_precedence(self, n): """ Gives precedence for op of n, otherwise -1. Lower number have precedence over higher numbers. """ binary_op_precedence = { # based on https://en.cppreference.com/w/c/language/operator_precedence '*': 3, '%': 3, '-': 4, '+': 4, '<<': 5, '>>': 5, '<': 6, '<=': 6, '>': 6, '>=': 6, '==': 7, '!=': 7, '&': 8, '^': 9, '|': 10, '&&': 11, '||': 12 } if not isinstance(n, c_ast.BinaryOp): return -1 else: return binary_op_precedence[n.op] def visit_BinaryOp(self, n): p = self.get_BinaryOp_precedence(n) lval_str = self._parenthesize_if(n.left, lambda d: not self._is_simple_node(d) and self.get_BinaryOp_precedence(d) > p) rval_str = self._parenthesize_if(n.right, lambda d: not self._is_simple_node(d) and self.get_BinaryOp_precedence(d) >= p) return '%s %s %s' % (lval_str, n.op, rval_str) ``` Would you like me to make a pull request and if so, is this implementation sufficient for now? Tests I would of cause add.
0.0
[ "tests/test_c_generator.py::TestCtoC::test_flattened_binaryops" ]
[ "tests/test_c_generator.py::TestFunctionDeclGeneration::test_partial_funcdecl_generation", "tests/test_c_generator.py::TestCtoC::test_array_decl", "tests/test_c_generator.py::TestCtoC::test_casts", "tests/test_c_generator.py::TestCtoC::test_comma_op_assignment", "tests/test_c_generator.py::TestCtoC::test_comma_op_in_ternary", "tests/test_c_generator.py::TestCtoC::test_comma_operator_funcarg", "tests/test_c_generator.py::TestCtoC::test_complex_decls", "tests/test_c_generator.py::TestCtoC::test_compound_literal", "tests/test_c_generator.py::TestCtoC::test_enum", "tests/test_c_generator.py::TestCtoC::test_enum_typedef", "tests/test_c_generator.py::TestCtoC::test_expr_list_in_initializer_list", "tests/test_c_generator.py::TestCtoC::test_exprlist_with_semi", "tests/test_c_generator.py::TestCtoC::test_exprlist_with_subexprlist", "tests/test_c_generator.py::TestCtoC::test_exprs", "tests/test_c_generator.py::TestCtoC::test_generate_struct_union_enum_exception", "tests/test_c_generator.py::TestCtoC::test_initlist", "tests/test_c_generator.py::TestCtoC::test_issue246", "tests/test_c_generator.py::TestCtoC::test_issue36", "tests/test_c_generator.py::TestCtoC::test_issue37", "tests/test_c_generator.py::TestCtoC::test_issue66", "tests/test_c_generator.py::TestCtoC::test_issue83", "tests/test_c_generator.py::TestCtoC::test_issue84", "tests/test_c_generator.py::TestCtoC::test_krstyle", "tests/test_c_generator.py::TestCtoC::test_nest_initializer_list", "tests/test_c_generator.py::TestCtoC::test_nest_named_initializer", "tests/test_c_generator.py::TestCtoC::test_nested_sizeof", "tests/test_c_generator.py::TestCtoC::test_pragma", "tests/test_c_generator.py::TestCtoC::test_ptr_decl", "tests/test_c_generator.py::TestCtoC::test_statements", "tests/test_c_generator.py::TestCtoC::test_struct_decl", "tests/test_c_generator.py::TestCtoC::test_switchcase", "tests/test_c_generator.py::TestCtoC::test_ternary", "tests/test_c_generator.py::TestCtoC::test_trivial_decls", "tests/test_c_generator.py::TestCasttoC::test_to_type", "tests/test_c_generator.py::TestCasttoC::test_to_type_with_cpp" ]
2020-10-01 17:17:55+00:00
2,104
emissions-api__sentinel5dl-29
diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..2301243 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,3 @@ +[report] +omit = + */tests/* diff --git a/.travis.yml b/.travis.yml index a4c4ae5..8511f0b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,9 @@ dist: bionic # https://devguide.python.org/#branchstatus python: - - "3.6" - - "3.7" + - 3.6 + - 3.7 + - 3.8 addons: apt: @@ -13,18 +14,18 @@ addons: - libgnutls28-dev install: - - pip install flake8 coverage + - pip install flake8 coverage coveralls - python setup.py install script: - flake8 sentinel5dl - coverage run --source=sentinel5dl -m tests - - coverage report after_success: - pip install sphinx sphinx-rtd-theme - make -C docs clean html - touch docs/build/html/.nojekyll # create this file to prevent Github's Jekyll processing + - coveralls deploy: provider: pages diff --git a/README.rst b/README.rst index a5aed3e..47748ce 100644 --- a/README.rst +++ b/README.rst @@ -3,6 +3,10 @@ Sentinel-5P Downloader .. image:: https://travis-ci.com/emissions-api/sentinel5dl.svg?branch=master :target: https://travis-ci.com/emissions-api/sentinel5dl + :alt: CI Builds +.. image:: https://coveralls.io/repos/github/emissions-api/sentinel5dl/badge.svg?branch=master + :target: https://coveralls.io/github/emissions-api/sentinel5dl?branch=master + :alt: Test Coverage .. image:: https://img.shields.io/github/issues-raw/emissions-api/sentinel5dl?color=blue :target: https://github.com/emissions-api/sentinel5dl/issues :alt: GitHub issues diff --git a/docs/Makefile b/docs/Makefile index d0c3cbf..a4de0bf 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -3,7 +3,7 @@ # You can set these variables from the command line, and also # from the environment for the first two. -SPHINXOPTS ?= +SPHINXOPTS ?= -W SPHINXBUILD ?= sphinx-build SOURCEDIR = source BUILDDIR = build diff --git a/docs/source/index.rst b/docs/source/index.rst index 7d41c3d..5ead6ed 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,4 +1,4 @@ -.. include:: ../../readme.rst +.. include:: ../../README.rst .. toctree:: diff --git a/sentinel5dl/__init__.py b/sentinel5dl/__init__.py index 278956d..0be61eb 100644 --- a/sentinel5dl/__init__.py +++ b/sentinel5dl/__init__.py @@ -38,6 +38,28 @@ def __md5(filename): return hash_md5.hexdigest().upper() +def __check_md5(filename, base_path): + '''Check the md5 sum of a given file against the ESA API. + + :param filename: Path of local file to check + :param base_path: Base API path to for this product + :returns: If the local file matches the md5 checksum + :rtype: bool + ''' + md5file = f'{filename}.md5sum' + try: + with open(md5file, 'r') as f: + md5sum = f.read() + except FileNotFoundError: + md5sum = __http_request(f'{base_path}/Checksum/Value/$value') + md5sum = md5sum.decode('ascii') + with open(md5file, 'w') as f: + f.write(md5sum) + + # Compare md5 sum + return __md5(filename) == md5sum + + def __http_request(path, filename=None): '''Make an HTTP request to the API via HTTP, optionally downloading the response. @@ -140,20 +162,15 @@ def download(products, output_dir='.'): uuid = product['uuid'] filename = os.path.join(output_dir, product['identifier'] + '.nc') logger.info(f'Downloading {uuid} to {filename}') - path = f'/odata/v1/Products(\'{uuid}\')/$value' + base_path = f"/odata/v1/Products('{uuid}')" # Check if file exist if os.path.exists(filename): - # Get md5 sum - md5um_path = f"/odata/v1/Products('{uuid}')/Checksum/Value/$value" - md5sum = __http_request(md5um_path) - md5sum = md5sum.decode() - - # Compare md5 sum - if __md5(filename) == md5sum: + # Skip download if checksum matches + if __check_md5(filename, base_path): logger.info(f'Skipping {filename} since it already exist.') continue logger.info(f'Overriding {filename} since md5 hash differs.') # Download file - __http_request(path, filename) + __http_request(f'{base_path}/$value', filename) diff --git a/setup.py b/setup.py index 9bfe958..1e7a6c5 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ def read(filename): setup( name='sentinel5dl', - version='0.4', + version='0.5', description='Sentinel-5p Downloader', author='Emissions API Developers', license='MIT', @@ -24,6 +24,7 @@ setup( 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', 'Operating System :: OS Independent', 'Topic :: Scientific/Engineering :: GIS', ],
emissions-api/sentinel5dl
03f4148332a9b7cba0b8ea420aa0fb885d234694
diff --git a/tests/__main__.py b/tests/__main__.py index a3472df..ad1d698 100644 --- a/tests/__main__.py +++ b/tests/__main__.py @@ -12,18 +12,22 @@ class TestSentinel5dl(unittest.TestCase): def _mock_http_request(self, path, filename=None): '''Mock HTTP requests to the ESA API ''' + # download if filename is not None: self._count_download += 1 with open(filename, 'wb') as f: f.write(b'123') return - # no nownload - self._count_request += 1 + # search request if path.startswith('/api/stub/products?'): + self._count_search_request += 1 with open(os.path.join(testpath, 'products.json'), 'rb') as f: return f.read() + + # checksum request if path.endswith('/Checksum/Value/$value'): + self._count_checksum_request += 1 # MD5 checksum for string `123` return b'202CB962AC59075B964B07152D234B70' @@ -32,7 +36,8 @@ class TestSentinel5dl(unittest.TestCase): make any HTTP requests and reset the request counters. ''' setattr(sentinel5dl, '__http_request', self._mock_http_request) - self._count_request = 0 + self._count_search_request = 0 + self._count_checksum_request = 0 self._count_download = 0 def test(self): @@ -46,7 +51,7 @@ class TestSentinel5dl(unittest.TestCase): # The result returned by the mock contains four products but claims a # total of eight products, making sentinel5dl request resources twice. - self.assertEqual(self._count_request, 2) + self.assertEqual(self._count_search_request, 2) self.assertEqual(result['totalresults'], 8) self.assertEqual(result['totalresults'], len(result['products'])) @@ -66,10 +71,12 @@ class TestSentinel5dl(unittest.TestCase): with open(filename, 'rb') as f: self.assertEqual(f.read(), b'123') - # We should have made an additional five requests for checksums: - # - one for the file we created manually - # - four for the duplicated entries in the loaded test data - self.assertEqual(self._count_request, 7) + # We should have downloaded four files and have an additional four + # files storing md5 checksums + self.assertEqual(len(os.listdir(tmpdir)), 8) + + # We should have four checksum requests. One for each file + self.assertEqual(self._count_checksum_request, 4) # We should have downloaded four unique files self.assertEqual(self._count_download, 4)
Store also hash files We should store the hash files after we have downloaded them. So we can check if the hash file matches the downloaded .nc file without any network connection. This is pretty handy, since the ESA website is painfully slow even for the hash files.
0.0
[ "tests/__main__.py::TestSentinel5dl::test" ]
[]
2019-10-27 11:00:02+00:00
2,105
emsig__emg3d-325
diff --git a/emg3d/electrodes.py b/emg3d/electrodes.py index 8a31385..e31ec0f 100644 --- a/emg3d/electrodes.py +++ b/emg3d/electrodes.py @@ -323,7 +323,7 @@ class Dipole(Wire): if is_flat: # Re-arrange for points. - points = np.array([coordinates[::2], coordinates[1::2]]) + points = coordinates.reshape((2, 3), order='F') # Store original input. self._coordinates = coordinates @@ -375,10 +375,20 @@ class Dipole(Wire): # Finite dipole. else: - s1 = (f" e1={{{self.points[0, 0]:,.1f}; " - f"{self.points[0, 1]:,.1f}; {self.points[0, 2]:,.1f}}} m; ") - s2 = (f"e2={{{self.points[1, 0]:,.1f}; " - f"{self.points[1, 1]:,.1f}; {self.points[1, 2]:,.1f}}} m") + + # Finite magnetic dipole. + if self._xtype == 'magnetic': + if self.coordinates.ndim == 1: + points = self.coordinates + else: + points = self.coordinates.ravel('F') + else: + points = self.points.ravel('F') + + s1 = (f" e1={{{points[0]:,.1f}; " + f"{points[2]:,.1f}; {points[4]:,.1f}}} m; ") + s2 = (f"e2={{{points[1]:,.1f}; " + f"{points[3]:,.1f}; {points[5]:,.1f}}} m") return s0 + s1 + s2 if len(s1+s2) < 80 else s0 + s1 + "\n " + s2
emsig/emg3d
8750f85bfcebaf67ed2e6beff941b960a048a1b3
diff --git a/tests/test_electrodes.py b/tests/test_electrodes.py index baa98ba..d0a5e06 100644 --- a/tests/test_electrodes.py +++ b/tests/test_electrodes.py @@ -273,6 +273,8 @@ def test_tx_magnetic_dipole(): s5a = electrodes.TxMagneticDipole( (-1, 1, -1, 1, -np.sqrt(2), np.sqrt(2)), strength=np.pi) s5b = electrodes.TxMagneticDipole.from_dict(s5a.to_dict()) + rep = s5b.__repr__() + assert "m; e2={1.0; 1.0; " in rep assert s5a == s5b s6a = electrodes.TxMagneticDipole( [[-1, -1, -np.sqrt(2)], [1, 1, np.sqrt(2)]], strength=np.pi) @@ -287,7 +289,7 @@ def test_tx_magnetic_dipole(): rep = s6b.__repr__() assert "3.1 A" in rep - assert "m; e2={-0.7" in rep + assert "m; e2={1.0; 1.0; " in rep def test_tx_electric_wire():
`emg3d.TxMagneticDipole` shows wrong coordinates. ``` > src = emg3d.TxMagneticDipole(coordinates=[0.0, 0.0, 0.0, 0.0, -0.5, 0.5]) > src TxMagneticDipole: 1.0 A; e1={0.0; 0.7; 0.0} m; e2={-0.7; 0.0; 0.0} m ``` which are just the first two points of it, ``` > src.points array([[ 0. , 0.70710678, 0. ], [-0.70710678, 0. , 0. ], [ 0. , -0.70710678, 0. ], [ 0.70710678, 0. , 0. ], [ 0. , 0.70710678, 0. ]]) ```
0.0
[ "tests/test_electrodes.py::test_tx_magnetic_dipole" ]
[ "tests/test_electrodes.py::TestWire::test_basics", "tests/test_electrodes.py::TestWire::test_basic_repr", "tests/test_electrodes.py::TestWire::test_warnings", "tests/test_electrodes.py::test_point", "tests/test_electrodes.py::TestDipole::test_point", "tests/test_electrodes.py::TestDipole::test_flat", "tests/test_electrodes.py::TestDipole::test_dipole", "tests/test_electrodes.py::TestDipole::test_to_from_dict", "tests/test_electrodes.py::TestDipole::test_basic_repr", "tests/test_electrodes.py::TestDipole::test_warnings", "tests/test_electrodes.py::test_source", "tests/test_electrodes.py::test_tx_electric_point", "tests/test_electrodes.py::test_tx_electric_dipole", "tests/test_electrodes.py::test_tx_magnetic_point", "tests/test_electrodes.py::test_tx_electric_wire", "tests/test_electrodes.py::test_receiver", "tests/test_electrodes.py::test_rx_electric_point", "tests/test_electrodes.py::test_rx_magnetic_point", "tests/test_electrodes.py::test_point_to_dipole", "tests/test_electrodes.py::TestDipoleToPoint::test_axes_faces_quadrants", "tests/test_electrodes.py::TestDipoleToPoint::test_arbitrary", "tests/test_electrodes.py::test_point_to_square_loop", "tests/test_electrodes.py::test_rotation", "tests/test_electrodes.py::test_all_dir" ]
2024-03-05 15:10:11+00:00
2,106
en0__dnry-config-4
diff --git a/dnry/config/yaml/source.py b/dnry/config/yaml/source.py index 8742b25..23d9e8d 100644 --- a/dnry/config/yaml/source.py +++ b/dnry/config/yaml/source.py @@ -17,6 +17,9 @@ class YamlSource(IConfigSource): paths = ",".join(self.__paths) raise RuntimeError(f"Configuration Error: None of these paths could be found: {paths}") + elif path is None and not self.__required: + return dict() + with open(path, 'r') as f: return yaml.load(f, Loader=self.__loader) or dict()
en0/dnry-config
296dfdc2eee8f82f0926d102f42db2f5fd8f2efb
diff --git a/test/test_bugs.py b/test/test_bugs.py index e34fa06..e83dc27 100644 --- a/test/test_bugs.py +++ b/test/test_bugs.py @@ -9,7 +9,7 @@ from dnry.config.yaml import YamlSource class TestBugs(unittest.TestCase): def test_empty_yaml_file(self): - temp_file = f"./${uuid4()}.yaml" + temp_file = f"./{uuid4()}.yaml" with open(temp_file, 'w') as fd: fd.write('\n') try: @@ -21,3 +21,10 @@ class TestBugs(unittest.TestCase): finally: os.remove(temp_file) + + def test_optional_flag(self): + fact = ConfigFactory() + fact.add_source(YamlSource(f"./{uuid4()}", required=False)) + conf = fact.build() + none_val = conf.get("no:key") + self.assertIsNone(none_val)
Optional flag for yaml files is not obeyed When trying to add an optional YamlSource where the given yaml file does not exist, the following error is raised: ```expected str, bytes or os.PathLike object, not NoneType``` It appears the YamlSource load method is checking if the source is required or not to raise a runtime error. It correctly skips raising the error but still tries to read the file using open(). This results in the TypeError. Line 14 of `dnry/config/yaml/source.py` ```python def load(self, fact: IConfigFactory, conf: IConfigSection) -> dict: path = self.__get_first_existing_path() if path is None and self.__required: paths = ",".join(self.__paths) raise RuntimeError(f"Configuration Error: None of these paths could be found: {paths}") with open(path, 'r') as f: return yaml.load(f, Loader=self.__loader```
0.0
[ "test/test_bugs.py::TestBugs::test_optional_flag" ]
[ "test/test_bugs.py::TestBugs::test_empty_yaml_file" ]
2019-11-23 17:43:55+00:00
2,107
encode__httpcore-631
diff --git a/httpcore/_async/connection_pool.py b/httpcore/_async/connection_pool.py index 5541689..e6c4ef6 100644 --- a/httpcore/_async/connection_pool.py +++ b/httpcore/_async/connection_pool.py @@ -301,19 +301,11 @@ class AsyncConnectionPool(AsyncRequestInterface): Close any connections in the pool. """ async with self._pool_lock: - requests_still_in_flight = len(self._requests) - for connection in self._pool: await connection.aclose() self._pool = [] self._requests = [] - if requests_still_in_flight: - raise RuntimeError( - f"The connection pool was closed while {requests_still_in_flight} " - f"HTTP requests/responses were still in-flight." - ) - async def __aenter__(self) -> "AsyncConnectionPool": return self diff --git a/httpcore/_sync/connection_pool.py b/httpcore/_sync/connection_pool.py index 020893d..53536d0 100644 --- a/httpcore/_sync/connection_pool.py +++ b/httpcore/_sync/connection_pool.py @@ -301,19 +301,11 @@ class ConnectionPool(RequestInterface): Close any connections in the pool. """ with self._pool_lock: - requests_still_in_flight = len(self._requests) - for connection in self._pool: connection.close() self._pool = [] self._requests = [] - if requests_still_in_flight: - raise RuntimeError( - f"The connection pool was closed while {requests_still_in_flight} " - f"HTTP requests/responses were still in-flight." - ) - def __enter__(self) -> "ConnectionPool": return self diff --git a/httpcore/backends/asyncio.py b/httpcore/backends/asyncio.py index 3b8abf1..23f7dce 100644 --- a/httpcore/backends/asyncio.py +++ b/httpcore/backends/asyncio.py @@ -26,6 +26,7 @@ class AsyncIOStream(AsyncNetworkStream): exc_map = { TimeoutError: ReadTimeout, anyio.BrokenResourceError: ReadError, + anyio.ClosedResourceError: ReadError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): @@ -43,6 +44,7 @@ class AsyncIOStream(AsyncNetworkStream): exc_map = { TimeoutError: WriteTimeout, anyio.BrokenResourceError: WriteError, + anyio.ClosedResourceError: WriteError, } with map_exceptions(exc_map): with anyio.fail_after(timeout): diff --git a/httpcore/backends/mock.py b/httpcore/backends/mock.py index 8491f6d..9aba0ea 100644 --- a/httpcore/backends/mock.py +++ b/httpcore/backends/mock.py @@ -2,6 +2,7 @@ import ssl import typing from typing import Optional +from .._exceptions import ReadError from .base import AsyncNetworkBackend, AsyncNetworkStream, NetworkBackend, NetworkStream @@ -17,8 +18,11 @@ class MockStream(NetworkStream): def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2 + self._closed = False def read(self, max_bytes: int, timeout: Optional[float] = None) -> bytes: + if self._closed: + raise ReadError("Connection closed") if not self._buffer: return b"" return self._buffer.pop(0) @@ -27,7 +31,7 @@ class MockStream(NetworkStream): pass def close(self) -> None: - pass + self._closed = True def start_tls( self, @@ -68,8 +72,11 @@ class AsyncMockStream(AsyncNetworkStream): def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: self._buffer = buffer self._http2 = http2 + self._closed = False async def read(self, max_bytes: int, timeout: Optional[float] = None) -> bytes: + if self._closed: + raise ReadError("Connection closed") if not self._buffer: return b"" return self._buffer.pop(0) @@ -78,7 +85,7 @@ class AsyncMockStream(AsyncNetworkStream): pass async def aclose(self) -> None: - pass + self._closed = True async def start_tls( self, diff --git a/httpcore/backends/trio.py b/httpcore/backends/trio.py index 7786d02..951016c 100644 --- a/httpcore/backends/trio.py +++ b/httpcore/backends/trio.py @@ -27,6 +27,7 @@ class TrioStream(AsyncNetworkStream): exc_map: ExceptionMapping = { trio.TooSlowError: ReadTimeout, trio.BrokenResourceError: ReadError, + trio.ClosedResourceError: ReadError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf): @@ -43,6 +44,7 @@ class TrioStream(AsyncNetworkStream): exc_map: ExceptionMapping = { trio.TooSlowError: WriteTimeout, trio.BrokenResourceError: WriteError, + trio.ClosedResourceError: WriteError, } with map_exceptions(exc_map): with trio.fail_after(timeout_or_inf):
encode/httpcore
6a97dade2a57283491c7830385d52daccbeaf93b
diff --git a/tests/_async/test_connection_pool.py b/tests/_async/test_connection_pool.py index 684e9ba..d2ac58a 100644 --- a/tests/_async/test_connection_pool.py +++ b/tests/_async/test_connection_pool.py @@ -3,7 +3,13 @@ from typing import List, Optional import pytest import trio as concurrency -from httpcore import AsyncConnectionPool, ConnectError, PoolTimeout, UnsupportedProtocol +from httpcore import ( + AsyncConnectionPool, + ConnectError, + PoolTimeout, + ReadError, + UnsupportedProtocol, +) from httpcore.backends.base import AsyncNetworkStream from httpcore.backends.mock import AsyncMockBackend @@ -463,9 +469,10 @@ async def test_connection_pool_closed_while_request_in_flight(): ) as pool: # Send a request, and then close the connection pool while the # response has not yet been streamed. - async with pool.stream("GET", "https://example.com/"): - with pytest.raises(RuntimeError): - await pool.aclose() + async with pool.stream("GET", "https://example.com/") as response: + await pool.aclose() + with pytest.raises(ReadError): + await response.aread() @pytest.mark.anyio diff --git a/tests/_sync/test_connection_pool.py b/tests/_sync/test_connection_pool.py index 3ab0c87..453b7fd 100644 --- a/tests/_sync/test_connection_pool.py +++ b/tests/_sync/test_connection_pool.py @@ -3,7 +3,13 @@ from typing import List, Optional import pytest from tests import concurrency -from httpcore import ConnectionPool, ConnectError, PoolTimeout, UnsupportedProtocol +from httpcore import ( + ConnectionPool, + ConnectError, + PoolTimeout, + ReadError, + UnsupportedProtocol, +) from httpcore.backends.base import NetworkStream from httpcore.backends.mock import MockBackend @@ -463,9 +469,10 @@ def test_connection_pool_closed_while_request_in_flight(): ) as pool: # Send a request, and then close the connection pool while the # response has not yet been streamed. - with pool.stream("GET", "https://example.com/"): - with pytest.raises(RuntimeError): - pool.close() + with pool.stream("GET", "https://example.com/") as response: + pool.close() + with pytest.raises(ReadError): + response.read()
List in-flight connections `AsyncConnectionPool.aclose()` raises `RuntimeError: The connection pool was closed while 1 HTTP requests/responses were still in-flight.` if there are any on-going requests. It would be nice to provide a list of URLs to help me understand what I'm doing wrong. At the moment I'm adding `print` statements to the httpcore code to figure this out. Something like this would be nice: ``` RuntimeError: The connection pool was closed while 3 HTTP requests/responses were still in-flight: URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/foo') URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/bar') URL(scheme=b'https', host=b'www.example.net', port=None, target=b'/baz') ```
0.0
[ "tests/_async/test_connection_pool.py::test_connection_pool_closed_while_request_in_flight[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_closed_while_request_in_flight[trio]", "tests/_sync/test_connection_pool.py::test_connection_pool_closed_while_request_in_flight" ]
[ "tests/_async/test_connection_pool.py::test_connection_pool_with_keepalive[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_close[asyncio]", "tests/_async/test_connection_pool.py::test_trace_request[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_http_exception[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_connect_exception[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_immediate_expiry[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_no_keepalive_connections_allowed[asyncio]", "tests/_async/test_connection_pool.py::test_unsupported_protocol[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_timeout[asyncio]", "tests/_async/test_connection_pool.py::test_http11_upgrade_connection[asyncio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_keepalive[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_close[trio]", "tests/_async/test_connection_pool.py::test_trace_request[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_http_exception[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_connect_exception[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_immediate_expiry[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_with_no_keepalive_connections_allowed[trio]", "tests/_async/test_connection_pool.py::test_unsupported_protocol[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_timeout[trio]", "tests/_async/test_connection_pool.py::test_http11_upgrade_connection[trio]", "tests/_async/test_connection_pool.py::test_connection_pool_concurrency", "tests/_async/test_connection_pool.py::test_connection_pool_concurrency_same_domain_closing", "tests/_async/test_connection_pool.py::test_connection_pool_concurrency_same_domain_keepalive", "tests/_sync/test_connection_pool.py::test_connection_pool_with_keepalive", "tests/_sync/test_connection_pool.py::test_connection_pool_with_close", "tests/_sync/test_connection_pool.py::test_trace_request", "tests/_sync/test_connection_pool.py::test_connection_pool_with_http_exception", "tests/_sync/test_connection_pool.py::test_connection_pool_with_connect_exception", "tests/_sync/test_connection_pool.py::test_connection_pool_with_immediate_expiry", "tests/_sync/test_connection_pool.py::test_connection_pool_with_no_keepalive_connections_allowed", "tests/_sync/test_connection_pool.py::test_connection_pool_concurrency", "tests/_sync/test_connection_pool.py::test_connection_pool_concurrency_same_domain_closing", "tests/_sync/test_connection_pool.py::test_connection_pool_concurrency_same_domain_keepalive", "tests/_sync/test_connection_pool.py::test_unsupported_protocol", "tests/_sync/test_connection_pool.py::test_connection_pool_timeout", "tests/_sync/test_connection_pool.py::test_http11_upgrade_connection" ]
2022-11-30 15:48:32+00:00
2,108
encode__httpcore-641
diff --git a/httpcore/_async/http11.py b/httpcore/_async/http11.py index 7ad3664..32fa3a6 100644 --- a/httpcore/_async/http11.py +++ b/httpcore/_async/http11.py @@ -20,6 +20,7 @@ from .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, + WriteError, map_exceptions, ) from .._models import Origin, Request, Response @@ -84,10 +85,21 @@ class AsyncHTTP11Connection(AsyncConnectionInterface): try: kwargs = {"request": request} - async with Trace("send_request_headers", logger, request, kwargs) as trace: - await self._send_request_headers(**kwargs) - async with Trace("send_request_body", logger, request, kwargs) as trace: - await self._send_request_body(**kwargs) + try: + async with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + await self._send_request_headers(**kwargs) + async with Trace("send_request_body", logger, request, kwargs) as trace: + await self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: diff --git a/httpcore/_sync/http11.py b/httpcore/_sync/http11.py index edcce72..0cc100e 100644 --- a/httpcore/_sync/http11.py +++ b/httpcore/_sync/http11.py @@ -20,6 +20,7 @@ from .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, + WriteError, map_exceptions, ) from .._models import Origin, Request, Response @@ -84,10 +85,21 @@ class HTTP11Connection(ConnectionInterface): try: kwargs = {"request": request} - with Trace("send_request_headers", logger, request, kwargs) as trace: - self._send_request_headers(**kwargs) - with Trace("send_request_body", logger, request, kwargs) as trace: - self._send_request_body(**kwargs) + try: + with Trace( + "send_request_headers", logger, request, kwargs + ) as trace: + self._send_request_headers(**kwargs) + with Trace("send_request_body", logger, request, kwargs) as trace: + self._send_request_body(**kwargs) + except WriteError: + # If we get a write error while we're writing the request, + # then we supress this error and move on to attempting to + # read the response. Servers can sometimes close the request + # pre-emptively and then respond with a well formed HTTP + # error response. + pass + with Trace( "receive_response_headers", logger, request, kwargs ) as trace:
encode/httpcore
80ff02f1276eba3cb6b6493b3f0b033a26d6348d
diff --git a/tests/_async/test_connection.py b/tests/_async/test_connection.py index 8b29942..b6ee0c7 100644 --- a/tests/_async/test_connection.py +++ b/tests/_async/test_connection.py @@ -9,10 +9,13 @@ from httpcore import ( SOCKET_OPTION, AsyncHTTPConnection, AsyncMockBackend, + AsyncMockStream, AsyncNetworkStream, ConnectError, ConnectionNotAvailable, Origin, + RemoteProtocolError, + WriteError, ) @@ -83,7 +86,109 @@ async def test_concurrent_requests_not_available_on_http11_connections(): await conn.request("GET", "https://example.com/") [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.anyio +async def test_write_error_with_response_sent(): + """ + If a server half-closes the connection while the client is sending + the request, it may still send a response. In this case the client + should successfully read and return the response. + + See also the `test_write_error_without_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(AsyncMockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + async def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(AsyncMockBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> AsyncMockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge( + [ + b"HTTP/1.1 413 Payload Too Large\r\n", + b"Content-Type: plain/text\r\n", + b"Content-Length: 37\r\n", + b"\r\n", + b"Request body exceeded 1,000,000 bytes", + ] + ) + + async with AsyncHTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + response = await conn.request("POST", "https://example.com/", content=content) + assert response.status == 413 + assert response.content == b"Request body exceeded 1,000,000 bytes" + + [email protected] [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +async def test_write_error_without_response_sent(): + """ + If a server fully closes the connection while the client is sending + the request, then client should raise an error. + + See also the `test_write_error_with_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(AsyncMockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + async def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(AsyncMockBackend): + async def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> AsyncMockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge([]) + + async with AsyncHTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + with pytest.raises(RemoteProtocolError) as exc_info: + await conn.request("POST", "https://example.com/", content=content) + assert str(exc_info.value) == "Server disconnected without sending a response." + + [email protected] [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") async def test_http2_connection(): origin = Origin(b"https", b"example.com", 443) network_backend = AsyncMockBackend( diff --git a/tests/_sync/test_connection.py b/tests/_sync/test_connection.py index 9e0c403..37c82e0 100644 --- a/tests/_sync/test_connection.py +++ b/tests/_sync/test_connection.py @@ -9,10 +9,13 @@ from httpcore import ( SOCKET_OPTION, HTTPConnection, MockBackend, + MockStream, NetworkStream, ConnectError, ConnectionNotAvailable, Origin, + RemoteProtocolError, + WriteError, ) @@ -83,7 +86,109 @@ def test_concurrent_requests_not_available_on_http11_connections(): conn.request("GET", "https://example.com/") [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +def test_write_error_with_response_sent(): + """ + If a server half-closes the connection while the client is sending + the request, it may still send a response. In this case the client + should successfully read and return the response. + + See also the `test_write_error_without_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(MockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(MockBackend): + def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> MockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge( + [ + b"HTTP/1.1 413 Payload Too Large\r\n", + b"Content-Type: plain/text\r\n", + b"Content-Length: 37\r\n", + b"\r\n", + b"Request body exceeded 1,000,000 bytes", + ] + ) + + with HTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + response = conn.request("POST", "https://example.com/", content=content) + assert response.status == 413 + assert response.content == b"Request body exceeded 1,000,000 bytes" + + + [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") +def test_write_error_without_response_sent(): + """ + If a server fully closes the connection while the client is sending + the request, then client should raise an error. + + See also the `test_write_error_with_response_sent` test above. + """ + + class ErrorOnRequestTooLargeStream(MockStream): + def __init__(self, buffer: typing.List[bytes], http2: bool = False) -> None: + super().__init__(buffer, http2) + self.count = 0 + + def write( + self, buffer: bytes, timeout: typing.Optional[float] = None + ) -> None: + self.count += len(buffer) + + if self.count > 1_000_000: + raise WriteError() + + class ErrorOnRequestTooLarge(MockBackend): + def connect_tcp( + self, + host: str, + port: int, + timeout: typing.Optional[float] = None, + local_address: typing.Optional[str] = None, + socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, + ) -> MockStream: + return ErrorOnRequestTooLargeStream(list(self._buffer), http2=self._http2) + + origin = Origin(b"https", b"example.com", 443) + network_backend = ErrorOnRequestTooLarge([]) + + with HTTPConnection( + origin=origin, network_backend=network_backend, keepalive_expiry=5.0 + ) as conn: + content = b"x" * 10_000_000 + with pytest.raises(RemoteProtocolError) as exc_info: + conn.request("POST", "https://example.com/", content=content) + assert str(exc_info.value) == "Server disconnected without sending a response." + + + [email protected]("ignore::pytest.PytestUnraisableExceptionWarning") def test_http2_connection(): origin = Origin(b"https", b"example.com", 443) network_backend = MockBackend(
Handle HTTP/1.1 half-closed connections gracefully. There's an HTTP/1.1 case that can occur where... * The client starts sending a request. * The server half-closes the connection. * The server sends a response, such as an HTTP 413 Content Too Large. Currently our behaviour here is that we'll see a `WriteError` occur here and never get a response. A more graceful behaviour is handle this case, and return the 413 response. Prompted via https://github.com/encode/httpx/discussions/2503. *A follow up question to this will be... is there an equivalent to this for HTTP/2 streams? But let's only consider that once we've dealt with this as a precursor.*
0.0
[ "tests/_async/test_connection.py::test_write_error_with_response_sent[asyncio]", "tests/_async/test_connection.py::test_write_error_without_response_sent[asyncio]", "tests/_async/test_connection.py::test_write_error_with_response_sent[trio]", "tests/_async/test_connection.py::test_write_error_without_response_sent[trio]", "tests/_sync/test_connection.py::test_write_error_with_response_sent", "tests/_sync/test_connection.py::test_write_error_without_response_sent" ]
[ "tests/_async/test_connection.py::test_http_connection[asyncio]", "tests/_async/test_connection.py::test_concurrent_requests_not_available_on_http11_connections[asyncio]", "tests/_async/test_connection.py::test_http2_connection[asyncio]", "tests/_async/test_connection.py::test_request_to_incorrect_origin[asyncio]", "tests/_async/test_connection.py::test_connection_retries[asyncio]", "tests/_async/test_connection.py::test_connection_retries_tls[asyncio]", "tests/_async/test_connection.py::test_uds_connections[asyncio]", "tests/_async/test_connection.py::test_http_connection[trio]", "tests/_async/test_connection.py::test_concurrent_requests_not_available_on_http11_connections[trio]", "tests/_async/test_connection.py::test_http2_connection[trio]", "tests/_async/test_connection.py::test_request_to_incorrect_origin[trio]", "tests/_async/test_connection.py::test_connection_retries[trio]", "tests/_async/test_connection.py::test_connection_retries_tls[trio]", "tests/_async/test_connection.py::test_uds_connections[trio]", "tests/_sync/test_connection.py::test_http_connection", "tests/_sync/test_connection.py::test_concurrent_requests_not_available_on_http11_connections", "tests/_sync/test_connection.py::test_http2_connection", "tests/_sync/test_connection.py::test_request_to_incorrect_origin", "tests/_sync/test_connection.py::test_connection_retries", "tests/_sync/test_connection.py::test_connection_retries_tls", "tests/_sync/test_connection.py::test_uds_connections" ]
2022-12-13 19:52:44+00:00
2,109
encode__httpx-1002
diff --git a/httpx/_client.py b/httpx/_client.py index 7248f87..2c56edc 100644 --- a/httpx/_client.py +++ b/httpx/_client.py @@ -322,6 +322,10 @@ class BaseClient: url = URL(location, allow_relative=True) + # Check that we can handle the scheme + if url.scheme and url.scheme not in ("http", "https"): + raise InvalidURL(f'Scheme "{url.scheme}" not supported.') + # Handle malformed 'Location' headers that are "absolute" form, have no host. # See: https://github.com/encode/httpx/issues/771 if url.scheme and not url.host:
encode/httpx
21d7e16559d9360ae3a5c5cfd23bab8bb85ee4a8
diff --git a/tests/client/test_redirects.py b/tests/client/test_redirects.py index e91bb7e..fa5ae4e 100644 --- a/tests/client/test_redirects.py +++ b/tests/client/test_redirects.py @@ -8,6 +8,7 @@ import pytest from httpx import ( URL, AsyncClient, + InvalidURL, NotRedirectResponse, RequestBodyUnavailable, TooManyRedirects, @@ -140,6 +141,17 @@ class MockDispatch(httpcore.AsyncHTTPTransport): else: return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!") + elif path == b"/redirect_custom_scheme": + status_code = codes.MOVED_PERMANENTLY + headers = [(b"location", b"market://details?id=42")] + return ( + b"HTTP/1.1", + status_code, + b"Moved Permanently", + headers, + ByteStream(b""), + ) + return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!") @@ -431,3 +443,11 @@ async def test_redirect_cookie_behavior(): response = await client.get("https://example.com/") assert response.url == "https://example.com/" assert response.text == "Not logged in" + + [email protected]("async_environment") +async def test_redirect_custom_scheme(): + client = AsyncClient(dispatch=MockDispatch()) + with pytest.raises(InvalidURL) as e: + await client.post("https://example.org/redirect_custom_scheme") + assert str(e.value) == 'Scheme "market" not supported.'
KeyError occurs when redirect to custom scheme(ex. market://) # Information OS platform : mac OS Python version : 3.7.2 Installed dependencies and versions : `httpx==0.9.3` Code snippet ``` @property def port(self) -> int: port = self._uri_reference.port if port is None: return {"https": 443, "http": 80}[self.scheme] return int(port) ``` Error traceback ``` [2020-02-24 14:57:08 +0900] [82150] [ERROR] Exception Traceback (most recent call last): File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/sanic/testing.py", line 120, in _collect_response method, url, *request_args, **request_kwargs File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/sanic/testing.py", line 41, in _local_request url, verify=False, *args, **kwargs File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 671, in get trust_env=trust_env, File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 268, in request trust_env=trust_env, File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 410, in send allow_redirects=allow_redirects, File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 478, in send_handling_redirects request = self.build_redirect_request(request, response) File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 500, in build_redirect_request headers = self.redirect_headers(request, url, method) File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/client.py", line 555, in redirect_headers if url.origin != request.url.origin: File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/models.py", line 215, in origin return Origin(self) File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/models.py", line 287, in __init__ self.port = url.port File "/Users/sym/.pyenv/versions/airbridge-ads-was/lib/python3.7/site-packages/httpx/models.py", line 165, in port return {"https": 443, "http": 80}[self.scheme] KeyError: 'market' [2020-02-24 14:57:08 +0900] [82150] [INFO] Starting worker [82150] [2020-02-24 14:57:08 +0900] [82150] [INFO] Stopping worker [82150] [2020-02-24 14:57:08 +0900] [82150] [INFO] Server Stopped ``` # Description i'm using sanic and sanic uses httpx to test web request. when i make a redirect response which goes to "market://details?id=~~" (android market url)", KeyError occurred. I think it is associated with `port` property method. Is this the intended behavior? Thank you.
0.0
[ "tests/client/test_redirects.py::test_redirect_custom_scheme[asyncio]", "tests/client/test_redirects.py::test_redirect_custom_scheme[trio]" ]
[ "tests/client/test_redirects.py::test_no_redirect[asyncio]", "tests/client/test_redirects.py::test_no_redirect[trio]", "tests/client/test_redirects.py::test_redirect_301[asyncio]", "tests/client/test_redirects.py::test_redirect_301[trio]", "tests/client/test_redirects.py::test_redirect_302[asyncio]", "tests/client/test_redirects.py::test_redirect_302[trio]", "tests/client/test_redirects.py::test_redirect_303[asyncio]", "tests/client/test_redirects.py::test_redirect_303[trio]", "tests/client/test_redirects.py::test_disallow_redirects[asyncio]", "tests/client/test_redirects.py::test_disallow_redirects[trio]", "tests/client/test_redirects.py::test_relative_redirect[asyncio]", "tests/client/test_redirects.py::test_relative_redirect[trio]", "tests/client/test_redirects.py::test_malformed_redirect[asyncio]", "tests/client/test_redirects.py::test_malformed_redirect[trio]", "tests/client/test_redirects.py::test_no_scheme_redirect[asyncio]", "tests/client/test_redirects.py::test_no_scheme_redirect[trio]", "tests/client/test_redirects.py::test_fragment_redirect[asyncio]", "tests/client/test_redirects.py::test_fragment_redirect[trio]", "tests/client/test_redirects.py::test_multiple_redirects[asyncio]", "tests/client/test_redirects.py::test_multiple_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[trio]", "tests/client/test_redirects.py::test_redirect_loop[asyncio]", "tests/client/test_redirects.py::test_redirect_loop[trio]", "tests/client/test_redirects.py::test_cross_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_domain_redirect[trio]", "tests/client/test_redirects.py::test_same_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_same_domain_redirect[trio]", "tests/client/test_redirects.py::test_body_redirect[asyncio]", "tests/client/test_redirects.py::test_body_redirect[trio]", "tests/client/test_redirects.py::test_no_body_redirect[asyncio]", "tests/client/test_redirects.py::test_no_body_redirect[trio]", "tests/client/test_redirects.py::test_can_stream_if_no_redirect[asyncio]", "tests/client/test_redirects.py::test_can_stream_if_no_redirect[trio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[asyncio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[trio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[trio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[asyncio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[trio]" ]
2020-05-27 19:28:29+00:00
2,110
encode__httpx-1034
diff --git a/httpx/_decoders.py b/httpx/_decoders.py index 2a2e703..1ea47b0 100644 --- a/httpx/_decoders.py +++ b/httpx/_decoders.py @@ -261,7 +261,7 @@ class LineDecoder: text = text[idx + 1 :] break elif next_char is None: - self.buffer = text + self.buffer += text text = "" break diff --git a/requirements.txt b/requirements.txt index 246a08e..4260706 100644 --- a/requirements.txt +++ b/requirements.txt @@ -31,4 +31,4 @@ trustme uvicorn seed-isort-config -attrs>=19.2 # See: https://github.com/encode/httpx/pull/566#issuecomment-559862665 +attrs>=19.3.0 # See: https://github.com/encode/httpx/pull/566#issuecomment-559862665
encode/httpx
27b0dbc22da1424a020c2bb769c81490f39ce283
diff --git a/tests/test_decoders.py b/tests/test_decoders.py index 9f2fa51..89c545b 100644 --- a/tests/test_decoders.py +++ b/tests/test_decoders.py @@ -225,6 +225,15 @@ def test_line_decoder_nl(): assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"] assert decoder.flush() == [] + # Issue #1033 + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("12345\n") == ["12345\n"] + assert decoder.decode("foo ") == [] + assert decoder.decode("bar ") == [] + assert decoder.decode("baz\n") == ["foo bar baz\n"] + assert decoder.flush() == [] + def test_line_decoder_cr(): decoder = LineDecoder() @@ -237,6 +246,16 @@ def test_line_decoder_cr(): assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"] assert decoder.flush() == ["c\n"] + # Issue #1033 + # TODO: This seems like another bug; fix expectations and results. + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("12345\r") == [] + assert decoder.decode("foo ") == [] + assert decoder.decode("bar ") == [] + assert decoder.decode("baz\r") == [] + assert decoder.flush() == ["12345\rfoo bar baz\n"] + def test_line_decoder_crnl(): decoder = LineDecoder() @@ -255,6 +274,15 @@ def test_line_decoder_crnl(): assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"] assert decoder.flush() == ["c"] + # Issue #1033 + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("12345\r\n") == ["12345\n"] + assert decoder.decode("foo ") == [] + assert decoder.decode("bar ") == [] + assert decoder.decode("baz\r\n") == ["foo bar baz\n"] + assert decoder.flush() == [] + def test_invalid_content_encoding_header(): headers = [(b"Content-Encoding", b"invalid-header")]
aiter_lines() doesn't return full lines that span multiple chunks <https://gist.github.com/scr-oath/aa76d200222a0409d09a0d6feb1a13e2> shows an example setup using cherry.py as server that just outputs two lines - the json is big enough to be sent in two chunks; httpx aiter_lines() gets confused and sends data from the middle of the json line - seems to skip the starting part - which was most likely sent in a chunk without a newline ### test-httpx.py ```python import asyncio import json import httpx class TestHttpx: def __init__(self): pass async def __call__(self): http_client = httpx.AsyncClient() async with http_client.stream(method="GET", url='http://localhost:8080/lines') as response: is_message = True async for line in response.aiter_lines(): is_message = not is_message if is_message: message = json.loads(line) print(message) def main(): test_httpx = TestHttpx() asyncio.run(test_httpx()) if __name__ == '__main__': main() ```
0.0
[ "tests/test_decoders.py::test_line_decoder_nl", "tests/test_decoders.py::test_line_decoder_cr", "tests/test_decoders.py::test_line_decoder_crnl" ]
[ "tests/test_decoders.py::test_deflate", "tests/test_decoders.py::test_zlib", "tests/test_decoders.py::test_gzip", "tests/test_decoders.py::test_brotli", "tests/test_decoders.py::test_multi", "tests/test_decoders.py::test_multi_with_identity", "tests/test_decoders.py::test_streaming", "tests/test_decoders.py::test_empty_content[deflate]", "tests/test_decoders.py::test_empty_content[gzip]", "tests/test_decoders.py::test_empty_content[br]", "tests/test_decoders.py::test_empty_content[identity]", "tests/test_decoders.py::test_decoders_empty_cases[BrotliDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[DeflateDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[GZipDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[IdentityDecoder]", "tests/test_decoders.py::test_decoding_errors[deflate]", "tests/test_decoders.py::test_decoding_errors[gzip]", "tests/test_decoders.py::test_decoding_errors[br]", "tests/test_decoders.py::test_text_decoder[data0-ascii]", "tests/test_decoders.py::test_text_decoder[data1-utf-8]", "tests/test_decoders.py::test_text_decoder[data2-shift-jis]", "tests/test_decoders.py::test_text_decoder[data3-shift-jis]", "tests/test_decoders.py::test_text_decoder[data4-MacCyrillic]", "tests/test_decoders.py::test_text_decoder[data5-euc-jp]", "tests/test_decoders.py::test_text_decoder_known_encoding", "tests/test_decoders.py::test_text_decoder_empty_cases", "tests/test_decoders.py::test_invalid_content_encoding_header" ]
2020-06-24 21:05:17+00:00
2,111
encode__httpx-1044
diff --git a/httpx/__init__.py b/httpx/__init__.py index 7a2b8a9..155ea5c 100644 --- a/httpx/__init__.py +++ b/httpx/__init__.py @@ -25,6 +25,7 @@ from ._exceptions import ( ResponseNotRead, StreamConsumed, StreamError, + TimeoutException, TooManyRedirects, WriteError, WriteTimeout, @@ -81,6 +82,7 @@ __all__ = [ "StreamConsumed", "StreamError", "ProxyError", + "TimeoutException", "TooManyRedirects", "WriteError", "WriteTimeout", diff --git a/httpx/_client.py b/httpx/_client.py index c2a485f..fd9c1e5 100644 --- a/httpx/_client.py +++ b/httpx/_client.py @@ -18,7 +18,14 @@ from ._config import ( UnsetType, ) from ._content_streams import ContentStream -from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects +from ._exceptions import ( + HTTPCORE_EXC_MAP, + HTTPError, + InvalidURL, + RequestBodyUnavailable, + TooManyRedirects, + map_exceptions, +) from ._models import URL, Cookies, Headers, Origin, QueryParams, Request, Response from ._status_codes import codes from ._transports.asgi import ASGITransport @@ -705,19 +712,20 @@ class Client(BaseClient): transport = self.transport_for_url(request.url) try: - ( - http_version, - status_code, - reason_phrase, - headers, - stream, - ) = transport.request( - request.method.encode(), - request.url.raw, - headers=request.headers.raw, - stream=request.stream, - timeout=timeout.as_dict(), - ) + with map_exceptions(HTTPCORE_EXC_MAP): + ( + http_version, + status_code, + reason_phrase, + headers, + stream, + ) = transport.request( + request.method.encode(), + request.url.raw, + headers=request.headers.raw, + stream=request.stream, + timeout=timeout.as_dict(), + ) except HTTPError as exc: # Add the original request to any HTTPError unless # there'a already a request attached in the case of @@ -1255,19 +1263,20 @@ class AsyncClient(BaseClient): transport = self.transport_for_url(request.url) try: - ( - http_version, - status_code, - reason_phrase, - headers, - stream, - ) = await transport.request( - request.method.encode(), - request.url.raw, - headers=request.headers.raw, - stream=request.stream, - timeout=timeout.as_dict(), - ) + with map_exceptions(HTTPCORE_EXC_MAP): + ( + http_version, + status_code, + reason_phrase, + headers, + stream, + ) = await transport.request( + request.method.encode(), + request.url.raw, + headers=request.headers.raw, + stream=request.stream, + timeout=timeout.as_dict(), + ) except HTTPError as exc: # Add the original request to any HTTPError unless # there'a already a request attached in the case of diff --git a/httpx/_exceptions.py b/httpx/_exceptions.py index d8b3c8b..ae07ec5 100644 --- a/httpx/_exceptions.py +++ b/httpx/_exceptions.py @@ -1,3 +1,4 @@ +import contextlib import typing import httpcore @@ -28,25 +29,87 @@ class HTTPError(Exception): # Timeout exceptions... -ConnectTimeout = httpcore.ConnectTimeout -ReadTimeout = httpcore.ReadTimeout -WriteTimeout = httpcore.WriteTimeout -PoolTimeout = httpcore.PoolTimeout + +class TimeoutException(HTTPError): + """ + The base class for timeout errors. + + An operation has timed out. + """ + + +class ConnectTimeout(TimeoutException): + """ + Timed out while connecting to the host. + """ + + +class ReadTimeout(TimeoutException): + """ + Timed out while receiving data from the host. + """ + + +class WriteTimeout(TimeoutException): + """ + Timed out while sending data to the host. + """ + + +class PoolTimeout(TimeoutException): + """ + Timed out waiting to acquire a connection from the pool. + """ # Core networking exceptions... -NetworkError = httpcore.NetworkError -ReadError = httpcore.ReadError -WriteError = httpcore.WriteError -ConnectError = httpcore.ConnectError -CloseError = httpcore.CloseError + +class NetworkError(HTTPError): + """ + The base class for network-related errors. + + An error occurred while interacting with the network. + """ + + +class ReadError(NetworkError): + """ + Failed to receive data from the network. + """ + + +class WriteError(NetworkError): + """ + Failed to send data through the network. + """ + + +class ConnectError(NetworkError): + """ + Failed to establish a connection. + """ + + +class CloseError(NetworkError): + """ + Failed to close a connection. + """ # Other transport exceptions... -ProxyError = httpcore.ProxyError -ProtocolError = httpcore.ProtocolError + +class ProxyError(HTTPError): + """ + An error occurred while proxying a request. + """ + + +class ProtocolError(HTTPError): + """ + A protocol was violated by the server. + """ # HTTP exceptions... @@ -138,3 +201,43 @@ class CookieConflict(HTTPError): """ Attempted to lookup a cookie by name, but multiple cookies existed. """ + + [email protected] +def map_exceptions( + mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]] +) -> typing.Iterator[None]: + try: + yield + except Exception as exc: + mapped_exc = None + + for from_exc, to_exc in mapping.items(): + if not isinstance(exc, from_exc): + continue + # We want to map to the most specific exception we can find. + # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to + # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. + if mapped_exc is None or issubclass(to_exc, mapped_exc): + mapped_exc = to_exc + + if mapped_exc is None: + raise + + raise mapped_exc(exc) from None + + +HTTPCORE_EXC_MAP = { + httpcore.TimeoutException: TimeoutException, + httpcore.ConnectTimeout: ConnectTimeout, + httpcore.ReadTimeout: ReadTimeout, + httpcore.WriteTimeout: WriteTimeout, + httpcore.PoolTimeout: PoolTimeout, + httpcore.NetworkError: NetworkError, + httpcore.ConnectError: ConnectError, + httpcore.ReadError: ReadError, + httpcore.WriteError: WriteError, + httpcore.CloseError: CloseError, + httpcore.ProxyError: ProxyError, + httpcore.ProtocolError: ProtocolError, +}
encode/httpx
fab427972b7a5cb64d8dfb43467b84cdf430ff24
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 1ce71e8..34a1752 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -1,6 +1,46 @@ +from typing import Any + +import httpcore import pytest import httpx +from httpx._exceptions import HTTPCORE_EXC_MAP + + +def test_httpcore_all_exceptions_mapped() -> None: + """ + All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific + exception class. + """ + not_mapped = [ + value + for name, value in vars(httpcore).items() + if isinstance(value, type) + and issubclass(value, Exception) + and value not in HTTPCORE_EXC_MAP + ] + + if not_mapped: + pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}") + + +def test_httpcore_exception_mapping() -> None: + """ + HTTPCore exception mapping works as expected. + """ + + # Make sure we don't just map to `NetworkError`. + with pytest.raises(httpx.ConnectError): + httpx.get("http://doesnotexist") + + # Make sure it also works with custom transports. + class MockTransport(httpcore.SyncHTTPTransport): + def request(self, *args: Any, **kwargs: Any) -> Any: + raise httpcore.ProtocolError() + + client = httpx.Client(transport=MockTransport()) + with pytest.raises(httpx.ProtocolError): + client.get("http://testserver") def test_httpx_exceptions_exposed() -> None:
0.13: some `httpcore` exceptions are missing from top level package ### Checklist - [x] The bug is reproducible against the latest release and/or `master`. - [x] There are no similar issues or pull requests to fix it yet. ### Describe the bug I believe that `HTTPError` is expected to be the base exception for all exceptions that httpx may raise? Since 0.13 this is no longer true and comments in [`_exceptions.py`](https://github.com/encode/httpx/blob/master/httpx/_exceptions.py#L11) indicate this is a bug. In real world use I have at least one bit of code that has failed due to this. I could see an argument for trying to catch a more specific error, but I think this case `HTTPError` was really nice to use. Even if users should be using more specific exceptions having a single base exception is an incredibly useful feature for any library and it'd be great if we could ensure this behavior is set for the upcoming 1.0 release. ### To reproduce The following code assumes localhost does not have any webserver running on port 80. Running on httpx 0.12 it correctly catches the `HTTPError`, running on 0.13 it does not catch the exception (httpcore.ConnectError, which doesn't appear to be properly exported in [`\_\_init\_\_.py](https://github.com/encode/httpx/blob/master/httpx/__init__.py), though it is aliased in `_exceptions.py`). ```python import httpx try: httpx.get('http://localhost') except httpx.HTTPError: print('There was an httpx error') ``` ### Expected behavior If `HTTPError` is the base exception for httpx I'd expect catching `HTTPError` to actually catch all errors httpx may raise. ### Actual behavior Instead of catching `HTTPError` it appears that httpcore errors bubble up. This breaks exception handling that expects `HTTPError` to be the base exception. ### Environment - OS: macOS 10.15.5 - Python version: 3.8.3 - HTTPX version: 0.13 - Async environment: asyncio - HTTP proxy: No - Custom certificates: No
0.0
[ "tests/test_exceptions.py::test_httpcore_all_exceptions_mapped", "tests/test_exceptions.py::test_httpcore_exception_mapping", "tests/test_exceptions.py::test_httpx_exceptions_exposed" ]
[]
2020-07-02 17:12:43+00:00
2,112
encode__httpx-1075
diff --git a/httpx/_client.py b/httpx/_client.py index 1ee9352..d4ec7aa 100644 --- a/httpx/_client.py +++ b/httpx/_client.py @@ -80,7 +80,7 @@ class BaseClient: self.timeout = Timeout(timeout) self.max_redirects = max_redirects self.trust_env = trust_env - self.netrc = NetRCInfo() + self._netrc = NetRCInfo() def _get_proxy_map( self, proxies: typing.Optional[ProxiesTypes], trust_env: bool, @@ -269,7 +269,7 @@ class BaseClient: return BasicAuth(username=username, password=password) if self.trust_env and "Authorization" not in request.headers: - credentials = self.netrc.get_credentials(request.url.authority) + credentials = self._netrc.get_credentials(request.url.authority) if credentials is not None: return BasicAuth(username=credentials[0], password=credentials[1]) diff --git a/httpx/_decoders.py b/httpx/_decoders.py index 1ea47b0..d1c60fb 100644 --- a/httpx/_decoders.py +++ b/httpx/_decoders.py @@ -233,12 +233,18 @@ class LineDecoder: def decode(self, text: str) -> typing.List[str]: lines = [] - if text.startswith("\n") and self.buffer and self.buffer[-1] == "\r": - # Handle the case where we have an "\r\n" split across - # our previous input, and our new chunk. - lines.append(self.buffer[:-1] + "\n") - self.buffer = "" - text = text[1:] + if text and self.buffer and self.buffer[-1] == "\r": + if text.startswith("\n"): + # Handle the case where we have an "\r\n" split across + # our previous input, and our new chunk. + lines.append(self.buffer[:-1] + "\n") + self.buffer = "" + text = text[1:] + else: + # Handle the case where we have "\r" at the end of our + # previous input. + lines.append(self.buffer[:-1] + "\n") + self.buffer = "" while text: num_chars = len(text) diff --git a/httpx/_models.py b/httpx/_models.py index 892a959..dca3eff 100644 --- a/httpx/_models.py +++ b/httpx/_models.py @@ -87,10 +87,6 @@ class URL: if not self.host: raise InvalidURL("No host included in URL.") - # Allow setting full_path to custom attributes requests - # like OPTIONS, CONNECT, and forwarding proxy requests. - self._full_path: typing.Optional[str] = None - @property def scheme(self) -> str: return self._uri_reference.scheme or "" @@ -138,17 +134,11 @@ class URL: @property def full_path(self) -> str: - if self._full_path is not None: - return self._full_path path = self.path if self.query: path += "?" + self.query return path - @full_path.setter - def full_path(self, value: typing.Optional[str]) -> None: - self._full_path = value - @property def fragment(self) -> str: return self._uri_reference.fragment or ""
encode/httpx
064160661929089864938a62ae18dcf0cff75737
diff --git a/tests/models/test_url.py b/tests/models/test_url.py index f9a568a..7910a8e 100644 --- a/tests/models/test_url.py +++ b/tests/models/test_url.py @@ -177,13 +177,6 @@ def test_url_set(): assert all(url in urls for url in url_set) -def test_url_full_path_setter(): - url = URL("http://example.org") - - url.full_path = "http://example.net" - assert url.full_path == "http://example.net" - - def test_origin_from_url_string(): origin = Origin("https://example.com") assert origin.scheme == "https" diff --git a/tests/test_decoders.py b/tests/test_decoders.py index 89c545b..6b79931 100644 --- a/tests/test_decoders.py +++ b/tests/test_decoders.py @@ -247,14 +247,13 @@ def test_line_decoder_cr(): assert decoder.flush() == ["c\n"] # Issue #1033 - # TODO: This seems like another bug; fix expectations and results. decoder = LineDecoder() assert decoder.decode("") == [] assert decoder.decode("12345\r") == [] - assert decoder.decode("foo ") == [] + assert decoder.decode("foo ") == ["12345\n"] assert decoder.decode("bar ") == [] assert decoder.decode("baz\r") == [] - assert decoder.flush() == ["12345\rfoo bar baz\n"] + assert decoder.flush() == ["foo bar baz\n"] def test_line_decoder_crnl():
aiter_lines() doesn't return full lines that span multiple chunks <https://gist.github.com/scr-oath/aa76d200222a0409d09a0d6feb1a13e2> shows an example setup using cherry.py as server that just outputs two lines - the json is big enough to be sent in two chunks; httpx aiter_lines() gets confused and sends data from the middle of the json line - seems to skip the starting part - which was most likely sent in a chunk without a newline ### test-httpx.py ```python import asyncio import json import httpx class TestHttpx: def __init__(self): pass async def __call__(self): http_client = httpx.AsyncClient() async with http_client.stream(method="GET", url='http://localhost:8080/lines') as response: is_message = True async for line in response.aiter_lines(): is_message = not is_message if is_message: message = json.loads(line) print(message) def main(): test_httpx = TestHttpx() asyncio.run(test_httpx()) if __name__ == '__main__': main() ```
0.0
[ "tests/test_decoders.py::test_line_decoder_cr" ]
[ "tests/models/test_url.py::test_idna_url[http_with_port]", "tests/models/test_url.py::test_idna_url[unicode_tr46_compat]", "tests/models/test_url.py::test_idna_url[https_without_port]", "tests/models/test_url.py::test_idna_url[https_with_port]", "tests/models/test_url.py::test_idna_url[http_with_custom_port]", "tests/models/test_url.py::test_idna_url[https_with_custom_port]", "tests/models/test_url.py::test_url", "tests/models/test_url.py::test_url_eq_str", "tests/models/test_url.py::test_url_params", "tests/models/test_url.py::test_url_join", "tests/models/test_url.py::test_url_join_rfc3986", "tests/models/test_url.py::test_url_set", "tests/models/test_url.py::test_origin_from_url_string", "tests/models/test_url.py::test_origin_repr", "tests/models/test_url.py::test_origin_equal", "tests/models/test_url.py::test_url_copywith_for_authority", "tests/test_decoders.py::test_deflate", "tests/test_decoders.py::test_zlib", "tests/test_decoders.py::test_gzip", "tests/test_decoders.py::test_brotli", "tests/test_decoders.py::test_multi", "tests/test_decoders.py::test_multi_with_identity", "tests/test_decoders.py::test_streaming", "tests/test_decoders.py::test_empty_content[deflate]", "tests/test_decoders.py::test_empty_content[gzip]", "tests/test_decoders.py::test_empty_content[br]", "tests/test_decoders.py::test_empty_content[identity]", "tests/test_decoders.py::test_decoders_empty_cases[BrotliDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[DeflateDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[GZipDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[IdentityDecoder]", "tests/test_decoders.py::test_decoding_errors[deflate]", "tests/test_decoders.py::test_decoding_errors[gzip]", "tests/test_decoders.py::test_decoding_errors[br]", "tests/test_decoders.py::test_text_decoder[data0-ascii]", "tests/test_decoders.py::test_text_decoder[data1-utf-8]", "tests/test_decoders.py::test_text_decoder[data2-shift-jis]", "tests/test_decoders.py::test_text_decoder[data3-shift-jis]", "tests/test_decoders.py::test_text_decoder[data4-MacCyrillic]", "tests/test_decoders.py::test_text_decoder[data5-euc-jp]", "tests/test_decoders.py::test_text_decoder_known_encoding", "tests/test_decoders.py::test_text_decoder_empty_cases", "tests/test_decoders.py::test_line_decoder_nl", "tests/test_decoders.py::test_line_decoder_crnl", "tests/test_decoders.py::test_invalid_content_encoding_header" ]
2020-07-21 09:30:50+00:00
2,113
encode__httpx-139
diff --git a/httpx/models.py b/httpx/models.py index 710c030..9cbdc25 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -204,7 +204,7 @@ class URL: return hash(str(self)) def __eq__(self, other: typing.Any) -> bool: - return isinstance(other, URL) and str(self) == str(other) + return isinstance(other, (URL, str)) and str(self) == str(other) def __str__(self) -> str: return self.components.unsplit()
encode/httpx
37df46a83b93a0f40f2b8e10282f6f038dd908f6
diff --git a/tests/models/test_url.py b/tests/models/test_url.py index 5f5208c..70089e0 100644 --- a/tests/models/test_url.py +++ b/tests/models/test_url.py @@ -25,6 +25,12 @@ def test_url(): assert new.scheme == "http" +def test_url_eq_str(): + url = URL("https://example.org:123/path/to/somewhere?abc=123#anchor") + assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor" + assert str(url) == url + + def test_url__params(): url = URL("https://example.org:123/path/to/somewhere", params={"a": "123"}) assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
API design question - `Response.url` Currently our `Response.url` attribute exposes a `URL` instance. This is a breaking change from the requests API where it just exposes a plain string. It's feasible that we should instead only be exposing plain string URLs, in order to aim for drop-in replacement API compatibility w/ requests, *and* in order to keep the API surface area low. Options here are: * Expose `request.url` as a URL instance. (Richer information, URL class is also useful in its own right.) * Expose `request.url` as a str. (Better API compat. Lower API surface area to maintain.) * Expose `request.url` as a str, and `request.urlinfo` as a URL instance. (Better API compat. High API surface area.)
0.0
[ "tests/models/test_url.py::test_url_eq_str" ]
[ "tests/models/test_url.py::test_idna_url", "tests/models/test_url.py::test_url", "tests/models/test_url.py::test_url__params", "tests/models/test_url.py::test_url_set" ]
2019-07-24 15:22:02+00:00
2,114
encode__httpx-161
diff --git a/httpx/models.py b/httpx/models.py index df5d071..32e412f 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -89,16 +89,10 @@ class URL: params: QueryParamTypes = None, ) -> None: if isinstance(url, str): - self._uri_reference = rfc3986.api.uri_reference(url) + self._uri_reference = rfc3986.api.iri_reference(url).encode() else: self._uri_reference = url._uri_reference - # Handle IDNA domain names. - if self._uri_reference.authority: - idna_authority = self._uri_reference.authority.encode("idna").decode("ascii") - if idna_authority != self._uri_reference.authority: - self._uri_reference = self._uri_reference.copy_with(authority=idna_authority) - # Normalize scheme and domain name. if self.is_absolute_url: self._uri_reference = self._uri_reference.normalize()
encode/httpx
66754ad0c58d61d34489294530351aa4b17e217f
diff --git a/tests/models/test_url.py b/tests/models/test_url.py index 7c865f5..a556ed8 100644 --- a/tests/models/test_url.py +++ b/tests/models/test_url.py @@ -1,13 +1,65 @@ import pytest +import rfc3986 from httpx import URL from httpx.exceptions import InvalidURL -def test_idna_url(): - url = URL("http://δΈ­ε›½.icom.museum:80/") - assert url == URL("http://xn--fiqs8s.icom.museum:80/") - assert url.host == "xn--fiqs8s.icom.museum" [email protected]( + "given,idna,host,scheme,port", + [ + ( + "http://δΈ­ε›½.icom.museum:80/", + "http://xn--fiqs8s.icom.museum:80/", + "xn--fiqs8s.icom.museum", + "http", + 80, + ), + ( + "http://KΓΆnigsgÀßchen.de", + "http://xn--knigsgchen-b4a3dun.de", + "xn--knigsgchen-b4a3dun.de", + "http", + 80, + ), + ("https://faß.de", "https://xn--fa-hia.de", "xn--fa-hia.de", "https", 443), + ( + "https://Ξ²ΟŒΞ»ΞΏΟ‚.com:443", + "https://xn--nxasmm1c.com:443", + "xn--nxasmm1c.com", + "https", + 443, + ), + ( + "http://ΰ·ΰ·Šβ€ΰΆ»ΰ·“.com:444", + "http://xn--10cl1a0b660p.com:444", + "xn--10cl1a0b660p.com", + "http", + 444, + ), + ( + "https://Ω†Ψ§Ω…Ω‡β€ŒΨ§ΫŒ.com:4433", + "https://xn--mgba3gch31f060k.com:4433", + "xn--mgba3gch31f060k.com", + "https", + 4433, + ), + ], + ids=[ + "http_with_port", + "unicode_tr46_compat", + "https_without_port", + "https_with_port", + "http_with_custom_port", + "https_with_custom_port", + ], +) +def test_idna_url(given, idna, host, scheme, port): + url = URL(given) + assert url == URL(idna) + assert url.host == host + assert url.scheme == scheme + assert url.port == port def test_url():
Use IDNA 2008 instead of IDNA 2003 Using `str.encode("idna")` uses IDNA 2003 which isn't recommended for modern use. We should be using IDNA 2008 provided by the `idna` module (which is a dependency of `httpx` but I don't think we're using it anywhere?)
0.0
[ "tests/models/test_url.py::test_idna_url[unicode_tr46_compat]", "tests/models/test_url.py::test_idna_url[https_without_port]", "tests/models/test_url.py::test_idna_url[https_with_port]", "tests/models/test_url.py::test_idna_url[http_with_custom_port]", "tests/models/test_url.py::test_idna_url[https_with_custom_port]" ]
[ "tests/models/test_url.py::test_idna_url[http_with_port]", "tests/models/test_url.py::test_url", "tests/models/test_url.py::test_url_eq_str", "tests/models/test_url.py::test_url_params", "tests/models/test_url.py::test_url_join", "tests/models/test_url.py::test_url_join_rfc3986", "tests/models/test_url.py::test_url_set", "tests/models/test_url.py::test_hsts_preload_converted_to_https" ]
2019-07-27 23:07:27+00:00
2,115
encode__httpx-175
diff --git a/httpx/__init__.py b/httpx/__init__.py index 8de5276..fd17441 100644 --- a/httpx/__init__.py +++ b/httpx/__init__.py @@ -34,6 +34,8 @@ from .interfaces import ( AsyncDispatcher, BaseReader, BaseWriter, + BaseBackgroundManager, + BasePoolSemaphore, ConcurrencyBackend, Dispatcher, Protocol, diff --git a/httpx/models.py b/httpx/models.py index f98447c..df5d071 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -34,14 +34,17 @@ from .utils import ( is_known_encoding, normalize_header_key, normalize_header_value, + str_query_param ) +PrimitiveData = typing.Union[str, int, float, bool, type(None)] + URLTypes = typing.Union["URL", str] QueryParamTypes = typing.Union[ "QueryParams", - typing.Mapping[str, str], - typing.List[typing.Tuple[typing.Any, typing.Any]], + typing.Mapping[str, PrimitiveData], + typing.List[typing.Tuple[str, PrimitiveData]], str, ] @@ -268,8 +271,8 @@ class QueryParams(typing.Mapping[str, str]): else: items = value.items() # type: ignore - self._list = [(str(k), str(v)) for k, v in items] - self._dict = {str(k): str(v) for k, v in items} + self._list = [(str(k), str_query_param(v)) for k, v in items] + self._dict = {str(k): str_query_param(v) for k, v in items} def getlist(self, key: typing.Any) -> typing.List[str]: return [item_value for item_key, item_value in self._list if item_key == key] diff --git a/httpx/utils.py b/httpx/utils.py index 3d0d660..e96335f 100644 --- a/httpx/utils.py +++ b/httpx/utils.py @@ -20,6 +20,21 @@ def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes: return value.encode(encoding or "ascii") +def str_query_param(value: typing.Union[str, int, float, bool, type(None)]) -> str: + """ + Coerce a primitive data type into a string value for query params. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + def is_known_encoding(encoding: str) -> bool: """ Return `True` if `encoding` is a known codec.
encode/httpx
db6731a3d2dc882fc9bd9b9791544a2fba2cb559
diff --git a/tests/models/test_queryparams.py b/tests/models/test_queryparams.py index 983b09f..fbb559f 100644 --- a/tests/models/test_queryparams.py +++ b/tests/models/test_queryparams.py @@ -31,3 +31,23 @@ def test_queryparams(): q = QueryParams([("a", "123"), ("a", "456")]) assert QueryParams(q) == q + + +def test_queryparam_types(): + q = QueryParams({"a": True}) + assert str(q) == "a=true" + + q = QueryParams({"a": False}) + assert str(q) == "a=false" + + q = QueryParams({"a": ""}) + assert str(q) == "a=" + + q = QueryParams({"a": None}) + assert str(q) == "a=" + + q = QueryParams({"a": 1.23}) + assert str(q) == "a=1.23" + + q = QueryParams({"a": 123}) + assert str(q) == "a=123"
Change QueryParams(key=None) to not emit a parameter This one I know is [`requests` behaviour](https://github.com/psf/requests/blob/9a2e5df000691ad28613524ca7f80aa28a94a8d5/requests/models.py#L101): Take a dict: ```py >>> from httpx import QueryParams >>> params = {"thing_one": 1, "thing_two": [1,2,3], "thing_three": None} >>> QueryParams(params) QueryParams('thing_one=1&thing_two=%5B1%2C+2%2C+3%5D&thing_three=None') ``` Expected: ```py QueryParams('thing_one=1&thing_two=%5B1%2C+2%2C+3%5D') ``` Adding `if v is not None` [here](https://github.com/encode/httpx/blob/master/httpx/models.py#L263-L264) will do it.
0.0
[ "tests/models/test_queryparams.py::test_queryparam_types" ]
[ "tests/models/test_queryparams.py::test_queryparams" ]
2019-07-30 09:18:43+00:00
2,116
encode__httpx-199
diff --git a/httpx/__init__.py b/httpx/__init__.py index fd17441..39b44aa 100644 --- a/httpx/__init__.py +++ b/httpx/__init__.py @@ -32,10 +32,10 @@ from .exceptions import ( ) from .interfaces import ( AsyncDispatcher, - BaseReader, - BaseWriter, BaseBackgroundManager, BasePoolSemaphore, + BaseReader, + BaseWriter, ConcurrencyBackend, Dispatcher, Protocol, diff --git a/httpx/client.py b/httpx/client.py index e22d1a9..6b49797 100644 --- a/httpx/client.py +++ b/httpx/client.py @@ -20,11 +20,11 @@ from .dispatch.connection_pool import ConnectionPool from .dispatch.threaded import ThreadedDispatcher from .dispatch.wsgi import WSGIDispatch from .exceptions import ( + HTTPError, InvalidURL, RedirectBodyUnavailable, RedirectLoop, TooManyRedirects, - HTTPError, ) from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher from .models import ( @@ -312,6 +312,7 @@ class BaseClient: headers = Headers(request.headers) if url.origin != request.url.origin: del headers["Authorization"] + del headers["host"] return headers def redirect_content( diff --git a/httpx/exceptions.py b/httpx/exceptions.py index 21dc7f4..ddccbf8 100644 --- a/httpx/exceptions.py +++ b/httpx/exceptions.py @@ -9,7 +9,9 @@ class HTTPError(Exception): Base class for Httpx exception """ - def __init__(self, request: 'BaseRequest' = None, response: 'BaseResponse' = None, *args) -> None: + def __init__( + self, request: "BaseRequest" = None, response: "BaseResponse" = None, *args + ) -> None: self.response = response self.request = request or getattr(self.response, "request", None) super().__init__(*args) diff --git a/httpx/models.py b/httpx/models.py index e7e7a57..f397e78 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -33,7 +33,7 @@ from .utils import ( is_known_encoding, normalize_header_key, normalize_header_value, - str_query_param + str_query_param, ) PrimitiveData = typing.Union[str, int, float, bool, type(None)]
encode/httpx
ebbc003c55c5a0280208c4d7502bd6038520f29b
diff --git a/tests/client/test_headers.py b/tests/client/test_headers.py index bf82a57..2d17c12 100755 --- a/tests/client/test_headers.py +++ b/tests/client/test_headers.py @@ -1,15 +1,16 @@ #!/usr/bin/env python3 import json + from httpx import ( - __version__, - Client, + AsyncDispatcher, AsyncRequest, AsyncResponse, - VerifyTypes, CertTypes, + Client, TimeoutTypes, - AsyncDispatcher, + VerifyTypes, + __version__, ) diff --git a/tests/client/test_redirects.py b/tests/client/test_redirects.py index ff75475..f9c2075 100644 --- a/tests/client/test_redirects.py +++ b/tests/client/test_redirects.py @@ -86,6 +86,17 @@ class MockDispatch(AsyncDispatcher): body = json.dumps({"body": content.decode()}).encode() return AsyncResponse(codes.OK, content=body, request=request) + elif request.url.path == "/cross_subdomain": + if request.headers["host"] != "www.example.org": + headers = {"location": "https://www.example.org/cross_subdomain"} + return AsyncResponse( + codes.PERMANENT_REDIRECT, headers=headers, request=request + ) + else: + return AsyncResponse( + codes.OK, content=b"Hello, world!", request=request + ) + return AsyncResponse(codes.OK, content=b"Hello, world!", request=request) @@ -250,3 +261,11 @@ async def test_cannot_redirect_streaming_body(): with pytest.raises(RedirectBodyUnavailable): await client.post(url, data=streaming_body()) + + [email protected] +async def test_cross_dubdomain_redirect(): + client = AsyncClient(dispatch=MockDispatch()) + url = "https://example.com/cross_subdomain" + response = await client.get(url) + assert response.url == URL("https://www.example.org/cross_subdomain")
Erroneous Infinite Redirect Loop detected Our redirect loop detection or redirects in general is broken somehow because this shouldn't error out: ```python from httpx import Client client = Client() r = client.request("GET", "https://www.howsmyssl.com/a/check") # Completes successfully r = client.request("GET", "https://howsmyssl.com/a/check") # Sends a redirect to 'www.howsmyssl.com' but then errors? ```
0.0
[ "tests/client/test_redirects.py::test_cross_dubdomain_redirect" ]
[ "tests/client/test_headers.py::test_client_header", "tests/client/test_headers.py::test_header_merge", "tests/client/test_headers.py::test_header_merge_conflicting_headers", "tests/client/test_headers.py::test_header_update", "tests/client/test_redirects.py::test_redirect_301", "tests/client/test_redirects.py::test_redirect_302", "tests/client/test_redirects.py::test_redirect_303", "tests/client/test_redirects.py::test_disallow_redirects", "tests/client/test_redirects.py::test_relative_redirect", "tests/client/test_redirects.py::test_no_scheme_redirect", "tests/client/test_redirects.py::test_fragment_redirect", "tests/client/test_redirects.py::test_multiple_redirects", "tests/client/test_redirects.py::test_too_many_redirects", "tests/client/test_redirects.py::test_too_many_redirects_calling_next", "tests/client/test_redirects.py::test_redirect_loop", "tests/client/test_redirects.py::test_redirect_loop_calling_next", "tests/client/test_redirects.py::test_cross_domain_redirect", "tests/client/test_redirects.py::test_same_domain_redirect", "tests/client/test_redirects.py::test_body_redirect", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body" ]
2019-08-13 09:00:50+00:00
2,117
encode__httpx-2156
diff --git a/httpx/_client.py b/httpx/_client.py index cec0d63..ce7b92c 100644 --- a/httpx/_client.py +++ b/httpx/_client.py @@ -900,7 +900,7 @@ class Client(BaseClient): return response - except Exception as exc: + except BaseException as exc: response.close() raise exc @@ -932,7 +932,7 @@ class Client(BaseClient): request = next_request history.append(response) - except Exception as exc: + except BaseException as exc: response.close() raise exc finally: @@ -971,7 +971,7 @@ class Client(BaseClient): response.next_request = request return response - except Exception as exc: + except BaseException as exc: response.close() raise exc @@ -1604,7 +1604,7 @@ class AsyncClient(BaseClient): return response - except Exception as exc: # pragma: no cover + except BaseException as exc: # pragma: no cover await response.aclose() raise exc @@ -1636,7 +1636,7 @@ class AsyncClient(BaseClient): request = next_request history.append(response) - except Exception as exc: + except BaseException as exc: await response.aclose() raise exc finally: @@ -1676,7 +1676,7 @@ class AsyncClient(BaseClient): response.next_request = request return response - except Exception as exc: + except BaseException as exc: await response.aclose() raise exc
encode/httpx
67c297069f3d6b034069882428e4c1dd303d693c
diff --git a/tests/client/test_async_client.py b/tests/client/test_async_client.py index 219d612..da2387d 100644 --- a/tests/client/test_async_client.py +++ b/tests/client/test_async_client.py @@ -324,6 +324,46 @@ async def test_async_mock_transport(): assert response.text == "Hello, world!" [email protected]("async_environment") +async def test_cancellation_during_stream(): + """ + If any BaseException is raised during streaming the response, then the + stream should be closed. + + This includes: + + * `asyncio.CancelledError` (A subclass of BaseException from Python 3.8 onwards.) + * `trio.Cancelled` + * `KeyboardInterrupt` + * `SystemExit` + + See https://github.com/encode/httpx/issues/2139 + """ + stream_was_closed = False + + def response_with_cancel_during_stream(request): + class CancelledStream(httpx.AsyncByteStream): + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield b"Hello" + raise KeyboardInterrupt() + yield b", world" # pragma: nocover + + async def aclose(self) -> None: + nonlocal stream_was_closed + stream_was_closed = True + + return httpx.Response( + 200, headers={"Content-Length": "12"}, stream=CancelledStream() + ) + + transport = httpx.MockTransport(response_with_cancel_during_stream) + + async with httpx.AsyncClient(transport=transport) as client: + with pytest.raises(KeyboardInterrupt): + await client.get("https://www.example.com") + assert stream_was_closed + + @pytest.mark.usefixtures("async_environment") async def test_server_extensions(server): url = server.url
Response not closed when timeout/cancel reading response stream, which cause RuntimeError: The connection pool was closed while 1 HTTP requests/responses were still in-flight. Response not closed when timeout/cancel reading response stream, which cause `RuntimeError: The connection pool was closed while 1 HTTP requests/responses were still in-flight.` #### Reproduce: ```python import asyncio import httpx async def main(): url = "https://httpbin.org/drip?delay=0&duration=5" # Or use local httpbin server: # docker run -ti -p 8088:80 kennethreitz/httpbin:latest url = "http://127.0.0.1:8088/drip?delay=0&duration=5" async with httpx.AsyncClient(timeout=10, trust_env=False) as client: try: coro = client.get(url) response = await asyncio.wait_for(coro, 3) except Exception as ex: print(type(ex), repr(ex)) else: print(response) if __name__ == "__main__": asyncio.run(main()) ``` #### Output: ```python <class 'asyncio.exceptions.TimeoutError'> TimeoutError() Traceback (most recent call last): File "/Users/kk/dev/zhuwen/httpx/http_error2.py", line 22, in <module> asyncio.run(main()) File "/Users/kk/.pyenv/versions/3.9.7/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/Users/kk/.pyenv/versions/3.9.7/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/Users/kk/dev/zhuwen/httpx/http_error2.py", line 18, in main print(response) File "/Users/kk/dev/zhuwen/httpx/httpx/_client.py", line 1978, in __aexit__ await self._transport.__aexit__(exc_type, exc_value, traceback) File "/Users/kk/dev/zhuwen/httpx/httpx/_transports/default.py", line 332, in __aexit__ await self._pool.__aexit__(exc_type, exc_value, traceback) File "/Users/kk/.pyenv/versions/3.9.7/envs/httpx/lib/python3.9/site-packages/httpcore/_async/connection_pool.py", line 326, in __aexit__ await self.aclose() File "/Users/kk/.pyenv/versions/3.9.7/envs/httpx/lib/python3.9/site-packages/httpcore/_async/connection_pool.py", line 312, in aclose raise RuntimeError( RuntimeError: The connection pool was closed while 1 HTTP requests/responses were still in-flight. ``` #### Root cause: It's because use `except Exception` in _client.py which will not catch asyncio CancelledError, so except branch will not executed. https://github.com/encode/httpx/blob/master/httpx/_client.py#L1604 ```python try: if not stream: await response.aread() # will raise CancelledError return response except Exception as exc: # pragma: no cover await response.aclose() # will not executed raise exc ``` Change all `except Exception` in _client.py to `except BaseException` can resolve the issue.
0.0
[ "tests/client/test_async_client.py::test_cancellation_during_stream[asyncio]", "tests/client/test_async_client.py::test_cancellation_during_stream[trio]" ]
[ "tests/client/test_async_client.py::test_get[asyncio]", "tests/client/test_async_client.py::test_get[trio]", "tests/client/test_async_client.py::test_get_invalid_url[asyncio-scheme-not-http(s)]", "tests/client/test_async_client.py::test_get_invalid_url[asyncio-no-scheme]", "tests/client/test_async_client.py::test_get_invalid_url[asyncio-no-host]", "tests/client/test_async_client.py::test_get_invalid_url[trio-scheme-not-http(s)]", "tests/client/test_async_client.py::test_get_invalid_url[trio-no-scheme]", "tests/client/test_async_client.py::test_get_invalid_url[trio-no-host]", "tests/client/test_async_client.py::test_build_request[asyncio]", "tests/client/test_async_client.py::test_build_request[trio]", "tests/client/test_async_client.py::test_post[asyncio]", "tests/client/test_async_client.py::test_post[trio]", "tests/client/test_async_client.py::test_post_json[asyncio]", "tests/client/test_async_client.py::test_post_json[trio]", "tests/client/test_async_client.py::test_stream_response[asyncio]", "tests/client/test_async_client.py::test_stream_response[trio]", "tests/client/test_async_client.py::test_access_content_stream_response[asyncio]", "tests/client/test_async_client.py::test_access_content_stream_response[trio]", "tests/client/test_async_client.py::test_stream_request[asyncio]", "tests/client/test_async_client.py::test_stream_request[trio]", "tests/client/test_async_client.py::test_cannot_stream_sync_request[asyncio]", "tests/client/test_async_client.py::test_cannot_stream_sync_request[trio]", "tests/client/test_async_client.py::test_raise_for_status[asyncio]", "tests/client/test_async_client.py::test_raise_for_status[trio]", "tests/client/test_async_client.py::test_options[asyncio]", "tests/client/test_async_client.py::test_options[trio]", "tests/client/test_async_client.py::test_head[asyncio]", "tests/client/test_async_client.py::test_head[trio]", "tests/client/test_async_client.py::test_put[asyncio]", "tests/client/test_async_client.py::test_put[trio]", "tests/client/test_async_client.py::test_patch[asyncio]", "tests/client/test_async_client.py::test_patch[trio]", "tests/client/test_async_client.py::test_delete[asyncio]", "tests/client/test_async_client.py::test_delete[trio]", "tests/client/test_async_client.py::test_100_continue[asyncio]", "tests/client/test_async_client.py::test_100_continue[trio]", "tests/client/test_async_client.py::test_context_managed_transport[asyncio]", "tests/client/test_async_client.py::test_context_managed_transport[trio]", "tests/client/test_async_client.py::test_context_managed_transport_and_mount[asyncio]", "tests/client/test_async_client.py::test_context_managed_transport_and_mount[trio]", "tests/client/test_async_client.py::test_client_closed_state_using_implicit_open[asyncio]", "tests/client/test_async_client.py::test_client_closed_state_using_implicit_open[trio]", "tests/client/test_async_client.py::test_client_closed_state_using_with_block[asyncio]", "tests/client/test_async_client.py::test_client_closed_state_using_with_block[trio]", "tests/client/test_async_client.py::test_mounted_transport[asyncio]", "tests/client/test_async_client.py::test_mounted_transport[trio]", "tests/client/test_async_client.py::test_async_mock_transport[asyncio]", "tests/client/test_async_client.py::test_async_mock_transport[trio]", "tests/client/test_async_client.py::test_server_extensions[asyncio]", "tests/client/test_async_client.py::test_server_extensions[trio]" ]
2022-03-31 10:44:40+00:00
2,118
encode__httpx-2659
diff --git a/httpx/_utils.py b/httpx/_utils.py index c55d33a..2568fdc 100644 --- a/httpx/_utils.py +++ b/httpx/_utils.py @@ -1,5 +1,6 @@ import codecs import email.message +import ipaddress import mimetypes import os import re @@ -259,7 +260,16 @@ def get_environment_proxies() -> typing.Dict[str, typing.Optional[str]]: # NO_PROXY=google.com is marked as "all://*google.com, # which disables "www.google.com" and "google.com". # (But not "wwwgoogle.com") - mounts[f"all://*{hostname}"] = None + # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" + # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 + if is_ipv4_hostname(hostname): + mounts[f"all://{hostname}"] = None + elif is_ipv6_hostname(hostname): + mounts[f"all://[{hostname}]"] = None + elif hostname.lower() == "localhost": + mounts[f"all://{hostname}"] = None + else: + mounts[f"all://*{hostname}"] = None return mounts @@ -449,3 +459,19 @@ class URLPattern: def __eq__(self, other: typing.Any) -> bool: return isinstance(other, URLPattern) and self.pattern == other.pattern + + +def is_ipv4_hostname(hostname: str) -> bool: + try: + ipaddress.IPv4Address(hostname.split("/")[0]) + except: + return False + return True + + +def is_ipv6_hostname(hostname: str) -> bool: + try: + ipaddress.IPv6Address(hostname.split("/")[0]) + except: + return False + return True
encode/httpx
7d7c4f15b8784e4a550d974139acfa64193b32c2
diff --git a/tests/test_utils.py b/tests/test_utils.py index 3eaf245..ab0fcbe 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -185,6 +185,12 @@ def test_get_ssl_cert_file(): ), ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}), ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}), + ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}), + ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}), + ({"no_proxy": "::1"}, {"all://[::1]": None}), + ({"no_proxy": "localhost"}, {"all://localhost": None}), + ({"no_proxy": "github.com"}, {"all://*github.com": None}), + ({"no_proxy": ".github.com"}, {"all://*.github.com": None}), ], ) def test_get_environment_proxies(environment, proxies):
The `get_environment_proxies` function in _utils.py does not support IPv4, IPv6 correctly Hi, I encountered error when my environment `no_proxy` includes IPv6 address like `::1`. It is wrongly transformed into `all://*::1` and causes urlparse error since the _urlparse.py parses the `:1` as port. ![image](https://user-images.githubusercontent.com/26450272/232004919-042f07ff-dd55-4c3c-9e49-91d69c5cf3d6.png) The `get_environment_proxies` function in **_utils.py** is responsible for parsing and mounting proxy info from system environment. https://github.com/encode/httpx/blob/4b5a92e88e03443c2619f0905d756b159f9f0222/httpx/_utils.py#L229-L264 For env `no_proxy`, according to [CURLOPT_NOPROXY explained](https://curl.se/libcurl/c/CURLOPT_NOPROXY.html), it should support domains, IPv4, IPv6 and the `localhost`. However, current `get_environment_proxies` function implementation only supports domains correctly as it always adds wildcard `*` in front of the `hostname`. To fix this issue, I looked into this repo and suggest handling the `no_proxy` hostnames as domains, IPv4, IPv6 and the `localhost` seperately. I have updated the `get_environment_proxies` function in **_utils.py** and tested it. Refer to the PR: #2659 Replies and discussions are welcomed!
0.0
[ "tests/test_utils.py::test_get_environment_proxies[environment5-proxies5]", "tests/test_utils.py::test_get_environment_proxies[environment6-proxies6]", "tests/test_utils.py::test_get_environment_proxies[environment7-proxies7]", "tests/test_utils.py::test_get_environment_proxies[environment8-proxies8]" ]
[ "tests/test_utils.py::test_encoded[utf-32]", "tests/test_utils.py::test_encoded[utf-8-sig]", "tests/test_utils.py::test_encoded[utf-16]", "tests/test_utils.py::test_encoded[utf-8]", "tests/test_utils.py::test_encoded[utf-16-be]", "tests/test_utils.py::test_encoded[utf-16-le]", "tests/test_utils.py::test_encoded[utf-32-be]", "tests/test_utils.py::test_encoded[utf-32-le]", "tests/test_utils.py::test_bad_utf_like_encoding", "tests/test_utils.py::test_guess_by_bom[utf-16-be-utf-16]", "tests/test_utils.py::test_guess_by_bom[utf-16-le-utf-16]", "tests/test_utils.py::test_guess_by_bom[utf-32-be-utf-32]", "tests/test_utils.py::test_guess_by_bom[utf-32-le-utf-32]", "tests/test_utils.py::test_parse_header_links[<http:/.../front.jpeg>;", "tests/test_utils.py::test_parse_header_links[<http:/.../front.jpeg>-expected1]", "tests/test_utils.py::test_parse_header_links[<http:/.../front.jpeg>;-expected2]", "tests/test_utils.py::test_parse_header_links[-expected4]", "tests/test_utils.py::test_logging_request", "tests/test_utils.py::test_logging_redirect_chain", "tests/test_utils.py::test_logging_ssl", "tests/test_utils.py::test_get_ssl_cert_file", "tests/test_utils.py::test_get_environment_proxies[environment0-proxies0]", "tests/test_utils.py::test_get_environment_proxies[environment1-proxies1]", "tests/test_utils.py::test_get_environment_proxies[environment2-proxies2]", "tests/test_utils.py::test_get_environment_proxies[environment3-proxies3]", "tests/test_utils.py::test_get_environment_proxies[environment4-proxies4]", "tests/test_utils.py::test_get_environment_proxies[environment9-proxies9]", "tests/test_utils.py::test_get_environment_proxies[environment10-proxies10]", "tests/test_utils.py::test_obfuscate_sensitive_headers[headers0-output0]", "tests/test_utils.py::test_obfuscate_sensitive_headers[headers1-output1]", "tests/test_utils.py::test_obfuscate_sensitive_headers[headers2-output2]", "tests/test_utils.py::test_same_origin", "tests/test_utils.py::test_not_same_origin", "tests/test_utils.py::test_is_https_redirect", "tests/test_utils.py::test_is_not_https_redirect", "tests/test_utils.py::test_is_not_https_redirect_if_not_default_ports", "tests/test_utils.py::test_url_matches[http://example.com-http://example.com-True]", "tests/test_utils.py::test_url_matches[http://example.com-https://example.com-False]", "tests/test_utils.py::test_url_matches[http://example.com-http://other.com-False]", "tests/test_utils.py::test_url_matches[http://example.com:123-http://example.com:123-True]", "tests/test_utils.py::test_url_matches[http://example.com:123-http://example.com:456-False]", "tests/test_utils.py::test_url_matches[http://example.com:123-http://example.com-False]", "tests/test_utils.py::test_url_matches[all://example.com-http://example.com-True]", "tests/test_utils.py::test_url_matches[all://example.com-https://example.com-True]", "tests/test_utils.py::test_url_matches[http://-http://example.com-True]", "tests/test_utils.py::test_url_matches[http://-https://example.com-False]", "tests/test_utils.py::test_url_matches[all://-https://example.com:123-True]", "tests/test_utils.py::test_url_matches[-https://example.com:123-True]", "tests/test_utils.py::test_pattern_priority" ]
2023-04-14 09:34:36+00:00
2,119
encode__httpx-575
diff --git a/httpx/decoders.py b/httpx/decoders.py index 3ae822b..22c6104 100644 --- a/httpx/decoders.py +++ b/httpx/decoders.py @@ -211,6 +211,67 @@ class TextDecoder: return result +class LineDecoder: + """ + Handles incrementally reading lines from text. + + Uses universal line decoding, supporting any of `\n`, `\r`, or `\r\n` + as line endings, normalizing to `\n`. + """ + + def __init__(self) -> None: + self.buffer = "" + + def decode(self, text: str) -> typing.List[str]: + lines = [] + + if text.startswith("\n") and self.buffer and self.buffer[-1] == "\r": + # Handle the case where we have an "\r\n" split across + # our previous input, and our new chunk. + lines.append(self.buffer[:-1] + "\n") + self.buffer = "" + text = text[1:] + + while text: + num_chars = len(text) + for idx in range(num_chars): + char = text[idx] + next_char = None if idx + 1 == num_chars else text[idx + 1] + if char == "\n": + lines.append(self.buffer + text[: idx + 1]) + self.buffer = "" + text = text[idx + 1 :] + break + elif char == "\r" and next_char == "\n": + lines.append(self.buffer + text[:idx] + "\n") + self.buffer = "" + text = text[idx + 2 :] + break + elif char == "\r" and next_char is not None: + lines.append(self.buffer + text[:idx] + "\n") + self.buffer = "" + text = text[idx + 1 :] + break + elif next_char is None: + self.buffer = text + text = "" + break + + return lines + + def flush(self) -> typing.List[str]: + if self.buffer.endswith("\r"): + # Handle the case where we had a trailing '\r', which could have + # been a '\r\n' pair. + lines = [self.buffer[:-1] + "\n"] + elif self.buffer: + lines = [self.buffer] + else: + lines = [] + self.buffer = "" + return lines + + SUPPORTED_DECODERS = { "identity": IdentityDecoder, "gzip": GZipDecoder, diff --git a/httpx/models.py b/httpx/models.py index 5469efc..33cfb83 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -17,6 +17,7 @@ from .decoders import ( SUPPORTED_DECODERS, Decoder, IdentityDecoder, + LineDecoder, MultiDecoder, TextDecoder, ) @@ -936,6 +937,14 @@ class Response: yield decoder.decode(chunk) yield decoder.flush() + async def stream_lines(self) -> typing.AsyncIterator[str]: + decoder = LineDecoder() + async for text in self.stream_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + async def raw(self) -> typing.AsyncIterator[bytes]: """ A byte-iterator over the raw response content.
encode/httpx
fdaa01275a1b80e54be4423e579f9a19f7c63d8f
diff --git a/tests/models/test_responses.py b/tests/models/test_responses.py index e7be487..9b60c67 100644 --- a/tests/models/test_responses.py +++ b/tests/models/test_responses.py @@ -164,6 +164,18 @@ async def test_stream_text(): assert content == "Hello, world!" [email protected] +async def test_stream_lines(): + response = httpx.Response(200, content=b"Hello,\nworld!") + + await response.read() + + content = [] + async for line in response.stream_lines(): + content.append(line) + assert content == ["Hello,\n", "world!"] + + @pytest.mark.asyncio async def test_stream_interface_after_read(): response = httpx.Response(200, content=b"Hello, world!") diff --git a/tests/test_decoders.py b/tests/test_decoders.py index 7525239..a599ce0 100644 --- a/tests/test_decoders.py +++ b/tests/test_decoders.py @@ -9,6 +9,7 @@ from httpx.decoders import ( DeflateDecoder, GZipDecoder, IdentityDecoder, + LineDecoder, TextDecoder, ) @@ -167,6 +168,48 @@ def test_text_decoder_empty_cases(): assert decoder.flush() == "" +def test_line_decoder_nl(): + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\n\nb\nc") == ["a\n", "\n", "b\n"] + assert decoder.flush() == ["c"] + + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\n\nb\nc\n") == ["a\n", "\n", "b\n", "c\n"] + assert decoder.flush() == [] + + +def test_line_decoder_cr(): + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\r\rb\rc") == ["a\n", "\n", "b\n"] + assert decoder.flush() == ["c"] + + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\r\rb\rc\r") == ["a\n", "\n", "b\n"] + assert decoder.flush() == ["c\n"] + + +def test_line_decoder_crnl(): + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\r\n\r\nb\r\nc") == ["a\n", "\n", "b\n"] + assert decoder.flush() == ["c"] + + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\r\n\r\nb\r\nc\r\n") == ["a\n", "\n", "b\n", "c\n"] + assert decoder.flush() == [] + + decoder = LineDecoder() + assert decoder.decode("") == [] + assert decoder.decode("a\r") == [] + assert decoder.decode("\n\r\nb\r\nc") == ["a\n", "\n", "b\n"] + assert decoder.flush() == ["c"] + + def test_invalid_content_encoding_header(): headers = [(b"Content-Encoding", b"invalid-header")] body = b"test 123"
Feature Request: support iterating stream lines I think it is better to implement a api for iterating stream line by line. This scene is very common (e.g., kubernetes watch api). Now we need to create a wrapper for this. ```Python import json import httpx class StreamWrapper(object): def __init__(self, stream): self._stream = stream def __iter__(self): pending = "" for chunk in self._stream: chunk = pending + chunk lines = chunk.splitlines() if chunk and lines and lines[-1] and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = "" for line in lines: yield line if pending: yield pending timeout = httpx.TimeoutConfig( connect_timeout=5, read_timeout=None, write_timeout=5 ) resp = httpx.get( "http://127.0.0.1:18081/api/v1/watch/namespaces/default/pods", stream=True, timeout=timeout, ) for chunk in StreamWrapper(resp.stream_text()): print(json.loads(chunk)) ```
0.0
[ "tests/models/test_responses.py::test_response", "tests/models/test_responses.py::test_response_repr", "tests/models/test_responses.py::test_response_content_type_encoding", "tests/models/test_responses.py::test_response_autodetect_encoding", "tests/models/test_responses.py::test_response_fallback_to_autodetect", "tests/models/test_responses.py::test_response_default_text_encoding", "tests/models/test_responses.py::test_response_default_encoding", "tests/models/test_responses.py::test_response_non_text_encoding", "tests/models/test_responses.py::test_response_set_explicit_encoding", "tests/models/test_responses.py::test_response_force_encoding", "tests/models/test_responses.py::test_read_response", "tests/models/test_responses.py::test_raw_interface", "tests/models/test_responses.py::test_stream_interface", "tests/models/test_responses.py::test_stream_text", "tests/models/test_responses.py::test_stream_lines", "tests/models/test_responses.py::test_stream_interface_after_read", "tests/models/test_responses.py::test_streaming_response", "tests/models/test_responses.py::test_cannot_read_after_stream_consumed", "tests/models/test_responses.py::test_cannot_read_after_response_closed", "tests/models/test_responses.py::test_unknown_status_code", "tests/models/test_responses.py::test_json_with_specified_encoding", "tests/models/test_responses.py::test_json_with_options", "tests/models/test_responses.py::test_json_without_specified_encoding", "tests/models/test_responses.py::test_json_without_specified_encoding_decode_error", "tests/models/test_responses.py::test_link_headers[headers0-expected0]", "tests/models/test_responses.py::test_link_headers[headers1-expected1]", "tests/test_decoders.py::test_deflate", "tests/test_decoders.py::test_gzip", "tests/test_decoders.py::test_brotli", "tests/test_decoders.py::test_multi", "tests/test_decoders.py::test_multi_with_identity", "tests/test_decoders.py::test_streaming", "tests/test_decoders.py::test_empty_content[deflate]", "tests/test_decoders.py::test_empty_content[gzip]", "tests/test_decoders.py::test_empty_content[br]", "tests/test_decoders.py::test_empty_content[identity]", "tests/test_decoders.py::test_decoders_empty_cases[BrotliDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[DeflateDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[GZipDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[IdentityDecoder]", "tests/test_decoders.py::test_decoding_errors[deflate]", "tests/test_decoders.py::test_decoding_errors[gzip]", "tests/test_decoders.py::test_decoding_errors[br]", "tests/test_decoders.py::test_text_decoder[data0-ascii]", "tests/test_decoders.py::test_text_decoder[data1-utf-8]", "tests/test_decoders.py::test_text_decoder[data2-shift-jis]", "tests/test_decoders.py::test_text_decoder[data3-shift-jis]", "tests/test_decoders.py::test_text_decoder[data4-MacCyrillic]", "tests/test_decoders.py::test_text_decoder[data5-euc-jp]", "tests/test_decoders.py::test_text_decoder_known_encoding", "tests/test_decoders.py::test_text_decoder_empty_cases", "tests/test_decoders.py::test_line_decoder_nl", "tests/test_decoders.py::test_line_decoder_cr", "tests/test_decoders.py::test_line_decoder_crnl", "tests/test_decoders.py::test_invalid_content_encoding_header" ]
[]
2019-11-30 17:46:40+00:00
2,120
encode__httpx-685
diff --git a/httpx/auth.py b/httpx/auth.py index e0ef50c..e412c57 100644 --- a/httpx/auth.py +++ b/httpx/auth.py @@ -6,7 +6,7 @@ import typing from base64 import b64encode from urllib.request import parse_http_list -from .exceptions import ProtocolError +from .exceptions import ProtocolError, RequestBodyUnavailable from .models import Request, Response from .utils import to_bytes, to_str, unquote @@ -104,6 +104,8 @@ class DigestAuth(Auth): self.password = to_bytes(password) def __call__(self, request: Request) -> AuthFlow: + if not request.stream.can_replay(): + raise RequestBodyUnavailable("Request body is no longer available.") response = yield request if response.status_code != 401 or "www-authenticate" not in response.headers:
encode/httpx
bc6163c55a75f2e655ff59301ce0a53fa12973ec
diff --git a/tests/client/test_auth.py b/tests/client/test_auth.py index ea6ff8a..34ec77e 100644 --- a/tests/client/test_auth.py +++ b/tests/client/test_auth.py @@ -5,7 +5,15 @@ import typing import pytest -from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response +from httpx import ( + URL, + AsyncClient, + DigestAuth, + ProtocolError, + Request, + RequestBodyUnavailable, + Response, +) from httpx.auth import Auth, AuthFlow from httpx.config import CertTypes, TimeoutTypes, VerifyTypes from httpx.dispatch.base import Dispatcher @@ -442,3 +450,16 @@ async def test_auth_history() -> None: assert resp2.history == [resp1] assert len(resp1.history) == 0 + + [email protected] +async def test_digest_auth_unavailable_streaming_body(): + url = "https://example.org/" + auth = DigestAuth(username="tomchristie", password="password123") + client = AsyncClient(dispatch=MockDispatch()) + + async def streaming_body(): + yield b"Example request body" + + with pytest.raises(RequestBodyUnavailable): + await client.post(url, data=streaming_body(), auth=auth)
DigestAuth should raise a clear error if the request cannot replay. Our DigestAuth implementation cannot work with non-replayable requests. We ought to raise a nice clear error if `request.stream.is_replayable` is not True.
0.0
[ "tests/client/test_auth.py::test_digest_auth_unavailable_streaming_body" ]
[ "tests/client/test_auth.py::test_basic_auth", "tests/client/test_auth.py::test_basic_auth_in_url", "tests/client/test_auth.py::test_basic_auth_on_session", "tests/client/test_auth.py::test_custom_auth", "tests/client/test_auth.py::test_netrc_auth", "tests/client/test_auth.py::test_auth_header_has_priority_over_netrc", "tests/client/test_auth.py::test_trust_env_auth", "tests/client/test_auth.py::test_auth_hidden_url", "tests/client/test_auth.py::test_auth_hidden_header", "tests/client/test_auth.py::test_auth_invalid_type", "tests/client/test_auth.py::test_digest_auth_returns_no_auth_if_no_digest_header_in_response", "tests/client/test_auth.py::test_digest_auth_200_response_including_digest_auth_header", "tests/client/test_auth.py::test_digest_auth_401_response_without_digest_auth_header", "tests/client/test_auth.py::test_digest_auth[MD5-64-32]", "tests/client/test_auth.py::test_digest_auth[MD5-SESS-64-32]", "tests/client/test_auth.py::test_digest_auth[SHA-64-40]", "tests/client/test_auth.py::test_digest_auth[SHA-SESS-64-40]", "tests/client/test_auth.py::test_digest_auth[SHA-256-64-64]", "tests/client/test_auth.py::test_digest_auth[SHA-256-SESS-64-64]", "tests/client/test_auth.py::test_digest_auth[SHA-512-64-128]", "tests/client/test_auth.py::test_digest_auth[SHA-512-SESS-64-128]", "tests/client/test_auth.py::test_digest_auth_no_specified_qop", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[auth,", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[auth,auth-int]", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[unknown,auth]", "tests/client/test_auth.py::test_digest_auth_qop_auth_int_not_implemented", "tests/client/test_auth.py::test_digest_auth_qop_must_be_auth_or_auth_int", "tests/client/test_auth.py::test_digest_auth_incorrect_credentials", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[Digest", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[realm=\"[email protected]\",", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[DigestZ", "tests/client/test_auth.py::test_auth_history" ]
2019-12-26 08:37:55+00:00
2,121
encode__httpx-718
diff --git a/docs/quickstart.md b/docs/quickstart.md index 15defb1..0d68965 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -379,7 +379,7 @@ with additional API for accessing cookies by their domain or path. By default, HTTPX will follow redirects for anything except `HEAD` requests. The `history` property of the response can be used to inspect any followed redirects. -It contains a list of all any redirect responses that were followed, in the order +It contains a list of any redirect responses that were followed, in the order in which they were made. For example, GitHub redirects all HTTP requests to HTTPS. diff --git a/httpx/__init__.py b/httpx/__init__.py index caaa81a..01f4068 100644 --- a/httpx/__init__.py +++ b/httpx/__init__.py @@ -17,8 +17,8 @@ from .exceptions import ( ProtocolError, ProxyError, ReadTimeout, - RedirectBodyUnavailable, RedirectLoop, + RequestBodyUnavailable, ResponseClosed, ResponseNotRead, StreamConsumed, @@ -63,8 +63,8 @@ __all__ = [ "PoolTimeout", "ProtocolError", "ReadTimeout", - "RedirectBodyUnavailable", "RedirectLoop", + "RequestBodyUnavailable", "ResponseClosed", "ResponseNotRead", "StreamConsumed", diff --git a/httpx/client.py b/httpx/client.py index b2c2e5e..75f29ac 100644 --- a/httpx/client.py +++ b/httpx/client.py @@ -27,8 +27,8 @@ from .dispatch.proxy_http import HTTPProxy from .exceptions import ( HTTPError, InvalidURL, - RedirectBodyUnavailable, RedirectLoop, + RequestBodyUnavailable, TooManyRedirects, ) from .models import ( @@ -451,7 +451,7 @@ class AsyncClient: raise RedirectLoop() response = await self.send_handling_auth( - request, auth=auth, timeout=timeout, + request, history, auth=auth, timeout=timeout, ) response.history = list(history) @@ -561,12 +561,21 @@ class AsyncClient: """ if method != request.method and method == "GET": return None + if not request.stream.can_replay(): - raise RedirectBodyUnavailable() + raise RequestBodyUnavailable( + "Got a redirect response, but the request body was streaming " + "and is no longer available." + ) + return request.stream async def send_handling_auth( - self, request: Request, auth: Auth, timeout: Timeout, + self, + request: Request, + history: typing.List[Response], + auth: Auth, + timeout: Timeout, ) -> Response: auth_flow = auth(request) request = next(auth_flow) @@ -580,8 +589,10 @@ class AsyncClient: await response.aclose() raise exc from None else: + response.history = list(history) + await response.aread() request = next_request - await response.aclose() + history.append(response) async def send_single_request( self, request: Request, timeout: Timeout, diff --git a/httpx/exceptions.py b/httpx/exceptions.py index 2d8d27d..e199270 100644 --- a/httpx/exceptions.py +++ b/httpx/exceptions.py @@ -86,13 +86,6 @@ class TooManyRedirects(RedirectError): """ -class RedirectBodyUnavailable(RedirectError): - """ - Got a redirect response, but the request body was streaming, and is - no longer available. - """ - - class RedirectLoop(RedirectError): """ Infinite redirect loop. @@ -117,6 +110,13 @@ class StreamError(HTTPError): """ +class RequestBodyUnavailable(StreamError): + """ + Had to send the request again, but the request body was streaming, and is + no longer available. + """ + + class StreamConsumed(StreamError): """ Attempted to read or stream response content, but the content has already
encode/httpx
79a9748ae6df16b428c840d4bcdb5447c138df34
diff --git a/tests/client/test_auth.py b/tests/client/test_auth.py index d4dd76a..ea6ff8a 100644 --- a/tests/client/test_auth.py +++ b/tests/client/test_auth.py @@ -6,6 +6,7 @@ import typing import pytest from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response +from httpx.auth import Auth, AuthFlow from httpx.config import CertTypes, TimeoutTypes, VerifyTypes from httpx.dispatch.base import Dispatcher @@ -218,6 +219,7 @@ async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> assert response.status_code == 200 assert response.json() == {"auth": None} + assert len(response.history) == 0 @pytest.mark.asyncio @@ -233,6 +235,7 @@ async def test_digest_auth_200_response_including_digest_auth_header() -> None: assert response.status_code == 200 assert response.json() == {"auth": None} + assert len(response.history) == 0 @pytest.mark.asyncio @@ -245,6 +248,7 @@ async def test_digest_auth_401_response_without_digest_auth_header() -> None: assert response.status_code == 401 assert response.json() == {"auth": None} + assert len(response.history) == 0 @pytest.mark.parametrize( @@ -271,6 +275,8 @@ async def test_digest_auth( response = await client.get(url, auth=auth) assert response.status_code == 200 + assert len(response.history) == 1 + authorization = typing.cast(dict, response.json())["auth"] scheme, _, fields = authorization.partition(" ") assert scheme == "Digest" @@ -299,6 +305,8 @@ async def test_digest_auth_no_specified_qop() -> None: response = await client.get(url, auth=auth) assert response.status_code == 200 + assert len(response.history) == 1 + authorization = typing.cast(dict, response.json())["auth"] scheme, _, fields = authorization.partition(" ") assert scheme == "Digest" @@ -325,7 +333,10 @@ async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) auth = DigestAuth(username="tomchristie", password="password123") client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop)) - await client.get(url, auth=auth) + response = await client.get(url, auth=auth) + + assert response.status_code == 200 + assert len(response.history) == 1 @pytest.mark.asyncio @@ -357,6 +368,7 @@ async def test_digest_auth_incorrect_credentials() -> None: response = await client.get(url, auth=auth) assert response.status_code == 401 + assert len(response.history) == 1 @pytest.mark.parametrize( @@ -381,3 +393,52 @@ async def test_digest_auth_raises_protocol_error_on_malformed_header( with pytest.raises(ProtocolError): await client.get(url, auth=auth) + + [email protected] +async def test_auth_history() -> None: + """ + Test that intermediate requests sent as part of an authentication flow + are recorded in the response history. + """ + + class RepeatAuth(Auth): + """ + A mock authentication scheme that requires clients to send + the request a fixed number of times, and then send a last request containing + an aggregation of nonces that the server sent in 'WWW-Authenticate' headers + of intermediate responses. + """ + + def __init__(self, repeat: int): + self.repeat = repeat + + def __call__(self, request: Request) -> AuthFlow: + nonces = [] + + for index in range(self.repeat): + request.headers["Authorization"] = f"Repeat {index}" + response = yield request + nonces.append(response.headers["www-authenticate"]) + + key = ".".join(nonces) + request.headers["Authorization"] = f"Repeat {key}" + yield request + + url = "https://example.org/" + auth = RepeatAuth(repeat=2) + client = AsyncClient(dispatch=MockDispatch(auth_header="abc")) + + response = await client.get(url, auth=auth) + assert response.status_code == 200 + assert response.json() == {"auth": "Repeat abc.abc"} + + assert len(response.history) == 2 + resp1, resp2 = response.history + assert resp1.json() == {"auth": "Repeat 0"} + assert resp2.json() == {"auth": "Repeat 1"} + + assert len(resp2.history) == 1 + assert resp2.history == [resp1] + + assert len(resp1.history) == 0 diff --git a/tests/client/test_redirects.py b/tests/client/test_redirects.py index 663d2de..4c02745 100644 --- a/tests/client/test_redirects.py +++ b/tests/client/test_redirects.py @@ -7,9 +7,9 @@ from httpx import ( URL, AsyncClient, NotRedirectResponse, - RedirectBodyUnavailable, RedirectLoop, Request, + RequestBodyUnavailable, Response, TooManyRedirects, codes, @@ -293,7 +293,7 @@ async def test_cannot_redirect_streaming_body(): async def streaming_body(): yield b"Example request body" - with pytest.raises(RedirectBodyUnavailable): + with pytest.raises(RequestBodyUnavailable): await client.post(url, data=streaming_body())
Authentication flows should preserve history. If the authentication flow makes more that one request, then any prior requests should be visible in `response.history`.
0.0
[ "tests/client/test_auth.py::test_basic_auth", "tests/client/test_auth.py::test_basic_auth_in_url", "tests/client/test_auth.py::test_basic_auth_on_session", "tests/client/test_auth.py::test_custom_auth", "tests/client/test_auth.py::test_netrc_auth", "tests/client/test_auth.py::test_auth_header_has_priority_over_netrc", "tests/client/test_auth.py::test_trust_env_auth", "tests/client/test_auth.py::test_auth_hidden_url", "tests/client/test_auth.py::test_auth_hidden_header", "tests/client/test_auth.py::test_auth_invalid_type", "tests/client/test_auth.py::test_digest_auth_returns_no_auth_if_no_digest_header_in_response", "tests/client/test_auth.py::test_digest_auth_200_response_including_digest_auth_header", "tests/client/test_auth.py::test_digest_auth_401_response_without_digest_auth_header", "tests/client/test_auth.py::test_digest_auth[MD5-64-32]", "tests/client/test_auth.py::test_digest_auth[MD5-SESS-64-32]", "tests/client/test_auth.py::test_digest_auth[SHA-64-40]", "tests/client/test_auth.py::test_digest_auth[SHA-SESS-64-40]", "tests/client/test_auth.py::test_digest_auth[SHA-256-64-64]", "tests/client/test_auth.py::test_digest_auth[SHA-256-SESS-64-64]", "tests/client/test_auth.py::test_digest_auth[SHA-512-64-128]", "tests/client/test_auth.py::test_digest_auth[SHA-512-SESS-64-128]", "tests/client/test_auth.py::test_digest_auth_no_specified_qop", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[auth,", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[auth,auth-int]", "tests/client/test_auth.py::test_digest_auth_qop_including_spaces_and_auth_returns_auth[unknown,auth]", "tests/client/test_auth.py::test_digest_auth_qop_auth_int_not_implemented", "tests/client/test_auth.py::test_digest_auth_qop_must_be_auth_or_auth_int", "tests/client/test_auth.py::test_digest_auth_incorrect_credentials", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[Digest", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[realm=\"[email protected]\",", "tests/client/test_auth.py::test_digest_auth_raises_protocol_error_on_malformed_header[DigestZ", "tests/client/test_auth.py::test_auth_history", "tests/client/test_redirects.py::test_no_redirect[asyncio]", "tests/client/test_redirects.py::test_no_redirect[trio]", "tests/client/test_redirects.py::test_redirect_301[asyncio]", "tests/client/test_redirects.py::test_redirect_301[trio]", "tests/client/test_redirects.py::test_redirect_302[asyncio]", "tests/client/test_redirects.py::test_redirect_302[trio]", "tests/client/test_redirects.py::test_redirect_303[asyncio]", "tests/client/test_redirects.py::test_redirect_303[trio]", "tests/client/test_redirects.py::test_disallow_redirects[asyncio]", "tests/client/test_redirects.py::test_disallow_redirects[trio]", "tests/client/test_redirects.py::test_relative_redirect[asyncio]", "tests/client/test_redirects.py::test_relative_redirect[trio]", "tests/client/test_redirects.py::test_no_scheme_redirect[asyncio]", "tests/client/test_redirects.py::test_no_scheme_redirect[trio]", "tests/client/test_redirects.py::test_fragment_redirect[asyncio]", "tests/client/test_redirects.py::test_fragment_redirect[trio]", "tests/client/test_redirects.py::test_multiple_redirects[asyncio]", "tests/client/test_redirects.py::test_multiple_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[trio]", "tests/client/test_redirects.py::test_redirect_loop[asyncio]", "tests/client/test_redirects.py::test_redirect_loop[trio]", "tests/client/test_redirects.py::test_redirect_loop_calling_next[asyncio]", "tests/client/test_redirects.py::test_redirect_loop_calling_next[trio]", "tests/client/test_redirects.py::test_cross_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_domain_redirect[trio]", "tests/client/test_redirects.py::test_same_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_same_domain_redirect[trio]", "tests/client/test_redirects.py::test_body_redirect[asyncio]", "tests/client/test_redirects.py::test_body_redirect[trio]", "tests/client/test_redirects.py::test_no_body_redirect[asyncio]", "tests/client/test_redirects.py::test_no_body_redirect[trio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[asyncio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[trio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[trio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[asyncio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[trio]" ]
[]
2020-01-03 20:45:26+00:00
2,122
encode__httpx-763
diff --git a/README.md b/README.md index cf6b9b3..27fd542 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,18 @@ Let's get started... '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...' ``` +Or, using the async API... + +_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._ + +```python +>>> import httpx +>>> async with httpx.AsyncClient() as client: +>>> r = await client.get('https://www.example.org/') +>>> r +<Response [200 OK]> +``` + ## Features HTTPX builds on the well-established usability of `requests`, and gives you: diff --git a/docs/index.md b/docs/index.md index e3d6e2a..476f62a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -51,6 +51,18 @@ Let's get started... '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...' ``` +Or, using the async API... + +_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._ + +```python +>>> import httpx +>>> async with httpx.AsyncClient() as client: +>>> r = await client.get('https://www.example.org/') +>>> r +<Response [200 OK]> +``` + ## Features HTTPX is a high performance asynchronous HTTP client, that builds on the diff --git a/httpx/decoders.py b/httpx/decoders.py index 75d980d..454ec4a 100644 --- a/httpx/decoders.py +++ b/httpx/decoders.py @@ -45,12 +45,18 @@ class DeflateDecoder(Decoder): """ def __init__(self) -> None: - self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + self.first_attempt = True + self.decompressor = zlib.decompressobj() def decode(self, data: bytes) -> bytes: + was_first_attempt = self.first_attempt + self.first_attempt = False try: return self.decompressor.decompress(data) except zlib.error as exc: + if was_first_attempt: + self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + return self.decode(data) raise DecodingError from exc def flush(self) -> bytes: diff --git a/httpx/dispatch/urllib3.py b/httpx/dispatch/urllib3.py index 1782834..2728170 100644 --- a/httpx/dispatch/urllib3.py +++ b/httpx/dispatch/urllib3.py @@ -77,7 +77,7 @@ class URLLib3Dispatcher(SyncDispatcher): ) else: return urllib3.ProxyManager( - proxy_url=proxy.url, + proxy_url=str(proxy.url), proxy_headers=dict(proxy.headers), ssl_context=ssl_context, num_pools=num_pools,
encode/httpx
956129fbf71495c97844dc7adf4b595a9da4cd18
diff --git a/tests/test_decoders.py b/tests/test_decoders.py index f320d94..d9e82f7 100644 --- a/tests/test_decoders.py +++ b/tests/test_decoders.py @@ -18,6 +18,11 @@ REQUEST = httpx.Request("GET", "https://example.org") def test_deflate(): + """ + Deflate encoding may use either 'zlib' or 'deflate' in the wild. + + https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297 + """ body = b"test 123" compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) compressed_body = compressor.compress(body) + compressor.flush() @@ -29,6 +34,22 @@ def test_deflate(): assert response.content == body +def test_zlib(): + """ + Deflate encoding may use either 'zlib' or 'deflate' in the wild. + + https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib#answer-22311297 + """ + body = b"test 123" + compressed_body = zlib.compress(body) + + headers = [(b"Content-Encoding", b"deflate")] + response = httpx.Response( + 200, headers=headers, content=compressed_body, request=REQUEST + ) + assert response.content == body + + def test_gzip(): body = b"test 123" compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
urllib3.ProxyManager() instantiation is broken. python 3.7.5 httpx 0.11.0 urllib3 1.25.7 ``` $ ipython3 -c 'import httpx; r = httpx.get("https://www.google.com")' parse_url http://127.0.0.1:1234 <class 'httpx.models.URL'> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-d6fe3101235f> in <module> ----> 1 import httpx; r = httpx.get("https://www.google.com") /usr/local/lib/python3.7/site-packages/httpx/api.py in get(url, params, headers, cookies, auth, allow_redirects, cert, verify, timeout, trust_env) 168 verify=verify, 169 timeout=timeout, --> 170 trust_env=trust_env, 171 ) 172 /usr/local/lib/python3.7/site-packages/httpx/api.py in request(method, url, params, data, files, json, headers, cookies, auth, timeout, allow_redirects, verify, cert, trust_env) 82 """ 83 with Client( ---> 84 cert=cert, verify=verify, timeout=timeout, trust_env=trust_env, 85 ) as client: 86 return client.request( /usr/local/lib/python3.7/site-packages/httpx/client.py in __init__(self, auth, params, headers, cookies, verify, cert, proxies, timeout, pool_limits, max_redirects, base_url, dispatch, app, trust_env) 477 trust_env=trust_env, 478 ) --> 479 for key, proxy in proxy_map.items() 480 } 481 /usr/local/lib/python3.7/site-packages/httpx/client.py in <dictcomp>(.0) 477 trust_env=trust_env, 478 ) --> 479 for key, proxy in proxy_map.items() 480 } 481 /usr/local/lib/python3.7/site-packages/httpx/client.py in init_proxy_dispatch(self, proxy, verify, cert, pool_limits, trust_env) 512 cert=cert, 513 pool_limits=pool_limits, --> 514 trust_env=trust_env, 515 ) 516 /usr/local/lib/python3.7/site-packages/httpx/dispatch/urllib3.py in __init__(self, proxy, verify, cert, trust_env, pool_limits) 58 num_pools=num_pools, 59 maxsize=maxsize, ---> 60 block=block, 61 ) 62 /usr/local/lib/python3.7/site-packages/httpx/dispatch/urllib3.py in init_pool_manager(self, proxy, ssl_context, num_pools, maxsize, block) 83 num_pools=num_pools, 84 maxsize=maxsize, ---> 85 block=block, 86 ) 87 /usr/local/lib/python3.7/site-packages/urllib3/poolmanager.py in __init__(self, proxy_url, num_pools, headers, proxy_headers, **connection_pool_kw) 412 proxy_url.port, 413 ) --> 414 proxy = parse_url(proxy_url) 415 if not proxy.port: 416 port = port_by_scheme.get(proxy.scheme, 80) /usr/local/lib/python3.7/site-packages/urllib3/util/url.py in parse_url(url) 361 print('parse_url', url, type(url)) 362 source_url = url --> 363 if not SCHEME_RE.search(url): 364 url = "//" + url 365 TypeError: expected string or bytes-like object ```
0.0
[ "tests/test_decoders.py::test_zlib" ]
[ "tests/test_decoders.py::test_deflate", "tests/test_decoders.py::test_gzip", "tests/test_decoders.py::test_brotli", "tests/test_decoders.py::test_multi", "tests/test_decoders.py::test_multi_with_identity", "tests/test_decoders.py::test_streaming", "tests/test_decoders.py::test_empty_content[deflate]", "tests/test_decoders.py::test_empty_content[gzip]", "tests/test_decoders.py::test_empty_content[br]", "tests/test_decoders.py::test_empty_content[identity]", "tests/test_decoders.py::test_decoders_empty_cases[BrotliDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[DeflateDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[GZipDecoder]", "tests/test_decoders.py::test_decoders_empty_cases[IdentityDecoder]", "tests/test_decoders.py::test_decoding_errors[deflate]", "tests/test_decoders.py::test_decoding_errors[gzip]", "tests/test_decoders.py::test_decoding_errors[br]", "tests/test_decoders.py::test_text_decoder[data0-ascii]", "tests/test_decoders.py::test_text_decoder[data1-utf-8]", "tests/test_decoders.py::test_text_decoder[data2-shift-jis]", "tests/test_decoders.py::test_text_decoder[data3-shift-jis]", "tests/test_decoders.py::test_text_decoder[data4-MacCyrillic]", "tests/test_decoders.py::test_text_decoder[data5-euc-jp]", "tests/test_decoders.py::test_text_decoder_known_encoding", "tests/test_decoders.py::test_text_decoder_empty_cases", "tests/test_decoders.py::test_line_decoder_nl", "tests/test_decoders.py::test_line_decoder_cr", "tests/test_decoders.py::test_line_decoder_crnl", "tests/test_decoders.py::test_invalid_content_encoding_header" ]
2020-01-14 09:00:29+00:00
2,123
encode__httpx-774
diff --git a/httpx/client.py b/httpx/client.py index 590d5d0..4991478 100644 --- a/httpx/client.py +++ b/httpx/client.py @@ -330,6 +330,11 @@ class BaseClient: url = URL(location, allow_relative=True) + # Handle malformed 'Location' headers that are "absolute" form, have no host. + # See: https://github.com/encode/httpx/issues/771 + if url.scheme and not url.host: + url = url.copy_with(host=request.url.host) + # Facilitate relative 'Location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') if url.is_relative_url: diff --git a/httpx/models.py b/httpx/models.py index acaaf66..8d22738 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -201,7 +201,7 @@ class URL: or "port" in kwargs ): host = kwargs.pop("host", self.host) - port = kwargs.pop("port", self.port) + port = kwargs.pop("port", None if self.is_relative_url else self.port) username = kwargs.pop("username", self.username) password = kwargs.pop("password", self.password) @@ -216,7 +216,10 @@ class URL: kwargs["authority"] = authority - return URL(self._uri_reference.copy_with(**kwargs).unsplit()) + return URL( + self._uri_reference.copy_with(**kwargs).unsplit(), + allow_relative=self.is_relative_url, + ) def join(self, relative_url: URLTypes) -> "URL": """
encode/httpx
5a63540e8ab35209849894819ac731c836fdcf27
diff --git a/tests/client/test_redirects.py b/tests/client/test_redirects.py index eab44f0..1717d78 100644 --- a/tests/client/test_redirects.py +++ b/tests/client/test_redirects.py @@ -56,6 +56,10 @@ class MockDispatch(AsyncDispatcher): headers = {"location": "/"} return Response(codes.SEE_OTHER, headers=headers, request=request) + elif request.url.path == "/malformed_redirect": + headers = {"location": "https://:443/"} + return Response(codes.SEE_OTHER, headers=headers, request=request) + elif request.url.path == "/no_scheme_redirect": headers = {"location": "//example.org/"} return Response(codes.SEE_OTHER, headers=headers, request=request) @@ -176,6 +180,16 @@ async def test_relative_redirect(): assert len(response.history) == 1 [email protected]("async_environment") +async def test_malformed_redirect(): + # https://github.com/encode/httpx/issues/771 + client = AsyncClient(dispatch=MockDispatch()) + response = await client.get("http://example.org/malformed_redirect") + assert response.status_code == codes.OK + assert response.url == URL("https://example.org/") + assert len(response.history) == 1 + + @pytest.mark.usefixtures("async_environment") async def test_no_scheme_redirect(): client = AsyncClient(dispatch=MockDispatch())
Handle redirects with missing hostname in `Location:` header. While doing something like this: ``` import httpx def run_sync(url): with httpx.Client(verify=False) as client: response = client.get(url) print(response) run_sync('http://62.28.16.253') ``` I get a `httpx.exceptions.InvalidURL: No host included in URL.` However `curl -vLk http://62.28.16.253` works like normal, as well as other HTTP clients. I think this might be another sketchy server misconfiguration, but should work nonetheless.
0.0
[ "tests/client/test_redirects.py::test_malformed_redirect[asyncio]", "tests/client/test_redirects.py::test_malformed_redirect[trio]" ]
[ "tests/client/test_redirects.py::test_no_redirect[asyncio]", "tests/client/test_redirects.py::test_no_redirect[trio]", "tests/client/test_redirects.py::test_redirect_301[asyncio]", "tests/client/test_redirects.py::test_redirect_301[trio]", "tests/client/test_redirects.py::test_redirect_302[asyncio]", "tests/client/test_redirects.py::test_redirect_302[trio]", "tests/client/test_redirects.py::test_redirect_303[asyncio]", "tests/client/test_redirects.py::test_redirect_303[trio]", "tests/client/test_redirects.py::test_disallow_redirects[asyncio]", "tests/client/test_redirects.py::test_disallow_redirects[trio]", "tests/client/test_redirects.py::test_relative_redirect[asyncio]", "tests/client/test_redirects.py::test_relative_redirect[trio]", "tests/client/test_redirects.py::test_no_scheme_redirect[asyncio]", "tests/client/test_redirects.py::test_no_scheme_redirect[trio]", "tests/client/test_redirects.py::test_fragment_redirect[asyncio]", "tests/client/test_redirects.py::test_fragment_redirect[trio]", "tests/client/test_redirects.py::test_multiple_redirects[asyncio]", "tests/client/test_redirects.py::test_multiple_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects[trio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[asyncio]", "tests/client/test_redirects.py::test_too_many_redirects_calling_next[trio]", "tests/client/test_redirects.py::test_redirect_loop[asyncio]", "tests/client/test_redirects.py::test_redirect_loop[trio]", "tests/client/test_redirects.py::test_redirect_loop_calling_next[asyncio]", "tests/client/test_redirects.py::test_redirect_loop_calling_next[trio]", "tests/client/test_redirects.py::test_cross_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_domain_redirect[trio]", "tests/client/test_redirects.py::test_same_domain_redirect[asyncio]", "tests/client/test_redirects.py::test_same_domain_redirect[trio]", "tests/client/test_redirects.py::test_body_redirect[asyncio]", "tests/client/test_redirects.py::test_body_redirect[trio]", "tests/client/test_redirects.py::test_no_body_redirect[asyncio]", "tests/client/test_redirects.py::test_no_body_redirect[trio]", "tests/client/test_redirects.py::test_can_stream_if_no_redirect[asyncio]", "tests/client/test_redirects.py::test_can_stream_if_no_redirect[trio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[asyncio]", "tests/client/test_redirects.py::test_cannot_redirect_streaming_body[trio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[asyncio]", "tests/client/test_redirects.py::test_cross_subdomain_redirect[trio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[asyncio]", "tests/client/test_redirects.py::test_redirect_cookie_behavior[trio]" ]
2020-01-17 11:08:10+00:00
2,124
encode__httpx-995
diff --git a/httpx/_models.py b/httpx/_models.py index 865fd9a..683dde1 100644 --- a/httpx/_models.py +++ b/httpx/_models.py @@ -616,6 +616,9 @@ class Request: auto_headers: typing.List[typing.Tuple[bytes, bytes]] = [] has_host = "host" in self.headers + has_content_length = ( + "content-length" in self.headers or "transfer-encoding" in self.headers + ) has_user_agent = "user-agent" in self.headers has_accept = "accept" in self.headers has_accept_encoding = "accept-encoding" in self.headers @@ -626,6 +629,8 @@ class Request: if url.userinfo: url = url.copy_with(username=None, password=None) auto_headers.append((b"host", url.authority.encode("ascii"))) + if not has_content_length and self.method in ("POST", "PUT", "PATCH"): + auto_headers.append((b"content-length", b"0")) if not has_user_agent: auto_headers.append((b"user-agent", USER_AGENT.encode("ascii"))) if not has_accept:
encode/httpx
66a45379594e5cf836e4743931119e76dc8f22c7
diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 1555690..0bb1cc1 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -37,6 +37,22 @@ def test_build_request(server): assert response.json()["Custom-header"] == "value" +def test_build_post_request(server): + url = server.url.copy_with(path="/echo_headers") + headers = {"Custom-header": "value"} + + with httpx.Client() as client: + request = client.build_request("POST", url) + request.headers.update(headers) + response = client.send(request) + + assert response.status_code == 200 + assert response.url == url + + assert response.json()["Content-length"] == "0" + assert response.json()["Custom-header"] == "value" + + def test_post(server): with httpx.Client() as client: response = client.post(server.url, data=b"Hello, world!")
Content-Length header is missing in POST/DELETE/PUT/PATCH requests without body ### Checklist <!-- To help keep this issue tracker clean and focused, please make sure you tried *all* the following resources before submitting your question. --> - [x] I searched the [HTTPX documentation](https://www.python-httpx.org) but couldn't find what I'm looking for. - [x] I looked through similar issues on GitHub, but didn't find anything. - [x] I looked up "How to do ... in HTTPX" on a search engine and didn't find any information. - [x] I asked the [community chat](https://gitter.im/encode/community) for help ~~but didn't get an answer.~~ [and decided to create an issue. :)](https://gitter.im/encode/community?at=5ec95c46778fad0b13201d03) ### Environment **httpx version**: `0.13.1` **Python version**: `3.7.3` **OS**: Windows 7 ### Question I am not sure how to classify this issue: it could be a bug, since it is an incompatible with `requests`, on the other hand, it could be feature request, if you consider it is not that important. So, I decided to go with question. :D Was replacing `requests` with `httpx` in my small script and received an error from the server `httpx._exceptions.HTTPError: 411 Client Error: Length Required for url: ...` while doing a `POST` request **without a body** (same behavior is applicable for `PUT` and `PATCH` requests too). *Steps to reproduce:* ```python import requests import httpx for client in (requests, httpx): for method in ("get", "head", "delete", "post", "put", "patch"): r = client.request(method, f"https://httpbin.org/headers") print( f"[{client.__name__}] method={method.upper()} " f'Content-Length={r.request.headers.get("Content-Length")}' ) ``` `requests` adds `Content-Length` header in every possible http method, except `GET` and `HEAD`. `httpx` does not add `Content-Length` header at all, **unless requests has a body**. #866 added `Content-Length` to all methods, but since it is not needed in `GET` and `HEAD` methods, it was reverted. I assume, it should be handled during the `Request` building. `httpx` decides whether to add `Content-Length` depending on the steam type, which is handled in [_content_streams.py#L314](https://github.com/encode/httpx/blob/aa630d36c22642d7004a57abd222a14461ee4d77/httpx/_content_streams.py#L372). ### Thoughts on how to solve it To be honest, I am not sure what is the proper way to deal with this. :-( My first idea was to use `method` inside the [stream](https://github.com/encode/httpx/blob/aa630d36c22642d7004a57abd222a14461ee4d77/httpx/_content_streams.py#L49): ```python3 class ByteStream(ContentStream): def __init__(self, body: typing.Union[str, bytes], method: str) -> None: self.body = body.encode("utf-8") if isinstance(body, str) else body self.method = method def get_headers(self) -> typing.Dict[str, str]: if self.method in ("GET", "HEAD"): return {} content_length = str(len(self.body)) if self.body else "0" return {"Content-Length": content_length} ``` But this approach is not great, since it requires to pass `method` from `Request` to `encode` and then to `ByteStream` inside it. Also, it is not clear what `method` should I use when building stream in [`read`](https://github.com/encode/httpx/blob/aa630d36c22642d7004a57abd222a14461ee4d77/httpx/_models.py#L656) methods. Please, let me know what you think. Thanks!
0.0
[ "tests/client/test_client.py::test_build_post_request" ]
[ "tests/client/test_client.py::test_get", "tests/client/test_client.py::test_build_request", "tests/client/test_client.py::test_post", "tests/client/test_client.py::test_post_json", "tests/client/test_client.py::test_stream_response", "tests/client/test_client.py::test_stream_iterator", "tests/client/test_client.py::test_raw_iterator", "tests/client/test_client.py::test_raise_for_status", "tests/client/test_client.py::test_options", "tests/client/test_client.py::test_head", "tests/client/test_client.py::test_put", "tests/client/test_client.py::test_patch", "tests/client/test_client.py::test_delete", "tests/client/test_client.py::test_base_url", "tests/client/test_client.py::test_merge_url" ]
2020-05-25 09:46:44+00:00
2,125
encode__starlette-105
diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index 7345531..8bc3380 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -32,6 +32,8 @@ class CORSMiddleware: simple_headers = {} if "*" in allow_origins: simple_headers["Access-Control-Allow-Origin"] = "*" + else: + simple_headers["Vary"] = "Origin" if allow_credentials: simple_headers["Access-Control-Allow-Credentials"] = "true" if expose_headers: @@ -74,7 +76,7 @@ class CORSMiddleware: return self.preflight_response(request_headers=headers) else: return functools.partial( - self.simple_response, scope=scope, origin=origin + self.simple_response, scope=scope, request_headers=headers ) return self.app(scope) @@ -130,22 +132,31 @@ class CORSMiddleware: return PlainTextResponse("OK", status_code=200, headers=headers) - async def simple_response(self, receive, send, scope=None, origin=None): + async def simple_response(self, receive, send, scope=None, request_headers=None): inner = self.app(scope) - send = functools.partial(self.send, send=send, origin=origin) + send = functools.partial(self.send, send=send, request_headers=request_headers) await inner(receive, send) - async def send(self, message, send=None, origin=None): + async def send(self, message, send=None, request_headers=None): if message["type"] != "http.response.start": await send(message) return message.setdefault("headers", []) headers = MutableHeaders(message["headers"]) + origin = request_headers["Origin"] + has_cookie = "cookie" in request_headers + + # If request includes any cookie headers, then we must respond + # with the specific origin instead of '*'. + if self.allow_all_origins and has_cookie: + self.simple_headers["Access-Control-Allow-Origin"] = origin # If we only allow specific origins, then we have to mirror back # the Origin header in the response. - if not self.allow_all_origins and self.is_allowed_origin(origin=origin): + elif not self.allow_all_origins and self.is_allowed_origin(origin=origin): headers["Access-Control-Allow-Origin"] = origin + if "vary" in headers: + self.simple_headers["Vary"] = f"{headers.get('vary')}, Origin" headers.update(self.simple_headers) await send(message)
encode/starlette
cc09042c1ca5ccac78bf0ff689faa5dcd3e04f3a
diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 1b42a2f..ab3a077 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -206,3 +206,60 @@ def test_cors_allow_origin_regex(): assert response.status_code == 400 assert response.text == "Disallowed CORS origin" assert "access-control-allow-origin" not in response.headers + + +def test_cors_credentialed_requests_return_specific_origin(): + app = Starlette() + + app.add_middleware(CORSMiddleware, allow_origins=["*"]) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test credentialed request + headers = {"Origin": "https://example.org", "Cookie": "star_cookie=sugar"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert response.headers["access-control-allow-origin"] == "https://example.org" + + +def test_cors_vary_header_defaults_to_origin(): + app = Starlette() + + app.add_middleware(CORSMiddleware, allow_origins=["https://example.org"]) + + headers = {"Origin": "https://example.org"} + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.headers["vary"] == "Origin" + + +def test_cors_vary_header_is_properly_set(): + app = Starlette() + + app.add_middleware(CORSMiddleware, allow_origins=["https://example.org"]) + + headers = {"Origin": "https://example.org"} + + @app.route("/") + def homepage(request): + return PlainTextResponse( + "Homepage", status_code=200, headers={"Vary": "Accept-Encoding"} + ) + + client = TestClient(app) + + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.headers["vary"] == "Accept-Encoding, Origin"
Credentialed CORS standard requests should not respond with wildcard origins See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Credentialed_requests_and_wildcards If a standard request is made, that includes any cookie headers, then CORSMiddleware *ought* to strictly respond with the requested origin, rather than a wildcard. This is actually potentially a bit fiddly since we maybe also need to make sure to *set or add* Vary: Origin in those cases, in order to ensure correct cacheability.
0.0
[ "tests/test_middleware.py::test_cors_credentialed_requests_return_specific_origin", "tests/test_middleware.py::test_cors_vary_header_defaults_to_origin", "tests/test_middleware.py::test_cors_vary_header_is_properly_set" ]
[ "tests/test_middleware.py::test_trusted_host_middleware", "tests/test_middleware.py::test_https_redirect_middleware", "tests/test_middleware.py::test_cors_allow_all", "tests/test_middleware.py::test_cors_allow_specific_origin", "tests/test_middleware.py::test_cors_disallowed_preflight", "tests/test_middleware.py::test_cors_allow_origin_regex" ]
2018-10-11 22:53:24+00:00
2,126
encode__starlette-109
diff --git a/starlette/datastructures.py b/starlette/datastructures.py index 558c8a9..2705fd3 100644 --- a/starlette/datastructures.py +++ b/starlette/datastructures.py @@ -7,16 +7,20 @@ class URL: def __init__(self, url: str = "", scope: Scope = None) -> None: if scope is not None: assert not url, 'Cannot set both "url" and "scope".' - scheme = scope["scheme"] - host, port = scope["server"] + scheme = scope.get("scheme", "http") + server = scope.get("server", None) path = scope.get("root_path", "") + scope["path"] query_string = scope["query_string"] - default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] - if port == default_port: - url = "%s://%s%s" % (scheme, host, path) + if server is None: + url = path else: - url = "%s://%s:%s%s" % (scheme, host, port, path) + host, port = server + default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] + if port == default_port: + url = "%s://%s%s" % (scheme, host, path) + else: + url = "%s://%s:%s%s" % (scheme, host, port, path) if query_string: url += "?" + unquote(query_string.decode()) @@ -85,6 +89,9 @@ class URL: def __str__(self): return self._url + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._url)) + # Type annotations for valid `__init__` values to QueryParams and Headers. StrPairs = typing.Sequence[typing.Tuple[str, str]]
encode/starlette
02aaa4bddfe126b1458184b1ee1e8604af5041c7
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py index d6aa62f..4312e1c 100644 --- a/tests/test_datastructures.py +++ b/tests/test_datastructures.py @@ -27,6 +27,23 @@ def test_url(): assert new.hostname == "example.com" +def test_url_from_scope(): + u = URL(scope={"path": "/path/to/somewhere", "query_string": b"abc=123"}) + assert u == "/path/to/somewhere?abc=123" + assert repr(u) == "URL('/path/to/somewhere?abc=123')" + + u = URL( + scope={ + "scheme": "https", + "server": ("example.org", 123), + "path": "/path/to/somewhere", + "query_string": b"abc=123", + } + ) + assert u == "https://example.org:123/path/to/somewhere?abc=123" + assert repr(u) == "URL('https://example.org:123/path/to/somewhere?abc=123')" + + def test_headers(): h = Headers([(b"a", b"123"), (b"a", b"456"), (b"b", b"789")]) assert "a" in h
scope["server"] can be None From https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope > server: A two-item iterable of [host, port], where host is the listening address for this server as a unicode string, and port is the integer listening port. Optional, defaults to None. https://github.com/encode/starlette/blob/master/starlette/datastructures.py#L11 doesn't handle that option, it assumes scope["server"] is always a two-pair
0.0
[ "tests/test_datastructures.py::test_url_from_scope" ]
[ "tests/test_datastructures.py::test_url", "tests/test_datastructures.py::test_headers", "tests/test_datastructures.py::test_mutable_headers", "tests/test_datastructures.py::test_headers_mutablecopy", "tests/test_datastructures.py::test_queryparams" ]
2018-10-15 08:34:17+00:00
2,127
encode__starlette-1106
diff --git a/starlette/routing.py b/starlette/routing.py index ce5e4d1..1e6ae0b 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -2,7 +2,6 @@ import asyncio import functools import inspect import re -import sys import traceback import typing from enum import Enum @@ -33,11 +32,10 @@ class Match(Enum): def iscoroutinefunction_or_partial(obj: typing.Any) -> bool: """ Correctly determines if an object is a coroutine function, - with a fix for partials on Python < 3.8. + including those wrapped in functools.partial objects. """ - if sys.version_info < (3, 8): # pragma: no cover - while isinstance(obj, functools.partial): - obj = obj.func + while isinstance(obj, functools.partial): + obj = obj.func return inspect.iscoroutinefunction(obj)
encode/starlette
62e95b89fca3a4c60d6638776bddbe1b59fcd2f9
diff --git a/tests/test_routing.py b/tests/test_routing.py index 27640ef..8927c60 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -590,16 +590,35 @@ def test_raise_on_shutdown(): pass # pragma: nocover +class AsyncEndpointClassMethod: + @classmethod + async def async_endpoint(cls, arg, request): + return JSONResponse({"arg": arg}) + + async def _partial_async_endpoint(arg, request): return JSONResponse({"arg": arg}) partial_async_endpoint = functools.partial(_partial_async_endpoint, "foo") +partial_cls_async_endpoint = functools.partial( + AsyncEndpointClassMethod.async_endpoint, "foo" +) -partial_async_app = Router(routes=[Route("/", partial_async_endpoint)]) +partial_async_app = Router( + routes=[ + Route("/", partial_async_endpoint), + Route("/cls", partial_cls_async_endpoint), + ] +) def test_partial_async_endpoint(): - response = TestClient(partial_async_app).get("/") + test_client = TestClient(partial_async_app) + response = test_client.get("/") assert response.status_code == 200 assert response.json() == {"arg": "foo"} + + cls_method_response = test_client.get("/cls") + assert cls_method_response.status_code == 200 + assert cls_method_response.json() == {"arg": "foo"}
Asynchronous classmethod handlers not recognized as coroutines if wrapped in functools.partial https://github.com/encode/starlette/blob/e4307065ea6dbe708fba9643d14fe7adfff06d46/starlette/routing.py#L38 Although the recent 0.14.0 version adds support for functools.partial for Python 3.6 and Python 3.7, that support appears to be incomplete, not working for classmethods in Python 3.8. I was unaware of the fact that `inspect.iscoroutinefunction` does not properly detect a functools.partial as async if it wraps an async classmethod. TLDR: the previous PR was too cautious, we can always unwrap the functools.partial object to be sure we check the underlying object.
0.0
[ "tests/test_routing.py::test_partial_async_endpoint" ]
[ "tests/test_routing.py::test_router", "tests/test_routing.py::test_route_converters", "tests/test_routing.py::test_url_path_for", "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_router_add_route", "tests/test_routing.py::test_router_duplicate_path", "tests/test_routing.py::test_router_add_websocket_route", "tests/test_routing.py::test_protocol_switch", "tests/test_routing.py::test_mount_urls", "tests/test_routing.py::test_reverse_mount_urls", "tests/test_routing.py::test_mount_at_root", "tests/test_routing.py::test_host_routing", "tests/test_routing.py::test_host_reverse_urls", "tests/test_routing.py::test_subdomain_routing", "tests/test_routing.py::test_subdomain_reverse_urls", "tests/test_routing.py::test_url_for_with_root_path", "tests/test_routing.py::test_url_for_with_double_mount", "tests/test_routing.py::test_standalone_route_matches", "tests/test_routing.py::test_standalone_route_does_not_match", "tests/test_routing.py::test_standalone_ws_route_matches", "tests/test_routing.py::test_standalone_ws_route_does_not_match", "tests/test_routing.py::test_lifespan_async", "tests/test_routing.py::test_lifespan_sync", "tests/test_routing.py::test_raise_on_startup", "tests/test_routing.py::test_raise_on_shutdown" ]
2020-12-02 08:11:24+00:00
2,128
encode__starlette-1147
diff --git a/starlette/middleware/sessions.py b/starlette/middleware/sessions.py index d1b1d5a..a13ec5c 100644 --- a/starlette/middleware/sessions.py +++ b/starlette/middleware/sessions.py @@ -49,14 +49,16 @@ class SessionMiddleware: async def send_wrapper(message: Message) -> None: if message["type"] == "http.response.start": + path = scope.get("root_path", "") or "/" if scope["session"]: # We have session data to persist. data = b64encode(json.dumps(scope["session"]).encode("utf-8")) data = self.signer.sign(data) headers = MutableHeaders(scope=message) - header_value = "%s=%s; path=/; Max-Age=%d; %s" % ( + header_value = "%s=%s; path=%s; Max-Age=%d; %s" % ( self.session_cookie, data.decode("utf-8"), + path, self.max_age, self.security_flags, ) @@ -66,7 +68,7 @@ class SessionMiddleware: headers = MutableHeaders(scope=message) header_value = "{}={}; {}".format( self.session_cookie, - "null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;", + f"null; path={path}; expires=Thu, 01 Jan 1970 00:00:00 GMT;", self.security_flags, ) headers.append("Set-Cookie", header_value)
encode/starlette
23e15789bf6b879b455f1249e47a43d4c752b3ed
diff --git a/tests/middleware/test_session.py b/tests/middleware/test_session.py index 3f71232..68cf36d 100644 --- a/tests/middleware/test_session.py +++ b/tests/middleware/test_session.py @@ -101,3 +101,15 @@ def test_secure_session(): response = secure_client.get("/view_session") assert response.json() == {"session": {}} + + +def test_session_cookie_subpath(): + app = create_app() + second_app = create_app() + second_app.add_middleware(SessionMiddleware, secret_key="example") + app.mount("/second_app", second_app) + client = TestClient(app, base_url="http://testserver/second_app") + response = client.post("second_app/update_session", json={"some": "data"}) + cookie = response.headers["set-cookie"] + cookie_path = re.search(r"; path=(\S+);", cookie).groups()[0] + assert cookie_path == "/second_app"
Session cookie should use root path The session cookie currently uses '/'. It should really use the ASGI root path instead, in case the application is submounted.
0.0
[ "tests/middleware/test_session.py::test_session_cookie_subpath" ]
[ "tests/middleware/test_session.py::test_session", "tests/middleware/test_session.py::test_session_expires", "tests/middleware/test_session.py::test_secure_session" ]
2021-03-11 11:33:28+00:00
2,129
encode__starlette-134
diff --git a/docs/applications.md b/docs/applications.md index 2cce4ab..d4b44ca 100644 --- a/docs/applications.md +++ b/docs/applications.md @@ -56,7 +56,7 @@ There are two ways to add event handlers: * `@app.on_event(event_type)` - Add an event, decorator style * `app.add_event_handler(event_type, func)` - Add an event through a function call. -`event_type` must be specified as either `'startup'` or `'cleanup'`. +`event_type` must be specified as either `'startup'` or `'shutdown'`. ### Submounting other applications diff --git a/docs/events.md b/docs/events.md index b6696bb..3378a83 100644 --- a/docs/events.md +++ b/docs/events.md @@ -20,7 +20,7 @@ app = Starlette() async def open_database_connection_pool(): ... [email protected]_event('cleanup') [email protected]_event('shutdown') async def close_database_connection_pool(): ... ``` @@ -39,14 +39,14 @@ async def close_database_connection_pool(): ... app.add_event_handler('startup', open_database_connection_pool) -app.add_event_handler('cleanup', close_database_connection_pool) +app.add_event_handler('shutdown', close_database_connection_pool) ``` Starlette will not start serving any incoming requests until all of the registered startup handlers have completed. -The cleanup handlers will run once all connections have been closed, and +The shutdown handlers will run once all connections have been closed, and any in-process background tasks have completed. **Note**: The ASGI lifespan protocol has only recently been added to the spec, @@ -74,5 +74,5 @@ def test_homepage(): response = client.get("/") assert response.status_code == 200 - # Application 'cleanup' handlers are called on exiting the block. + # Application 'shutdown' handlers are called on exiting the block. ``` diff --git a/starlette/lifespan.py b/starlette/lifespan.py index a862298..b25ec8c 100644 --- a/starlette/lifespan.py +++ b/starlette/lifespan.py @@ -22,7 +22,7 @@ class LifespanHandler: return decorator def add_event_handler(self, event_type: str, func: typing.Callable) -> None: - assert event_type in ("startup", "cleanup") + assert event_type in ("startup", "shutdown", "cleanup") if event_type == "startup": self.startup_handlers.append(func) @@ -53,19 +53,26 @@ class LifespanHandler: await self.run_startup() await send({"type": "lifespan.startup.complete"}) message = await receive() - assert message["type"] == "lifespan.cleanup" + assert ( + message["type"] == "lifespan.shutdown" + or message["type"] == "lifespan.cleanup" + ) await self.run_cleanup() - await send({"type": "lifespan.cleanup.complete"}) + if message["type"] == "lifespan.shutdown": + await send({"type": "lifespan.shutdown.complete"}) + + if message["type"] == "lifespan.cleanup": + await send({"type": "lifespan.cleanup.complete"}) # pragma: no cover class LifespanContext: def __init__( - self, app: ASGIApp, startup_timeout: int = 10, cleanup_timeout: int = 10 + self, app: ASGIApp, startup_timeout: int = 10, shutdown_timeout: int = 10 ) -> None: self.startup_timeout = startup_timeout - self.cleanup_timeout = cleanup_timeout + self.shutdown_timeout = shutdown_timeout self.startup_event = asyncio.Event() - self.cleanup_event = asyncio.Event() + self.shutdown_event = asyncio.Event() self.receive_queue = asyncio.Queue() # type: asyncio.Queue self.asgi = app({"type": "lifespan"}) # type: ASGIInstance @@ -81,25 +88,25 @@ class LifespanContext: tb: TracebackType, ) -> None: loop = asyncio.get_event_loop() - loop.run_until_complete(self.wait_cleanup()) + loop.run_until_complete(self.wait_shutdown()) async def run_lifespan(self) -> None: try: await self.asgi(self.receive, self.send) finally: self.startup_event.set() - self.cleanup_event.set() + self.shutdown_event.set() async def send(self, message: Message) -> None: if message["type"] == "lifespan.startup.complete": assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR - assert not self.cleanup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR self.startup_event.set() else: - assert message["type"] == "lifespan.cleanup.complete" + assert message["type"] == "lifespan.shutdown.complete" assert self.startup_event.is_set(), STATE_TRANSITION_ERROR - assert not self.cleanup_event.is_set(), STATE_TRANSITION_ERROR - self.cleanup_event.set() + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() async def receive(self) -> Message: return await self.receive_queue.get() @@ -108,6 +115,8 @@ class LifespanContext: await self.receive_queue.put({"type": "lifespan.startup"}) await asyncio.wait_for(self.startup_event.wait(), timeout=self.startup_timeout) - async def wait_cleanup(self) -> None: - await self.receive_queue.put({"type": "lifespan.cleanup"}) - await asyncio.wait_for(self.cleanup_event.wait(), timeout=self.cleanup_timeout) + async def wait_shutdown(self) -> None: + await self.receive_queue.put({"type": "lifespan.shutdown"}) + await asyncio.wait_for( + self.shutdown_event.wait(), timeout=self.shutdown_timeout + )
encode/starlette
49f76ab5e9ef0ce5d966485553ad6019a9d37da5
diff --git a/tests/test_applications.py b/tests/test_applications.py index 8dc4c40..64a48c0 100644 --- a/tests/test_applications.py +++ b/tests/test_applications.py @@ -181,7 +181,7 @@ def test_app_add_event_handler(): cleanup_complete = True app.add_event_handler("startup", run_startup) - app.add_event_handler("cleanup", run_cleanup) + app.add_event_handler("shutdown", run_cleanup) assert not startup_complete assert not cleanup_complete diff --git a/tests/test_lifespan.py b/tests/test_lifespan.py index db4cb73..7b7372d 100644 --- a/tests/test_lifespan.py +++ b/tests/test_lifespan.py @@ -12,7 +12,7 @@ def test_lifespan_handler(): nonlocal startup_complete startup_complete = True - @handler.on_event("cleanup") + @handler.on_event("shutdown") def run_cleanup(): nonlocal cleanup_complete cleanup_complete = True @@ -36,7 +36,7 @@ def test_async_lifespan_handler(): nonlocal startup_complete startup_complete = True - @handler.on_event("cleanup") + @handler.on_event("shutdown") async def run_cleanup(): nonlocal cleanup_complete cleanup_complete = True @@ -60,7 +60,7 @@ def test_app_lifespan(): nonlocal startup_complete startup_complete = True - @app.on_event("cleanup") + @app.on_event("shutdown") def run_cleanup(): nonlocal cleanup_complete cleanup_complete = True
Support `shutdown` as a synonym for `cleanup` * Support either `cleanup` or `shutdown` as the ASGI lifespan message name. * Update uvicorn to move to shutdown - https://github.com/encode/uvicorn/issues/233 * Finally, after a small period of time, drop `cleanup` Easy PR for a contributor to jump on would be addressing the first part of this, and supporting either name.
0.0
[ "tests/test_applications.py::test_app_add_event_handler", "tests/test_lifespan.py::test_lifespan_handler", "tests/test_lifespan.py::test_async_lifespan_handler", "tests/test_lifespan.py::test_app_lifespan" ]
[ "tests/test_applications.py::test_func_route", "tests/test_applications.py::test_async_route", "tests/test_applications.py::test_class_route", "tests/test_applications.py::test_route_kwargs", "tests/test_applications.py::test_websocket_route", "tests/test_applications.py::test_400", "tests/test_applications.py::test_405", "tests/test_applications.py::test_500", "tests/test_applications.py::test_middleware", "tests/test_applications.py::test_app_mount", "tests/test_applications.py::test_app_debug" ]
2018-10-20 20:45:45+00:00
2,130
encode__starlette-1377
diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py index d09630f..da10a39 100644 --- a/starlette/staticfiles.py +++ b/starlette/staticfiles.py @@ -3,6 +3,7 @@ import os import stat import typing from email.utils import parsedate +from pathlib import Path import anyio @@ -51,7 +52,7 @@ class StaticFiles: self.all_directories = self.get_directories(directory, packages) self.html = html self.config_checked = False - if check_dir and directory is not None and not os.path.isdir(directory): + if check_dir and directory is not None and not Path(directory).is_dir(): raise RuntimeError(f"Directory '{directory}' does not exist") def get_directories( @@ -77,11 +78,9 @@ class StaticFiles: spec = importlib.util.find_spec(package) assert spec is not None, f"Package {package!r} could not be found." assert spec.origin is not None, f"Package {package!r} could not be found." - package_directory = os.path.normpath( - os.path.join(spec.origin, "..", statics_dir) - ) - assert os.path.isdir( - package_directory + package_directory = Path(spec.origin).joinpath("..", statics_dir).resolve() + assert ( + package_directory.is_dir() ), f"Directory '{statics_dir!r}' in package {package!r} could not be found." directories.append(package_directory) @@ -101,14 +100,14 @@ class StaticFiles: response = await self.get_response(path, scope) await response(scope, receive, send) - def get_path(self, scope: Scope) -> str: + def get_path(self, scope: Scope) -> Path: """ Given the ASGI scope, return the `path` string to serve up, with OS specific path separators, and any '..', '.' components removed. """ - return os.path.normpath(os.path.join(*scope["path"].split("/"))) + return Path(*scope["path"].split("/")) - async def get_response(self, path: str, scope: Scope) -> Response: + async def get_response(self, path: Path, scope: Scope) -> Response: """ Returns an HTTP response, given the incoming path, method and request headers. """ @@ -131,7 +130,7 @@ class StaticFiles: elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html: # We're in HTML mode, and have got a directory URL. # Check if we have 'index.html' file to serve. - index_path = os.path.join(path, "index.html") + index_path = path.joinpath("index.html") full_path, stat_result = await anyio.to_thread.run_sync( self.lookup_path, index_path ) @@ -158,20 +157,25 @@ class StaticFiles: raise HTTPException(status_code=404) def lookup_path( - self, path: str - ) -> typing.Tuple[str, typing.Optional[os.stat_result]]: + self, path: Path + ) -> typing.Tuple[Path, typing.Optional[os.stat_result]]: for directory in self.all_directories: - full_path = os.path.realpath(os.path.join(directory, path)) - directory = os.path.realpath(directory) - if os.path.commonprefix([full_path, directory]) != directory: - # Don't allow misbehaving clients to break out of the static files - # directory. - continue + original_path = Path(directory).joinpath(path) + full_path = original_path.resolve() + directory = Path(directory).resolve() try: - return full_path, os.stat(full_path) + stat_result = os.lstat(original_path) + full_path.relative_to(directory) + return full_path, stat_result + except ValueError: + # Allow clients to break out of the static files directory + # if following symlinks. + if stat.S_ISLNK(stat_result.st_mode): + stat_result = os.lstat(full_path) + return full_path, stat_result except (FileNotFoundError, NotADirectoryError): continue - return "", None + return Path(), None def file_response( self,
encode/starlette
d81545c71a7988cfd57c613be02f4661449c0793
diff --git a/tests/test_staticfiles.py b/tests/test_staticfiles.py index 7d13a05..53f3ea9 100644 --- a/tests/test_staticfiles.py +++ b/tests/test_staticfiles.py @@ -166,8 +166,8 @@ def test_staticfiles_prevents_breaking_out_of_directory(tmpdir): directory = os.path.join(tmpdir, "foo") os.mkdir(directory) - path = os.path.join(tmpdir, "example.txt") - with open(path, "w") as file: + file_path = os.path.join(tmpdir, "example.txt") + with open(file_path, "w") as file: file.write("outside root dir") app = StaticFiles(directory=directory) @@ -441,3 +441,28 @@ def test_staticfiles_unhandled_os_error_returns_500( response = client.get("/example.txt") assert response.status_code == 500 assert response.text == "Internal Server Error" + + +def test_staticfiles_follows_symlinks_to_break_out_of_dir( + tmp_path: pathlib.Path, test_client_factory +): + statics_path = tmp_path.joinpath("statics") + statics_path.mkdir() + + symlink_path = tmp_path.joinpath("symlink") + symlink_path.mkdir() + + symlink_file_path = symlink_path.joinpath("index.html") + with open(symlink_file_path, "w") as file: + file.write("<h1>Hello</h1>") + + statics_file_path = statics_path.joinpath("index.html") + statics_file_path.symlink_to(symlink_file_path) + + app = StaticFiles(directory=statics_path) + client = test_client_factory(app) + + response = client.get("/index.html") + assert response.url == "http://testserver/index.html" + assert response.status_code == 200 + assert response.text == "<h1>Hello</h1>"
StaticFiles middleware doesn't follow symlinks ### Checklist - [x] The bug is reproducible against the latest release and/or `master`. - [x] There are no similar issues or pull requests to fix it yet. ### Describe the bug The StaticFiles middleware is checking the `os.realpath` of a file and returning a 404 for symlinks that lead outside the static directory. ### To reproduce 1. create a minimal app with a staticfiles middleware 1. put a symlink in your static directory. the link's target must be above the static directory. 1. you'll get a 404 ### Expected behavior Support symlinks in static directory. The use case for symlinks in static is to target frontend assets that are being generated in file-watch mode. ### Actual behavior 404. ### Debugging material It's happening here: https://github.com/encode/starlette/blob/b95acea973c20eea3e7cbbca42d09b1f5d4a3412/starlette/staticfiles.py#L147-L149 ### Environment - OS: linux - Python version: 3.7.5 - Starlette version: 0.13.8 ### Additional context I'm happy to post a PR for this if useful, ideally adding a bool param to the StaticFiles middleware that allows symlinks.
0.0
[ "tests/test_staticfiles.py::test_staticfiles_follows_symlinks_to_break_out_of_dir[asyncio]", "tests/test_staticfiles.py::test_staticfiles_follows_symlinks_to_break_out_of_dir[trio]" ]
[ "tests/test_staticfiles.py::test_staticfiles[asyncio]", "tests/test_staticfiles.py::test_staticfiles[trio]", "tests/test_staticfiles.py::test_staticfiles_with_pathlib[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_pathlib[trio]", "tests/test_staticfiles.py::test_staticfiles_with_package[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_package[trio]", "tests/test_staticfiles.py::test_staticfiles_post[asyncio]", "tests/test_staticfiles.py::test_staticfiles_post[trio]", "tests/test_staticfiles.py::test_staticfiles_with_directory_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_directory_returns_404[trio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_file_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_file_returns_404[trio]", "tests/test_staticfiles.py::test_staticfiles_instantiated_with_missing_directory", "tests/test_staticfiles.py::test_staticfiles_configured_with_missing_directory[asyncio]", "tests/test_staticfiles.py::test_staticfiles_configured_with_missing_directory[trio]", "tests/test_staticfiles.py::test_staticfiles_configured_with_file_instead_of_directory[asyncio]", "tests/test_staticfiles.py::test_staticfiles_configured_with_file_instead_of_directory[trio]", "tests/test_staticfiles.py::test_staticfiles_config_check_occurs_only_once[asyncio]", "tests/test_staticfiles.py::test_staticfiles_config_check_occurs_only_once[trio]", "tests/test_staticfiles.py::test_staticfiles_prevents_breaking_out_of_directory", "tests/test_staticfiles.py::test_staticfiles_304_with_etag_match[asyncio]", "tests/test_staticfiles.py::test_staticfiles_304_with_etag_match[trio]", "tests/test_staticfiles.py::test_staticfiles_304_with_last_modified_compare_last_req[asyncio]", "tests/test_staticfiles.py::test_staticfiles_304_with_last_modified_compare_last_req[trio]", "tests/test_staticfiles.py::test_staticfiles_html_normal[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_normal[trio]", "tests/test_staticfiles.py::test_staticfiles_html_without_index[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_without_index[trio]", "tests/test_staticfiles.py::test_staticfiles_html_without_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_without_404[trio]", "tests/test_staticfiles.py::test_staticfiles_html_only_files[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_only_files[trio]", "tests/test_staticfiles.py::test_staticfiles_cache_invalidation_for_deleted_file_html_mode[asyncio]", "tests/test_staticfiles.py::test_staticfiles_cache_invalidation_for_deleted_file_html_mode[trio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_dir_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_dir_returns_404[trio]", "tests/test_staticfiles.py::test_staticfiles_access_file_as_dir_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_access_file_as_dir_returns_404[trio]", "tests/test_staticfiles.py::test_staticfiles_unhandled_os_error_returns_500[asyncio]", "tests/test_staticfiles.py::test_staticfiles_unhandled_os_error_returns_500[trio]" ]
2021-12-17 14:32:49+00:00
2,131
encode__starlette-145
diff --git a/docs/staticfiles.md b/docs/staticfiles.md index 03d9a58..f1b9d0a 100644 --- a/docs/staticfiles.md +++ b/docs/staticfiles.md @@ -1,20 +1,17 @@ -As well as the `FileResponse` class, Starlette also includes ASGI applications -for serving a specific file or directory: +Starlette also includes an `StaticFiles` class for serving a specific directory: -* `StaticFile(path)` - Serve a single file, given by `path`. * `StaticFiles(directory)` - Serve any files in the given `directory`. -You can combine these ASGI applications with Starlette's routing to provide +You can combine this ASGI application with Starlette's routing to provide comprehensive static file serving. ```python from starlette.routing import Router, Path, PathPrefix -from starlette.staticfiles import StaticFile, StaticFiles +from starlette.staticfiles import StaticFiles app = Router(routes=[ - Path('/', app=StaticFile(path='index.html')), PathPrefix('/static', app=StaticFiles(directory='static')), ]) ``` diff --git a/starlette/formparsers.py b/starlette/formparsers.py index 4d6580c..6d83320 100644 --- a/starlette/formparsers.py +++ b/starlette/formparsers.py @@ -1,9 +1,11 @@ -from enum import Enum -from starlette.datastructures import Headers -import asyncio import io -import tempfile import typing +import asyncio +import tempfile +from enum import Enum +from urllib.parse import unquote + +from starlette.datastructures import Headers try: from multipart.multipart import parse_options_header @@ -69,27 +71,22 @@ class FormParser: self.messages = [] # type: typing.List[typing.Tuple[FormMessage, bytes]] def on_field_start(self) -> None: - print("on_field_start") message = (FormMessage.FIELD_START, b"") self.messages.append(message) def on_field_name(self, data: bytes, start: int, end: int) -> None: - print("on_field_name") message = (FormMessage.FIELD_NAME, data[start:end]) self.messages.append(message) def on_field_data(self, data: bytes, start: int, end: int) -> None: - print("on_field_data") message = (FormMessage.FIELD_DATA, data[start:end]) self.messages.append(message) def on_field_end(self) -> None: - print("on_field_end") message = (FormMessage.FIELD_END, b"") self.messages.append(message) def on_end(self) -> None: - print("on_end") message = (FormMessage.END, b"") self.messages.append(message) @@ -127,7 +124,9 @@ class FormParser: elif message_type == FormMessage.FIELD_DATA: field_value += message_bytes elif message_type == FormMessage.FIELD_END: - result[field_name.decode("latin-1")] = field_value.decode("latin-1") + result[field_name.decode("latin-1")] = unquote( + field_value.decode("latin-1") + ) elif message_type == FormMessage.END: pass diff --git a/starlette/responses.py b/starlette/responses.py index 3471fbf..09ac58f 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -1,15 +1,16 @@ -import hashlib import os -import typing import json - +import stat +import typing +import hashlib +import http.cookies from email.utils import formatdate from mimetypes import guess_type +from urllib.parse import quote_plus + from starlette.background import BackgroundTask from starlette.datastructures import MutableHeaders, URL from starlette.types import Receive, Send -from urllib.parse import quote_plus -import http.cookies try: import aiofiles @@ -227,8 +228,15 @@ class FileResponse(Response): async def __call__(self, receive: Receive, send: Send) -> None: if self.stat_result is None: - stat_result = await aio_stat(self.path) - self.set_stat_headers(stat_result) + try: + stat_result = await aio_stat(self.path) + self.set_stat_headers(stat_result) + except FileNotFoundError: + raise RuntimeError(f"File at path {self.path} does not exist.") + else: + mode = stat_result.st_mode + if not stat.S_ISREG(mode): + raise RuntimeError(f"File at path {self.path} is not a file.") await send( { "type": "http.response.start", diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py index eb8f748..b9b54cf 100644 --- a/starlette/staticfiles.py +++ b/starlette/staticfiles.py @@ -7,17 +7,6 @@ from starlette.responses import PlainTextResponse, FileResponse, Response from starlette.types import Send, Receive, Scope, ASGIInstance -class StaticFile: - def __init__(self, *, path: str) -> None: - self.path = path - - def __call__(self, scope: Scope) -> ASGIInstance: - assert scope["type"] == "http" - if scope["method"] not in ("GET", "HEAD"): - return PlainTextResponse("Method Not Allowed", status_code=405) - return _StaticFileResponder(scope, path=self.path) - - class StaticFiles: def __init__(self, *, directory: str) -> None: self.directory = directory @@ -39,25 +28,6 @@ class StaticFiles: return _StaticFilesResponder(scope, path=path, check_directory=check_directory) -class _StaticFileResponder: - def __init__(self, scope: Scope, path: str) -> None: - self.scope = scope - self.path = path - - async def __call__(self, receive: Receive, send: Send) -> None: - try: - stat_result = await aio_stat(self.path) - except FileNotFoundError: - raise RuntimeError("StaticFile at path '%s' does not exist." % self.path) - else: - mode = stat_result.st_mode - if not stat.S_ISREG(mode): - raise RuntimeError("StaticFile at path '%s' is not a file." % self.path) - - response = FileResponse(self.path, stat_result=stat_result) - await response(receive, send) - - class _StaticFilesResponder: def __init__(self, scope: Scope, path: str, check_directory: str = None) -> None: self.scope = scope
encode/starlette
a32ea0a8e89567b24f3b8cd04847a1b01c9e98f0
diff --git a/tests/test_responses.py b/tests/test_responses.py index 467b360..63d5076 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -9,6 +9,7 @@ from starlette.requests import Request from starlette.testclient import TestClient from starlette import status import asyncio +import pytest import os @@ -144,6 +145,28 @@ def test_file_response(tmpdir): assert "etag" in response.headers +def test_file_response_with_directory_raises_error(tmpdir): + def app(scope): + return FileResponse(path=tmpdir, filename="example.png") + + client = TestClient(app) + with pytest.raises(RuntimeError) as exc: + client.get("/") + assert "is not a file" in str(exc) + + +def test_file_response_with_missing_file_raises_error(tmpdir): + path = os.path.join(tmpdir, "404.txt") + + def app(scope): + return FileResponse(path=path, filename="404.txt") + + client = TestClient(app) + with pytest.raises(RuntimeError) as exc: + client.get("/") + assert "does not exist" in str(exc) + + def test_set_cookie(): def app(scope): async def asgi(receive, send): diff --git a/tests/test_staticfiles.py b/tests/test_staticfiles.py index e21ce60..bc7ef0f 100644 --- a/tests/test_staticfiles.py +++ b/tests/test_staticfiles.py @@ -2,63 +2,7 @@ import os import pytest from starlette.testclient import TestClient -from starlette.staticfiles import StaticFile, StaticFiles - - -def test_staticfile(tmpdir): - path = os.path.join(tmpdir, "example.txt") - with open(path, "w") as file: - file.write("<file content>") - - app = StaticFile(path=path) - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200 - assert response.text == "<file content>" - - -def test_large_staticfile(tmpdir): - path = os.path.join(tmpdir, "example.txt") - content = "this is a lot of content" * 200 - print("content len = ", len(content)) - with open(path, "w") as file: - file.write(content) - - app = StaticFile(path=path) - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200 - assert len(content) == len(response.text) - assert content == response.text - - -def test_staticfile_post(tmpdir): - path = os.path.join(tmpdir, "example.txt") - with open(path, "w") as file: - file.write("<file content>") - - app = StaticFile(path=path) - client = TestClient(app) - response = client.post("/") - assert response.status_code == 405 - assert response.text == "Method Not Allowed" - - -def test_staticfile_with_directory_raises_error(tmpdir): - app = StaticFile(path=tmpdir) - client = TestClient(app) - with pytest.raises(RuntimeError) as exc: - client.get("/") - assert "is not a file" in str(exc) - - -def test_staticfile_with_missing_file_raises_error(tmpdir): - path = os.path.join(tmpdir, "404.txt") - app = StaticFile(path=path) - client = TestClient(app) - with pytest.raises(RuntimeError) as exc: - client.get("/") - assert "does not exist" in str(exc) +from starlette.staticfiles import StaticFiles def test_staticfiles(tmpdir):
Drop `StaticFile` app. We have `FileResponse` and `StaticFiles`. I think that including the `StaticFile` ASGI app complicates things unnecessarily, and that we should probably remove it. * Drop `StaticFile` app. * Put runtime checks that file exists, and file is a regular file in `FileResponse`.
0.0
[ "tests/test_responses.py::test_file_response_with_directory_raises_error", "tests/test_responses.py::test_file_response_with_missing_file_raises_error" ]
[ "tests/test_responses.py::test_text_response", "tests/test_responses.py::test_bytes_response", "tests/test_responses.py::test_ujson_response", "tests/test_responses.py::test_redirect_response", "tests/test_responses.py::test_streaming_response", "tests/test_responses.py::test_response_headers", "tests/test_responses.py::test_response_phrase", "tests/test_responses.py::test_file_response", "tests/test_responses.py::test_set_cookie", "tests/test_responses.py::test_delete_cookie", "tests/test_staticfiles.py::test_staticfiles", "tests/test_staticfiles.py::test_staticfiles_post", "tests/test_staticfiles.py::test_staticfiles_with_directory_returns_404", "tests/test_staticfiles.py::test_staticfiles_with_missing_file_returns_404", "tests/test_staticfiles.py::test_staticfiles_configured_with_missing_directory", "tests/test_staticfiles.py::test_staticfiles_configured_with_file_instead_of_directory", "tests/test_staticfiles.py::test_staticfiles_config_check_occurs_only_once", "tests/test_staticfiles.py::test_staticfiles_prevents_breaking_out_of_directory" ]
2018-10-26 18:55:36+00:00
2,132
encode__starlette-1617
diff --git a/starlette/applications.py b/starlette/applications.py index 8c51544..c3daade 100644 --- a/starlette/applications.py +++ b/starlette/applications.py @@ -1,10 +1,10 @@ import typing from starlette.datastructures import State, URLPath -from starlette.exceptions import ExceptionMiddleware from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.errors import ServerErrorMiddleware +from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import Response from starlette.routing import BaseRoute, Router diff --git a/starlette/exceptions.py b/starlette/exceptions.py index 61039c5..2b5acdd 100644 --- a/starlette/exceptions.py +++ b/starlette/exceptions.py @@ -1,11 +1,8 @@ -import asyncio import http import typing +import warnings -from starlette.concurrency import run_in_threadpool -from starlette.requests import Request -from starlette.responses import PlainTextResponse, Response -from starlette.types import ASGIApp, Message, Receive, Scope, Send +__all__ = ("HTTPException",) class HTTPException(Exception): @@ -26,86 +23,22 @@ class HTTPException(Exception): return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})" -class ExceptionMiddleware: - def __init__( - self, - app: ASGIApp, - handlers: typing.Optional[ - typing.Mapping[typing.Any, typing.Callable[[Request, Exception], Response]] - ] = None, - debug: bool = False, - ) -> None: - self.app = app - self.debug = debug # TODO: We ought to handle 404 cases if debug is set. - self._status_handlers: typing.Dict[int, typing.Callable] = {} - self._exception_handlers: typing.Dict[ - typing.Type[Exception], typing.Callable - ] = {HTTPException: self.http_exception} - if handlers is not None: - for key, value in handlers.items(): - self.add_exception_handler(key, value) - - def add_exception_handler( - self, - exc_class_or_status_code: typing.Union[int, typing.Type[Exception]], - handler: typing.Callable[[Request, Exception], Response], - ) -> None: - if isinstance(exc_class_or_status_code, int): - self._status_handlers[exc_class_or_status_code] = handler - else: - assert issubclass(exc_class_or_status_code, Exception) - self._exception_handlers[exc_class_or_status_code] = handler - - def _lookup_exception_handler( - self, exc: Exception - ) -> typing.Optional[typing.Callable]: - for cls in type(exc).__mro__: - if cls in self._exception_handlers: - return self._exception_handlers[cls] - return None - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] != "http": - await self.app(scope, receive, send) - return +__deprecated__ = "ExceptionMiddleware" - response_started = False - async def sender(message: Message) -> None: - nonlocal response_started +def __getattr__(name: str) -> typing.Any: # pragma: no cover + if name == __deprecated__: + from starlette.middleware.exceptions import ExceptionMiddleware - if message["type"] == "http.response.start": - response_started = True - await send(message) - - try: - await self.app(scope, receive, sender) - except Exception as exc: - handler = None - - if isinstance(exc, HTTPException): - handler = self._status_handlers.get(exc.status_code) - - if handler is None: - handler = self._lookup_exception_handler(exc) - - if handler is None: - raise exc - - if response_started: - msg = "Caught handled exception, but response already started." - raise RuntimeError(msg) from exc + warnings.warn( + f"{__deprecated__} is deprecated on `starlette.exceptions`. " + f"Import it from `starlette.middleware.exceptions` instead.", + category=DeprecationWarning, + stacklevel=3, + ) + return ExceptionMiddleware + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") - request = Request(scope, receive=receive) - if asyncio.iscoroutinefunction(handler): - response = await handler(request, exc) - else: - response = await run_in_threadpool(handler, request, exc) - await response(scope, receive, sender) - def http_exception(self, request: Request, exc: HTTPException) -> Response: - if exc.status_code in {204, 304}: - return Response(status_code=exc.status_code, headers=exc.headers) - return PlainTextResponse( - exc.detail, status_code=exc.status_code, headers=exc.headers - ) +def __dir__() -> typing.List[str]: + return sorted(list(__all__) + [__deprecated__]) # pragma: no cover diff --git a/starlette/formparsers.py b/starlette/formparsers.py index fd19492..4cde71b 100644 --- a/starlette/formparsers.py +++ b/starlette/formparsers.py @@ -38,6 +38,11 @@ def _user_safe_decode(src: bytes, codec: str) -> str: return src.decode("latin-1") +class MultiPartException(Exception): + def __init__(self, message: str) -> None: + self.message = message + + class FormParser: def __init__( self, headers: Headers, stream: typing.AsyncGenerator[bytes, None] @@ -159,7 +164,10 @@ class MultiPartParser: charset = params.get(b"charset", "utf-8") if type(charset) == bytes: charset = charset.decode("latin-1") - boundary = params[b"boundary"] + try: + boundary = params[b"boundary"] + except KeyError: + raise MultiPartException("Missing boundary in multipart.") # Callbacks dictionary. callbacks = { diff --git a/starlette/middleware/exceptions.py b/starlette/middleware/exceptions.py new file mode 100644 index 0000000..a3b4633 --- /dev/null +++ b/starlette/middleware/exceptions.py @@ -0,0 +1,93 @@ +import asyncio +import typing + +from starlette.concurrency import run_in_threadpool +from starlette.exceptions import HTTPException +from starlette.requests import Request +from starlette.responses import PlainTextResponse, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + + +class ExceptionMiddleware: + def __init__( + self, + app: ASGIApp, + handlers: typing.Optional[ + typing.Mapping[typing.Any, typing.Callable[[Request, Exception], Response]] + ] = None, + debug: bool = False, + ) -> None: + self.app = app + self.debug = debug # TODO: We ought to handle 404 cases if debug is set. + self._status_handlers: typing.Dict[int, typing.Callable] = {} + self._exception_handlers: typing.Dict[ + typing.Type[Exception], typing.Callable + ] = {HTTPException: self.http_exception} + if handlers is not None: + for key, value in handlers.items(): + self.add_exception_handler(key, value) + + def add_exception_handler( + self, + exc_class_or_status_code: typing.Union[int, typing.Type[Exception]], + handler: typing.Callable[[Request, Exception], Response], + ) -> None: + if isinstance(exc_class_or_status_code, int): + self._status_handlers[exc_class_or_status_code] = handler + else: + assert issubclass(exc_class_or_status_code, Exception) + self._exception_handlers[exc_class_or_status_code] = handler + + def _lookup_exception_handler( + self, exc: Exception + ) -> typing.Optional[typing.Callable]: + for cls in type(exc).__mro__: + if cls in self._exception_handlers: + return self._exception_handlers[cls] + return None + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + response_started = False + + async def sender(message: Message) -> None: + nonlocal response_started + + if message["type"] == "http.response.start": + response_started = True + await send(message) + + try: + await self.app(scope, receive, sender) + except Exception as exc: + handler = None + + if isinstance(exc, HTTPException): + handler = self._status_handlers.get(exc.status_code) + + if handler is None: + handler = self._lookup_exception_handler(exc) + + if handler is None: + raise exc + + if response_started: + msg = "Caught handled exception, but response already started." + raise RuntimeError(msg) from exc + + request = Request(scope, receive=receive) + if asyncio.iscoroutinefunction(handler): + response = await handler(request, exc) + else: + response = await run_in_threadpool(handler, request, exc) + await response(scope, receive, sender) + + def http_exception(self, request: Request, exc: HTTPException) -> Response: + if exc.status_code in {204, 304}: + return Response(status_code=exc.status_code, headers=exc.headers) + return PlainTextResponse( + exc.detail, status_code=exc.status_code, headers=exc.headers + ) diff --git a/starlette/requests.py b/starlette/requests.py index c738eba..66c510c 100644 --- a/starlette/requests.py +++ b/starlette/requests.py @@ -6,7 +6,8 @@ from http import cookies as http_cookies import anyio from starlette.datastructures import URL, Address, FormData, Headers, QueryParams, State -from starlette.formparsers import FormParser, MultiPartParser +from starlette.exceptions import HTTPException +from starlette.formparsers import FormParser, MultiPartException, MultiPartParser from starlette.types import Message, Receive, Scope, Send try: @@ -250,8 +251,13 @@ class Request(HTTPConnection): content_type_header = self.headers.get("Content-Type") content_type, options = parse_options_header(content_type_header) if content_type == b"multipart/form-data": - multipart_parser = MultiPartParser(self.headers, self.stream()) - self._form = await multipart_parser.parse() + try: + multipart_parser = MultiPartParser(self.headers, self.stream()) + self._form = await multipart_parser.parse() + except MultiPartException as exc: + if "app" in self.scope: + raise HTTPException(status_code=400, detail=exc.message) + raise exc elif content_type == b"application/x-www-form-urlencoded": form_parser = FormParser(self.headers, self.stream()) self._form = await form_parser.parse()
encode/starlette
621abc747a6604825190b93467918a0ec6456a24
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 50f6774..9acd421 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -1,6 +1,9 @@ +import warnings + import pytest -from starlette.exceptions import ExceptionMiddleware, HTTPException +from starlette.exceptions import HTTPException +from starlette.middleware.exceptions import ExceptionMiddleware from starlette.responses import PlainTextResponse from starlette.routing import Route, Router, WebSocketRoute @@ -130,3 +133,16 @@ def test_repr(): assert repr(CustomHTTPException(500, detail="Something custom")) == ( "CustomHTTPException(status_code=500, detail='Something custom')" ) + + +def test_exception_middleware_deprecation() -> None: + # this test should be removed once the deprecation shim is removed + with pytest.warns(DeprecationWarning): + from starlette.exceptions import ExceptionMiddleware # noqa: F401 + + with warnings.catch_warnings(): + warnings.simplefilter("error") + import starlette.exceptions + + with pytest.warns(DeprecationWarning): + starlette.exceptions.ExceptionMiddleware diff --git a/tests/test_formparsers.py b/tests/test_formparsers.py index 3d4b0a1..6710595 100644 --- a/tests/test_formparsers.py +++ b/tests/test_formparsers.py @@ -1,11 +1,15 @@ import os import typing +from contextlib import nullcontext as does_not_raise import pytest -from starlette.formparsers import UploadFile, _user_safe_decode +from starlette.applications import Starlette +from starlette.formparsers import MultiPartException, UploadFile, _user_safe_decode from starlette.requests import Request from starlette.responses import JSONResponse +from starlette.routing import Mount +from starlette.testclient import TestClient class ForceMultipartDict(dict): @@ -390,10 +394,19 @@ def test_user_safe_decode_ignores_wrong_charset(): assert result == "abc" -def test_missing_boundary_parameter(test_client_factory): [email protected]( + "app,expectation", + [ + (app, pytest.raises(MultiPartException)), + (Starlette(routes=[Mount("/", app=app)]), does_not_raise()), + ], +) +def test_missing_boundary_parameter( + app, expectation, test_client_factory: typing.Callable[..., TestClient] +) -> None: client = test_client_factory(app) - with pytest.raises(KeyError, match="boundary"): - client.post( + with expectation: + res = client.post( "/", data=( # file @@ -403,3 +416,5 @@ def test_missing_boundary_parameter(test_client_factory): ), headers={"Content-Type": "multipart/form-data; charset=utf-8"}, ) + assert res.status_code == 400 + assert res.text == "Missing boundary in multipart."
Send 400 on missing `boundary` I did some research about this PR, and to understand if the issue was reasonable. Here's what I've found out: - Flask raises `ValueError` when the `boundary` is not found: https://github.com/pallets/werkzeug/blob/dae7e0d06651e54a74f04e1cf24d806c4e2e9be9/src/werkzeug/formparser.py#L270-L291 - Django raises a custom exception: https://github.com/django/django/blob/abfdb4d7f384fb06ed9b7ca37b548542df7b5dda/django/http/multipartparser.py#L79-L83 - Django also verifies if the `boundary` is valid with https://github.com/python/cpython/blob/27ee43183437c473725eba00def0ea7647688926/Lib/cgi.py#L991-L997 - After that raise, Django catches that exception and raises a 400: https://github.com/django/django/blob/abfdb4d7f384fb06ed9b7ca37b548542df7b5dda/django/core/handlers/exception.py#L84-L94 On Starlette, we raise `KeyError` with "boundary key missing". Although this PR follows the issue that was raised, and it's actually an improvement, I think we should follow Django's lead, and also create a 400 response on this case. _Originally posted by @Kludex in https://github.com/encode/starlette/issues/1544#issuecomment-1080197920_
0.0
[ "tests/test_exceptions.py::test_repr", "tests/test_exceptions.py::test_exception_middleware_deprecation", "tests/test_formparsers.py::test_user_safe_decode_helper", "tests/test_formparsers.py::test_user_safe_decode_ignores_wrong_charset" ]
[]
2022-05-03 05:53:48+00:00
2,133
encode__starlette-173
diff --git a/starlette/routing.py b/starlette/routing.py index 9f29d99..a2b851f 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -8,7 +8,7 @@ from enum import Enum from starlette.datastructures import URL, URLPath from starlette.exceptions import HTTPException from starlette.requests import Request -from starlette.responses import PlainTextResponse +from starlette.responses import PlainTextResponse, RedirectResponse from starlette.types import ASGIApp, ASGIInstance, Receive, Scope, Send from starlette.websockets import WebSocket, WebSocketClose @@ -72,7 +72,9 @@ def get_name(endpoint: typing.Callable) -> str: return endpoint.__class__.__name__ -def replace_params(path: str, **path_params: str) -> typing.Tuple[str, dict]: +def replace_params( + path: str, path_params: typing.Dict[str, str] +) -> typing.Tuple[str, dict]: for key, value in list(path_params.items()): if "{" + key + "}" in path: path_params.pop(key) @@ -95,14 +97,16 @@ class Route(BaseRoute): def __init__( self, path: str, - *, endpoint: typing.Callable, + *, methods: typing.List[str] = None, + name: str = None, include_in_schema: bool = True ) -> None: + assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint - self.name = get_name(endpoint) + self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema if inspect.isfunction(endpoint) or inspect.ismethod(endpoint): @@ -137,7 +141,7 @@ class Route(BaseRoute): def url_path_for(self, name: str, **path_params: str) -> URLPath: if name != self.name or self.param_names != set(path_params.keys()): raise NoMatchFound() - path, remaining_params = replace_params(self.path, **path_params) + path, remaining_params = replace_params(self.path, path_params) assert not remaining_params return URLPath(path=path, protocol="http") @@ -158,10 +162,13 @@ class Route(BaseRoute): class WebSocketRoute(BaseRoute): - def __init__(self, path: str, *, endpoint: typing.Callable) -> None: + def __init__( + self, path: str, endpoint: typing.Callable, *, name: str = None + ) -> None: + assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint - self.name = get_name(endpoint) + self.name = get_name(endpoint) if name is None else name if inspect.isfunction(endpoint) or inspect.ismethod(endpoint): # Endpoint is function or method. Treat it as `func(websocket)`. @@ -189,7 +196,7 @@ class WebSocketRoute(BaseRoute): def url_path_for(self, name: str, **path_params: str) -> URLPath: if name != self.name or self.param_names != set(path_params.keys()): raise NoMatchFound() - path, remaining_params = replace_params(self.path, **path_params) + path, remaining_params = replace_params(self.path, path_params) assert not remaining_params return URLPath(path=path, protocol="websocket") @@ -205,12 +212,14 @@ class WebSocketRoute(BaseRoute): class Mount(BaseRoute): - def __init__(self, path: str, app: ASGIApp) -> None: - self.path = path + def __init__(self, path: str, app: ASGIApp, name: str = None) -> None: + assert path == "" or path.startswith("/"), "Routed paths must always start '/'" + self.path = path.rstrip("/") self.app = app - regex = "^" + path + regex = "^" + self.path + "(?P<path>/.*)$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]*)", regex) self.path_regex = re.compile(regex) + self.name = name @property def routes(self) -> typing.List[BaseRoute]: @@ -219,23 +228,40 @@ class Mount(BaseRoute): def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: match = self.path_regex.match(scope["path"]) if match: + matched_params = match.groupdict() + matched_path = matched_params.pop("path") path_params = dict(scope.get("path_params", {})) - path_params.update(match.groupdict()) + path_params.update(matched_params) child_scope = dict(scope) child_scope["path_params"] = path_params - child_scope["root_path"] = scope.get("root_path", "") + match.string - child_scope["path"] = scope["path"][match.span()[1] :] + child_scope["root_path"] = ( + scope.get("root_path", "") + scope["path"][: -len(matched_path)] + ) + child_scope["path"] = matched_path return Match.FULL, child_scope return Match.NONE, {} def url_path_for(self, name: str, **path_params: str) -> URLPath: - path, remaining_params = replace_params(self.path, **path_params) - for route in self.routes or []: - try: - url = route.url_path_for(name, **remaining_params) - return URLPath(path=path + str(url), protocol=url.protocol) - except NoMatchFound as exc: - pass + if self.name is not None and name == self.name and "path" in path_params: + # 'name' matches "<mount_name>". + path_params["path"] = path_params["path"].lstrip("/") + path, remaining_params = replace_params(self.path + "/{path}", path_params) + if not remaining_params: + return URLPath(path=path, protocol="http") + elif self.name is None or name.startswith(self.name + ":"): + if self.name is None: + # No mount name. + remaining_name = name + else: + # 'name' matches "<mount_name>:<child_name>". + remaining_name = name[len(self.name) + 1 :] + path, remaining_params = replace_params(self.path, path_params) + for route in self.routes or []: + try: + url = route.url_path_for(remaining_name, **remaining_params) + return URLPath(path=path + str(url), protocol=url.protocol) + except NoMatchFound as exc: + pass raise NoMatchFound() def __call__(self, scope: Scope) -> ASGIInstance: @@ -251,9 +277,13 @@ class Mount(BaseRoute): class Router: def __init__( - self, routes: typing.List[BaseRoute] = None, default: ASGIApp = None + self, + routes: typing.List[BaseRoute] = None, + redirect_slashes: bool = True, + default: ASGIApp = None, ) -> None: self.routes = [] if routes is None else routes + self.redirect_slashes = redirect_slashes self.default = self.not_found if default is None else default def mount(self, path: str, app: ASGIApp) -> None: @@ -337,6 +367,17 @@ class Router: if partial is not None: return partial(partial_scope) + + if self.redirect_slashes and not scope["path"].endswith("/"): + redirect_scope = dict(scope) + redirect_scope["path"] += "/" + + for route in self.routes: + match, child_scope = route.matches(redirect_scope) + if match != Match.NONE: + redirect_url = URL(scope=redirect_scope) + return RedirectResponse(url=str(redirect_url)) + return self.default(scope) def __eq__(self, other: typing.Any) -> bool:
encode/starlette
ed970c86be89a497e8082429726ce94dedcc6c0e
diff --git a/tests/test_routing.py b/tests/test_routing.py index 6988b9f..ee2a7f7 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -1,7 +1,7 @@ import pytest from starlette.exceptions import ExceptionMiddleware -from starlette.responses import Response +from starlette.responses import PlainTextResponse, Response from starlette.routing import Mount, NoMatchFound, Route, Router, WebSocketRoute from starlette.testclient import TestClient from starlette.websockets import WebSocket, WebSocketDisconnect @@ -30,7 +30,7 @@ app = Router( Mount( "/users", app=Router( - [Route("", endpoint=users), Route("/{username}", endpoint=user)] + [Route("/", endpoint=users), Route("/{username}", endpoint=user)] ), ), Mount("/static", app=staticfiles), @@ -176,3 +176,32 @@ def test_protocol_switch(): with pytest.raises(WebSocketDisconnect): client.websocket_connect("/404") + + +def ok(request): + return PlainTextResponse("OK") + + +def test_mount_urls(): + mounted = Router([Mount("/users", ok, name="users")]) + client = TestClient(mounted) + assert client.get("/users").status_code == 200 + assert client.get("/users").url == "http://testserver/users/" + assert client.get("/users/").status_code == 200 + assert client.get("/users/a").status_code == 200 + assert client.get("/usersa").status_code == 404 + + +def test_reverse_mount_urls(): + mounted = Router([Mount("/users", ok, name="users")]) + assert mounted.url_path_for("users", path="/a") == "/users/a" + + users = Router([Route("/{username}", ok, name="user")]) + mounted = Router([Mount("/{subpath}/users", users, name="users")]) + assert ( + mounted.url_path_for("users:user", subpath="test", username="tom") + == "/test/users/tom" + ) + assert ( + mounted.url_path_for("users", subpath="test", path="/tom") == "/test/users/tom" + )
[question] how to mount router into Starlette app? `app.mount('/', router)` does't work Example: ```python from starlette.applications import Starlette from starlette.middleware.cors import CORSMiddleware from starlette.requests import Request from starlette.routing import Router, Route import uvicorn from views import FooView app = Starlette(debug=True) # need middleware, so I use Starlette app app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"] ) router = Router([ Route('/foo', endpoint=FooView), ]) app.mount('/', router) # << doesn't work for some reason if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=4000) ```
0.0
[ "tests/test_routing.py::test_router", "tests/test_routing.py::test_mount_urls", "tests/test_routing.py::test_reverse_mount_urls" ]
[ "tests/test_routing.py::test_url_path_for", "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_router_add_route", "tests/test_routing.py::test_router_duplicate_path", "tests/test_routing.py::test_router_add_websocket_route", "tests/test_routing.py::test_protocol_switch" ]
2018-11-01 16:43:44+00:00
2,134
encode__starlette-195
diff --git a/docs/staticfiles.md b/docs/staticfiles.md index 448cc3b..cc8db5e 100644 --- a/docs/staticfiles.md +++ b/docs/staticfiles.md @@ -1,7 +1,12 @@ -Starlette also includes a `StaticFiles` class for serving a specific directory: +Starlette also includes a `StaticFiles` class for serving files in a given directory: -* `StaticFiles(directory)` - Serve any files in the given `directory`. +### StaticFiles + +Signature: `StaticFiles(directory, check_dir=True)` + +* `directory` - A string denoting the directory path +* `check_dir` - Ensure that the directory exists upon instantiation. Defaults to `True` You can combine this ASGI application with Starlette's routing to provide comprehensive static file serving. diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py index 8a7527a..ec2418e 100644 --- a/starlette/staticfiles.py +++ b/starlette/staticfiles.py @@ -8,7 +8,9 @@ from starlette.types import ASGIInstance, Receive, Scope, Send class StaticFiles: - def __init__(self, *, directory: str) -> None: + def __init__(self, *, directory: str, check_dir: bool = True) -> None: + if check_dir and not os.path.isdir(directory): + raise RuntimeError("Directory '%s' does not exist" % directory) self.directory = directory self.config_checked = False
encode/starlette
58888bb53fa54991479d8a9a4c32d6b41b334b2c
diff --git a/tests/test_staticfiles.py b/tests/test_staticfiles.py index 9d12de8..84f3368 100644 --- a/tests/test_staticfiles.py +++ b/tests/test_staticfiles.py @@ -54,9 +54,16 @@ def test_staticfiles_with_missing_file_returns_404(tmpdir): assert response.text == "Not Found" +def test_staticfiles_instantiated_with_missing_directory(tmpdir): + with pytest.raises(RuntimeError) as exc: + path = os.path.join(tmpdir, "no_such_directory") + app = StaticFiles(directory=path) + assert "does not exist" in str(exc) + + def test_staticfiles_configured_with_missing_directory(tmpdir): path = os.path.join(tmpdir, "no_such_directory") - app = StaticFiles(directory=path) + app = StaticFiles(directory=path, check_dir=False) client = TestClient(app) with pytest.raises(RuntimeError) as exc: client.get("/example.txt") @@ -68,7 +75,7 @@ def test_staticfiles_configured_with_file_instead_of_directory(tmpdir): with open(path, "w") as file: file.write("<file content>") - app = StaticFiles(directory=path) + app = StaticFiles(directory=path, check_dir=False) client = TestClient(app) with pytest.raises(RuntimeError) as exc: client.get("/example.txt")
Check directory exists when instantiating `StaticFiles` The `StaticFiles` application should ensure that the directory exists at the point it is instantiated. (With an optional switch to turn this behavior off)
0.0
[ "tests/test_staticfiles.py::test_staticfiles_instantiated_with_missing_directory", "tests/test_staticfiles.py::test_staticfiles_configured_with_missing_directory", "tests/test_staticfiles.py::test_staticfiles_configured_with_file_instead_of_directory" ]
[ "tests/test_staticfiles.py::test_staticfiles", "tests/test_staticfiles.py::test_staticfiles_post", "tests/test_staticfiles.py::test_staticfiles_with_directory_returns_404", "tests/test_staticfiles.py::test_staticfiles_with_missing_file_returns_404", "tests/test_staticfiles.py::test_staticfiles_config_check_occurs_only_once", "tests/test_staticfiles.py::test_staticfiles_prevents_breaking_out_of_directory" ]
2018-11-08 00:23:17+00:00
2,135
encode__starlette-208
diff --git a/starlette/responses.py b/starlette/responses.py index a6ebe8c..4390c29 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -31,13 +31,16 @@ class Response: def __init__( self, - content: typing.Any, + content: typing.Any = None, status_code: int = 200, headers: dict = None, media_type: str = None, background: BackgroundTask = None, ) -> None: - self.body = self.render(content) + if content is None: + self.body = b"" + else: + self.body = self.render(content) self.status_code = status_code if media_type is not None: self.media_type = media_type @@ -63,8 +66,8 @@ class Response: populate_content_length = b"content-length" in keys populate_content_type = b"content-type" in keys - body = getattr(self, "body", None) - if body is not None and populate_content_length: + body = getattr(self, "body", b"") + if body and populate_content_length: content_length = str(len(body)) raw_headers.append((b"content-length", content_length.encode("latin-1")))
encode/starlette
3a16d660490b54daad5711749fa00fd7a0970b4e
diff --git a/tests/test_responses.py b/tests/test_responses.py index 7e23e29..e68958e 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -126,11 +126,11 @@ def test_response_headers(): def test_response_phrase(): def app(scope): - return Response(b"", status_code=200) + return Response(status_code=204) client = TestClient(app) response = client.get("/") - assert response.reason == "OK" + assert response.reason == "No Content" def app(scope): return Response(b"", status_code=123)
the raw "Response" should'nt mandatory a content ... no ? I need to manage myself the etag/304 response ... to send a 304 if-none-match, I use : Response(status_code=304,content="",headers=rheaders) But the body content should not be written ... here the content is mandatory : None cause troubble, and empty string is an empty string ...
0.0
[ "tests/test_responses.py::test_response_phrase" ]
[ "tests/test_responses.py::test_text_response", "tests/test_responses.py::test_bytes_response", "tests/test_responses.py::test_ujson_response", "tests/test_responses.py::test_redirect_response", "tests/test_responses.py::test_streaming_response", "tests/test_responses.py::test_response_headers", "tests/test_responses.py::test_file_response", "tests/test_responses.py::test_file_response_with_directory_raises_error", "tests/test_responses.py::test_file_response_with_missing_file_raises_error", "tests/test_responses.py::test_set_cookie", "tests/test_responses.py::test_delete_cookie" ]
2018-11-09 17:57:50+00:00
2,136
encode__starlette-221
diff --git a/starlette/__init__.py b/starlette/__init__.py index 732155f..fa3ddd8 100644 --- a/starlette/__init__.py +++ b/starlette/__init__.py @@ -1,1 +1,1 @@ -__version__ = "0.8.3" +__version__ = "0.8.4" diff --git a/starlette/convertors.py b/starlette/convertors.py new file mode 100644 index 0000000..854f3a7 --- /dev/null +++ b/starlette/convertors.py @@ -0,0 +1,69 @@ +import math +import typing + + +class Convertor: + regex = "" + + def convert(self, value: str) -> typing.Any: + raise NotImplementedError() # pragma: no cover + + def to_string(self, value: typing.Any) -> str: + raise NotImplementedError() # pragma: no cover + + +class StringConvertor(Convertor): + regex = "[^/]+" + + def convert(self, value: str) -> typing.Any: + return value + + def to_string(self, value: typing.Any) -> str: + value = str(value) + assert "/" not in value, "May not contain path seperators" + assert value, "Must not be empty" + return value + + +class PathConvertor(Convertor): + regex = ".*" + + def convert(self, value: str) -> typing.Any: + return str(value) + + def to_string(self, value: typing.Any) -> str: + return str(value) + + +class IntegerConvertor(Convertor): + regex = "[0-9]+" + + def convert(self, value: str) -> typing.Any: + return int(value) + + def to_string(self, value: typing.Any) -> str: + value = int(value) + assert value >= 0, "Negative integers are not supported" + return str(value) + + +class FloatConvertor(Convertor): + regex = "[0-9]+(.[0-9]+)?" + + def convert(self, value: str) -> typing.Any: + return float(value) + + def to_string(self, value: typing.Any) -> str: + value = float(value) + assert value >= 0.0, "Negative floats are not supported" + assert not math.isnan(value), "NaN values are not supported" + assert not math.isinf(value), "Infinite values are not supported" + return ("%0.20f" % value).rstrip("0").rstrip(".") + + +CONVERTOR_TYPES = { + "str": StringConvertor(), + "path": PathConvertor(), + "int": IntegerConvertor(), + "float": FloatConvertor(), +} diff --git a/starlette/routing.py b/starlette/routing.py index c6b6e98..2b799e2 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -6,6 +6,7 @@ from concurrent.futures import ThreadPoolExecutor from enum import Enum from starlette.concurrency import run_in_threadpool +from starlette.convertors import CONVERTOR_TYPES, Convertor from starlette.datastructures import URL, URLPath from starlette.exceptions import HTTPException from starlette.requests import Request @@ -73,15 +74,22 @@ def get_name(endpoint: typing.Callable) -> str: def replace_params( - path: str, path_params: typing.Dict[str, str] + path: str, + param_convertors: typing.Dict[str, Convertor], + path_params: typing.Dict[str, str], ) -> typing.Tuple[str, dict]: for key, value in list(path_params.items()): if "{" + key + "}" in path: - path_params.pop(key) + convertor = param_convertors[key] + value = convertor.to_string(value) path = path.replace("{" + key + "}", value) + path_params.pop(key) return path, path_params +PARAM_REGEX = re.compile("{([a-zA-Z_][a-zA-Z0-9_]*)(:[a-zA-Z_][a-zA-Z0-9_]*)?}") + + class BaseRoute: def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: raise NotImplementedError() # pragma: no cover @@ -92,6 +100,45 @@ class BaseRoute: def __call__(self, scope: Scope) -> ASGIInstance: raise NotImplementedError() # pragma: no cover + def compile_path( + self, path: str + ) -> typing.Tuple[typing.Pattern, str, typing.Dict[str, Convertor]]: + """ + Given a path string, like: "/{username:str}", return a three-tuple + of (regex, format, {param_name:convertor}). + + regex: "/(?P<username>[^/]+)" + format: "/{username}" + convertors: {"username": StringConvertor()} + """ + path_regex = "^" + path_format = "" + + idx = 0 + param_convertors = {} + for match in PARAM_REGEX.finditer(path): + param_name, convertor_type = match.groups("str") + convertor_type = convertor_type.lstrip(":") + assert convertor_type in CONVERTOR_TYPES, ( + "Unknown path convertor '%s'" % convertor_type + ) + convertor = CONVERTOR_TYPES[convertor_type] + + path_regex += path[idx : match.start()] + path_regex += "(?P<%s>%s)" % (param_name, convertor.regex) + + path_format += path[idx : match.start()] + path_format += "{%s}" % param_name + + param_convertors[param_name] = convertor + + idx = match.end() + + path_regex += path[idx:] + "$" + path_format += path[idx:] + + return re.compile(path_regex), path_format, param_convertors + class Route(BaseRoute): def __init__( @@ -119,17 +166,19 @@ class Route(BaseRoute): self.app = endpoint self.methods = methods - regex = "^" + path + "$" - regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) - self.path_regex = re.compile(regex) - self.param_names = set(self.path_regex.groupindex.keys()) + self.path_regex, self.path_format, self.param_convertors = self.compile_path( + path + ) def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: if scope["type"] == "http": match = self.path_regex.match(scope["path"]) if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) path_params = dict(scope.get("path_params", {})) - path_params.update(match.groupdict()) + path_params.update(matched_params) child_scope = {"endpoint": self.endpoint, "path_params": path_params} if self.methods and scope["method"] not in self.methods: return Match.PARTIAL, child_scope @@ -138,9 +187,15 @@ class Route(BaseRoute): return Match.NONE, {} def url_path_for(self, name: str, **path_params: str) -> URLPath: - if name != self.name or self.param_names != set(path_params.keys()): + seen_params = set(path_params.keys()) + expected_params = set(self.param_convertors.keys()) + + if name != self.name or seen_params != expected_params: raise NoMatchFound() - path, remaining_params = replace_params(self.path, path_params) + + path, remaining_params = replace_params( + self.path_format, self.param_convertors, path_params + ) assert not remaining_params return URLPath(path=path, protocol="http") @@ -178,23 +233,33 @@ class WebSocketRoute(BaseRoute): regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) - self.path_regex = re.compile(regex) - self.param_names = set(self.path_regex.groupindex.keys()) + self.path_regex, self.path_format, self.param_convertors = self.compile_path( + path + ) def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: if scope["type"] == "websocket": match = self.path_regex.match(scope["path"]) if match: + matched_params = match.groupdict() + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) path_params = dict(scope.get("path_params", {})) - path_params.update(match.groupdict()) + path_params.update(matched_params) child_scope = {"endpoint": self.endpoint, "path_params": path_params} return Match.FULL, child_scope return Match.NONE, {} def url_path_for(self, name: str, **path_params: str) -> URLPath: - if name != self.name or self.param_names != set(path_params.keys()): + seen_params = set(path_params.keys()) + expected_params = set(self.param_convertors.keys()) + + if name != self.name or seen_params != expected_params: raise NoMatchFound() - path, remaining_params = replace_params(self.path, path_params) + + path, remaining_params = replace_params( + self.path_format, self.param_convertors, path_params + ) assert not remaining_params return URLPath(path=path, protocol="websocket") @@ -214,10 +279,10 @@ class Mount(BaseRoute): assert path == "" or path.startswith("/"), "Routed paths must always start '/'" self.path = path.rstrip("/") self.app = app - regex = "^" + self.path + "(?P<path>/.*)$" - regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]*)", regex) - self.path_regex = re.compile(regex) self.name = name + self.path_regex, self.path_format, self.param_convertors = self.compile_path( + path + "/{path:path}" + ) @property def routes(self) -> typing.List[BaseRoute]: @@ -228,7 +293,9 @@ class Mount(BaseRoute): match = self.path_regex.match(path) if match: matched_params = match.groupdict() - remaining_path = matched_params.pop("path") + for key, value in matched_params.items(): + matched_params[key] = self.param_convertors[key].convert(value) + remaining_path = "/" + matched_params.pop("path") matched_path = path[: -len(remaining_path)] path_params = dict(scope.get("path_params", {})) path_params.update(matched_params) @@ -245,7 +312,9 @@ class Mount(BaseRoute): if self.name is not None and name == self.name and "path" in path_params: # 'name' matches "<mount_name>". path_params["path"] = path_params["path"].lstrip("/") - path, remaining_params = replace_params(self.path + "/{path}", path_params) + path, remaining_params = replace_params( + self.path_format, self.param_convertors, path_params + ) if not remaining_params: return URLPath(path=path, protocol="http") elif self.name is None or name.startswith(self.name + ":"): @@ -255,11 +324,16 @@ class Mount(BaseRoute): else: # 'name' matches "<mount_name>:<child_name>". remaining_name = name[len(self.name) + 1 :] - path, remaining_params = replace_params(self.path, path_params) + path_params["path"] = "" + path, remaining_params = replace_params( + self.path_format, self.param_convertors, path_params + ) for route in self.routes or []: try: url = route.url_path_for(remaining_name, **remaining_params) - return URLPath(path=path + str(url), protocol=url.protocol) + return URLPath( + path=path.rstrip("/") + str(url), protocol=url.protocol + ) except NoMatchFound as exc: pass raise NoMatchFound()
encode/starlette
a0bb1f5f231d8763c570876374c29ce89a83d4be
diff --git a/tests/test_routing.py b/tests/test_routing.py index ee2a7f7..2d14392 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -1,7 +1,7 @@ import pytest from starlette.exceptions import ExceptionMiddleware -from starlette.responses import PlainTextResponse, Response +from starlette.responses import JSONResponse, PlainTextResponse, Response from starlette.routing import Mount, NoMatchFound, Route, Router, WebSocketRoute from starlette.testclient import TestClient from starlette.websockets import WebSocket, WebSocketDisconnect @@ -48,6 +48,24 @@ def contact(request): return Response("Hello, POST!", media_type="text/plain") [email protected]("/int/{param:int}", name="int-convertor") +def int_convertor(request): + number = request.path_params["param"] + return JSONResponse({"int": number}) + + [email protected]("/float/{param:float}", name="float-convertor") +def float_convertor(request): + num = request.path_params["param"] + return JSONResponse({"float": num}) + + [email protected]("/path/{param:path}", name="path-convertor") +def path_convertor(request): + path = request.path_params["param"] + return JSONResponse({"path": path}) + + @app.websocket_route("/ws") async def websocket_endpoint(session): await session.accept() @@ -91,12 +109,38 @@ def test_router(): assert response.text == "xxxxx" +def test_route_converters(): + # Test integer conversion + response = client.get("/int/5") + assert response.status_code == 200 + assert response.json() == {"int": 5} + assert app.url_path_for("int-convertor", param=5) == "/int/5" + + # Test float conversion + response = client.get("/float/25.5") + assert response.status_code == 200 + assert response.json() == {"float": 25.5} + assert app.url_path_for("float-convertor", param=25.5) == "/float/25.5" + + # Test path conversion + response = client.get("/path/some/example") + assert response.status_code == 200 + assert response.json() == {"path": "some/example"} + assert ( + app.url_path_for("path-convertor", param="some/example") == "/path/some/example" + ) + + def test_url_path_for(): assert app.url_path_for("homepage") == "/" assert app.url_path_for("user", username="tomchristie") == "/users/tomchristie" assert app.url_path_for("websocket_endpoint") == "/ws" with pytest.raises(NoMatchFound): assert app.url_path_for("broken") + with pytest.raises(AssertionError): + app.url_path_for("user", username="tom/christie") + with pytest.raises(AssertionError): + app.url_path_for("user", username="") def test_url_for():
Support route convertors Hi, I've just discovered starlette (seems to be the perfect asgi fw ! great) Looking into docs/unitests ... but it seems that regex routing is not implemented yet (will look into the code) Is it possible to declare something like that ? ```python @app.route("/api/{name:.*}") def ... ``` It's the only thing it seems to miss (to quit aiohttp)
0.0
[ "tests/test_routing.py::test_route_converters", "tests/test_routing.py::test_url_path_for" ]
[ "tests/test_routing.py::test_router", "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_router_add_route", "tests/test_routing.py::test_router_duplicate_path", "tests/test_routing.py::test_router_add_websocket_route", "tests/test_routing.py::test_protocol_switch", "tests/test_routing.py::test_mount_urls", "tests/test_routing.py::test_reverse_mount_urls" ]
2018-11-16 13:08:29+00:00
2,137
encode__starlette-2231
diff --git a/requirements.txt b/requirements.txt index 65e2408..4794d12 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,8 +12,8 @@ types-contextvars==2.4.7.2 types-PyYAML==6.0.12.10 types-dataclasses==0.6.6 pytest==7.4.0 -trio==0.22.1 -anyio@git+https://github.com/agronholm/anyio.git +trio==0.21.0 +anyio==3.7.1 # Documentation mkdocs==1.4.3 diff --git a/starlette/_utils.py b/starlette/_utils.py index f06dd55..26854f3 100644 --- a/starlette/_utils.py +++ b/starlette/_utils.py @@ -2,12 +2,20 @@ import asyncio import functools import sys import typing +from contextlib import contextmanager if sys.version_info >= (3, 10): # pragma: no cover from typing import TypeGuard else: # pragma: no cover from typing_extensions import TypeGuard +has_exceptiongroups = True +if sys.version_info < (3, 11): # pragma: no cover + try: + from exceptiongroup import BaseExceptionGroup + except ImportError: + has_exceptiongroups = False + T = typing.TypeVar("T") AwaitableCallable = typing.Callable[..., typing.Awaitable[T]] @@ -66,3 +74,15 @@ class AwaitableOrContextManagerWrapper(typing.Generic[SupportsAsyncCloseType]): async def __aexit__(self, *args: typing.Any) -> typing.Union[None, bool]: await self.entered.close() return None + + +@contextmanager +def collapse_excgroups() -> typing.Generator[None, None, None]: + try: + yield + except BaseException as exc: + if has_exceptiongroups: + while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1: + exc = exc.exceptions[0] # pragma: no cover + + raise exc diff --git a/starlette/middleware/base.py b/starlette/middleware/base.py index ee99ee6..ad3ffcf 100644 --- a/starlette/middleware/base.py +++ b/starlette/middleware/base.py @@ -1,18 +1,14 @@ -import sys import typing -from contextlib import contextmanager import anyio from anyio.abc import ObjectReceiveStream, ObjectSendStream +from starlette._utils import collapse_excgroups from starlette.background import BackgroundTask from starlette.requests import ClientDisconnect, Request from starlette.responses import ContentStream, Response, StreamingResponse from starlette.types import ASGIApp, Message, Receive, Scope, Send -if sys.version_info < (3, 11): # pragma: no cover - from exceptiongroup import BaseExceptionGroup - RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, RequestResponseEndpoint], typing.Awaitable[Response] @@ -20,17 +16,6 @@ DispatchFunction = typing.Callable[ T = typing.TypeVar("T") -@contextmanager -def _convert_excgroups() -> typing.Generator[None, None, None]: - try: - yield - except BaseException as exc: - while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1: - exc = exc.exceptions[0] - - raise exc - - class _CachedRequest(Request): """ If the user calls Request.body() from their dispatch function @@ -201,7 +186,7 @@ class BaseHTTPMiddleware: response.raw_headers = message["headers"] return response - with _convert_excgroups(): + with collapse_excgroups(): async with anyio.create_task_group() as task_group: response = await self.dispatch_func(request, call_next) await response(scope, wrapped_receive, send)
encode/starlette
a8b8856ce393a82ab4a714131085dbc4d658e34d
diff --git a/tests/middleware/test_wsgi.py b/tests/middleware/test_wsgi.py index ad39754..fe527e3 100644 --- a/tests/middleware/test_wsgi.py +++ b/tests/middleware/test_wsgi.py @@ -2,11 +2,9 @@ import sys import pytest +from starlette._utils import collapse_excgroups from starlette.middleware.wsgi import WSGIMiddleware, build_environ -if sys.version_info < (3, 11): # pragma: no cover - from exceptiongroup import ExceptionGroup - def hello_world(environ, start_response): status = "200 OK" @@ -69,12 +67,9 @@ def test_wsgi_exception(test_client_factory): # The HTTP protocol implementations would catch this error and return 500. app = WSGIMiddleware(raise_exception) client = test_client_factory(app) - with pytest.raises(ExceptionGroup) as exc: + with pytest.raises(RuntimeError), collapse_excgroups(): client.get("/") - assert len(exc.value.exceptions) == 1 - assert isinstance(exc.value.exceptions[0], RuntimeError) - def test_wsgi_exc_info(test_client_factory): # Note that we're testing the WSGI app directly here.
No module named 'exceptiongroup' when upgraded to starlette 0.31.0 After upgrading to starlette 0.31.0 today, we run into the following exception when importing starlette: ``` from starlette import applications, requests, responses, routing 2023-07-24 15:47:43 File "/opt/conda/lib/python3.8/site-packages/starlette/applications.py", line 8, in <module> 2023-07-24 15:47:43 from starlette.middleware.base import BaseHTTPMiddleware 2023-07-24 15:47:43 File "/opt/conda/lib/python3.8/site-packages/starlette/middleware/base.py", line 14, in <module> 2023-07-24 15:47:43 from exceptiongroup import BaseExceptionGroup 2023-07-24 15:47:43 ModuleNotFoundError: No module named 'exceptiongroup' ``` This is likely introduced from https://github.com/encode/starlette/pull/2211/files
0.0
[ "tests/middleware/test_wsgi.py::test_wsgi_get[asyncio]", "tests/middleware/test_wsgi.py::test_wsgi_post[asyncio]", "tests/middleware/test_wsgi.py::test_wsgi_exception[asyncio]", "tests/middleware/test_wsgi.py::test_wsgi_exc_info[asyncio]", "tests/middleware/test_wsgi.py::test_build_environ", "tests/middleware/test_wsgi.py::test_build_environ_encoding" ]
[]
2023-07-26 20:17:03+00:00
2,138
encode__starlette-2334
diff --git a/starlette/responses.py b/starlette/responses.py index 507e79b..b33aa86 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -311,7 +311,7 @@ class FileResponse(Response): content_length = str(stat_result.st_size) last_modified = formatdate(stat_result.st_mtime, usegmt=True) etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size) - etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False) + etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"' self.headers.setdefault("content-length", content_length) self.headers.setdefault("last-modified", last_modified) diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py index 30fbc11..895105a 100644 --- a/starlette/staticfiles.py +++ b/starlette/staticfiles.py @@ -225,7 +225,7 @@ class StaticFiles: try: if_none_match = request_headers["if-none-match"] etag = response_headers["etag"] - if if_none_match == etag: + if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]: return True except KeyError: pass
encode/starlette
efa03ebd64b9a1927cb6d0da61784b400fa5a0de
diff --git a/tests/test_staticfiles.py b/tests/test_staticfiles.py index 23d0b57..2bb7305 100644 --- a/tests/test_staticfiles.py +++ b/tests/test_staticfiles.py @@ -208,6 +208,11 @@ def test_staticfiles_304_with_etag_match(tmpdir, test_client_factory): second_resp = client.get("/example.txt", headers={"if-none-match": last_etag}) assert second_resp.status_code == 304 assert second_resp.content == b"" + second_resp = client.get( + "/example.txt", headers={"if-none-match": f'W/{last_etag}, "123"'} + ) + assert second_resp.status_code == 304 + assert second_resp.content == b"" def test_staticfiles_304_with_last_modified_compare_last_req(
Strong and weak etags for StaticFiles ### Discussed in https://github.com/encode/starlette/discussions/2297 <div type='discussions-op-text'> <sup>Originally posted by **markus1978** October 6, 2023</sup> tl;tr: It seems that `starlette.staticfiles.StaticFiles` does not use "proper" HTTP etags which causes issues with reverse proxies and browsers. The `starlette.staticfiles.StaticFiles` class supports etags, e.g. it creates a `Etag` header in all responses and considers `If-None-Match` headers in its `is_not_modified` method. However, it only puts the plain hash values in the response `Etag` header and also only interprets `If-None-Match` values as plain hash values . HTTP Etags are either weak or strong and the values are supposed to be wrapped in `W/"..."` or `"..."` respectively (https://datatracker.ietf.org/doc/html/rfc7232#section-2.3.1). This causes two problems for me. First, nginx as a reverse proxy is considering all starlette etag headers as weak etags and the gzip module removes. Secondly, when the browser sends a strong or weak etag in the `If-None-Match` header, it never matches because `'...some-tag...' != '"...some-tag..."'`. I currently use this work arround to solve my issues: ```python class StaticFiles(StarletteStaticFiles): etag_re = r'^(W/)?"?([^"]*)"?$' def is_not_modified( self, response_headers: Headers, request_headers: Headers ) -> bool: try: if_none_match = request_headers["if-none-match"] # I remove all weak/strong etag syntax, basically doing a weak match match = re.match(StaticFiles.etag_re, if_none_match) if_none_match = match.group(2) etag = response_headers["etag"] if if_none_match == etag: return True except KeyError: pass return super().is_not_modified(response_headers, request_headers) def file_response( self, full_path: PathLike, stat_result: os.stat_result, scope: Scope, status_code: int = 200, ) -> Response: response = super().file_response(full_path, stat_result, scope, status_code) # I add strong etag syntax, basically wrapping the etag value in "..." if 'etag' in response.headers: response.headers['etag'] = f'"{response.headers.get("etag")}"' return response ``` I am not an expert in etags, just trying to make it work in our app. I am glad for any hints, if i am getting it wrong or missing anything here. For reference, the relevant part from the current starlette. From `staticfiles.py::StaticFiles` ```python def is_not_modified( self, response_headers: Headers, request_headers: Headers ) -> bool: """ Given the request and response headers, return `True` if an HTTP "Not Modified" response could be returned instead. """ try: if_none_match = request_headers["if-none-match"] etag = response_headers["etag"] if if_none_match == etag: return True except KeyError: pass try: if_modified_since = parsedate(request_headers["if-modified-since"]) last_modified = parsedate(response_headers["last-modified"]) if ( if_modified_since is not None and last_modified is not None and if_modified_since >= last_modified ): return True except KeyError: pass return False ``` From `responses.py::FileResponse` ```python def set_stat_headers(self, stat_result: os.stat_result) -> None: content_length = str(stat_result.st_size) last_modified = formatdate(stat_result.st_mtime, usegmt=True) etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size) etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False) self.headers.setdefault("content-length", content_length) self.headers.setdefault("last-modified", last_modified) self.headers.setdefault("etag", etag) ```</div> <!-- POLAR PLEDGE BADGE START --> > [!IMPORTANT] > - We're using [Polar.sh](https://polar.sh/encode) so you can upvote and help fund this issue. > - We receive the funding once the issue is completed & confirmed by you. > - Thank you in advance for helping prioritize & fund our backlog. <a href="https://polar.sh/encode/starlette/issues/2298"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/encode/starlette/issues/2298/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/encode/starlette/issues/2298/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END -->
0.0
[ "tests/test_staticfiles.py::test_staticfiles_304_with_etag_match[asyncio]" ]
[ "tests/test_staticfiles.py::test_staticfiles[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_pathlib[asyncio]", "tests/test_staticfiles.py::test_staticfiles_head_with_middleware[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_package[asyncio]", "tests/test_staticfiles.py::test_staticfiles_post[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_directory_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_file_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_configured_with_missing_directory[asyncio]", "tests/test_staticfiles.py::test_staticfiles_configured_with_file_instead_of_directory[asyncio]", "tests/test_staticfiles.py::test_staticfiles_config_check_occurs_only_once[asyncio]", "tests/test_staticfiles.py::test_staticfiles_never_read_file_for_head_method[asyncio]", "tests/test_staticfiles.py::test_staticfiles_304_with_last_modified_compare_last_req[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_normal[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_without_index[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_without_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_html_only_files[asyncio]", "tests/test_staticfiles.py::test_staticfiles_cache_invalidation_for_deleted_file_html_mode[asyncio]", "tests/test_staticfiles.py::test_staticfiles_with_missing_dir_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_access_file_as_dir_returns_404[asyncio]", "tests/test_staticfiles.py::test_staticfiles_unhandled_os_error_returns_500[asyncio]", "tests/test_staticfiles.py::test_staticfiles_follows_symlinks[asyncio]", "tests/test_staticfiles.py::test_staticfiles_follows_symlink_directories[asyncio]", "tests/test_staticfiles.py::test_staticfiles_instantiated_with_missing_directory", "tests/test_staticfiles.py::test_staticfiles_prevents_breaking_out_of_directory", "tests/test_staticfiles.py::test_staticfiles_disallows_path_traversal_with_symlinks", "tests/test_staticfiles.py::test_staticfiles_avoids_path_traversal" ]
2023-11-12 05:56:52+00:00
2,139
encode__starlette-2352
diff --git a/starlette/requests.py b/starlette/requests.py index 5c7a429..83a52ac 100644 --- a/starlette/requests.py +++ b/starlette/requests.py @@ -101,9 +101,7 @@ class HTTPConnection(typing.Mapping[str, typing.Any]): base_url_scope = dict(self.scope) base_url_scope["path"] = "/" base_url_scope["query_string"] = b"" - base_url_scope["root_path"] = base_url_scope.get( - "app_root_path", base_url_scope.get("root_path", "") - ) + base_url_scope["root_path"] = base_url_scope.get("root_path", "") self._base_url = URL(scope=base_url_scope) return self._base_url diff --git a/starlette/routing.py b/starlette/routing.py index cb1b1d9..b167f35 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -251,8 +251,11 @@ class Route(BaseRoute): self.path_regex, self.path_format, self.param_convertors = compile_path(path) def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: + path_params: "typing.Dict[str, typing.Any]" if scope["type"] == "http": - match = self.path_regex.match(scope["path"]) + root_path = scope.get("route_root_path", scope.get("root_path", "")) + path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"])) + match = self.path_regex.match(path) if match: matched_params = match.groupdict() for key, value in matched_params.items(): @@ -338,8 +341,11 @@ class WebSocketRoute(BaseRoute): self.path_regex, self.path_format, self.param_convertors = compile_path(path) def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: + path_params: "typing.Dict[str, typing.Any]" if scope["type"] == "websocket": - match = self.path_regex.match(scope["path"]) + root_path = scope.get("route_root_path", scope.get("root_path", "")) + path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"])) + match = self.path_regex.match(path) if match: matched_params = match.groupdict() for key, value in matched_params.items(): @@ -410,23 +416,25 @@ class Mount(BaseRoute): return getattr(self._base_app, "routes", []) def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]: + path_params: "typing.Dict[str, typing.Any]" if scope["type"] in ("http", "websocket"): path = scope["path"] - match = self.path_regex.match(path) + root_path = scope.get("route_root_path", scope.get("root_path", "")) + route_path = scope.get("route_path", re.sub(r"^" + root_path, "", path)) + match = self.path_regex.match(route_path) if match: matched_params = match.groupdict() for key, value in matched_params.items(): matched_params[key] = self.param_convertors[key].convert(value) remaining_path = "/" + matched_params.pop("path") - matched_path = path[: -len(remaining_path)] + matched_path = route_path[: -len(remaining_path)] path_params = dict(scope.get("path_params", {})) path_params.update(matched_params) root_path = scope.get("root_path", "") child_scope = { "path_params": path_params, - "app_root_path": scope.get("app_root_path", root_path), - "root_path": root_path + matched_path, - "path": remaining_path, + "route_root_path": root_path + matched_path, + "route_path": remaining_path, "endpoint": self.app, } return Match.FULL, child_scope @@ -767,11 +775,15 @@ class Router: await partial.handle(scope, receive, send) return - if scope["type"] == "http" and self.redirect_slashes and scope["path"] != "/": + root_path = scope.get("route_root_path", scope.get("root_path", "")) + path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"])) + if scope["type"] == "http" and self.redirect_slashes and path != "/": redirect_scope = dict(scope) - if scope["path"].endswith("/"): + if path.endswith("/"): + redirect_scope["route_path"] = path.rstrip("/") redirect_scope["path"] = redirect_scope["path"].rstrip("/") else: + redirect_scope["route_path"] = path + "/" redirect_scope["path"] = redirect_scope["path"] + "/" for route in self.routes: diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py index 2f1f1dd..f36d586 100644 --- a/starlette/staticfiles.py +++ b/starlette/staticfiles.py @@ -1,5 +1,6 @@ import importlib.util import os +import re import stat import typing from email.utils import parsedate @@ -108,7 +109,9 @@ class StaticFiles: Given the ASGI scope, return the `path` string to serve up, with OS specific path separators, and any '..', '.' components removed. """ - return os.path.normpath(os.path.join(*scope["path"].split("/"))) # type: ignore[no-any-return] # noqa: E501 + root_path = scope.get("route_root_path", scope.get("root_path", "")) + path = scope.get("route_path", re.sub(r"^" + root_path, "", scope["path"])) + return os.path.normpath(os.path.join(*path.split("/"))) # type: ignore[no-any-return] # noqa: E501 async def get_response(self, path: str, scope: Scope) -> Response: """
encode/starlette
164b35021654107cea51ce0a66191f7691855cbe
diff --git a/tests/test_routing.py b/tests/test_routing.py index 7644f5a..1e99e33 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -159,7 +159,7 @@ app = Router( @pytest.fixture -def client(test_client_factory): +def client(test_client_factory: typing.Callable[..., TestClient]): with test_client_factory(app) as client: yield client @@ -170,7 +170,7 @@ def client(test_client_factory): r":UserWarning" r":charset_normalizer.api" ) -def test_router(client): +def test_router(client: TestClient): response = client.get("/") assert response.status_code == 200 assert response.text == "Hello, world" @@ -1210,3 +1210,57 @@ def test_decorator_deprecations() -> None: ... # pragma: nocover router.on_event("startup")(startup) + + +async def echo_paths(request: Request, name: str): + return JSONResponse( + { + "name": name, + "path": request.scope["path"], + "root_path": request.scope["root_path"], + } + ) + + +echo_paths_routes = [ + Route( + "/path", + functools.partial(echo_paths, name="path"), + name="path", + methods=["GET"], + ), + Mount( + "/root", + name="mount", + routes=[ + Route( + "/path", + functools.partial(echo_paths, name="subpath"), + name="subpath", + methods=["GET"], + ) + ], + ), +] + + +def test_paths_with_root_path(test_client_factory: typing.Callable[..., TestClient]): + app = Starlette(routes=echo_paths_routes) + client = test_client_factory( + app, base_url="https://www.example.org/", root_path="/root" + ) + response = client.get("/root/path") + assert response.status_code == 200 + assert response.json() == { + "name": "path", + "path": "/root/path", + "root_path": "/root", + } + + response = client.get("/root/root/path") + assert response.status_code == 200 + assert response.json() == { + "name": "subpath", + "path": "/root/root/path", + "root_path": "/root", + }
Handling of `scope["root_path"]` and `scope["path"]` differs from ASGI spec ### Checklist <!-- Please make sure you check all these items before submitting your bug report. --> - [x] The bug is reproducible against the latest release and/or `master`. - [x] There are no similar issues or pull requests to fix it yet. ### Describe the bug <!-- A clear and concise description of what the bug is. --> Accoring to https://github.com/django/asgiref/issues/229#issuecomment-765583185, `scope["path"]` includes the `scope["root_path"]`. So if root_path is `/foo` and request for `/foo/bar` has come, the upstream application servers (such as uvicorn) are passing `scope["path"] == "/foo/bar" and scope["root_path"] == "/foo"`, which is correct behavior. But starlette does not conform this. It assumes `scope["path"]` is a remainder of stripping `scope["root_path"]` from original request path. In this case, `scope["path"] == "/bar" and scope["root_path"] == "/foo"`. This ASGI incompatible assumption can be seen [here](https://github.com/encode/starlette/blob/6af5c515e0a896cbf3f86ee043b88f6c24200bcf/starlette/routing.py#L368) or [here](https://github.com/encode/starlette/blob/6af5c515e0a896cbf3f86ee043b88f6c24200bcf/starlette/datastructures.py#L23) and many other places. The following "To reproduce" section shows just one aspect of this wrong assumption. ### To reproduce <!-- Provide a *minimal* example with steps to reproduce the bug locally. NOTE: try to keep any external dependencies *at an absolute minimum* (middleware, servers, proxies, certificates...). In other words, remove anything that doesn't make the bug go away. --> 1. Save `main.py` as follows. ```python from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route, Mount class Bar: async def __call__(self, scope, receive, send): await PlainTextResponse(f"bar {scope['root_path']=} {scope['path']=}")(scope, receive, send) class FooBar: async def __call__(self, scope, receive, send): await PlainTextResponse(f"foobar {scope['root_path']=} {scope['path']=}")(scope, receive, send) routes =[ Route('/bar', endpoint=Bar()), Mount('/foo', routes=[ Route('/bar', endpoint=FooBar()) ]) ] app = Starlette(routes=routes) ``` 2. Run `uvicorn main:app --port 8000 --root-path /foo` 3. Access by `curl http://localhost:8000/foo/bar` ### Expected behavior <!-- A clear and concise description of what you expected to happen. --> Receives ``` bar scope['root_path']='/foo' scope['path']='/foo/bar' ``` ### Actual behavior <!-- A clear and concise description of what actually happens. --> Receives ``` foobar scope['root_path']='/foo/foo' scope['path']='/bar' ``` Some points here are, 1. `scope['path']` does not include `scope['root_path']` , which is ASGI incompatible. 2. `FooBar` ASGI handler is called. It does not take `scope['root_path']` into account when routing. ### Environment - OS: Linux - Python version: 3.8.2 - Starlette version: 0.17.0 ### Additional context <!-- Any additional information that can help understanding the problem. Eg. linked issues, or a description of what you were trying to achieve. --> This may be a root cause of [this issue in fastapi](https://github.com/tiangolo/fastapi/issues/2872) <!-- POLAR PLEDGE BADGE START --> > [!IMPORTANT] > - We're using [Polar.sh](https://polar.sh/encode) so you can upvote and help fund this issue. > - We receive the funding once the issue is completed & confirmed by you. > - Thank you in advance for helping prioritize & fund our backlog. <a href="https://polar.sh/encode/starlette/issues/1336"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/encode/starlette/issues/1336/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/encode/starlette/issues/1336/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END -->
0.0
[ "tests/test_routing.py::test_protocol_switch[asyncio]", "tests/test_routing.py::test_subdomain_routing[asyncio]", "tests/test_routing.py::test_raise_on_shutdown[asyncio]", "tests/test_routing.py::test_paths_with_root_path[asyncio]", "tests/test_routing.py::test_paths_with_root_path[trio]" ]
[ "tests/test_routing.py::test_router[asyncio]", "tests/test_routing.py::test_route_converters[asyncio]", "tests/test_routing.py::test_router_add_route[asyncio]", "tests/test_routing.py::test_router_add_websocket_route[asyncio]", "tests/test_routing.py::test_mount_at_root[asyncio]", "tests/test_routing.py::test_host_routing[asyncio]", "tests/test_routing.py::test_url_for_with_root_path[asyncio]", "tests/test_routing.py::test_standalone_route_matches[asyncio]", "tests/test_routing.py::test_standalone_route_does_not_match[asyncio]", "tests/test_routing.py::test_standalone_ws_route_matches[asyncio]", "tests/test_routing.py::test_standalone_ws_route_does_not_match[asyncio]", "tests/test_routing.py::test_lifespan_async[asyncio]", "tests/test_routing.py::test_lifespan_with_on_events[asyncio]", "tests/test_routing.py::test_lifespan_state_unsupported[asyncio]", "tests/test_routing.py::test_raise_on_startup[asyncio]", "tests/test_routing.py::test_partial_async_ws_endpoint[asyncio]", "tests/test_routing.py::test_base_route_middleware[asyncio-app0]", "tests/test_routing.py::test_base_route_middleware[asyncio-app1]", "tests/test_routing.py::test_base_route_middleware[asyncio-app2]", "tests/test_routing.py::test_add_route_to_app_after_mount[asyncio]", "tests/test_routing.py::test_exception_on_mounted_apps[asyncio]", "tests/test_routing.py::test_mounted_middleware_does_not_catch_exception[asyncio]", "tests/test_routing.py::test_websocket_route_middleware[asyncio]", "tests/test_routing.py::test_router_add_websocket_route[trio]", "tests/test_routing.py::test_mount_urls[trio]", "tests/test_routing.py::test_mount_at_root[trio]", "tests/test_routing.py::test_subdomain_routing[trio]", "tests/test_routing.py::test_url_for_with_root_path[trio]", "tests/test_routing.py::test_standalone_route_matches[trio]", "tests/test_routing.py::test_standalone_route_does_not_match[trio]", "tests/test_routing.py::test_standalone_ws_route_matches[trio]", "tests/test_routing.py::test_standalone_ws_route_does_not_match[trio]", "tests/test_routing.py::test_lifespan_async[trio]", "tests/test_routing.py::test_lifespan_with_on_events[trio]", "tests/test_routing.py::test_lifespan_state_async_cm[trio]", "tests/test_routing.py::test_raise_on_startup[trio]", "tests/test_routing.py::test_partial_async_endpoint[trio]", "tests/test_routing.py::test_partial_async_ws_endpoint[trio]", "tests/test_routing.py::test_websocket_route_middleware[trio]", "tests/test_routing.py::test_url_path_for", "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_reverse_mount_urls", "tests/test_routing.py::test_host_reverse_urls", "tests/test_routing.py::test_subdomain_reverse_urls", "tests/test_routing.py::test_url_for_with_double_mount", "tests/test_routing.py::test_duplicated_param_names", "tests/test_routing.py::test_route_name[function]", "tests/test_routing.py::test_route_name[method]", "tests/test_routing.py::test_route_name[classmethod]", "tests/test_routing.py::test_route_name[staticmethod]", "tests/test_routing.py::test_route_name[object]", "tests/test_routing.py::test_route_name[lambda]", "tests/test_routing.py::test_mount_routes_with_middleware_url_path_for", "tests/test_routing.py::test_mount_asgi_app_with_middleware_url_path_for", "tests/test_routing.py::test_route_repr", "tests/test_routing.py::test_route_repr_without_methods", "tests/test_routing.py::test_websocket_route_repr", "tests/test_routing.py::test_mount_repr", "tests/test_routing.py::test_mount_named_repr", "tests/test_routing.py::test_host_repr", "tests/test_routing.py::test_host_named_repr", "tests/test_routing.py::test_decorator_deprecations" ]
2023-11-29 15:26:10+00:00
2,140
encode__starlette-269
diff --git a/docs/responses.md b/docs/responses.md index 2072bb6..be23a3d 100644 --- a/docs/responses.md +++ b/docs/responses.md @@ -86,6 +86,51 @@ class App: await response(receive, send) ``` +###Β TemplateResponse + +The `TemplateResponse` class return plain text responses generated +from a template instance, and a dictionary of context to render into the +template. + +A `request` argument must always be included in the context. Responses default +to `text/html` unless an alternative `media_type` is specified. + +```python +from starlette.responses import TemplateResponse +from starlette.requests import Request + +from jinja2 import Environment, FileSystemLoader + + +env = Environment(loader=FileSystemLoader('templates')) + + +class App: + def __init__(self, scope): + self.scope = scope + + async def __call__(self, receive, send): + template = env.get_template('index.html') + context = { + 'request': Request(self.scope), + } + response = TemplateResponse(template, context) + await response(receive, send) +``` + +The advantage with using `TemplateResponse` over `HTMLResponse` is that +it will make `template` and `context` properties available on response instances +returned by the test client. + +```python +def test_app(): + client = TestClient(App) + response = client.get("/") + assert response.status_code == 200 + assert response.template.name == "index.html" + assert "request" in response.context +``` + ### JSONResponse Takes some data and returns an `application/json` encoded response. diff --git a/starlette/responses.py b/starlette/responses.py index 35062ba..542e800 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -138,6 +138,39 @@ class PlainTextResponse(Response): media_type = "text/plain" +class TemplateResponse(Response): + media_type = "text/html" + + def __init__( + self, + template: typing.Any, + context: dict, + status_code: int = 200, + headers: dict = None, + media_type: str = None, + background: BackgroundTask = None, + ): + if "request" not in context: + raise ValueError('context must include a "request" key') + self.template = template + self.context = context + content = template.render(context) + super().__init__(content, status_code, headers, media_type, background) + + async def __call__(self, receive: Receive, send: Send) -> None: + request = self.context["request"] + extensions = request.get("extensions", {}) + if "http.response.template" in extensions: + await send( + { + "type": "http.response.template", + "template": self.template, + "context": self.context, + } + ) + await super().__call__(receive, send) + + class JSONResponse(Response): media_type = "application/json"
encode/starlette
2f02b6068b47aa3a76943b0dd2cff7c1fe38475f
diff --git a/starlette/testclient.py b/starlette/testclient.py index 2f901c1..53afb45 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -126,6 +126,7 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): "headers": headers, "client": ["testclient", 50000], "server": [host, port], + "extensions": {"http.response.template": {}}, } async def receive() -> Message: @@ -147,7 +148,7 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): return {"type": "http.request", "body": body_bytes} async def send(message: Message) -> None: - nonlocal raw_kwargs, response_started, response_complete + nonlocal raw_kwargs, response_started, response_complete, template, context if message["type"] == "http.response.start": assert ( @@ -177,10 +178,15 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): if not more_body: raw_kwargs["body"].seek(0) response_complete = True + elif message["type"] == "http.response.template": + template = message["template"] + context = message["context"] response_started = False response_complete = False raw_kwargs = {"body": io.BytesIO()} # type: typing.Dict[str, typing.Any] + template = None + context = None try: loop = asyncio.get_event_loop() @@ -209,7 +215,11 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): } raw = requests.packages.urllib3.HTTPResponse(**raw_kwargs) - return self.build_response(request, raw) + response = self.build_response(request, raw) + if template is not None: + response.template = template + response.context = context + return response class WebSocketTestSession: diff --git a/tests/test_responses.py b/tests/test_responses.py index e68958e..0b79051 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -11,6 +11,7 @@ from starlette.responses import ( RedirectResponse, Response, StreamingResponse, + TemplateResponse, UJSONResponse, ) from starlette.testclient import TestClient @@ -243,3 +244,34 @@ def test_delete_cookie(): assert response.cookies["mycookie"] response = client.get("/") assert not response.cookies.get("mycookie") + + +def test_template_response(): + def app(scope): + request = Request(scope) + + class Template: + def __init__(self, name): + self.name = name + + def render(self, context): + return "username: %s" % context["username"] + + async def asgi(receive, send): + template = Template("index.html") + context = {"username": "tomchristie", "request": request} + response = TemplateResponse(template, context) + await response(receive, send) + + return asgi + + client = TestClient(app) + response = client.get("/") + assert response.text == "username: tomchristie" + assert response.template.name == "index.html" + assert response.context["username"] == "tomchristie" + + +def test_template_response_requires_request(): + with pytest.raises(ValueError): + TemplateResponse(None, {})
Testing template reponses This is going to require a bit of thinking about. ```python app = Starlette(template_directory='templates') @app.route('/') async def homepage(request): template = app.get_template('index.html') content = template.render(request=request) return HTMLResponse(content) client = TestClient(app) response = client.get('/') assert response.template = 'index.html' assert 'request' in response.context ``` Two issues here. Firstly we haven't associated the template name or context with the response in any way, so we can't reference them from the template. We could do so, with something like... ```python return app.render_reponse('index.html', context={'request': request}) ``` Or... ```python return TemplateResponse(template, context={'request': request})) # I *guess* `template` has the "index.html" name string associated with it somewhere? ``` Secondly, we don't have access to the response instance itself, we've just been sent ASGI messages. We'd need to ensure that `TemplateResponse` included some extra info ("template", "context") in the messages that it sent back, and that `TestClient` was able to additionally annotate the response with that information.
0.0
[ "tests/test_responses.py::test_text_response", "tests/test_responses.py::test_bytes_response", "tests/test_responses.py::test_ujson_response", "tests/test_responses.py::test_redirect_response", "tests/test_responses.py::test_streaming_response", "tests/test_responses.py::test_response_headers", "tests/test_responses.py::test_response_phrase", "tests/test_responses.py::test_file_response", "tests/test_responses.py::test_file_response_with_directory_raises_error", "tests/test_responses.py::test_file_response_with_missing_file_raises_error", "tests/test_responses.py::test_set_cookie", "tests/test_responses.py::test_delete_cookie", "tests/test_responses.py::test_template_response", "tests/test_responses.py::test_template_response_requires_request" ]
[]
2018-12-13 13:02:24+00:00
2,141
encode__starlette-273
diff --git a/docs/background.md b/docs/background.md index de7135f..d27fa65 100644 --- a/docs/background.md +++ b/docs/background.md @@ -6,6 +6,8 @@ the response has been sent. ### Background Task +Used to add a single background task to a response. + Signature: `BackgroundTask(func, *args, **kwargs)` ```python @@ -27,3 +29,35 @@ async def signup(request): async def send_welcome_email(to_address): ... ``` + +### BackgroundTasks + +Used to add multiple background tasks to a response. + +Signature: `BackgroundTasks(tasks=[])` + +```python +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.background import BackgroundTasks + +app = Starlette() + [email protected]('/user/signup', methods=['POST']) +async def signup(request): + data = await request.json() + username = data['username'] + email = data['email'] + tasks = BackgroundTasks() + tasks.add_task(send_welcome_email, to_address=email) + tasks.add_task(send_admin_notification, username=username) + message = {'status': 'Signup successful'} + return JSONResponse(message, background=tasks) + +async def send_welcome_email(to_address): + ... + +async def send_admin_notification(username): + ... + +``` diff --git a/docs/graphql.md b/docs/graphql.md index 16f9188..785a837 100644 --- a/docs/graphql.md +++ b/docs/graphql.md @@ -41,6 +41,27 @@ class Query(graphene.ObjectType): return request.headers.get("User-Agent", "<unknown>") ``` +## Adding background tasks + +You can add background tasks to run once the response has been sent. + +```python +class Query(graphene.ObjectType): + user_agent = graphene.String() + + def resolve_user_agent(self, info): + """ + Return the User-Agent of the incoming request. + """ + user_agent = request.headers.get("User-Agent", "<unknown>") + background = info.context["background"] + background.add_task(log_user_agent, user_agent=user_agent) + return user_agent + +async def log_user_agent(user_agent): + ... +``` + ## Sync or Async executors If you're working with a standard ORM, then just use regular function calls for diff --git a/starlette/background.py b/starlette/background.py index dbe7592..b2a3cfe 100644 --- a/starlette/background.py +++ b/starlette/background.py @@ -18,3 +18,18 @@ class BackgroundTask: await self.func(*self.args, **self.kwargs) else: await run_in_threadpool(self.func, *self.args, **self.kwargs) + + +class BackgroundTasks(BackgroundTask): + def __init__(self, tasks: typing.Sequence[BackgroundTask] = []): + self.tasks = list(tasks) + + def add_task( + self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any + ) -> None: + task = BackgroundTask(func, *args, **kwargs) + self.tasks.append(task) + + async def __call__(self) -> None: + for task in self.tasks: + await task() diff --git a/starlette/graphql.py b/starlette/graphql.py index f01ac81..3d95b1d 100644 --- a/starlette/graphql.py +++ b/starlette/graphql.py @@ -3,6 +3,7 @@ import json import typing from starlette import status +from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response @@ -73,7 +74,10 @@ class GraphQLApp: status_code=status.HTTP_400_BAD_REQUEST, ) - result = await self.execute(request, query, variables) + background = BackgroundTasks() + context = {"request": request, "background": background} + + result = await self.execute(query, variables=variables, context=context) error_data = ( [format_graphql_error(err) for err in result.errors] if result.errors @@ -83,13 +87,14 @@ class GraphQLApp: status_code = ( status.HTTP_400_BAD_REQUEST if result.errors else status.HTTP_200_OK ) - return JSONResponse(response_data, status_code=status_code) + + return JSONResponse( + response_data, status_code=status_code, background=background + ) async def execute( # type: ignore - self, request, query, variables=None, operation_name=None + self, query, variables=None, context=None, operation_name=None ): - context = dict(request=request) - if self.is_async: return await self.schema.execute( query,
encode/starlette
a2613494a475ed113f821ee1c48bc45556911f6c
diff --git a/tests/test_background.py b/tests/test_background.py index 7a60e40..9baeb17 100644 --- a/tests/test_background.py +++ b/tests/test_background.py @@ -1,4 +1,4 @@ -from starlette.background import BackgroundTask +from starlette.background import BackgroundTask, BackgroundTasks from starlette.responses import Response from starlette.testclient import TestClient @@ -49,3 +49,29 @@ def test_sync_task(): response = client.get("/") assert response.text == "task initiated" assert TASK_COMPLETE + + +def test_multiple_tasks(): + TASK_COUNTER = 0 + + def increment(amount): + nonlocal TASK_COUNTER + TASK_COUNTER += amount + + def app(scope): + async def asgi(receive, send): + tasks = BackgroundTasks() + tasks.add_task(increment, amount=1) + tasks.add_task(increment, amount=2) + tasks.add_task(increment, amount=3) + response = Response( + "tasks initiated", media_type="text/plain", background=tasks + ) + await response(receive, send) + + return asgi + + client = TestClient(app) + response = client.get("/") + assert response.text == "tasks initiated" + assert TASK_COUNTER == 1 + 2 + 3
Support for background tasks for `GraphQLApp` Since Response provided by starlette take a background argument, Any plans to add support for running a list of background tasks after the response has been sent in the case of `GraphQLApp`? A naive implementation looks like this ```python class Holder(object): def __init__(self): self._list = [] def add(self, function, *args, **kwargs): func = functools.partial(function, *args, **kwargs) self._list.append(func) def clean(self): self._list = [] def run_all_tasks(self): for i in self._list: i() ``` ```python class EnhancedGraphqlApp(GraphQLApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.holder = Holder() async def execute(self, query, variables=None, operation_name=None): # type: ignore print("Started") print(self.holder._list) if self.is_async: result = await self.schema.execute( query, variables=variables, operation_name=operation_name, context={"holder": self.holder}, executor=self.executor, return_promise=True, ) else: func = functools.partial( self.schema.execute, context={"holder": self.holder}, variables=variables, operation_name=operation_name, ) loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, func, query) return result def run_tasks(self): for i in self.holder._list: i() self.holder.clean() async def handle_graphql(self, request: Request) -> Response: # existing implementation ... tasks = BackgroundTask(self.run_tasks) return JSONResponse(response_data, background=tasks, status_code=status_code) ``` And usage in the Schema class would be just like how context is used generally ```python def hello(name): print(f"My name is {name}") class Query(object): hello = graphene.String(name=graphene.String(default_value="stranger")) alls = graphene.List(AllModel) async def resolve_alls(self, info): rresult = await async_print_all_models() holder = info.context.get('holder') holder.add(hello,"James") return [AllModel(name=x.name) for x in rresult] ```
0.0
[ "tests/test_background.py::test_async_task", "tests/test_background.py::test_sync_task", "tests/test_background.py::test_multiple_tasks" ]
[]
2018-12-14 14:56:24+00:00
2,142
encode__starlette-291
diff --git a/starlette/responses.py b/starlette/responses.py index 542e800..3b8d275 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -63,8 +63,8 @@ class Response: for k, v in headers.items() ] keys = [h[0] for h in raw_headers] - populate_content_length = b"content-length" in keys - populate_content_type = b"content-type" in keys + populate_content_length = b"content-length" not in keys + populate_content_type = b"content-type" not in keys body = getattr(self, "body", b"") if body and populate_content_length:
encode/starlette
9d20c9f6d6a8e659460e6781745d8a286dc42442
diff --git a/tests/test_responses.py b/tests/test_responses.py index 0b79051..d4bafaf 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -275,3 +275,15 @@ def test_template_response(): def test_template_response_requires_request(): with pytest.raises(ValueError): TemplateResponse(None, {}) + + +def test_populate_headers(): + def app(scope): + headers = {} + return Response(content="hi", headers=headers, media_type="text/html") + + client = TestClient(app) + response = client.get("/") + assert response.text == "hi" + assert response.headers["content-length"] == "2" + assert response.headers["content-type"] == "text/html; charset=utf-8"
Content-Type and Content-Length headers not automatically populated if headers is given Hi! I was playing around with responses and stumbled upon what seems like a bug. I have already pushed a [fix](https://github.com/florimondmanca/starlette/commit/e6dc80d203b613f211003df63352a37550538e9a) on my fork and would be happy to open a PR. :) --- **Expected behavior** If the `headers` dictionary passed to `Response` does not contain the `Content-Type` or `Content-Length` headers, the resulting response should populate automatically said headers based on the given `media_type` and `content`. **Actual behavior** The `Content-Type` and `Content-Length` headers are not set. **To reproduce** ```python from starlette.responses import Response from starlette.testclient import TestClient def app(scope): return Response(content="hi", headers={}, media_type="text/plain") client = TestClient(app) response = client.get("/") assert response.headers["content-length"] == "2" # fails: KeyError assert response.headers["content-type"] == "text/plain; charset=utf-8" # fails: KeyError ``` **Possible solutions** After inspecting the code in [responses.py], there seems to be a logical fallacy: ```python if headers is None: # ... else: raw_headers = [...] keys = [h[0] for h in raw_headers] populate_content_length = b"content-length" in keys # (*) populate_content_type = b"content-type" in keys # (*) ``` Lines (*) (66 and 67) mean that the headers are populate if they are *already* present in `headers`. They should be populated if they are *not* present => switching to `not in keys` there should fix the bug. **Specs** - macOS 10.12 - Python 3.7.1 - Starlette@master
0.0
[ "tests/test_responses.py::test_populate_headers" ]
[ "tests/test_responses.py::test_text_response", "tests/test_responses.py::test_bytes_response", "tests/test_responses.py::test_ujson_response", "tests/test_responses.py::test_redirect_response", "tests/test_responses.py::test_streaming_response", "tests/test_responses.py::test_response_headers", "tests/test_responses.py::test_response_phrase", "tests/test_responses.py::test_file_response", "tests/test_responses.py::test_file_response_with_directory_raises_error", "tests/test_responses.py::test_file_response_with_missing_file_raises_error", "tests/test_responses.py::test_set_cookie", "tests/test_responses.py::test_delete_cookie", "tests/test_responses.py::test_template_response", "tests/test_responses.py::test_template_response_requires_request" ]
2018-12-26 16:54:19+00:00
2,143
encode__starlette-292
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5cd3e51 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# Contributing to Starlette + +The Starlette team happily welcomes contributions. This document will help you get ready to contribute to Starlette! + +> **NOTE**: before writing any code, please first [open an issue] and discuss your ideas with the maintainers. + +## Setting up the repository + +1. Fork the repo. +2. Clone your fork on your local computer: `git clone https://github.com/<username>/starlette.git`. +3. Install Starlette locally and run the tests (see next sections). +4. Create a branch for your work, e.g. `git checkout -b fix-some-bug`. +5. Remember to include tests and documentation updates if applicable. +6. Once ready, push to your remote: `git push origin fix-some-bug`. + 7. [Open a PR] on the main repo. + +## Install + +- Make sure you are using a compatible Python version, as specified in our README. +- Create a virtual environment and install project dependencies: + +```bash +python -m venv venv +source venv/bin/activate +pip install -r requirements.txt +``` + +- Install an editable version of the project: `pip install -e .` (see [Editable Installs] in the `pip` docs). + +## Running the tests + +The tests are written using [pytest] and located in the `tests/` directory. + +**Note**: tests should be run before making any changes to the code in order to make sure that everything is running as expected. + +We provide a stand-alone **test script** to run tests in a reliable manner. Run it with: + +```bash +./scripts/test +``` + +By default, tests involving a database are excluded. To include them, set the `STARLETTE_TEST_DATABASE` environment variable to the URL of a PostgreSQL database, e.g.: + +```bash +export STARLETTE_TEST_DATABASE="postgresql://localhost/starlette" +``` + +## Linting + +We use [Black] as a code formatter. To run it along with a few other linting tools, we provide a stand-alone linting script: + +```bash +./scripts/lint +``` + +If linting has anything to say about the code, it will format it in-place. + +To keep the code style consistent, you should apply linting before committing. + +## Documentation + +The documentation is built with [MkDocs], a Markdown-based documentation site generator. + +To run the docs site in hot-reload mode (useful when editing the docs), run `$ mkdocs serve` in the project root directory. + +For your information, the docs site configuration is located in the `mkdocs.yml` file. + +Please refer to the [MkDocs docs][MkDocs] for more usage information, including how to add new pages. + +[open an issue]: https://github.com/encode/starlette/issues/new +[Open a PR]: https://github.com/encode/starlette/compare +[pytest]: https://docs.pytest.org +[pytest-cov]: https://github.com/pytest-dev/pytest-cov +[Black]: https://www.google.com/search?client=safari&rls=en&q=github+black&ie=UTF-8&oe=UTF-8 +[MkDocs]: https://www.mkdocs.org +[Editable Installs]: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs diff --git a/starlette/responses.py b/starlette/responses.py index 542e800..3b8d275 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -63,8 +63,8 @@ class Response: for k, v in headers.items() ] keys = [h[0] for h in raw_headers] - populate_content_length = b"content-length" in keys - populate_content_type = b"content-type" in keys + populate_content_length = b"content-length" not in keys + populate_content_type = b"content-type" not in keys body = getattr(self, "body", b"") if body and populate_content_length:
encode/starlette
9d20c9f6d6a8e659460e6781745d8a286dc42442
diff --git a/tests/test_responses.py b/tests/test_responses.py index 0b79051..d4bafaf 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -275,3 +275,15 @@ def test_template_response(): def test_template_response_requires_request(): with pytest.raises(ValueError): TemplateResponse(None, {}) + + +def test_populate_headers(): + def app(scope): + headers = {} + return Response(content="hi", headers=headers, media_type="text/html") + + client = TestClient(app) + response = client.get("/") + assert response.text == "hi" + assert response.headers["content-length"] == "2" + assert response.headers["content-type"] == "text/html; charset=utf-8"
Contributing guidelines Hi! While figuring out a potential solution for #289, I had to setup the repo and install Starlette locally. Although the process is rather straight-forward, I think it would be good practice to have contribution guidelines to make things clear and facilitate contributor onboarding. I already went ahead and committed a [draft](https://github.com/encode/starlette/commit/df8805aa1ba26e46d90673a53e7029bc113380b7) to my fork based on the guidelines I wrote for Bocadillo. If it looks fine, I'd be happy to open a PR. :+1:
0.0
[ "tests/test_responses.py::test_populate_headers" ]
[ "tests/test_responses.py::test_text_response", "tests/test_responses.py::test_bytes_response", "tests/test_responses.py::test_ujson_response", "tests/test_responses.py::test_redirect_response", "tests/test_responses.py::test_streaming_response", "tests/test_responses.py::test_response_headers", "tests/test_responses.py::test_response_phrase", "tests/test_responses.py::test_file_response", "tests/test_responses.py::test_file_response_with_directory_raises_error", "tests/test_responses.py::test_file_response_with_missing_file_raises_error", "tests/test_responses.py::test_set_cookie", "tests/test_responses.py::test_delete_cookie", "tests/test_responses.py::test_template_response", "tests/test_responses.py::test_template_response_requires_request" ]
2018-12-26 17:08:39+00:00
2,144
encode__starlette-339
diff --git a/starlette/datastructures.py b/starlette/datastructures.py index 1ce3aab..67e3d05 100644 --- a/starlette/datastructures.py +++ b/starlette/datastructures.py @@ -1,9 +1,11 @@ +import tempfile import typing from collections import namedtuple from collections.abc import Sequence from shlex import shlex from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse +from starlette.concurrency import run_in_threadpool from starlette.types import Scope Address = namedtuple("Address", ["host", "port"]) @@ -302,6 +304,94 @@ class QueryParams(typing.Mapping[str, str]): return f"{self.__class__.__name__}(query_string={repr(str(self))})" +class UploadFile: + def __init__(self, filename: str, file: typing.IO = None) -> None: + self.filename = filename + if file is None: + file = tempfile.SpooledTemporaryFile() + self.file = file + + async def write(self, data: typing.Union[bytes, str]) -> None: + await run_in_threadpool(self.file.write, data) + + async def read(self, size: int = None) -> typing.Union[bytes, str]: + return await run_in_threadpool(self.file.read, size) + + async def seek(self, offset: int) -> None: + await run_in_threadpool(self.file.seek, offset) + + async def close(self) -> None: + await run_in_threadpool(self.file.close) + + +FormValue = typing.Union[str, UploadFile] + + +class FormData(typing.Mapping[str, FormValue]): + """ + An immutable multidict, containing both file uploads and text input. + """ + + def __init__( + self, + form: typing.Union["FormData", typing.Mapping[str, FormValue]] = None, + items: typing.List[typing.Tuple[str, FormValue]] = None, + ) -> None: + _items = [] # type: typing.List[typing.Tuple[str, FormValue]] + if form is not None: + assert items is None, "Cannot set both 'form' and 'items'" + if isinstance(form, FormData): + _items = list(form.multi_items()) + else: + _items = list(form.items()) + elif items is not None: + _items = list(items) + + self._dict = {k: v for k, v in _items} + self._list = _items + + def getlist(self, key: typing.Any) -> typing.List[FormValue]: + return [item_value for item_key, item_value in self._list if item_key == key] + + def keys(self) -> typing.List[str]: # type: ignore + return list(self._dict.keys()) + + def values(self) -> typing.List[FormValue]: # type: ignore + return list(self._dict.values()) + + def items(self) -> typing.List[typing.Tuple[str, FormValue]]: # type: ignore + return list(self._dict.items()) + + def multi_items(self) -> typing.List[typing.Tuple[str, FormValue]]: + return list(self._list) + + def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + if key in self._dict: + return self._dict[key] + return default + + def __getitem__(self, key: typing.Any) -> FormValue: + return self._dict[key] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, FormData): + return False + return sorted(self._list) == sorted(other._list) + + def __repr__(self) -> str: + items = self.multi_items() + return f"{self.__class__.__name__}(items={repr(items)})" + + class Headers(typing.Mapping[str, str]): """ An immutable, case-insensitive multidict. diff --git a/starlette/formparsers.py b/starlette/formparsers.py index d148df8..223119f 100644 --- a/starlette/formparsers.py +++ b/starlette/formparsers.py @@ -1,12 +1,8 @@ -import asyncio -import io -import tempfile import typing from enum import Enum from urllib.parse import unquote_plus -from starlette.concurrency import run_in_threadpool -from starlette.datastructures import Headers +from starlette.datastructures import FormData, FormValue, Headers, UploadFile try: from multipart.multipart import parse_options_header @@ -35,31 +31,6 @@ class MultiPartMessage(Enum): END = 8 -class UploadFile: - def __init__(self, filename: str) -> None: - self.filename = filename - self._file = io.BytesIO() # type: typing.IO[typing.Any] - self._loop = asyncio.get_event_loop() - - def create_tempfile(self) -> None: - self._file = tempfile.SpooledTemporaryFile() - - async def setup(self) -> None: - await run_in_threadpool(self.create_tempfile) - - async def write(self, data: bytes) -> None: - await run_in_threadpool(self._file.write, data) - - async def read(self, size: int = None) -> bytes: - return await run_in_threadpool(self._file.read, size) - - async def seek(self, offset: int) -> None: - await run_in_threadpool(self._file.seek, offset) - - async def close(self) -> None: - await run_in_threadpool(self._file.close) - - class FormParser: def __init__( self, headers: Headers, stream: typing.AsyncGenerator[bytes, None] @@ -91,7 +62,7 @@ class FormParser: message = (FormMessage.END, b"") self.messages.append(message) - async def parse(self) -> typing.Dict[str, typing.Union[str, UploadFile]]: + async def parse(self) -> FormData: # Callbacks dictionary. callbacks = { "on_field_start": self.on_field_start, @@ -106,7 +77,7 @@ class FormParser: field_name = b"" field_value = b"" - result = {} # type: typing.Dict[str, typing.Union[str, UploadFile]] + items = [] # type: typing.List[typing.Tuple[str, FormValue]] # Feed the parser with data from the request. async for chunk in self.stream: @@ -127,11 +98,11 @@ class FormParser: elif message_type == FormMessage.FIELD_END: name = unquote_plus(field_name.decode("latin-1")) value = unquote_plus(field_value.decode("latin-1")) - result[name] = value + items.append((name, value)) elif message_type == FormMessage.END: pass - return result + return FormData(items=items) class MultiPartParser: @@ -177,7 +148,7 @@ class MultiPartParser: message = (MultiPartMessage.END, b"") self.messages.append(message) - async def parse(self) -> typing.Dict[str, typing.Union[str, UploadFile]]: + async def parse(self) -> FormData: # Parse the Content-Type header to get the multipart boundary. content_type, params = parse_options_header(self.headers["Content-Type"]) boundary = params.get(b"boundary") @@ -203,7 +174,7 @@ class MultiPartParser: data = b"" file = None # type: typing.Optional[UploadFile] - result = {} # type: typing.Dict[str, typing.Union[str, UploadFile]] + items = [] # type: typing.List[typing.Tuple[str, FormValue]] # Feed the parser with data from the request. async for chunk in self.stream: @@ -230,7 +201,6 @@ class MultiPartParser: if b"filename" in options: filename = options[b"filename"].decode("latin-1") file = UploadFile(filename=filename) - await file.setup() else: file = None elif message_type == MultiPartMessage.PART_DATA: @@ -240,12 +210,12 @@ class MultiPartParser: await file.write(message_bytes) elif message_type == MultiPartMessage.PART_END: if file is None: - result[field_name] = data.decode("latin-1") + items.append((field_name, data.decode("latin-1"))) else: await file.seek(0) - result[field_name] = file + items.append((field_name, file)) elif message_type == MultiPartMessage.END: pass parser.finalize() - return result + return FormData(items=items) diff --git a/starlette/requests.py b/starlette/requests.py index 5b703ce..600e6fb 100644 --- a/starlette/requests.py +++ b/starlette/requests.py @@ -4,7 +4,7 @@ import json import typing from collections.abc import Mapping -from starlette.datastructures import URL, Address, Headers, QueryParams +from starlette.datastructures import URL, Address, FormData, Headers, QueryParams from starlette.formparsers import FormParser, MultiPartParser from starlette.types import Message, Receive, Scope @@ -168,7 +168,7 @@ class Request(HTTPConnection): self._json = json.loads(body) return self._json - async def form(self) -> dict: + async def form(self) -> FormData: if not hasattr(self, "_form"): assert ( parse_options_header is not None @@ -182,12 +182,12 @@ class Request(HTTPConnection): form_parser = FormParser(self.headers, self.stream()) self._form = await form_parser.parse() else: - self._form = {} + self._form = FormData() return self._form async def close(self) -> None: if hasattr(self, "_form"): - for item in self._form.values(): + for key, item in self._form.multi_items(): if hasattr(item, "close"): await item.close() # type: ignore
encode/starlette
774cb40a1750723f6ad6fa8fb778978b41227317
diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py index 51c9ba8..bcf1535 100644 --- a/tests/test_datastructures.py +++ b/tests/test_datastructures.py @@ -1,7 +1,10 @@ +import io + from starlette.datastructures import ( URL, CommaSeparatedStrings, DatabaseURL, + FormData, Headers, MutableHeaders, QueryParams, @@ -201,3 +204,30 @@ def test_queryparams(): q = QueryParams(items=[("a", "123"), ("a", "456")]) assert QueryParams(q) == q + + +def test_formdata(): + upload = io.BytesIO(b"test") + form = FormData(items=[("a", "123"), ("a", "456"), ("b", upload)]) + assert "a" in form + assert "A" not in form + assert "c" not in form + assert form["a"] == "456" + assert form.get("a") == "456" + assert form.get("nope", default=None) is None + assert form.getlist("a") == ["123", "456"] + assert form.keys() == ["a", "b"] + assert form.values() == ["456", upload] + assert form.items() == [("a", "456"), ("b", upload)] + assert len(form) == 2 + assert list(form) == ["a", "b"] + assert dict(form) == {"a": "456", "b": upload} + assert ( + repr(form) + == "FormData(items=[('a', '123'), ('a', '456'), ('b', " + repr(upload) + ")])" + ) + assert FormData(form) == form + assert FormData({"a": "123", "b": "789"}) == FormData( + items=[("a", "123"), ("b", "789")] + ) + assert FormData({"a": "123", "b": "789"}) != {"a": "123", "b": "789"} diff --git a/tests/test_formparsers.py b/tests/test_formparsers.py index 1d533ce..2f263fd 100644 --- a/tests/test_formparsers.py +++ b/tests/test_formparsers.py @@ -33,6 +33,28 @@ def app(scope): return asgi +def multi_items_app(scope): + async def asgi(receive, send): + request = Request(scope, receive) + data = await request.form() + output = {} + for key, value in data.multi_items(): + if key not in output: + output[key] = [] + if isinstance(value, UploadFile): + content = await value.read() + output[key].append( + {"filename": value.filename, "content": content.decode()} + ) + else: + output[key].append(value) + await request.close() + response = JSONResponse(output) + await response(receive, send) + + return asgi + + def app_read_body(scope): async def asgi(receive, send): request = Request(scope, receive) @@ -86,6 +108,29 @@ def test_multipart_request_multiple_files(tmpdir): } +def test_multi_items(tmpdir): + path1 = os.path.join(tmpdir, "test1.txt") + with open(path1, "wb") as file: + file.write(b"<file1 content>") + + path2 = os.path.join(tmpdir, "test2.txt") + with open(path2, "wb") as file: + file.write(b"<file2 content>") + + client = TestClient(multi_items_app) + with open(path1, "rb") as f1, open(path2, "rb") as f2: + response = client.post( + "/", data=[("test1", "abc")], files=[("test1", f1), ("test1", f2)] + ) + assert response.json() == { + "test1": [ + "abc", + {"filename": "test1.txt", "content": "<file1 content>"}, + {"filename": "test2.txt", "content": "<file2 content>"}, + ] + } + + def test_multipart_request_mixed_files_and_data(tmpdir): client = TestClient(app) response = client.post( diff --git a/tests/test_requests.py b/tests/test_requests.py index 32d0ab6..8e3f368 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -130,7 +130,7 @@ def test_request_form_urlencoded(): async def asgi(receive, send): request = Request(scope, receive) form = await request.form() - response = JSONResponse({"form": form}) + response = JSONResponse({"form": dict(form)}) await response(receive, send) return asgi
Support for Multiple Files for One Form Field I am trying to submit a list of data files under the same parameter name but only the first file is parsed from `request.form()`. ```bash curl -X POST "http://0.0.0.0:3031/myapi" -H "accept: multipart/form-data" -H "Authorization: Bearer atoken" -F "data=@/path/tp/favicon-16x16.png" -F"data=@/path/to/file.txt" ``` According to IETF RFC 7578 this should be supported. Is this something you would consider supporting? https://tools.ietf.org/html/rfc7578#section-4.3 ``` 4.3. Multiple Files for One Form Field The form data for a form field might include multiple files. [RFC2388] suggested that multiple files for a single form field be transmitted using a nested "multipart/mixed" part. This usage is deprecated. To match widely deployed implementations, multiple files MUST be sent by supplying each file in a separate part but all with the same "name" parameter. Receiving applications intended for wide applicability (e.g., multipart/form-data parsing libraries) SHOULD also support the older method of supplying multiple files. ```
0.0
[ "tests/test_datastructures.py::test_url", "tests/test_datastructures.py::test_hidden_password", "tests/test_datastructures.py::test_database_url", "tests/test_datastructures.py::test_csv", "tests/test_datastructures.py::test_url_from_scope", "tests/test_datastructures.py::test_headers", "tests/test_datastructures.py::test_mutable_headers", "tests/test_datastructures.py::test_headers_mutablecopy", "tests/test_datastructures.py::test_queryparams", "tests/test_datastructures.py::test_formdata", "tests/test_formparsers.py::test_multipart_request_data", "tests/test_formparsers.py::test_multipart_request_files", "tests/test_formparsers.py::test_multipart_request_multiple_files", "tests/test_formparsers.py::test_multi_items", "tests/test_formparsers.py::test_multipart_request_mixed_files_and_data", "tests/test_formparsers.py::test_urlencoded_request_data", "tests/test_formparsers.py::test_no_request_data", "tests/test_formparsers.py::test_urlencoded_percent_encoding", "tests/test_formparsers.py::test_urlencoded_percent_encoding_keys", "tests/test_formparsers.py::test_urlencoded_multi_field_app_reads_body", "tests/test_formparsers.py::test_multipart_multi_field_app_reads_body", "tests/test_requests.py::test_request_url", "tests/test_requests.py::test_request_query_params", "tests/test_requests.py::test_request_headers", "tests/test_requests.py::test_request_client", "tests/test_requests.py::test_request_body", "tests/test_requests.py::test_request_stream", "tests/test_requests.py::test_request_form_urlencoded", "tests/test_requests.py::test_request_body_then_stream", "tests/test_requests.py::test_request_stream_then_body", "tests/test_requests.py::test_request_json", "tests/test_requests.py::test_request_scope_interface", "tests/test_requests.py::test_request_without_setting_receive", "tests/test_requests.py::test_request_disconnect", "tests/test_requests.py::test_request_is_disconnected", "tests/test_requests.py::test_request_cookies", "tests/test_requests.py::test_chunked_encoding" ]
[]
2019-01-22 19:12:41+00:00
2,145
encode__starlette-409
diff --git a/docs/config.md b/docs/config.md index baa9e38..7c5b2a6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -9,13 +9,13 @@ that is not committed to source control. ```python from starlette.applications import Starlette from starlette.config import Config -from starlette.datastructures import CommaSeparatedStrings, DatabaseURL, Secret +from starlette.datastructures import CommaSeparatedStrings, Secret # Config will be read from environment variables and/or ".env" files. config = Config(".env") DEBUG = config('DEBUG', cast=bool, default=False) -DATABASE_URL = config('DATABASE_URL', cast=DatabaseURL) +DATABASE_URL = config('DATABASE_URL', cast=URL) SECRET_KEY = config('SECRET_KEY', cast=Secret) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=CommaSeparatedStrings) @@ -62,7 +62,7 @@ Secret('**********') '98n349$%8b8-7yjn0n8y93T$23r' ``` -Similarly, the `URL` and `DatabaseURL` class will hide any password component +Similarly, the `URL` class will hide any password component in their representations. ```python @@ -128,7 +128,7 @@ application logic separated: ```python from starlette.config import Config -from starlette.datastructures import DatabaseURL, Secret +from starlette.datastructures import URL, Secret config = Config(".env") @@ -136,7 +136,7 @@ DEBUG = config('DEBUG', cast=bool, default=False) TESTING = config('TESTING', cast=bool, default=False) SECRET_KEY = config('SECRET_KEY', cast=Secret) -DATABASE_URL = config('DATABASE_URL', cast=DatabaseURL) +DATABASE_URL = config('DATABASE_URL', cast=URL) if TESTING: DATABASE_URL = DATABASE_URL.replace(database='test_' + DATABASE_URL.database) ``` @@ -180,6 +180,8 @@ app.add_middleware( @app.route('/', methods=['GET']) async def homepage(request): ... + + ``` Now let's deal with our test configuration. diff --git a/docs/database.md b/docs/database.md index 5bab16d..39e605b 100644 --- a/docs/database.md +++ b/docs/database.md @@ -186,7 +186,7 @@ import pytest from starlette.config import environ from starlette.testclient import TestClient from sqlalchemy import create_engine -from sqlalchemy_utils import database_exists, create_database +from sqlalchemy_utils import database_exists, create_database, drop_database # This sets `os.environ`, but provides some additional protection. # If we placed it below the application import, it would raise an error diff --git a/docs/requests.md b/docs/requests.md index 317699b..7df7733 100644 --- a/docs/requests.md +++ b/docs/requests.md @@ -8,7 +8,7 @@ Signature: `Request(scope, receive=None)` ```python from starlette.requests import Request -from starlette.response import Response +from starlette.responses import Response class App: diff --git a/docs/third-party-packages.md b/docs/third-party-packages.md index 2153b7c..7869220 100644 --- a/docs/third-party-packages.md +++ b/docs/third-party-packages.md @@ -3,85 +3,29 @@ Starlette has a rapidly growing community of developers, building tools that int Here are some of those third party packages: + +## Backports + +### Python 3.5 port + +<a href="https://github.com/em92/starlette" target="_blank">Github</a> + ## Plugins ### Starlette APISpec <a href="https://github.com/Woile/starlette-apispec" target="_blank">Github</a> -Easy APISpec integration for Starlette. - -Document your REST API built with Starlette by declaring OpenAPI (Swagger) schemas in YAML format in your endpoints' docstrings. +Simple APISpec integration for Starlette. +Document your REST API built with Starlette by declaring OpenAPI (Swagger) +schemas in YAML format in your endpoint's docstrings. ### Starlette API <a href="https://github.com/PeRDy/starlette-api" target="_blank">Github</a> -That library aims to bring a layer on top of Starlette framework to provide useful mechanism for building APIs. It's -based on API Star, inheriting some nice ideas like: - -* **Schema system** based on [Marshmallow](https://github.com/marshmallow-code/marshmallow/) that allows to **declare** -the inputs and outputs of endpoints and provides a reliable way of **validate** data against those schemas. -* **Dependency Injection** that ease the process of managing parameters needed in endpoints. -* **Components** as the base of the plugin ecosystem, allowing you to create custom or use those already defined in -your endpoints, injected as parameters. -* **Starlette ASGI** objects like `Request`, `Response`, `Session` and so on are defined as components and ready to be -injected in your endpoints. -* **Auto generated API schema** using OpenAPI standard. It uses the schema system of your endpoints to extract all the -necessary information to generate your API Schema. -* **Auto generated docs** providing a [Swagger UI](https://swagger.io/tools/swagger-ui/) or -[ReDocs](https://rebilly.github.io/ReDoc/) endpoint. - - -```python -from marshmallow import Schema, fields, validate -from starlette_api.applications import Starlette - - -# Data Schema -class Puppy(Schema): - id = fields.Integer() - name = fields.String() - age = fields.Integer(validate=validate.Range(min=0)) - - -# Database -puppies = [ - {"id": 1, "name": "Canna", "age": 6}, - {"id": 2, "name": "Sandy", "age": 12}, -] - - -# Application -app = Starlette( - components=[], # Without custom components - title="Foo", # API title - version="0.1", # API version - description="Bar", # API description - schema="/schema/", # Path to expose OpenAPI schema - docs="/docs/", # Path to expose Swagger UI docs - redoc="/redoc/", # Path to expose ReDoc docs -) - - -# Views [email protected]("/", methods=["GET"]) -def list_puppies(name: str = None) -> Puppy(many=True): - """ - List the puppies collection. There is an optional query parameter that - specifies a name for filtering the collection based on it. - - Request example: - GET http://example.com/?name=Sandy - - Response example: - 200 - [ - {"id": 2, "name": "Sandy", "age": 12} - ] - """ - return [puppy for puppy in puppies if puppy["name"] == name] -``` +That library aims to bring a layer on top of Starlette framework to provide useful mechanism for building APIs. Based on API Star. Some featuers: marshmallow schemas, dependency injection, auto generated api schemas, +auto generated docs. ### webargs-starlette @@ -93,84 +37,17 @@ of [webargs](https://github.com/marshmallow-code/webargs). Allows you to parse querystring, JSON, form, headers, and cookies using type annotations. -```python -import uvicorn -from starlette.applications import Starlette -from starlette.responses import JSONResponse -from webargs_starlette import use_annotations - -app = Starlette() - - [email protected]("/") -@use_annotations(locations=("query",)) -async def index(request, name: str = "World"): - return JSONResponse({"Hello": name}) - - -if __name__ == "__main__": - uvicorn.run(app, port=5000) - -# curl 'http://localhost:5000/' -# {"Hello": "World"} -# curl 'http://localhost:5000/?name=Ada' -# {"Hello": "Ada"} -``` - ### Mangum <a href="https://github.com/erm/mangum" target="_blank">Github</a> Serverless ASGI adapter for AWS Lambda & API Gateway. -```Python -from starlette.applications import Starlette -from starlette.responses import PlainTextResponse -from mangum import Mangum - - -app = Starlette() - - [email protected]("/") -def homepage(request): - return PlainTextResponse("Hello, world!") - - -handler = Mangum(app) # optionally set debug=True -``` - ### Nejma ⭐ <a href="https://github.com/taoufik07/nejma" target="_blank">Github</a> -Helps you manage and send messages to groups of channels. - -```python - -from nejma.ext.starlette import WebSocketEndpoint - [email protected]_route("/ws") -class Chat(WebSocketEndpoint): - encoding = "json" - - async def on_receive(self, websocket, data): - room_id = data['room_id'] - message = data['message'] - username = data['username'] - - if message.strip(): - group = f"group_{room_id}" - - self.channel_layer.add(group, self.channel) - - payload = { - "username": username, - "message": message, - "room_id": room_id - } - await self.channel_layer.group_send(group, payload) -``` +Manage and send messages to groups of channels using websockets. Checkout <a href="https://github.com/taoufik07/nejma-chat" target="_blank">nejma-chat</a>, a simple chat application built using `nejma` and `starlette`. ## Frameworks @@ -180,81 +57,16 @@ Checkout <a href="https://github.com/taoufik07/nejma-chat" target="_blank">nejma <a href="https://github.com/kennethreitz/responder" target="_blank">Github</a> | <a href="https://python-responder.org/en/latest/" target="_blank">Documentation</a> -A familiar HTTP Service Framework for Python. - -* Flask-style route expression, with new capabilities -- all while using Python 3.6+'s new f-string syntax. -* Falcon's "every request and response is passed into to each view and mutated" methodology. -* Support for YAML by default. -* Several of Starlette's optional dependencies pre-installed, like: - * Production static file server. - * Uvicorn server. - * GraphQL support, via Graphene. - -```Python -import responder - -api = responder.API() - [email protected]("/{greeting}") -async def greet_world(req, resp, *, greeting): - resp.text = f"{greeting}, world!" - -if __name__ == '__main__': - api.run() -``` +Async web service framework. Some Features: flask-style route expression, +yaml support, OpenAPI schema generation, background tasks, graphql. ### FastAPI <a href="https://github.com/tiangolo/fastapi" target="_blank">Github</a> | <a href="https://fastapi.tiangolo.com/" target="_blank">Documentation</a> -High performance, easy to learn, fast to code, ready for production. - -An API framework inspired by **APIStar**'s previous server system with type declarations for route parameters, based on the OpenAPI specification version 3.0.0+ (with JSON Schema), powered by **Pydantic** for the data handling. - -Use standard Python 3.6+ types as parameters to get: - -* Autocomplete everywhere. -* Data conversion. -* Data validation. -* Automatic documentation with OpenAPI (and JSON Schema), based on the same Python types. - -Includes: - -* A simple but powerful **dependency injection** system. -* Automatic interactive documentation (based on Swagger UI and ReDoc). -* Security utilities, including **OAuth2** with **JWT tokens**. - -```Python -from fastapi import FastAPI - -app = FastAPI() - - [email protected]("/") -def read_root(): - return {"Hello": "World"} - - [email protected]("/items/{item_id}") -def read_item(item_id: int, q: str = None): - return {"item_id": item_id, "q": q} -``` - -This code declares a path `/`, and a path `/items/{item_id}`. - -The path for `/items/{item_id}` has: - -* A path parameter `item_id` that will be validated as an `int`, with automatic errors when invalid. -* An optional (by default `None`) query parameter `q` of type `str`. - -Calling `http://example.com/items/2?q=myquery` will return: - -```JSON -{"item_id": 2, "q": "myquery"} -``` - -The same way you can declare JSON body schemas, headers, etc. +High performance, easy to learn, fast to code, ready for production web API framework. +Inspired by **APIStar**'s previous server system with type declarations for route parameters, based on the OpenAPI specification version 3.0.0+ (with JSON Schema), powered by **Pydantic** for the data handling. ### Bocadillo @@ -262,30 +74,4 @@ The same way you can declare JSON body schemas, headers, etc. <a href="https://bocadilloproject.github.io" target="_blank">Documentation</a> A modern Python web framework filled with asynchronous salsa. - Bocadillo is **async-first** and designed with productivity and simplicity in mind. It is not meant to be minimal: a **carefully chosen set of included batteries** helps you build performant web apps and services with minimal setup. - -Key features include: - -* Simple, powerful and familiar views and routing, inspired by the greatest (Flask, Falcon). -* First-class support for both HTTP / REST and WebSocket. -* Built-in CORS, HSTS, GZip, HTTP streaming, Jinja2 templates, background tasks, static files… - -… and more ahead, as depicted in the <a href="https://github.com/bocadilloproject/bocadillo/blob/master/ROADMAP.md" target="_blank">Roadmap</a>. - -The example below demonstrates a simple WebSocket echo server. - -```python -from bocadillo import API, WebSocket - -api = API() - [email protected]_route("/echo") -async def echo(ws: WebSocket): - async with ws: - async for message in ws: - await ws.send(message) - -if __name__ == "__main__": - api.run() -``` diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index 5021714..076708a 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -56,7 +56,7 @@ class CORSMiddleware: self.app = app self.allow_origins = allow_origins self.allow_methods = allow_methods - self.allow_headers = allow_headers + self.allow_headers = [h.lower() for h in allow_headers] self.allow_all_origins = "*" in allow_origins self.allow_all_headers = "*" in allow_headers self.allow_origin_regex = compiled_allow_origin_regex @@ -117,7 +117,7 @@ class CORSMiddleware: if self.allow_all_headers and requested_headers is not None: headers["Access-Control-Allow-Headers"] = requested_headers elif requested_headers is not None: - for header in requested_headers.split(","): + for header in [h.lower() for h in requested_headers.split(",")]: if header.strip() not in self.allow_headers: failures.append("headers")
encode/starlette
9944bb7048458fed0c096a5f77baaa369935cec6
diff --git a/tests/middleware/test_cors.py b/tests/middleware/test_cors.py index ddd0028..ecd32d2 100644 --- a/tests/middleware/test_cors.py +++ b/tests/middleware/test_cors.py @@ -55,7 +55,7 @@ def test_cors_allow_specific_origin(): app.add_middleware( CORSMiddleware, allow_origins=["https://example.org"], - allow_headers=["X-Example"], + allow_headers=["X-Example", "Content-Type"], ) @app.route("/") @@ -68,13 +68,13 @@ def test_cors_allow_specific_origin(): headers = { "Origin": "https://example.org", "Access-Control-Request-Method": "GET", - "Access-Control-Request-Headers": "X-Example", + "Access-Control-Request-Headers": "X-Example, Content-Type", } response = client.options("/", headers=headers) assert response.status_code == 200 assert response.text == "OK" assert response.headers["access-control-allow-origin"] == "https://example.org" - assert response.headers["access-control-allow-headers"] == "X-Example" + assert response.headers["access-control-allow-headers"] == "X-Example, Content-Type" # Test standard response headers = {"Origin": "https://example.org"} @@ -120,7 +120,9 @@ def test_cors_allow_origin_regex(): app = Starlette() app.add_middleware( - CORSMiddleware, allow_headers=["X-Example"], allow_origin_regex="https://*" + CORSMiddleware, + allow_headers=["X-Example", "Content-Type"], + allow_origin_regex="https://*", ) @app.route("/") @@ -149,13 +151,13 @@ def test_cors_allow_origin_regex(): headers = { "Origin": "https://another.com", "Access-Control-Request-Method": "GET", - "Access-Control-Request-Headers": "X-Example", + "Access-Control-Request-Headers": "X-Example, content-type", } response = client.options("/", headers=headers) assert response.status_code == 200 assert response.text == "OK" assert response.headers["access-control-allow-origin"] == "https://another.com" - assert response.headers["access-control-allow-headers"] == "X-Example" + assert response.headers["access-control-allow-headers"] == "X-Example, Content-Type" # Test disallowed pre-flight response headers = {
Config/Settings dump? What's the best way to dump all of the settings using starlette.config? I want to create an endpoint to make it easy to review the settings being used but I don't want the Secrets to be viewable, e.g. things like: JWT_SECRET = config("JWT_SECRET", cast=starlette.datastructures.Secret) We are currently using: ``` @router.get("/settings", tags=["Info"]) def get_settings() -> dict: dctconfig = dict(settings.config) return dctconfig ``` But it shows the the secrets (instead of Secret('**********')) along with everything else.
0.0
[ "tests/middleware/test_cors.py::test_cors_allow_origin_regex" ]
[ "tests/middleware/test_cors.py::test_cors_allow_all", "tests/middleware/test_cors.py::test_cors_allow_specific_origin", "tests/middleware/test_cors.py::test_cors_disallowed_preflight", "tests/middleware/test_cors.py::test_cors_credentialed_requests_return_specific_origin", "tests/middleware/test_cors.py::test_cors_vary_header_defaults_to_origin", "tests/middleware/test_cors.py::test_cors_vary_header_is_properly_set" ]
2019-02-23 21:13:05+00:00
2,146
encode__starlette-563
diff --git a/starlette/middleware/httpsredirect.py b/starlette/middleware/httpsredirect.py index 13f3a70..7f646ed 100644 --- a/starlette/middleware/httpsredirect.py +++ b/starlette/middleware/httpsredirect.py @@ -13,7 +13,7 @@ class HTTPSRedirectMiddleware: redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme] netloc = url.hostname if url.port in (80, 443) else url.netloc url = url.replace(scheme=redirect_scheme, netloc=netloc) - response = RedirectResponse(url, status_code=301) + response = RedirectResponse(url, status_code=308) await response(scope, receive, send) else: await self.app(scope, receive, send) diff --git a/starlette/responses.py b/starlette/responses.py index 13982db..a755d24 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -161,7 +161,7 @@ class UJSONResponse(JSONResponse): class RedirectResponse(Response): def __init__( - self, url: typing.Union[str, URL], status_code: int = 302, headers: dict = None + self, url: typing.Union[str, URL], status_code: int = 307, headers: dict = None ) -> None: super().__init__(content=b"", status_code=status_code, headers=headers) self.headers["location"] = quote_plus(str(url), safe=":/%#?&=@[]!$&'()*+,;")
encode/starlette
b2f9f4359b93a9f941779c575af764019e5183c7
diff --git a/tests/middleware/test_https_redirect.py b/tests/middleware/test_https_redirect.py index 15f1e3f..6a81ed3 100644 --- a/tests/middleware/test_https_redirect.py +++ b/tests/middleware/test_https_redirect.py @@ -19,20 +19,20 @@ def test_https_redirect_middleware(): client = TestClient(app) response = client.get("/", allow_redirects=False) - assert response.status_code == 301 + assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:80") response = client.get("/", allow_redirects=False) - assert response.status_code == 301 + assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:443") response = client.get("/", allow_redirects=False) - assert response.status_code == 301 + assert response.status_code == 308 assert response.headers["location"] == "https://testserver/" client = TestClient(app, base_url="http://testserver:123") response = client.get("/", allow_redirects=False) - assert response.status_code == 301 + assert response.status_code == 308 assert response.headers["location"] == "https://testserver:123/"
Use "308 Permanent Redirect" for redirect slashes behavior. Hi, I stumbled upon a quirk in starlette that is not properly documented. It seems like all of my HTTP request to a route without trailing slash are being redirected to route with trailing slashes. Say I am hitting `http://hostname/mountpoint/api` it will be redirected (302) to `http://hostname/mountpoint/api/`. This messed up your api calls; if you call POST to `http://hostname/mountpoint/api` it will be redirected to GET `http://hostname/mountpoint/api/`. I dig on the source and see this redirect_slashes flag and setting it to False fix this. I feel this behavior (the auto redirection) should be documented.
0.0
[ "tests/middleware/test_https_redirect.py::test_https_redirect_middleware" ]
[]
2019-06-24 22:10:37+00:00
2,147
encode__starlette-65
diff --git a/docs/background.md b/docs/background.md new file mode 100644 index 0000000..9963c08 --- /dev/null +++ b/docs/background.md @@ -0,0 +1,31 @@ + +Starlette includes a `BackgroundTask` class for tasks that do not need to be completed before the response is sent. + +### Background Task + +Signature: `BackgroundTask(func, *args, **kwargs) + +```python +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.background import BackgroundTask +from email.mime.text import MIMEText + +app = Starlette() + [email protected]('/user/signup', methods=['POST']) +async def create_new_user(request): + user = await request.json() + # Do stuff here + task = BackgroundTask(send_welcome_email, user) + return JSONResponse( + {'msg': 'User successfully created'}, + background=task + ) + +async def send_welcome_email(info): + # Do stuff here + message = MIMEText(f"Thank you for registering, {info['name']}") + message['To'] = info['email'] + await send_message(message) +``` \ No newline at end of file diff --git a/docs/endpoints.md b/docs/endpoints.md index b849139..87a5536 100644 --- a/docs/endpoints.md +++ b/docs/endpoints.md @@ -1,6 +1,8 @@ -Starlette includes an `HTTPEndpoint` class that provides a class-based view pattern which -handles HTTP method dispatching. +Starlette includes the classes `HTTPEndpoint` and `WebSocketEndpoint` that provide a class-based view pattern for +handling HTTP method dispatching and WebSocket sessions. + +### HTTPEndpoint The `HTTPEndpoint` class can be used as an ASGI application: @@ -42,3 +44,104 @@ class User(HTTPEndpoint): HTTP endpoint classes will respond with "405 Method not allowed" responses for any request methods which do not map to a corresponding handler. + +### WebSocketEndpoint + +The `WebSocketEndpoint` class is an ASGI application that presents a wrapper around +the functionality of a `WebSocket` instance. + +The ASGI connection scope is accessible on the endpoint instance via `.scope` and +has an attribute `encoding` which may optionally be set, in order to validate the expected websocket data in the `on_receive` method. + +The encoding types are: + +* `'json'` +* `'bytes'` +* `'text'` + +There are three overridable methods for handling specific ASGI websocket message types: + +* `async def on_connect(websocket, **kwargs)` +* `async def on_receive(websocket, data)` +* `async def on_disconnect(websocket, close_code)` + +```python +from starlette.endpoints import WebSocketEndpoint + + +class App(WebSocketEndpoint): + encoding = 'bytes' + + async def on_connect(self, websocket, **kwargs): + await websocket.accept() + + async def on_receive(self, websocket, data): + await websocket.send_bytes(b"Message: " + data) + + async def on_disconnect(self, websocket, close_code): + pass +``` + +The `WebSocketEndpoint` can also be used with the `Starlette` application class: + +```python +import uvicorn +from starlette.applications import Starlette +from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint +from starlette.responses import HTMLResponse + +app = Starlette() + +html = """ +<!DOCTYPE html> +<html> + <head> + <title>Chat</title> + </head> + <body> + <h1>WebSocket Chat</h1> + <form action="" onsubmit="sendMessage(event)"> + <input type="text" id="messageText" autocomplete="off"/> + <button>Send</button> + </form> + <ul id='messages'> + </ul> + <script> + var ws = new WebSocket("ws://localhost:8000/ws"); + ws.onmessage = function(event) { + var messages = document.getElementById('messages') + var message = document.createElement('li') + var content = document.createTextNode(event.data) + message.appendChild(content) + messages.appendChild(message) + }; + function sendMessage(event) { + var input = document.getElementById("messageText") + ws.send(input.value) + input.value = '' + event.preventDefault() + } + </script> + </body> +</html> +""" + + [email protected]("/") +class Homepage(HTTPEndpoint): + async def get(self, request): + return HTMLResponse(html) + + [email protected]_route("/ws") +class Echo(WebSocketEndpoint): + + encoding = "text" + + async def on_receive(self, websocket, data): + await websocket.send_text(f"Message text was: {data}") + + +if __name__ == "__main__": + uvicorn.run(app, host="0.0.0.0", port=8000) +``` diff --git a/starlette/background.py b/starlette/background.py new file mode 100644 index 0000000..9838735 --- /dev/null +++ b/starlette/background.py @@ -0,0 +1,17 @@ +import asyncio +import functools + + +class BackgroundTask: + def __init__(self, func, *args, **kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + + async def __call__(self): + if asyncio.iscoroutinefunction(self.func): + await asyncio.ensure_future(self.func(*self.args, **self.kwargs)) + else: + fn = functools.partial(self.func, *self.args, **self.kwargs) + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, fn) diff --git a/starlette/debug.py b/starlette/debug.py index cc6e846..11eca43 100644 --- a/starlette/debug.py +++ b/starlette/debug.py @@ -1,10 +1,13 @@ -from starlette.requests import Request -from starlette.responses import HTMLResponse, PlainTextResponse import html import traceback +import typing + +from starlette.requests import Request +from starlette.responses import HTMLResponse, PlainTextResponse, Response +from starlette.types import Scope, Receive, Send, Message, ASGIApp, ASGIInstance -def get_debug_response(request, exc): +def get_debug_response(request: Request, exc: Exception) -> Response: accept = request.headers.get("accept", "") if "text/html" in accept: exc_html = "".join(traceback.format_tb(exc.__traceback__)) @@ -18,22 +21,22 @@ def get_debug_response(request, exc): class DebugMiddleware: - def __init__(self, app): + def __init__(self, app: ASGIApp) -> None: self.app = app - def __call__(self, scope): + def __call__(self, scope: Scope) -> ASGIInstance: if scope["type"] != "http": return self.app(scope) return _DebugResponder(self.app, scope) class _DebugResponder: - def __init__(self, app, scope): + def __init__(self, app: ASGIApp, scope: Scope) -> None: self.app = app self.scope = scope self.response_started = False - async def __call__(self, receive, send): + async def __call__(self, receive: Receive, send: Send) -> None: self.raw_send = send try: asgi = self.app(self.scope) @@ -45,7 +48,7 @@ class _DebugResponder: await response(receive, send) raise exc from None - async def send(self, message): + async def send(self, message: Message) -> None: if message["type"] == "http.response.start": self.response_started = True await self.raw_send(message) diff --git a/starlette/endpoints.py b/starlette/endpoints.py index 40d0041..608f28a 100644 --- a/starlette/endpoints.py +++ b/starlette/endpoints.py @@ -1,8 +1,9 @@ import asyncio import typing - +import json from starlette.exceptions import HTTPException from starlette.requests import Request +from starlette.websockets import WebSocket from starlette.responses import Response, PlainTextResponse from starlette.types import Receive, Send, Scope @@ -35,3 +36,67 @@ class HTTPEndpoint: if "app" in self.scope: raise HTTPException(status_code=405) return PlainTextResponse("Method Not Allowed", status_code=405) + + +class WebSocketEndpoint: + + encoding = None # May be "text", "bytes", or "json". + + def __init__(self, scope: Scope): + self.scope = scope + + async def __call__(self, receive: Receive, send: Send): + websocket = WebSocket(self.scope, receive=receive, send=send) + kwargs = self.scope.get("kwargs", {}) + await self.on_connect(websocket, **kwargs) + + close_code = None + + try: + while True: + message = await websocket.receive() + if message["type"] == "websocket.receive": + data = await self.decode(websocket, message) + await self.on_receive(websocket, data) + elif message["type"] == "websocket.disconnect": + close_code = message.get("code", 1000) + return + finally: + await self.on_disconnect(websocket, close_code) + + async def decode(self, websocket, message): + + if self.encoding == "text": + if "text" not in message: + await websocket.close(code=1003) + raise RuntimeError("Expected text websocket messages, but got bytes") + return message["text"] + + elif self.encoding == "bytes": + if "bytes" not in message: + await websocket.close(code=1003) + raise RuntimeError("Expected bytes websocket messages, but got text") + return message["bytes"] + + elif self.encoding == "json": + if "bytes" not in message: + await websocket.close(code=1003) + raise RuntimeError( + "Expected JSON to be transferred as bytes websocket messages, but got text" + ) + return json.loads(message["bytes"].decode("utf-8")) + + assert ( + self.encoding is None + ), f"Unsupported 'encoding' attribute {self.encoding}" + return message["text"] if "text" in message else message["bytes"] + + async def on_connect(self, websocket, **kwargs): + """Override to handle an incoming websocket connection""" + await websocket.accept() + + async def on_receive(self, websocket, data): + """Override to handle an incoming websocket message""" + + async def on_disconnect(self, websocket, close_code): + """Override to handle a disconnecting websocket""" diff --git a/starlette/responses.py b/starlette/responses.py index 369bf92..5ea906b 100644 --- a/starlette/responses.py +++ b/starlette/responses.py @@ -1,5 +1,6 @@ from email.utils import formatdate from mimetypes import guess_type +from starlette.background import BackgroundTask from starlette.datastructures import MutableHeaders from starlette.types import Receive, Send from urllib.parse import quote_plus @@ -41,11 +42,13 @@ class Response: status_code: int = 200, headers: dict = None, media_type: str = None, + background: BackgroundTask = None, ) -> None: self.body = self.render(content) self.status_code = status_code if media_type is not None: self.media_type = media_type + self.background = background self.init_headers(headers) def render(self, content: typing.Any) -> bytes: @@ -96,6 +99,9 @@ class Response: ) await send({"type": "http.response.body", "body": self.body}) + if self.background is not None: + await self.background() + class HTMLResponse(Response): media_type = "text/html"
encode/starlette
29c53d5a54989494f7a7a8cb5ab2379d965467a7
diff --git a/tests/test_background.py b/tests/test_background.py new file mode 100644 index 0000000..1a4c9f5 --- /dev/null +++ b/tests/test_background.py @@ -0,0 +1,52 @@ +from starlette.responses import Response +from starlette.background import BackgroundTask +from starlette.testclient import TestClient +import asyncio + + +def test_async_task(): + async def async_task(): + count = 0 + for num in range(3): + count += 1 + await asyncio.sleep(1) + return count + + task = BackgroundTask(async_task) + + def app(scope): + async def asgi(receive, send): + response = Response( + "task initiated", media_type="text/plain", background=task + ) + await response(receive, send) + + return asgi + + client = TestClient(app) + response = client.get("/") + assert response.text == "task initiated" + + +def test_sync_task(): + def sync_task(): + num = 500 + count = 0 + while count != num: + count += 1 + return count + + task = BackgroundTask(sync_task) + + def app(scope): + async def asgi(receive, send): + response = Response( + "task initiated", media_type="text/plain", background=task + ) + await response(receive, send) + + return asgi + + client = TestClient(app) + response = client.get("/") + assert response.text == "task initiated" diff --git a/tests/test_debug.py b/tests/test_debug.py index a93b277..700c836 100644 --- a/tests/test_debug.py +++ b/tests/test_debug.py @@ -46,7 +46,7 @@ def test_debug_after_response_sent(): app = DebugMiddleware(app) client = TestClient(app) with pytest.raises(RuntimeError): - response = client.get("/") + client.get("/") def test_debug_error_during_scope(): diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py index 4b5a39e..ec93bec 100644 --- a/tests/test_endpoints.py +++ b/tests/test_endpoints.py @@ -2,7 +2,7 @@ import pytest from starlette.responses import PlainTextResponse from starlette.routing import Router, Path from starlette.testclient import TestClient -from starlette.endpoints import HTTPEndpoint +from starlette.endpoints import HTTPEndpoint, WebSocketEndpoint class Homepage(HTTPEndpoint): @@ -17,19 +17,109 @@ app = Router(routes=[Path("/", Homepage), Path("/{username}", Homepage)]) client = TestClient(app) -def test_route(): +def test_http_endpoint_route(): response = client.get("/") assert response.status_code == 200 assert response.text == "Hello, world!" -def test_route_kwargs(): +def test_http_endpoint_route_kwargs(): response = client.get("/tomchristie") assert response.status_code == 200 assert response.text == "Hello, tomchristie!" -def test_route_method(): +def test_http_endpoint_route_method(): response = client.post("/") assert response.status_code == 405 assert response.text == "Method Not Allowed" + + +def test_websocket_endpoint_on_connect(): + class WebSocketApp(WebSocketEndpoint): + async def on_connect(self, websocket, **kwargs): + assert websocket["subprotocols"] == ["soap", "wamp"] + await websocket.accept(subprotocol="wamp") + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws", subprotocols=["soap", "wamp"]) as websocket: + assert websocket.accepted_subprotocol == "wamp" + + +def test_websocket_endpoint_on_receive_bytes(): + class WebSocketApp(WebSocketEndpoint): + encoding = "bytes" + + async def on_receive(self, websocket, data): + await websocket.send_bytes(b"Message bytes was: " + data) + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws") as websocket: + websocket.send_bytes(b"Hello, world!") + _bytes = websocket.receive_bytes() + assert _bytes == b"Message bytes was: Hello, world!" + + with pytest.raises(RuntimeError): + with client.websocket_connect("/ws") as websocket: + websocket.send_text("Hello world") + + +def test_websocket_endpoint_on_receive_json(): + class WebSocketApp(WebSocketEndpoint): + encoding = "json" + + async def on_receive(self, websocket, data): + await websocket.send_json({"message": data}) + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws") as websocket: + websocket.send_json({"hello": "world"}) + data = websocket.receive_json() + assert data == {"message": {"hello": "world"}} + + with pytest.raises(RuntimeError): + with client.websocket_connect("/ws") as websocket: + websocket.send_text("Hello world") + + +def test_websocket_endpoint_on_receive_text(): + class WebSocketApp(WebSocketEndpoint): + encoding = "text" + + async def on_receive(self, websocket, data): + await websocket.send_text(f"Message text was: {data}") + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws") as websocket: + websocket.send_text("Hello, world!") + _text = websocket.receive_text() + assert _text == "Message text was: Hello, world!" + + with pytest.raises(RuntimeError): + with client.websocket_connect("/ws") as websocket: + websocket.send_bytes(b"Hello world") + + +def test_websocket_endpoint_on_default(): + class WebSocketApp(WebSocketEndpoint): + encoding = None + + async def on_receive(self, websocket, data): + await websocket.send_text(f"Message text was: {data}") + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws") as websocket: + websocket.send_text("Hello, world!") + _text = websocket.receive_text() + assert _text == "Message text was: Hello, world!" + + +def test_websocket_endpoint_on_disconnect(): + class WebSocketApp(WebSocketEndpoint): + async def on_disconnect(self, websocket, close_code): + assert close_code == 1001 + await websocket.close(code=close_code) + + client = TestClient(WebSocketApp) + with client.websocket_connect("/ws") as websocket: + websocket.close(code=1001)
Background tasks * Add a `background=...` keyword argument to all responses. It should be either `None` or a coroutine with no arguments. * The response `__call__` should run the background coroutine if it exists (after sending the response). * Provide a `BackgroundTask()` class that wraps a callable and some arguments. This can then be used to pass a function *or* coroutine with args/kwargs to a response. ```python class BackgroundTask: def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs async def __call__(self): if asyncio.iscoroutine(self.func): await self.func(*self.args, **self.kwargs) else: self.func(*self.args, **self.kwargs) ``` Then we can do... ``` return Response(..., background=BackgroundTask(my_func, a=123) ``` Naming might need some thinking about - not sure that conflicting with asyncio's `Task` is ideal. This'd be a good feature to get in, since it's a low amount of work, but provides functionality that WSGI is unable to do.
0.0
[ "tests/test_background.py::test_async_task", "tests/test_background.py::test_sync_task", "tests/test_debug.py::test_debug_text", "tests/test_debug.py::test_debug_html", "tests/test_debug.py::test_debug_after_response_sent", "tests/test_debug.py::test_debug_error_during_scope", "tests/test_debug.py::test_debug_not_http", "tests/test_endpoints.py::test_http_endpoint_route", "tests/test_endpoints.py::test_http_endpoint_route_kwargs", "tests/test_endpoints.py::test_http_endpoint_route_method", "tests/test_endpoints.py::test_websocket_endpoint_on_connect", "tests/test_endpoints.py::test_websocket_endpoint_on_receive_bytes", "tests/test_endpoints.py::test_websocket_endpoint_on_receive_json", "tests/test_endpoints.py::test_websocket_endpoint_on_receive_text", "tests/test_endpoints.py::test_websocket_endpoint_on_default", "tests/test_endpoints.py::test_websocket_endpoint_on_disconnect" ]
[]
2018-09-22 20:31:40+00:00
2,148
encode__starlette-699
diff --git a/starlette/datastructures.py b/starlette/datastructures.py index 930c581..4080624 100644 --- a/starlette/datastructures.py +++ b/starlette/datastructures.py @@ -21,7 +21,7 @@ class URL: scheme = scope.get("scheme", "http") server = scope.get("server", None) path = scope.get("root_path", "") + scope["path"] - query_string = scope["query_string"] + query_string = scope.get("query_string", b"") host_header = None for key, value in scope["headers"]: @@ -185,7 +185,8 @@ class URLPath(str): else: netloc = base_url.netloc - return str(URL(scheme=scheme, netloc=netloc, path=str(self))) + path = base_url.path.rstrip("/") + str(self) + return str(URL(scheme=scheme, netloc=netloc, path=path)) class Secret: diff --git a/starlette/requests.py b/starlette/requests.py index a9955cf..c2f9f2b 100644 --- a/starlette/requests.py +++ b/starlette/requests.py @@ -56,6 +56,18 @@ class HTTPConnection(Mapping): self._url = URL(scope=self.scope) return self._url + @property + def base_url(self) -> URL: + if not hasattr(self, "_base_url"): + base_url_scope = dict(self.scope) + base_url_scope["path"] = "/" + base_url_scope["query_string"] = b"" + base_url_scope["root_path"] = base_url_scope.get( + "app_root_path", base_url_scope.get("root_path", "") + ) + self._base_url = URL(scope=base_url_scope) + return self._base_url + @property def headers(self) -> Headers: if not hasattr(self, "_headers"): @@ -123,7 +135,7 @@ class HTTPConnection(Mapping): def url_for(self, name: str, **path_params: typing.Any) -> str: router = self.scope["router"] url_path = router.url_path_for(name, **path_params) - return url_path.make_absolute_url(base_url=self.url) + return url_path.make_absolute_url(base_url=self.base_url) async def empty_receive() -> Message: diff --git a/starlette/routing.py b/starlette/routing.py index 48ed8ee..7a0d7ef 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -309,9 +309,11 @@ class Mount(BaseRoute): matched_path = path[: -len(remaining_path)] path_params = dict(scope.get("path_params", {})) path_params.update(matched_params) + root_path = scope.get("root_path", "") child_scope = { "path_params": path_params, - "root_path": scope.get("root_path", "") + matched_path, + "app_root_path": scope.get("app_root_path", root_path), + "root_path": root_path + matched_path, "path": remaining_path, "endpoint": self.app, }
encode/starlette
1ea45ad54954e6af78a640acc4cd7cc665beb901
diff --git a/starlette/testclient.py b/starlette/testclient.py index eb0e8be..471e623 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -88,9 +88,12 @@ class _WrapASGI2: class _ASGIAdapter(requests.adapters.HTTPAdapter): - def __init__(self, app: ASGI3App, raise_server_exceptions: bool = True) -> None: + def __init__( + self, app: ASGI3App, raise_server_exceptions: bool = True, root_path: str = "" + ) -> None: self.app = app self.raise_server_exceptions = raise_server_exceptions + self.root_path = root_path def send( # type: ignore self, request: requests.PreparedRequest, *args: typing.Any, **kwargs: typing.Any @@ -131,7 +134,7 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): scope = { "type": "websocket", "path": unquote(path), - "root_path": "", + "root_path": self.root_path, "scheme": scheme, "query_string": query.encode(), "headers": headers, @@ -147,7 +150,7 @@ class _ASGIAdapter(requests.adapters.HTTPAdapter): "http_version": "1.1", "method": request.method, "path": unquote(path), - "root_path": "", + "root_path": self.root_path, "scheme": scheme, "query_string": query.encode(), "headers": headers, @@ -365,6 +368,7 @@ class TestClient(requests.Session): app: typing.Union[ASGI2App, ASGI3App], base_url: str = "http://testserver", raise_server_exceptions: bool = True, + root_path: str = "", ) -> None: super(TestClient, self).__init__() if _is_asgi3(app): @@ -374,7 +378,9 @@ class TestClient(requests.Session): app = typing.cast(ASGI2App, app) asgi_app = _WrapASGI2(app) # Β type: ignore adapter = _ASGIAdapter( - asgi_app, raise_server_exceptions=raise_server_exceptions + asgi_app, + raise_server_exceptions=raise_server_exceptions, + root_path=root_path, ) self.mount("http://", adapter) self.mount("https://", adapter) diff --git a/tests/test_routing.py b/tests/test_routing.py index 3c0c4cd..9723e46 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -1,5 +1,6 @@ import pytest +from starlette.applications import Starlette from starlette.responses import JSONResponse, PlainTextResponse, Response from starlette.routing import Host, Mount, NoMatchFound, Route, Router, WebSocketRoute from starlette.testclient import TestClient @@ -164,12 +165,24 @@ def test_url_for(): app.url_path_for("homepage").make_absolute_url(base_url="https://example.org") == "https://example.org/" ) + assert ( + app.url_path_for("homepage").make_absolute_url( + base_url="https://example.org/root_path/" + ) + == "https://example.org/root_path/" + ) assert ( app.url_path_for("user", username="tomchristie").make_absolute_url( base_url="https://example.org" ) == "https://example.org/users/tomchristie" ) + assert ( + app.url_path_for("user", username="tomchristie").make_absolute_url( + base_url="https://example.org/root_path/" + ) + == "https://example.org/root_path/users/tomchristie" + ) assert ( app.url_path_for("websocket_endpoint").make_absolute_url( base_url="https://example.org" @@ -353,3 +366,37 @@ def test_subdomain_reverse_urls(): ).make_absolute_url("https://whatever") == "https://foo.example.org/homepage" ) + + +async def echo_urls(request): + return JSONResponse( + { + "index": request.url_for("index"), + "submount": request.url_for("mount:submount"), + } + ) + + +echo_url_routes = [ + Route("/", echo_urls, name="index", methods=["GET"]), + Mount( + "/submount", + name="mount", + routes=[Route("/", echo_urls, name="submount", methods=["GET"])], + ), +] + + +def test_url_for_with_root_path(): + app = Starlette(routes=echo_url_routes) + client = TestClient(app, base_url="https://www.example.org/", root_path="/sub_path") + response = client.get("/") + assert response.json() == { + "index": "https://www.example.org/sub_path/", + "submount": "https://www.example.org/sub_path/submount/", + } + response = client.get("/submount/") + assert response.json() == { + "index": "https://www.example.org/sub_path/", + "submount": "https://www.example.org/sub_path/submount/", + }
Starlette behind reverse proxy, url_for does not return externally valid urls Suppose I have my application reverse proxied, such that http://my.domain/foo (e.g. Traefik or Nginx) has the upstream http://localhost:8000 (the Starlette app). `url_for` will generate urls relative to the upstream url. How do I make it produce urls relative to the external url (with prefix /foo)? For other projects, e.g. Flask/Werkzeug, this can be handled by setting `SCRIPT_NAME` in the request environment (scope) if the 'X-Forwarded-Prefix' header is set. It does not look like there is an equivalent option in Starlette. Am I missing something? Otherwise, consider this a feature request.
0.0
[ "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_url_for_with_root_path" ]
[ "tests/test_routing.py::test_router", "tests/test_routing.py::test_route_converters", "tests/test_routing.py::test_url_path_for", "tests/test_routing.py::test_router_add_route", "tests/test_routing.py::test_router_duplicate_path", "tests/test_routing.py::test_router_add_websocket_route", "tests/test_routing.py::test_protocol_switch", "tests/test_routing.py::test_mount_urls", "tests/test_routing.py::test_reverse_mount_urls", "tests/test_routing.py::test_mount_at_root", "tests/test_routing.py::test_host_routing", "tests/test_routing.py::test_host_reverse_urls", "tests/test_routing.py::test_subdomain_routing", "tests/test_routing.py::test_subdomain_reverse_urls" ]
2019-11-01 13:08:52+00:00
2,149
encode__starlette-701
diff --git a/starlette/routing.py b/starlette/routing.py index 7a0d7ef..a1e4619 100644 --- a/starlette/routing.py +++ b/starlette/routing.py @@ -336,15 +336,18 @@ class Mount(BaseRoute): else: # 'name' matches "<mount_name>:<child_name>". remaining_name = name[len(self.name) + 1 :] + path_kwarg = path_params.get("path") path_params["path"] = "" - path, remaining_params = replace_params( + path_prefix, remaining_params = replace_params( self.path_format, self.param_convertors, path_params ) + if path_kwarg is not None: + remaining_params["path"] = path_kwarg for route in self.routes or []: try: url = route.url_path_for(remaining_name, **remaining_params) return URLPath( - path=path.rstrip("/") + str(url), protocol=url.protocol + path=path_prefix.rstrip("/") + str(url), protocol=url.protocol ) except NoMatchFound: pass
encode/starlette
a92df1f61ede3b63ee9dcb315ce363c14242597b
diff --git a/tests/test_routing.py b/tests/test_routing.py index 9723e46..30645ef 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -400,3 +400,14 @@ def test_url_for_with_root_path(): "index": "https://www.example.org/sub_path/", "submount": "https://www.example.org/sub_path/submount/", } + + +double_mount_routes = [ + Mount("/mount", name="mount", routes=[Mount("/static", ..., name="static")],), +] + + +def test_url_for_with_double_mount(): + app = Starlette(routes=double_mount_routes) + url = app.url_path_for("mount:static", path="123") + assert url == "/mount/static/123"
Mounts without a name strips the path arg from calls to child routes in url_path_for I'm using an unnamed Mount which contains a mount to a StaticFiles instance and when using "url_for" it is unable to find the matching file. After a bit of digging it seems to be directly related to url_for_path in Mount clearing the path arg whenever the mount does not have a name set. https://github.com/encode/starlette/blob/master/starlette/routing.py#L337 Calling url_path_for in the child router works as expected. I'm unclear as to why you'd want to strip this arg just because the mount is not named. ``` app.mount('/stuff', app=Router(routes=[ Mount('/static', app=StaticFiles(directory='static'), name='static'), ])) ``` ``` In [6]: app.url_path_for('static', path='css/bootstap.min.css') --------------------------------------------------------------------------- NoMatchFound ... In [7]: app.routes[0].routes[0].url_path_for('static', path='css/bootstap.min.css') Out[7]: '/static/css/bootstap.min.css' ```
0.0
[ "tests/test_routing.py::test_url_for_with_double_mount" ]
[ "tests/test_routing.py::test_router", "tests/test_routing.py::test_route_converters", "tests/test_routing.py::test_url_path_for", "tests/test_routing.py::test_url_for", "tests/test_routing.py::test_router_add_route", "tests/test_routing.py::test_router_duplicate_path", "tests/test_routing.py::test_router_add_websocket_route", "tests/test_routing.py::test_protocol_switch", "tests/test_routing.py::test_mount_urls", "tests/test_routing.py::test_reverse_mount_urls", "tests/test_routing.py::test_mount_at_root", "tests/test_routing.py::test_host_routing", "tests/test_routing.py::test_host_reverse_urls", "tests/test_routing.py::test_subdomain_routing", "tests/test_routing.py::test_subdomain_reverse_urls", "tests/test_routing.py::test_url_for_with_root_path" ]
2019-11-01 15:15:31+00:00
2,150
encode__starlette-8
diff --git a/README.md b/README.md index f80bdb0..a8fb92f 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ the incoming request, rather than accessing the ASGI scope and receive channel d ### Request -Signature: `Request(scope, receive)` +Signature: `Request(scope, receive=None)` ```python class App: @@ -166,6 +166,11 @@ class App: await response(receive, send) ``` +Requests present a mapping interface, so you can use them in the same +way as a `scope`. + +For instance: `request['path']` will return the ASGI path. + #### Method The request method is accessed as `request.method`. diff --git a/starlette/decorators.py b/starlette/decorators.py index 8c57531..6c7969b 100644 --- a/starlette/decorators.py +++ b/starlette/decorators.py @@ -5,8 +5,10 @@ from starlette.types import ASGIInstance, Receive, Send, Scope def asgi_application(func): def app(scope: Scope) -> ASGIInstance: + request = Request(scope) + async def awaitable(receive: Receive, send: Send) -> None: - request = Request(scope, receive) + request.set_receive_channel(receive) response = func(request) await response(receive, send) diff --git a/starlette/request.py b/starlette/request.py index 25918e0..b677bee 100644 --- a/starlette/request.py +++ b/starlette/request.py @@ -1,19 +1,33 @@ from starlette.datastructures import URL, Headers, QueryParams +from collections.abc import Mapping import json +import typing -class Request: - def __init__(self, scope, receive): +class Request(Mapping): + def __init__(self, scope, receive=None): self._scope = scope self._receive = receive self._stream_consumed = False + def __getitem__(self, key): + return self._scope[key] + + def __iter__(self): + return iter(self._scope) + + def __len__(self): + return len(self._scope) + + def set_receive_channel(self, receive): + self._receive = receive + @property - def method(self): + def method(self) -> str: return self._scope["method"] @property - def url(self): + def url(self) -> URL: if not hasattr(self, "_url"): scheme = self._scope["scheme"] host, port = self._scope["server"] @@ -32,7 +46,7 @@ class Request: return self._url @property - def headers(self): + def headers(self) -> Headers: if not hasattr(self, "_headers"): self._headers = Headers( [ @@ -43,7 +57,7 @@ class Request: return self._headers @property - def query_params(self): + def query_params(self) -> QueryParams: if not hasattr(self, "_query_params"): query_string = self._scope["query_string"].decode() self._query_params = QueryParams(query_string) @@ -57,6 +71,9 @@ class Request: if self._stream_consumed: raise RuntimeError("Stream consumed") + if self._receive is None: + raise RuntimeError("Receive channel has not been made available") + self._stream_consumed = True while True: message = await self._receive()
encode/starlette
4c621d58c0ce2f111fee4745f944ea6417f1cb53
diff --git a/tests/test_request.py b/tests/test_request.py index 8dd2d41..fbbc4cd 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -157,3 +157,37 @@ def test_request_json(): client = TestClient(app) response = client.post("/", json={"a": "123"}) assert response.json() == {"json": {"a": "123"}} + + +def test_request_scope_interface(): + """ + A Request can be isntantiated with a scope, and presents a `Mapping` + interface. + """ + request = Request({"method": "GET", "path": "/abc/"}) + assert request["method"] == "GET" + assert dict(request) == {"method": "GET", "path": "/abc/"} + assert len(request) == 2 + + +def test_request_without_setting_receive(): + """ + If Request is instantiated without the receive channel, then .body() + is not available. + """ + + def app(scope): + async def asgi(receive, send): + request = Request(scope) + try: + data = await request.json() + except RuntimeError: + data = "Receive channel not available" + response = JSONResponse({"json": data}) + await response(receive, send) + + return asgi + + client = TestClient(app) + response = client.post("/", json={"a": "123"}) + assert response.json() == {"json": "Receive channel not available"}
Request should present a scope-like interface The `Request` class should present a dict-like interface so that it can be used in the same way as `scope`. Should also allow it to be instantiated without a `receive` channel being set initially.
0.0
[ "tests/test_request.py::test_request_scope_interface", "tests/test_request.py::test_request_without_setting_receive" ]
[ "tests/test_request.py::test_request_url", "tests/test_request.py::test_request_query_params", "tests/test_request.py::test_request_headers", "tests/test_request.py::test_request_body", "tests/test_request.py::test_request_stream", "tests/test_request.py::test_request_body_then_stream", "tests/test_request.py::test_request_stream_then_body", "tests/test_request.py::test_request_json" ]
2018-06-26 09:52:39+00:00
2,151
encode__starlette-801
diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index ad2eeff..90ba180 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -87,7 +87,7 @@ class CORSMiddleware: if self.allow_all_origins: return True - if self.allow_origin_regex is not None and self.allow_origin_regex.match( + if self.allow_origin_regex is not None and self.allow_origin_regex.fullmatch( origin ): return True
encode/starlette
5c43dde0ec0917673bb280bcd7ab0c37b78061b7
diff --git a/tests/middleware/test_cors.py b/tests/middleware/test_cors.py index bcba704..e8bf72f 100644 --- a/tests/middleware/test_cors.py +++ b/tests/middleware/test_cors.py @@ -122,7 +122,7 @@ def test_cors_allow_origin_regex(): app.add_middleware( CORSMiddleware, allow_headers=["X-Example", "Content-Type"], - allow_origin_regex="https://*", + allow_origin_regex="https://.*", ) @app.route("/") @@ -171,6 +171,39 @@ def test_cors_allow_origin_regex(): assert "access-control-allow-origin" not in response.headers +def test_cors_allow_origin_regex_fullmatch(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, + allow_headers=["X-Example", "Content-Type"], + allow_origin_regex="https://.*\.example.org", + ) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test standard response + headers = {"Origin": "https://subdomain.example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert ( + response.headers["access-control-allow-origin"] + == "https://subdomain.example.org" + ) + + # Test diallowed standard response + headers = {"Origin": "https://subdomain.example.org.hacker.com"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert "access-control-allow-origin" not in response.headers + + def test_cors_credentialed_requests_return_specific_origin(): app = Starlette()
Dangerous example regex for CORS Middleware? Looking at the docs for CORS Middlware here: https://www.starlette.io/middleware/#corsmiddleware , under the `allow_origin_regex` attribute, the example value is `https://.*\.example\.org`. However, based on the handler code for this at https://github.com/encode/starlette/blob/ab86530eddfcf56e0f7e5ca56f6ab69c15594a7d/starlette/middleware/cors.py#L90 , it appears `https://www.example.org.hacker.com` would pass as a valid origin, right? It seems like the example should be `https://.*\.example\.org$`, yes?
0.0
[ "tests/middleware/test_cors.py::test_cors_allow_origin_regex_fullmatch" ]
[ "tests/middleware/test_cors.py::test_cors_allow_all", "tests/middleware/test_cors.py::test_cors_allow_specific_origin", "tests/middleware/test_cors.py::test_cors_disallowed_preflight", "tests/middleware/test_cors.py::test_cors_allow_origin_regex", "tests/middleware/test_cors.py::test_cors_credentialed_requests_return_specific_origin", "tests/middleware/test_cors.py::test_cors_vary_header_defaults_to_origin", "tests/middleware/test_cors.py::test_cors_vary_header_is_properly_set", "tests/middleware/test_cors.py::test_cors_allowed_origin_does_not_leak_between_credentialed_requests" ]
2020-01-14 22:31:47+00:00
2,152
encode__starlette-83
diff --git a/docs/background.md b/docs/background.md index 0b6789a..de7135f 100644 --- a/docs/background.md +++ b/docs/background.md @@ -6,7 +6,7 @@ the response has been sent. ### Background Task -Signature: `BackgroundTask(func, *args, **kwargs) +Signature: `BackgroundTask(func, *args, **kwargs)` ```python from starlette.applications import Starlette diff --git a/docs/middleware.md b/docs/middleware.md new file mode 100644 index 0000000..9f0c026 --- /dev/null +++ b/docs/middleware.md @@ -0,0 +1,111 @@ + +Starlette includes several middleware classes for adding behaviour that is applied across your entire application. These are all implemented as standard ASGI +middleware classes, and can be applied either to Starlette or to any other ASGI application. + +The Starlette application class allows you to include the ASGI middleware +in a way that ensures that it remains wrapped by the exception handler. + +```python +from starlette.applications import Starlette +from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware +from starlette.middleware.trustedhost import TrustedHostMiddleware + + +app = Starlette() + +# Ensure that all requests include an 'example.com' host header, +# and strictly enforce https-only access. +app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com']) +app.add_middleware(HTTPSRedirectMiddleware) +``` + +The following middleware implementations are available in the Starlette package: + +## CORSMiddleware + +Adds appropriate [CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) to outgoing responses in order to allow cross-origin requests from browsers. + +The default parameters used by the CORSMiddleware implementation are restrictive by default, +so you'll need to explicitly enable particular origins, methods, or headers, in order +for browsers to be permitted to use them in a Cross-Domain context. + +```python +from starlette.applications import Starlette +from starlette.middleware.cors import CORSMiddleware + + +app = Starlette() +app.add_middleware(CORSMiddleware, allow_origins=['*']) +``` + +The following arguments are supported: + +* `allow_origins` - A list of origins that should be permitted to make cross-origin requests. eg. `['https://example.org', 'https://www.example.org']`. You can use `['*']` to allow any origin. +* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`. You can use `['*']` to allow all standard methods. +* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers. The `Accept`, `Accept-Language`, `Content-Language` and `Content-Type` headers are always allowed for CORS requests. +* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`. +* `expose_headers` - Indicate any response headers that should be made accessible to the browser. Defaults to `[]`. +* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `60`. + +The middleware responds to two particular types of HTTP request... + +#### CORS preflight requests + +These are any `OPTION` request with `Origin` and `Access-Control-Request-Method` headers. +In this case the middleware will intercept the incoming request and respond with +appropriate CORS headers, and either a 200 or 400 response for informational purposes. + +#### Simple requests + +Any request with an `Origin` header. In this case the middleware will pass the +request through as normal, but will include appropriate CORS headers on the response. + +## HTTPSRedirectMiddleware + +Enforces that all incoming requests must either be `https` or `wss`. Any incoming +requests to `http` or `ws` will be redirected to the secure scheme instead. + +```python +from starlette.applications import Starlette +from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware + + +app = Starlette() +app.add_middleware(HTTPSRedirectMiddleware) +``` + +There are no configuration options for this middleware class. + +## TrustedHostMiddleware + +Enforces that all incoming requests have a correctly set `Host` header, in order +to guard against HTTP Host Header attacks. + +```python +from starlette.applications import Starlette +from starlette.middleware.trustedhost import TrustedHostMiddleware + + +app = Starlette() +app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com']) +``` + +The following arguments are supported: + +* `allowed_hosts` - A list of domain names that should be allowed as hostnames. + +If an incoming request does not validate correctly then a 400 response will be sent. + +## Using ASGI middleware without Starlette + +To wrap ASGI middleware around other ASGI applications, you should use the +more general pattern of wrapping the application instance: + +```python +app = TrustedHostMiddleware(app, allowed_hosts=['example.com']) +``` + +You can do this with a Starlette application instance too, but it is preferable +to use `.add_middleware`, as it'll ensure that you don't lose the reference +to the application object, and that the exception handling always wraps around +any other behaviour. diff --git a/starlette/datastructures.py b/starlette/datastructures.py index c5fece3..d00f3f4 100644 --- a/starlette/datastructures.py +++ b/starlette/datastructures.py @@ -274,3 +274,7 @@ class MutableHeaders(Headers): return item_value.decode("latin-1") self._list.append((set_key, set_value)) return value + + def update(self, other: dict): + for key, val in other.items(): + self[key] = val diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index e69de29..aa367f9 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -0,0 +1,130 @@ +from starlette.datastructures import Headers, MutableHeaders, URL +from starlette.responses import PlainTextResponse +from starlette.types import ASGIApp, ASGIInstance, Scope +import functools +import typing + + +ALL_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT") + + +class CORSMiddleware: + def __init__( + self, + app: ASGIApp, + allow_origins: typing.Sequence[str] = (), + allow_methods: typing.Sequence[str] = ("GET",), + allow_headers: typing.Sequence[str] = (), + allow_credentials: bool = False, + expose_headers: typing.Sequence[str] = (), + max_age: int = 600, + ): + + if "*" in allow_methods: + allow_methods = ALL_METHODS + + simple_headers = {} + if "*" in allow_origins: + simple_headers["Access-Control-Allow-Origin"] = "*" + if allow_credentials: + simple_headers["Access-Control-Allow-Credentials"] = "true" + if expose_headers: + simple_headers["Access-Control-Expose-Headers"] = ", ".join(expose_headers) + + preflight_headers = {} + if "*" in allow_origins: + preflight_headers["Access-Control-Allow-Origin"] = "*" + else: + preflight_headers["Vary"] = "Origin" + preflight_headers.update( + { + "Access-Control-Allow-Methods": ", ".join(allow_methods), + "Access-Control-Max-Age": str(max_age), + } + ) + if allow_headers and "*" not in allow_headers: + preflight_headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers) + if allow_credentials: + preflight_headers["Access-Control-Allow-Credentials"] = "true" + + self.app = app + self.allow_origins = allow_origins + self.allow_methods = allow_methods + self.allow_headers = allow_headers + self.allow_all_origins = "*" in allow_origins + self.allow_all_headers = "*" in allow_headers + self.simple_headers = simple_headers + self.preflight_headers = preflight_headers + + def __call__(self, scope: Scope): + if scope["type"] == "http": + method = scope["method"] + headers = Headers(scope["headers"]) + origin = headers.get("origin") + + if origin is not None: + if method == "OPTIONS" and "access-control-request-method" in headers: + return self.preflight_response(request_headers=headers) + else: + return functools.partial( + self.simple_response, scope=scope, origin=origin + ) + + return self.app(scope) + + def preflight_response(self, request_headers): + requested_origin = request_headers["origin"] + requested_method = request_headers["access-control-request-method"] + requested_headers = request_headers.get("access-control-request-headers") + requested_cookie = "cookie" in request_headers + + headers = dict(self.preflight_headers) + failures = [] + + # If we only allow specific origins, then we have to mirror back + # the Origin header in the response. + if not self.allow_all_origins: + if requested_origin in self.allow_origins: + headers["Access-Control-Allow-Origin"] = requested_origin + else: + failures.append("origin") + + if requested_method not in self.allow_methods: + failures.append("method") + + # If we allow all headers, then we have to mirror back any requested + # headers in the response. + if self.allow_all_headers and requested_headers is not None: + headers["Access-Control-Allow-Headers"] = requested_headers + elif requested_headers is not None: + for header in requested_headers.split(","): + if header.strip() not in self.allow_headers: + failures.append("headers") + + # We don't strictly need to use 400 responses here, since its up to + # the browser to enforce the CORS policy, but its more informative + # if we do. + if failures: + failure_text = "Disallowed CORS " + ", ".join(failures) + return PlainTextResponse(failure_text, status_code=400, headers=headers) + + return PlainTextResponse("OK", status_code=200, headers=headers) + + async def simple_response(self, receive, send, scope=None, origin=None): + inner = self.app(scope) + send = functools.partial(self.send, send=send, origin=origin) + await inner(receive, send) + + async def send(self, message, send=None, origin=None): + if message["type"] != "http.response.start": + await send(message) + + message.setdefault("headers", []) + headers = MutableHeaders(message["headers"]) + + # If we only allow specific origins, then we have to mirror back + # the Origin header in the response. + if not self.allow_all_origins and origin in self.allow_origins: + headers["Access-Control-Allow-Origin"] = origin + headers.update(self.simple_headers) + await send(message) diff --git a/starlette/middleware/httpsredirect.py b/starlette/middleware/httpsredirect.py index a608301..6420804 100644 --- a/starlette/middleware/httpsredirect.py +++ b/starlette/middleware/httpsredirect.py @@ -1,12 +1,13 @@ from starlette.datastructures import URL from starlette.responses import RedirectResponse +from starlette.types import ASGIApp, ASGIInstance, Scope class HTTPSRedirectMiddleware: - def __init__(self, app): + def __init__(self, app: ASGIApp) -> None: self.app = app - def __call__(self, scope): + def __call__(self, scope: Scope) -> ASGIInstance: if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): redirect_scheme = {"http": "https", "ws": "wss"}[scope["scheme"]] url = URL(scope=scope) diff --git a/starlette/middleware/trustedhost.py b/starlette/middleware/trustedhost.py index a3966e3..d0e57c0 100644 --- a/starlette/middleware/trustedhost.py +++ b/starlette/middleware/trustedhost.py @@ -1,14 +1,18 @@ from starlette.datastructures import Headers from starlette.responses import PlainTextResponse +from starlette.types import ASGIApp, ASGIInstance, Scope +import typing class TrustedHostMiddleware: - def __init__(self, app, allowed_hosts=["*"]): + def __init__( + self, app: ASGIApp, allowed_hosts: typing.Sequence[str] = ["*"] + ) -> None: self.app = app self.allowed_hosts = allowed_hosts self.allow_any = "*" in allowed_hosts - def __call__(self, scope): + def __call__(self, scope: Scope) -> ASGIInstance: if scope["type"] in ("http", "websocket") and not self.allow_any: headers = Headers(scope["headers"]) host = headers.get("host")
encode/starlette
19670ae2cd5ec4a78d610f7ceebbf896fd8fc049
diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 2649134..07a22b0 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -1,6 +1,7 @@ from starlette.applications import Starlette -from starlette.middleware.trustedhost import TrustedHostMiddleware +from starlette.middleware.cors import CORSMiddleware from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware +from starlette.middleware.trustedhost import TrustedHostMiddleware from starlette.responses import PlainTextResponse from starlette.testclient import TestClient @@ -40,3 +41,115 @@ def test_https_redirect_middleware(): response = client.get("/", allow_redirects=False) assert response.status_code == 301 assert response.headers["location"] == "https://testserver/" + + +def test_cors_allow_all(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_headers=["*"], + allow_methods=["*"], + expose_headers=["X-Status"], + allow_credentials=True, + ) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test pre-flight response + headers = { + "Origin": "https://example.org", + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "X-Example", + } + response = client.options("/", headers=headers) + assert response.status_code == 200 + assert response.text == "OK" + assert response.headers["access-control-allow-origin"] == "*" + assert response.headers["access-control-allow-headers"] == "X-Example" + + # Test standard response + headers = {"Origin": "https://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert response.headers["access-control-allow-origin"] == "*" + assert response.headers["access-control-expose-headers"] == "X-Status" + + # Test non-CORS response + response = client.get("/") + assert response.status_code == 200 + assert response.text == "Homepage" + assert "access-control-allow-origin" not in response.headers + + +def test_cors_allow_specific_origin(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, + allow_origins=["https://example.org"], + allow_headers=["X-Example"], + ) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test pre-flight response + headers = { + "Origin": "https://example.org", + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "X-Example", + } + response = client.options("/", headers=headers) + assert response.status_code == 200 + assert response.text == "OK" + assert response.headers["access-control-allow-origin"] == "https://example.org" + assert response.headers["access-control-allow-headers"] == "X-Example" + + # Test standard response + headers = {"Origin": "https://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert response.headers["access-control-allow-origin"] == "https://example.org" + + # Test non-CORS response + response = client.get("/") + assert response.status_code == 200 + assert response.text == "Homepage" + assert "access-control-allow-origin" not in response.headers + + +def test_cors_disallowed_preflight(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, + allow_origins=["https://example.org"], + allow_headers=["X-Example"], + ) + + @app.route("/") + def homepage(request): + pass # pragma: no cover + + client = TestClient(app) + + # Test pre-flight response + headers = { + "Origin": "https://another.org", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "X-Nope", + } + response = client.options("/", headers=headers) + assert response.status_code == 400 + assert response.text == "Disallowed CORS origin, method, headers"
CORS support Related to https://github.com/encode/starlette/issues/1 I'm having trouble figuring out an appropriate pattern for including CORS support. My use-case is that I am connecting a React app to an ASGI backend that uses Starlette's routing and response classes, but enabling CORS support would require altering the response class headers which cannot be accomplished simply by wrapping the ASGI app at this point. What should CORS support look like in Starlette? An example of my use-case can be found [here](https://github.com/erm/apistar-react/blob/master/app.py), it uses APIStar and a CORS extension to achieve what I want to do with Starlette as well. Below is my work-in-progress attempt at an ASGI CORS middleware that I would ultimately like to work into Starlette somehow. ```python3 from starlette import PlainTextResponse from starlette.datastructures import Headers ACCESS_CONTROL_ALLOW_ORIGIN = b"Access-Control-Allow-Origin" ACCESS_CONTROL_EXPOSE_HEADERS = b"Access-Control-Expose-Headers" ACCESS_CONTROL_ALLOW_CREDENTIALS = b"Access-Control-Allow-Credentials" ACCESS_CONTROL_ALLOW_HEADERS = b"Access-Control-Allow-Headers" ACCESS_CONTROL_ALLOW_METHODS = b"Access-Control-Allow-Methods" ACCESS_CONTROL_MAX_AGE = b"Access-Control-Max-Age" ACCESS_CONTROL_REQUEST_METHOD = b"Access-Control-Request-Method" ACCESS_CONTROL_REQUEST_HEADERS = b"Access-Control-Request-Headers" DEFAULT_OPTIONS = { "allow_origin": [b"*"], "allow_credentials": False, "allow_headers": [b"*"], "allow_methods": [ b"GET", b"HEAD", b"POST", b"OPTIONS", b"PUT", b"PATCH", b"DELETE", ], "expose_headers": [b""], "max_age": b"86400", } class CORSMiddleware: def __init__(self, app, options=None): self.app = app self.options = options or DEFAULT_OPTIONS def __call__(self, scope): headers = Headers(scope.get("headers", [])) origin = headers.get("origin", None) if origin is None: return self.app(scope) allow_origin = self.options["allow_origin"] if origin not in allow_origin and b"*" not in allow_origin: return PlainTextResponse("Origin not allowed", status_code=400) if scope["method"] == "OPTIONS": method = headers.get(ACCESS_CONTROL_REQUEST_METHOD, None) if method is None: return PlainTextResponse( "Access-Control-Request-Method header missing", status_code=400 ) cors_headers = [] if origin != "*" and len(allow_origin) > 1: # todo double-check this cors_headers.append((b"vary", b"origin")) cors_allow_origin = b", ".join(self.options["allow_origin"]) cors_allow_credentials = self.options["allow_credentials"] cors_allow_headers = b", ".join(self.options["allow_headers"]) cors_allow_methods = b", ".join(self.options["allow_methods"]) cors_expose_headers = b", ".join(self.options["expose_headers"]) cors_max_age = self.options["max_age"] cors_headers.append((ACCESS_CONTROL_ALLOW_ORIGIN, cors_allow_origin)) cors_headers.append((ACCESS_CONTROL_ALLOW_METHODS, cors_allow_methods)) cors_headers.append((ACCESS_CONTROL_ALLOW_HEADERS, cors_allow_headers)) cors_headers.append((ACCESS_CONTROL_ALLOW_CREDENTIALS, cors_allow_credentials)) cors_headers.append((ACCESS_CONTROL_EXPOSE_HEADERS, cors_expose_headers)) cors_headers.append((ACCESS_CONTROL_MAX_AGE, cors_max_age)) scope["headers"].extend(cors_headers) print(scope["headers"]) return self.app(scope) ```
0.0
[ "tests/test_middleware.py::test_trusted_host_middleware", "tests/test_middleware.py::test_https_redirect_middleware", "tests/test_middleware.py::test_cors_allow_all", "tests/test_middleware.py::test_cors_allow_specific_origin", "tests/test_middleware.py::test_cors_disallowed_preflight" ]
[]
2018-10-05 15:33:51+00:00
2,153
encode__starlette-867
diff --git a/docs/requests.md b/docs/requests.md index f0ffc66..a72cb75 100644 --- a/docs/requests.md +++ b/docs/requests.md @@ -73,6 +73,8 @@ Cookies are exposed as a regular dictionary interface. For example: `request.cookies.get('mycookie')` +Cookies are ignored in case of an invalid cookie. (RFC2109) + #### Body There are a few different interfaces for returning the body of the request: diff --git a/starlette/requests.py b/starlette/requests.py index 1f7b09e..0ebeb3f 100644 --- a/starlette/requests.py +++ b/starlette/requests.py @@ -91,7 +91,10 @@ class HTTPConnection(Mapping): cookie_header = self.headers.get("cookie") if cookie_header: cookie = http.cookies.SimpleCookie() # type: http.cookies.BaseCookie - cookie.load(cookie_header) + try: + cookie.load(cookie_header) + except http.cookies.CookieError: + pass for key, morsel in cookie.items(): cookies[key] = morsel.value self._cookies = cookies
encode/starlette
0cb2d909a2a6d21219c66f8eec75a95f4b6d1c53
diff --git a/tests/test_requests.py b/tests/test_requests.py index defdf3a..3381249 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -285,6 +285,17 @@ def test_request_cookies(): assert response.text == "Hello, cookies!" +def test_invalid_cookie(): + async def app(scope, receive, send): + request = Request(scope, receive) + response = JSONResponse({"cookies": request.cookies}) + await response(scope, receive, send) + + client = TestClient(app) + response = client.get("/", cookies={"invalid/cookie": "test", "valid": "test2"}) + assert response.json() == {"cookies": {}} + + def test_chunked_encoding(): async def app(scope, receive, send): request = Request(scope, receive)
[bug] Invalid cookie name leads to exception When handling a request with an invalid cookie name (does not conform to RFC2109) starlette raises an exception. i.e iam/cookiename This is because Starlette uses Python's stdlib cookie library, which is very strict. I do understand the strictness, but in real life scenarios you receive such malformed cookies and I want to handle those requests. My suggestion for a solution would be to catch those exceptions and ignore the invalid cookie. ** EDIT ** I just realized stdlib is used for the whole cookie header, hence can't ignore only one cookie. I'll create a PR for ignoring the whole cookie on such case, but maybe we should create our own Cookie/Morsel class and override the methods to ignore such error in the inbound case?
0.0
[ "tests/test_requests.py::test_invalid_cookie" ]
[ "tests/test_requests.py::test_request_url", "tests/test_requests.py::test_request_query_params", "tests/test_requests.py::test_request_headers", "tests/test_requests.py::test_request_client", "tests/test_requests.py::test_request_body", "tests/test_requests.py::test_request_stream", "tests/test_requests.py::test_request_form_urlencoded", "tests/test_requests.py::test_request_body_then_stream", "tests/test_requests.py::test_request_stream_then_body", "tests/test_requests.py::test_request_json", "tests/test_requests.py::test_request_scope_interface", "tests/test_requests.py::test_request_without_setting_receive", "tests/test_requests.py::test_request_disconnect", "tests/test_requests.py::test_request_is_disconnected", "tests/test_requests.py::test_request_state_object", "tests/test_requests.py::test_request_state", "tests/test_requests.py::test_request_cookies", "tests/test_requests.py::test_chunked_encoding", "tests/test_requests.py::test_request_send_push_promise", "tests/test_requests.py::test_request_send_push_promise_without_push_extension", "tests/test_requests.py::test_request_send_push_promise_without_setting_send" ]
2020-03-18 07:42:23+00:00
2,154
encode__starlette-92
diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index e299e74..99b0687 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -3,6 +3,7 @@ from starlette.responses import PlainTextResponse from starlette.types import ASGIApp, ASGIInstance, Scope import functools import typing +import re ALL_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT") @@ -16,6 +17,7 @@ class CORSMiddleware: allow_methods: typing.Sequence[str] = ("GET",), allow_headers: typing.Sequence[str] = (), allow_credentials: bool = False, + allow_origin_regex: str = None, expose_headers: typing.Sequence[str] = (), max_age: int = 600, ): @@ -23,6 +25,10 @@ class CORSMiddleware: if "*" in allow_methods: allow_methods = ALL_METHODS + if allow_origin_regex is not None: + regex = re.compile(allow_origin_regex) + allow_origin_regex = regex + simple_headers = {} if "*" in allow_origins: simple_headers["Access-Control-Allow-Origin"] = "*" @@ -53,6 +59,7 @@ class CORSMiddleware: self.allow_headers = allow_headers self.allow_all_origins = "*" in allow_origins self.allow_all_headers = "*" in allow_headers + self.allow_origin_regex = allow_origin_regex self.simple_headers = simple_headers self.preflight_headers = preflight_headers @@ -66,12 +73,22 @@ class CORSMiddleware: if method == "OPTIONS" and "access-control-request-method" in headers: return self.preflight_response(request_headers=headers) else: - return functools.partial( - self.simple_response, scope=scope, origin=origin - ) + if self.is_allowed_origin(origin=origin): + return functools.partial( + self.simple_response, scope=scope, origin=origin + ) + return PlainTextResponse("Disallowed CORS origin", status_code=400) return self.app(scope) + def is_allowed_origin(self, origin): + if self.allow_origin_regex: + return self.allow_origin_regex.match(origin) + if self.allow_all_origins: + return True + + return origin in self.allow_origins + def preflight_response(self, request_headers): requested_origin = request_headers["origin"] requested_method = request_headers["access-control-request-method"] @@ -84,7 +101,7 @@ class CORSMiddleware: # If we only allow specific origins, then we have to mirror back # the Origin header in the response. if not self.allow_all_origins: - if requested_origin in self.allow_origins: + if self.is_allowed_origin(origin=requested_origin): headers["Access-Control-Allow-Origin"] = requested_origin else: failures.append("origin") @@ -125,7 +142,7 @@ class CORSMiddleware: # If we only allow specific origins, then we have to mirror back # the Origin header in the response. - if not self.allow_all_origins and origin in self.allow_origins: + if not self.allow_all_origins and self.is_allowed_origin(origin=origin): headers["Access-Control-Allow-Origin"] = origin headers.update(self.simple_headers) await send(message)
encode/starlette
bdf99f1f6173dc4fbe9ea323bf3f86905d479ac1
diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 07a22b0..6d7273d 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -153,3 +153,42 @@ def test_cors_disallowed_preflight(): response = client.options("/", headers=headers) assert response.status_code == 400 assert response.text == "Disallowed CORS origin, method, headers" + + +def test_cors_allow_origin_regex(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, allow_headers=["X-Example"], allow_origin_regex="https://*" + ) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test standard response + headers = {"Origin": "https://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert response.headers["access-control-allow-origin"] == "https://example.org" + + # Test disallowed origin + headers = {"Origin": "http://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 400 + assert response.text == "Disallowed CORS origin" + + # Test pre-flight response + headers = { + "Origin": "https://another.com", + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "X-Example", + } + response = client.options("/", headers=headers) + assert response.status_code == 200 + assert response.text == "OK" + assert response.headers["access-control-allow-origin"] == "https://another.com" + assert response.headers["access-control-allow-headers"] == "X-Example"
Add `allow_origin_regex` to CORSMiddleware. It'd be helpful if `CORSMiddleware` supported an `allow_origin_regex`, so that users could do... ```python # Enforce a subdomain CORS policy app.add_middleware(CORSMiddleware, allow_origin_regex="(http|https)://*.example.com") ``` Or... ```python # Enforce an HTTPS-only CORS policy. app.add_middleware(CORSMiddleware, allow_origin_regex="https://*") ``` The string should be compiled to a regex by the middleware and matches should be anchored to the start/end of the origin string.
0.0
[ "tests/test_middleware.py::test_cors_allow_origin_regex" ]
[ "tests/test_middleware.py::test_trusted_host_middleware", "tests/test_middleware.py::test_https_redirect_middleware", "tests/test_middleware.py::test_cors_allow_all", "tests/test_middleware.py::test_cors_allow_specific_origin", "tests/test_middleware.py::test_cors_disallowed_preflight" ]
2018-10-08 23:42:41+00:00
2,155
encode__typesystem-122
diff --git a/docs/json_schema.md b/docs/json_schema.md index a66f287..7605a76 100644 --- a/docs/json_schema.md +++ b/docs/json_schema.md @@ -7,7 +7,7 @@ TypeSystem can convert Schema or Field instances to/from JSON Schema. All references should be of the style `{"$ref": "#/components/schemas/..."}`. Using hyperlinked references, relative references, or references to parts - of the document other than "definitions" is not supported. + of the document other than "components/schemas" is not supported. Let's define a schema, and dump it out into a JSON schema document: diff --git a/docs/references.md b/docs/references.md index 4f204de..d4d46db 100644 --- a/docs/references.md +++ b/docs/references.md @@ -53,42 +53,44 @@ definitions["Album"] = album_schema document = typesystem.to_json_schema(definitions) print(json.dumps(document, indent=4)) # { -# "definitions": { -# "Artist": { -# "type": "object", -# "properties": { -# "name": { -# "type": "string", -# "minLength": 1, -# "maxLength": 100 -# } -# }, -# "required": [ -# "name" -# ] -# }, -# "Album": { -# "type": "object", -# "properties": { -# "title": { -# "type": "string", -# "minLength": 1, -# "maxLength": 100 -# }, -# "release_date": { -# "type": "string", -# "minLength": 1, -# "format": "date" +# "components":{ +# "schemas":{ +# "Artist":{ +# "type":"object", +# "properties":{ +# "name":{ +# "type":"string", +# "minLength":1, +# "maxLength":100 +# } # }, -# "artist": { -# "$ref": "#/definitions/Artist" -# } +# "required":[ +# "name" +# ] # }, -# "required": [ -# "title", -# "release_date", -# "artist" -# ] +# "Album":{ +# "type":"object", +# "properties":{ +# "title":{ +# "type":"string", +# "minLength":1, +# "maxLength":100 +# }, +# "release_date":{ +# "type":"string", +# "minLength":1, +# "format":"date" +# }, +# "artist":{ +# "$ref":"#/components/schemas/Artist" +# } +# }, +# "required":[ +# "title", +# "release_date", +# "artist" +# ] +# } # } # } # } diff --git a/typesystem/json_schema.py b/typesystem/json_schema.py index bae941e..b03135e 100644 --- a/typesystem/json_schema.py +++ b/typesystem/json_schema.py @@ -115,7 +115,7 @@ def from_json_schema( if definitions is None: definitions = Definitions() - for key, value in data.get("definitions", {}).items(): + for key, value in data.get("components", {}).get("schemas", {}).items(): ref = f"#/components/schemas/{key}" definitions[ref] = from_json_schema(value, definitions=definitions) @@ -571,7 +571,8 @@ def to_json_schema( raise ValueError(f"Cannot convert field type {name!r} to JSON Schema") if is_root and definitions: - data["definitions"] = definitions + data["components"] = {} + data["components"]["schemas"] = definitions return data
encode/typesystem
2e9dc5671d72fde45a1684cc28434b56ee3eda06
diff --git a/tests/jsonschema/draft7/definitions.json b/tests/jsonschema/draft7/definitions.json index 4360406..3b3e3e6 100644 --- a/tests/jsonschema/draft7/definitions.json +++ b/tests/jsonschema/draft7/definitions.json @@ -1,13 +1,19 @@ [ { "description": "valid definition", - "schema": {"$ref": "http://json-schema.org/draft-07/schema#"}, + "schema": { + "$ref": "http://json-schema.org/draft-07/schema#" + }, "tests": [ { "description": "valid definition schema", "data": { - "definitions": { - "foo": {"type": "integer"} + "components": { + "schemas": { + "foo": { + "type": "integer" + } + } } }, "valid": true @@ -16,17 +22,23 @@ }, { "description": "invalid definition", - "schema": {"$ref": "http://json-schema.org/draft-07/schema#"}, + "schema": { + "$ref": "http://json-schema.org/draft-07/schema#" + }, "tests": [ { "description": "invalid definition schema", "data": { - "definitions": { - "foo": {"type": 1} + "components": { + "schemas": { + "foo": { + "type": 1 + } + } } }, "valid": false } ] } -] +] \ No newline at end of file diff --git a/tests/jsonschema/draft7/definitionsRef.json b/tests/jsonschema/draft7/definitionsRef.json index 9661bd5..e967743 100644 --- a/tests/jsonschema/draft7/definitionsRef.json +++ b/tests/jsonschema/draft7/definitionsRef.json @@ -2,10 +2,18 @@ { "description": "nested refs", "schema": { - "definitions": { - "a": {"type": "integer"}, - "b": {"$ref": "#/components/schemas/a"}, - "c": {"$ref": "#/components/schemas/b"} + "components": { + "schemas": { + "a": { + "type": "integer" + }, + "b": { + "$ref": "#/components/schemas/a" + }, + "c": { + "$ref": "#/components/schemas/b" + } + } }, "$ref": "#/components/schemas/c" }, @@ -25,9 +33,11 @@ { "description": "ref overrides any sibling keywords", "schema": { - "definitions": { - "reffed": { - "type": "array" + "components": { + "schemas": { + "reffed": { + "type": "array" + } } }, "properties": { @@ -40,17 +50,27 @@ "tests": [ { "description": "ref valid", - "data": { "foo": [] }, + "data": { + "foo": [] + }, "valid": true }, { "description": "ref valid, maxItems ignored", - "data": { "foo": [ 1, 2, 3] }, + "data": { + "foo": [ + 1, + 2, + 3 + ] + }, "valid": true }, { "description": "ref invalid", - "data": { "foo": "string" }, + "data": { + "foo": "string" + }, "valid": false } ] @@ -59,8 +79,10 @@ "description": "$ref to boolean schema true", "schema": { "$ref": "#/components/schemas/bool", - "definitions": { - "bool": true + "components": { + "schemas": { + "bool": true + } } }, "tests": [ @@ -75,8 +97,10 @@ "description": "$ref to boolean schema false", "schema": { "$ref": "#/components/schemas/bool", - "definitions": { - "bool": false + "components": { + "schemas": { + "bool": false + } } }, "tests": [ @@ -87,4 +111,4 @@ } ] } -] +] \ No newline at end of file diff --git a/tests/jsonschema/draft7/ref.json b/tests/jsonschema/draft7/ref.json index 7579507..8d204dd 100644 --- a/tests/jsonschema/draft7/ref.json +++ b/tests/jsonschema/draft7/ref.json @@ -3,29 +3,43 @@ "description": "root pointer ref", "schema": { "properties": { - "foo": {"$ref": "#"} + "foo": { + "$ref": "#" + } }, "additionalProperties": false }, "tests": [ { "description": "match", - "data": {"foo": false}, + "data": { + "foo": false + }, "valid": true }, { "description": "recursive match", - "data": {"foo": {"foo": false}}, + "data": { + "foo": { + "foo": false + } + }, "valid": true }, { "description": "mismatch", - "data": {"bar": false}, + "data": { + "bar": false + }, "valid": false }, { "description": "recursive mismatch", - "data": {"foo": {"bar": false}}, + "data": { + "foo": { + "bar": false + } + }, "valid": false } ] @@ -34,19 +48,27 @@ "description": "relative pointer ref to object", "schema": { "properties": { - "foo": {"type": "integer"}, - "bar": {"$ref": "#/properties/foo"} + "foo": { + "type": "integer" + }, + "bar": { + "$ref": "#/properties/foo" + } } }, "tests": [ { "description": "match", - "data": {"bar": 3}, + "data": { + "bar": 3 + }, "valid": true }, { "description": "mismatch", - "data": {"bar": true}, + "data": { + "bar": true + }, "valid": false } ] @@ -55,19 +77,29 @@ "description": "relative pointer ref to array", "schema": { "items": [ - {"type": "integer"}, - {"$ref": "#/items/0"} + { + "type": "integer" + }, + { + "$ref": "#/items/0" + } ] }, "tests": [ { "description": "match array", - "data": [1, 2], + "data": [ + 1, + 2 + ], "valid": true }, { "description": "mismatch array", - "data": [1, "foo"], + "data": [ + 1, + "foo" + ], "valid": false } ] @@ -75,44 +107,68 @@ { "description": "escaped pointer ref", "schema": { - "tilda~field": {"type": "integer"}, - "slash/field": {"type": "integer"}, - "percent%field": {"type": "integer"}, + "tilda~field": { + "type": "integer" + }, + "slash/field": { + "type": "integer" + }, + "percent%field": { + "type": "integer" + }, "properties": { - "tilda": {"$ref": "#/tilda~0field"}, - "slash": {"$ref": "#/slash~1field"}, - "percent": {"$ref": "#/percent%25field"} + "tilda": { + "$ref": "#/tilda~0field" + }, + "slash": { + "$ref": "#/slash~1field" + }, + "percent": { + "$ref": "#/percent%25field" + } } }, "tests": [ { "description": "slash invalid", - "data": {"slash": "aoeu"}, + "data": { + "slash": "aoeu" + }, "valid": false }, { "description": "tilda invalid", - "data": {"tilda": "aoeu"}, + "data": { + "tilda": "aoeu" + }, "valid": false }, { "description": "percent invalid", - "data": {"percent": "aoeu"}, + "data": { + "percent": "aoeu" + }, "valid": false }, { "description": "slash valid", - "data": {"slash": 123}, + "data": { + "slash": 123 + }, "valid": true }, { "description": "tilda valid", - "data": {"tilda": 123}, + "data": { + "tilda": 123 + }, "valid": true }, { "description": "percent valid", - "data": {"percent": 123}, + "data": { + "percent": 123 + }, "valid": true } ] @@ -120,12 +176,18 @@ { "description": "nested refs", "schema": { - "definitions": { - "a": {"type": "integer"}, - "b": {"$ref": "#/definitions/a"}, - "c": {"$ref": "#/definitions/b"} + "components/schemas": { + "a": { + "type": "integer" + }, + "b": { + "$ref": "#/components/schemas/a" + }, + "c": { + "$ref": "#/components/schemas/b" + } }, - "$ref": "#/definitions/c" + "$ref": "#/components/schemas/c" }, "tests": [ { @@ -143,14 +205,14 @@ { "description": "ref overrides any sibling keywords", "schema": { - "definitions": { + "components/schemas": { "reffed": { "type": "array" } }, "properties": { "foo": { - "$ref": "#/definitions/reffed", + "$ref": "#/components/schemas/reffed", "maxItems": 2 } } @@ -158,33 +220,49 @@ "tests": [ { "description": "ref valid", - "data": { "foo": [] }, + "data": { + "foo": [] + }, "valid": true }, { "description": "ref valid, maxItems ignored", - "data": { "foo": [ 1, 2, 3] }, + "data": { + "foo": [ + 1, + 2, + 3 + ] + }, "valid": true }, { "description": "ref invalid", - "data": { "foo": "string" }, + "data": { + "foo": "string" + }, "valid": false } ] }, { "description": "remote ref, containing refs itself", - "schema": {"$ref": "http://json-schema.org/draft-07/schema#"}, + "schema": { + "$ref": "http://json-schema.org/draft-07/schema#" + }, "tests": [ { "description": "remote ref valid", - "data": {"minLength": 1}, + "data": { + "minLength": 1 + }, "valid": true }, { "description": "remote ref invalid", - "data": {"minLength": -1}, + "data": { + "minLength": -1 + }, "valid": false } ] @@ -193,18 +271,24 @@ "description": "property named $ref that is not a reference", "schema": { "properties": { - "$ref": {"type": "string"} + "$ref": { + "type": "string" + } } }, "tests": [ { "description": "property named $ref valid", - "data": {"$ref": "a"}, + "data": { + "$ref": "a" + }, "valid": true }, { "description": "property named $ref invalid", - "data": {"$ref": 2}, + "data": { + "$ref": 2 + }, "valid": false } ] @@ -212,8 +296,8 @@ { "description": "$ref to boolean schema true", "schema": { - "$ref": "#/definitions/bool", - "definitions": { + "$ref": "#/components/schemas/bool", + "components/schemas": { "bool": true } }, @@ -228,8 +312,8 @@ { "description": "$ref to boolean schema false", "schema": { - "$ref": "#/definitions/bool", - "definitions": { + "$ref": "#/components/schemas/bool", + "components/schemas": { "bool": false } }, @@ -248,30 +332,43 @@ "description": "tree of nodes", "type": "object", "properties": { - "meta": {"type": "string"}, + "meta": { + "type": "string" + }, "nodes": { "type": "array", - "items": {"$ref": "node"} + "items": { + "$ref": "node" + } } }, - "required": ["meta", "nodes"], - "definitions": { + "required": [ + "meta", + "nodes" + ], + "components/schemas": { "node": { "$id": "http://localhost:1234/node", "description": "node", "type": "object", "properties": { - "value": {"type": "number"}, - "subtree": {"$ref": "tree"} + "value": { + "type": "number" + }, + "subtree": { + "$ref": "tree" + } }, - "required": ["value"] + "required": [ + "value" + ] } } }, "tests": [ { "description": "valid tree", - "data": { + "data": { "meta": "root", "nodes": [ { @@ -279,8 +376,12 @@ "subtree": { "meta": "child", "nodes": [ - {"value": 1.1}, - {"value": 1.2} + { + "value": 1.1 + }, + { + "value": 1.2 + } ] } }, @@ -289,8 +390,12 @@ "subtree": { "meta": "child", "nodes": [ - {"value": 2.1}, - {"value": 2.2} + { + "value": 2.1 + }, + { + "value": 2.2 + } ] } } @@ -300,7 +405,7 @@ }, { "description": "invalid tree", - "data": { + "data": { "meta": "root", "nodes": [ { @@ -308,8 +413,12 @@ "subtree": { "meta": "child", "nodes": [ - {"value": "string is invalid"}, - {"value": 1.2} + { + "value": "string is invalid" + }, + { + "value": 1.2 + } ] } }, @@ -318,8 +427,12 @@ "subtree": { "meta": "child", "nodes": [ - {"value": 2.1}, - {"value": 2.2} + { + "value": 2.1 + }, + { + "value": 2.2 + } ] } } @@ -329,4 +442,4 @@ } ] } -] +] \ No newline at end of file diff --git a/tests/jsonschema/draft7/refRemote.json b/tests/jsonschema/draft7/refRemote.json index 819d326..b035816 100644 --- a/tests/jsonschema/draft7/refRemote.json +++ b/tests/jsonschema/draft7/refRemote.json @@ -1,7 +1,9 @@ [ { "description": "remote ref", - "schema": {"$ref": "http://localhost:1234/integer.json"}, + "schema": { + "$ref": "http://localhost:1234/integer.json" + }, "tests": [ { "description": "remote ref valid", @@ -17,7 +19,9 @@ }, { "description": "fragment within remote ref", - "schema": {"$ref": "http://localhost:1234/subSchemas.json#/integer"}, + "schema": { + "$ref": "http://localhost:1234/subSchemas.json#/integer" + }, "tests": [ { "description": "remote fragment valid", @@ -55,18 +59,28 @@ "$id": "http://localhost:1234/", "items": { "$id": "folder/", - "items": {"$ref": "folderInteger.json"} + "items": { + "$ref": "folderInteger.json" + } } }, "tests": [ { "description": "base URI change ref valid", - "data": [[1]], + "data": [ + [ + 1 + ] + ], "valid": true }, { "description": "base URI change ref invalid", - "data": [["a"]], + "data": [ + [ + "a" + ] + ], "valid": false } ] @@ -75,27 +89,39 @@ "description": "base URI change - change folder", "schema": { "$id": "http://localhost:1234/scope_change_defs1.json", - "type" : "object", + "type": "object", "properties": { - "list": {"$ref": "#/definitions/baz"} + "list": { + "$ref": "#/components/schemas/baz" + } }, - "definitions": { + "components/schemas": { "baz": { "$id": "folder/", "type": "array", - "items": {"$ref": "folderInteger.json"} + "items": { + "$ref": "folderInteger.json" + } } } }, "tests": [ { "description": "number is valid", - "data": {"list": [1]}, + "data": { + "list": [ + 1 + ] + }, "valid": true }, { "description": "string is invalid", - "data": {"list": ["a"]}, + "data": { + "list": [ + "a" + ] + }, "valid": false } ] @@ -104,17 +130,21 @@ "description": "base URI change - change folder in subschema", "schema": { "$id": "http://localhost:1234/scope_change_defs2.json", - "type" : "object", + "type": "object", "properties": { - "list": {"$ref": "#/definitions/baz/definitions/bar"} + "list": { + "$ref": "#/components/schemas/baz/components/schemas/bar" + } }, - "definitions": { + "components/schemas": { "baz": { "$id": "folder/", - "definitions": { + "components/schemas": { "bar": { "type": "array", - "items": {"$ref": "folderInteger.json"} + "items": { + "$ref": "folderInteger.json" + } } } } @@ -123,12 +153,20 @@ "tests": [ { "description": "number is valid", - "data": {"list": [1]}, + "data": { + "list": [ + 1 + ] + }, "valid": true }, { "description": "string is invalid", - "data": {"list": ["a"]}, + "data": { + "list": [ + "a" + ] + }, "valid": false } ] @@ -139,7 +177,9 @@ "$id": "http://localhost:1234/object", "type": "object", "properties": { - "name": {"$ref": "name.json#/definitions/orNull"} + "name": { + "$ref": "name.json#/components/schemas/orNull" + } } }, "tests": [ @@ -168,4 +208,4 @@ } ] } -] +] \ No newline at end of file diff --git a/tests/test_schemas.py b/tests/test_schemas.py index a2feaf9..b37e372 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -454,13 +454,15 @@ def test_nested_schema_to_json_schema(): "artist": {"$ref": "#/components/schemas/Artist"}, }, "required": ["title", "release_date", "artist"], - "definitions": { - "Artist": { - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1, "maxLength": 100} - }, - "required": ["name"], + "components": { + "schemas": { + "Artist": { + "type": "object", + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 100} + }, + "required": ["name"], + } } }, } @@ -485,27 +487,29 @@ def test_definitions_to_json_schema(): schema = typesystem.to_json_schema(definitions) assert schema == { - "definitions": { - "Artist": { - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1, "maxLength": 100} + "components": { + "schemas": { + "Artist": { + "type": "object", + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 100} + }, + "required": ["name"], }, - "required": ["name"], - }, - "Album": { - "type": "object", - "properties": { - "title": {"type": "string", "minLength": 1, "maxLength": 100}, - "release_date": { - "type": "string", - "minLength": 1, - "format": "date", + "Album": { + "type": "object", + "properties": { + "title": {"type": "string", "minLength": 1, "maxLength": 100}, + "release_date": { + "type": "string", + "minLength": 1, + "format": "date", + }, + "artist": {"$ref": "#/components/schemas/Artist"}, }, - "artist": {"$ref": "#/components/schemas/Artist"}, + "required": ["title", "release_date", "artist"], }, - "required": ["title", "release_date", "artist"], - }, + } } }
References are broken for JSON schema (0.4.0) ### Checklist <!-- Please make sure you check all these items before submitting your bug report. --> - [x] The bug is reproducible against the latest release and/or `master`. - [x] There are no similar issues or pull requests to fix it yet. ### Describe the bug Quoting the following change from the changelog for [0.4.0](https://github.com/encode/typesystem/releases/tag/0.4.0): > Update JSON schema ref according to OAS 3: #/components/schemas/ Currently I'm facing the issue that when a typesystem schema contains a reference, it will not be resolvable in the resulting JSON Schema. I made an example based on https://github.com/encode/typesystem/blob/master/docs/references.md. <!-- A clear and concise description of what the bug is. --> ### To reproduce ```python import json import typesystem definitions = typesystem.Definitions() artist_schema = typesystem.Schema(fields={"name": typesystem.String(max_length=100)}) album_schema = typesystem.Schema( fields={ "title": typesystem.String(max_length=100), "release_date": typesystem.Date(), "artist": typesystem.Reference(to="Artist", definitions=definitions), } ) definitions["Artist"] = artist_schema definitions["Album"] = album_schema document = typesystem.to_json_schema(album_schema) print(json.dumps(document, indent=4)) ``` I'm simply trying to get a JSON Schema out of the defined `album_schema`. ### Expected behavior Receive a JSON Schema output that contains the correct `$ref` which makes it resolvable. ### Actual behavior JSON Schema output that contains a `definitions` key which is not in line with the new syntax (i.e.: `"$ref": "#/components/schemas/Artist"`) ```json { "type": "object", "properties": { "title": { "type": "string", "minLength": 1, "maxLength": 100 }, "release_date": { "type": "string", "minLength": 1, "format": "date" }, "artist": { "$ref": "#/components/schemas/Artist" } }, "required": [ "title", "release_date", "artist" ], "definitions": { "Artist": { "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 100 } }, "required": [ "name" ] } } } ``` With the newly generated reference syntax ("`#/components/schemas/Artist`"), shouldn't the document contain the elements "components" as well as "schemas" and respectively "Artist" in this example? ### Environment - OS: macOS - Python version: 3.9.6 - Typesystem version: 0.4.0
0.0
[ "tests/test_schemas.py::test_nested_schema_to_json_schema", "tests/test_schemas.py::test_definitions_to_json_schema" ]
[ "tests/test_schemas.py::test_schema", "tests/test_schemas.py::test_required", "tests/test_schemas.py::test_schema_validation", "tests/test_schemas.py::test_schema_array_serialization", "tests/test_schemas.py::test_schema_date_serialization", "tests/test_schemas.py::test_schema_time_serialization", "tests/test_schemas.py::test_schema_datetime_serialization", "tests/test_schemas.py::test_schema_decimal_serialization", "tests/test_schemas.py::test_schema_uuid_serialization", "tests/test_schemas.py::test_schema_reference_serialization", "tests/test_schemas.py::test_schema_with_callable_default", "tests/test_schemas.py::test_nested_schema", "tests/test_schemas.py::test_nested_schema_array", "tests/test_schemas.py::test_schema_email_serialization", "tests/test_schemas.py::test_schema_ipaddress_serialization", "tests/test_schemas.py::test_schema_url_serialization" ]
2021-11-18 08:48:50+00:00
2,156
encode__typesystem-16
diff --git a/typesystem/fields.py b/typesystem/fields.py index 90716ef..266177c 100644 --- a/typesystem/fields.py +++ b/typesystem/fields.py @@ -63,6 +63,12 @@ class Field: def has_default(self) -> bool: return hasattr(self, "default") + def get_default_value(self) -> typing.Any: + default = getattr(self, "default", None) + if callable(default): + return default() + return default + def error(self, code: str) -> ValidationError: text = self.errors[code].format(**self.__dict__) return ValidationError(text=text, code=code) @@ -423,7 +429,7 @@ class Object(Field): for key, child_schema in self.properties.items(): if key not in value: if child_schema.has_default(): - validated[key] = child_schema.default + validated[key] = child_schema.get_default_value() continue item = value[key] child_value, error = child_schema.validate(item, strict=strict) diff --git a/typesystem/schemas.py b/typesystem/schemas.py index 6cb847c..fe2f873 100644 --- a/typesystem/schemas.py +++ b/typesystem/schemas.py @@ -68,7 +68,7 @@ class Schema(Mapping, metaclass=SchemaMetaclass): raise TypeError(message) setattr(self, key, value) elif schema.has_default(): - setattr(self, key, schema.default) + setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0]
encode/typesystem
2fcc6daebd0193a02d135daee4564f0e219e95ed
diff --git a/tests/test_schemas.py b/tests/test_schemas.py index c4e2ecc..202af7b 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -125,3 +125,12 @@ def test_schema_decimal_serialization(): assert item.price == decimal.Decimal("123.45") assert item["price"] == 123.45 + + +def test_schema_with_callable_default(): + class Example(typesystem.Schema): + created = typesystem.Date(default=datetime.date.today) + + value, error = Example.validate({}) + print(value) + assert value.created == datetime.date.today()
Callable defaults Eg. ```python class Something(typesystem.Schema): created = typesystem.DateTime(default=datetime.datetime.now) ... ```
0.0
[ "tests/test_schemas.py::test_schema_with_callable_default" ]
[ "tests/test_schemas.py::test_schema_validation", "tests/test_schemas.py::test_schema_eq", "tests/test_schemas.py::test_schema_repr", "tests/test_schemas.py::test_schema_instantiation", "tests/test_schemas.py::test_schema_subclass", "tests/test_schemas.py::test_schema_serialization", "tests/test_schemas.py::test_schema_len", "tests/test_schemas.py::test_schema_getattr", "tests/test_schemas.py::test_schema_missing_getattr", "tests/test_schemas.py::test_schema_format_serialization", "tests/test_schemas.py::test_schema_decimal_serialization" ]
2019-02-28 17:03:18+00:00
2,157
encode__typesystem-65
diff --git a/typesystem/base.py b/typesystem/base.py index bd15068..def115c 100644 --- a/typesystem/base.py +++ b/typesystem/base.py @@ -78,6 +78,10 @@ class Message: and self.end_position == other.end_position ) + def __hash__(self) -> int: + ident = (self.code, tuple(self.index)) + return hash(ident) + def __repr__(self) -> str: class_name = self.__class__.__name__ index_str = f", index={self.index!r}" if self.index else "" @@ -183,6 +187,10 @@ class BaseError(Mapping, Exception): def __eq__(self, other: typing.Any) -> bool: return isinstance(other, ValidationError) and self._messages == other._messages + def __hash__(self) -> int: + ident = tuple(hash(m) for m in self._messages) + return hash(ident) + def __repr__(self) -> str: class_name = self.__class__.__name__ if len(self._messages) == 1 and not self._messages[0].index:
encode/typesystem
453c6fb05a43efe26ffeb476ca311a199a4fb704
diff --git a/tests/test_fields.py b/tests/test_fields.py index b908a66..56f24e6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -825,3 +825,9 @@ def test_error_messages_interface(): validator = Integer() value, error = validator.validate_or_error("abc") assert error.messages() == [Message(text="Must be a number.", code="type")] + + +def test_validation_error_is_hashable(): + validator = Integer() + _, error = validator.validate_or_error("abc") + hash(error)
ValidationError can't be shown with `traceback.print_exc()` in Python 3.6 Consider the following code: ```python import traceback import typesystem try: typesystem.Integer().validate("hello") except typesystem.ValidationError: traceback.print_exc() ``` Because of an issue with Python 3.6 discussed in [issue 28803](https://bugs.python.org/issue28603), since `ValidationError` implements `__eq__` but not `__hash__` it is not hashable and `print_exc()` fails to process it correctly. ``` TypeError: unhashable type: 'ValidationError' ``` (Full traceback available [here](https://travis-ci.org/bocadilloproject/bocadillo/jobs/513086149)) Looks like we'd need to implement `ValidationError.__hash__()` to fix this.
0.0
[ "tests/test_fields.py::test_validation_error_is_hashable" ]
[ "tests/test_fields.py::test_string", "tests/test_fields.py::test_integer", "tests/test_fields.py::test_float", "tests/test_fields.py::test_decimal", "tests/test_fields.py::test_number", "tests/test_fields.py::test_boolean", "tests/test_fields.py::test_choice", "tests/test_fields.py::test_object", "tests/test_fields.py::test_array", "tests/test_fields.py::test_date", "tests/test_fields.py::test_time", "tests/test_fields.py::test_datetime", "tests/test_fields.py::test_uuid", "tests/test_fields.py::test_union", "tests/test_fields.py::test_const", "tests/test_fields.py::test_errors_dict_interface", "tests/test_fields.py::test_error_messages_interface" ]
2019-03-30 13:25:54+00:00
2,158
encode__uvicorn-114
diff --git a/uvicorn/__init__.py b/uvicorn/__init__.py index bfd395e..385fbc3 100644 --- a/uvicorn/__init__.py +++ b/uvicorn/__init__.py @@ -1,4 +1,4 @@ from uvicorn.main import main, run -__version__ = "0.2.5" +__version__ = "0.2.6" __all__ = ["main", "run"] diff --git a/uvicorn/protocols/http/h11.py b/uvicorn/protocols/http/h11.py index 6848630..073cddd 100644 --- a/uvicorn/protocols/http/h11.py +++ b/uvicorn/protocols/http/h11.py @@ -72,11 +72,15 @@ class H11Protocol(asyncio.Protocol): if self.access_logs: self.logger.debug("%s - Disconnected", self.server[0]) - if self.cycle and self.cycle.more_body: + if self.cycle and not self.cycle.response_complete: self.cycle.disconnected = True if self.conn.our_state != h11.ERROR: event = h11.ConnectionClosed() - self.conn.send(event) + try: + self.conn.send(event) + except h11.LocalProtocolError: + # Premature client disconnect + pass self.client_event.set() def eof_received(self): @@ -215,6 +219,9 @@ class RequestResponseCycle: protocol = self.protocol message_type = message["type"] + if self.disconnected: + return + if not protocol.writable: await protocol.writable_event.wait() diff --git a/uvicorn/protocols/http/httptools.py b/uvicorn/protocols/http/httptools.py index 7344b01..ebbbb39 100644 --- a/uvicorn/protocols/http/httptools.py +++ b/uvicorn/protocols/http/httptools.py @@ -83,7 +83,7 @@ class HttpToolsProtocol(asyncio.Protocol): if self.access_logs: self.logger.debug("%s - Disconnected", self.server[0]) - if self.cycle and self.cycle.more_body: + if self.cycle and not self.cycle.response_complete: self.cycle.disconnected = True self.client_event.set() @@ -238,6 +238,9 @@ class RequestResponseCycle: protocol = self.protocol message_type = message["type"] + if self.disconnected: + return + if not protocol.writable: await protocol.writable_event.wait()
encode/uvicorn
df2e97eaf6560dc4f7f3d321ab1f085553125ba0
diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index 88658dd..3b08fee 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -340,6 +340,17 @@ def test_value_returned(protocol_cls): assert protocol.transport.is_closing() [email protected]("protocol_cls", [HttpToolsProtocol, H11Protocol]) +def test_early_disconnect(protocol_cls): + def app(scope): + return Response(b"xxx", headers={"content-length": 10}) + + protocol = get_connected_protocol(app, protocol_cls) + protocol.data_received(SIMPLE_GET_REQUEST) + protocol.connection_lost(None) + protocol.loop.run_one() + + @pytest.mark.parametrize("protocol_cls", [HttpToolsProtocol, H11Protocol]) def test_http10_request(protocol_cls): def app(scope):
RuntimeError in uvicorn for some requests `uvicorn==0.2.5` is throwing errors for some requests. ``` ERROR: Exception in ASGI application Traceback (most recent call last): File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/uvicorn/protocols/http/httptools.py", line 196, in run_asgi result = await asgi(self.receive, self.send) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/channels/http.py", line 190, in __call__ await self.handle(body) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/asgiref/sync.py", line 110, in __call__ return await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/asgiref/sync.py", line 125, in thread_handler return self.func(*args, **kwargs) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/channels/http.py", line 229, in handle self.send(response_message) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/asgiref/sync.py", line 64, in __call__ return call_result.result() File "/usr/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/asgiref/sync.py", line 78, in main_wrap result = await self.awaitable(*args, **kwargs) File "/home/chillar/.virtualenvs/library/lib/python3.6/site-packages/uvicorn/protocols/http/httptools.py", line 308, in send protocol.transport.write(body) File "uvloop/handles/stream.pyx", line 636, in uvloop.loop.UVStream.write File "uvloop/handles/handle.pyx", line 165, in uvloop.loop.UVHandle._ensure_alive RuntimeError: unable to perform operation on <TCPTransport closed=True reading=False 0x1a48ad8>; the handler is closed ```
0.0
[ "tests/protocols/test_http.py::test_early_disconnect[H11Protocol]" ]
[ "tests/protocols/test_http.py::test_get_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_get_request[H11Protocol]", "tests/protocols/test_http.py::test_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_post_request[H11Protocol]", "tests/protocols/test_http.py::test_keepalive[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive[H11Protocol]", "tests/protocols/test_http.py::test_close[HttpToolsProtocol]", "tests/protocols/test_http.py::test_close[H11Protocol]", "tests/protocols/test_http.py::test_undersized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[H11Protocol]", "tests/protocols/test_http.py::test_oversized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_oversized_request[H11Protocol]", "tests/protocols/test_http.py::test_app_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[H11Protocol]", "tests/protocols/test_http.py::test_app_init_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_init_exception[H11Protocol]", "tests/protocols/test_http.py::test_exception_during_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_exception_during_response[H11Protocol]", "tests/protocols/test_http.py::test_no_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_no_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_partial_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_partial_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_duplicate_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_duplicate_start_message[H11Protocol]", "tests/protocols/test_http.py::test_missing_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_missing_start_message[H11Protocol]", "tests/protocols/test_http.py::test_message_after_body_complete[HttpToolsProtocol]", "tests/protocols/test_http.py::test_message_after_body_complete[H11Protocol]", "tests/protocols/test_http.py::test_value_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_value_returned[H11Protocol]", "tests/protocols/test_http.py::test_early_disconnect[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[H11Protocol]" ]
2018-07-05 18:09:44+00:00
2,159
encode__uvicorn-115
diff --git a/uvicorn/protocols/http/h11.py b/uvicorn/protocols/http/h11.py index 073cddd..2e22ea8 100644 --- a/uvicorn/protocols/http/h11.py +++ b/uvicorn/protocols/http/h11.py @@ -28,6 +28,8 @@ STATUS_PHRASES = { DEFAULT_HEADERS = _get_default_headers() +HIGH_WATER_LIMIT = 65536 + class H11Protocol(asyncio.Protocol): def __init__(self, app, loop=None, state=None, logger=None): @@ -88,15 +90,29 @@ class H11Protocol(asyncio.Protocol): def data_received(self, data): self.conn.receive_data(data) + self.handle_events() + + def handle_events(self): while True: - event = self.conn.next_event() + try: + event = self.conn.next_event() + except h11.RemoteProtocolError: + msg = "Invalid HTTP request received." + self.logger.warn(msg) + self.transport.close() + return event_type = type(event) if event_type is h11.NEED_DATA: break elif event_type is h11.PAUSED: + # This case can occur in HTTP pipelining, so we need to + # stop reading any more data, and ensure that at the end + # of the active request/response cycle we handle any + # events that have been buffered up. self.pause_reading() + self.cycle.done_callback = self.on_response_complete break elif event_type is h11.Request: @@ -119,7 +135,8 @@ class H11Protocol(asyncio.Protocol): if self.conn.our_state is h11.DONE: continue self.cycle.body += event.data - self.pause_reading() + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.pause_reading() self.client_event.set() elif event_type is h11.EndOfMessage: @@ -128,9 +145,12 @@ class H11Protocol(asyncio.Protocol): self.conn.start_next_cycle() continue self.cycle.more_body = False - self.pause_reading() self.client_event.set() + def on_response_complete(self): + self.resume_reading() + self.handle_events() + # Flow control def pause_reading(self): if self.readable: @@ -157,11 +177,12 @@ class RequestResponseCycle: def __init__(self, scope, protocol): self.scope = scope self.protocol = protocol + self.disconnected = False + self.done_callback = None # Request state self.body = b"" self.more_body = True - self.disconnected = False self.receive_finished = False # Response state @@ -195,6 +216,8 @@ class RequestResponseCycle: self.protocol.logger.error(msg, result) self.protocol.transport.close() finally: + if self.done_callback is not None: + self.done_callback() self.protocol.state["total_requests"] += 1 async def send_500_response(self): diff --git a/uvicorn/protocols/http/httptools.py b/uvicorn/protocols/http/httptools.py index ebbbb39..3db3b35 100644 --- a/uvicorn/protocols/http/httptools.py +++ b/uvicorn/protocols/http/httptools.py @@ -30,13 +30,16 @@ STATUS_LINE = { DEFAULT_HEADERS = _get_default_headers() +HIGH_WATER_LIMIT = 65536 + class HttpToolsProtocol(asyncio.Protocol): __slots__ = ( 'app', 'loop', 'state', 'logger', 'access_logs', 'parser', 'transport', 'server', 'client', 'scheme', 'scope', 'headers', 'cycle', 'client_event', - 'readable', 'writable', 'writable_event' + 'readable', 'writable', 'writable_event', + 'pipeline' ) def __init__(self, app, loop=None, state=None, logger=None): @@ -65,6 +68,8 @@ class HttpToolsProtocol(asyncio.Protocol): self.writable_event = asyncio.Event() self.writable_event.set() + self.pipeline = [] + @classmethod def tick(cls): global DEFAULT_HEADERS @@ -126,23 +131,40 @@ class HttpToolsProtocol(asyncio.Protocol): self.scope["http_version"] = http_version if self.parser.should_upgrade(): return + + existing_cycle = self.cycle self.cycle = RequestResponseCycle(self.scope, self) - self.loop.create_task(self.cycle.run_asgi(self.app)) + if existing_cycle is None or existing_cycle.response_complete: + # Standard case - start processing the request. + self.loop.create_task(self.cycle.run_asgi(self.app)) + else: + # Pipelined HTTP requests need to be queued up. + self.pause_reading() + existing_cycle.done_callback = self.on_response_complete + self.pipeline.insert(0, self.cycle) def on_body(self, body: bytes): if self.parser.should_upgrade() or self.cycle.response_complete: return self.cycle.body += body - self.pause_reading() + if len(self.cycle.body) > HIGH_WATER_LIMIT: + self.pause_reading() self.client_event.set() def on_message_complete(self): if self.parser.should_upgrade() or self.cycle.response_complete: return self.cycle.more_body = False - self.pause_reading() self.client_event.set() + def on_response_complete(self): + # Callback for pipelined HTTP requests to be started. + if self.pipeline and not self.transport.is_closing(): + cycle = self.pipeline.pop() + self.loop.create_task(cycle.run_asgi(self.app)) + if not self.pipeline: + self.resume_reading() + # Flow control def pause_reading(self): if self.readable: @@ -167,19 +189,20 @@ class HttpToolsProtocol(asyncio.Protocol): class RequestResponseCycle: __slots__ = ( - 'scope', 'protocol', - 'body', 'more_body', 'disconnected', 'receive_finished', + 'scope', 'protocol', 'disconnected', 'done_callback', + 'body', 'more_body', 'receive_finished', 'response_started', 'response_complete', 'keep_alive', 'chunked_encoding', 'expected_content_length' ) def __init__(self, scope, protocol): self.scope = scope self.protocol = protocol + self.disconnected = False + self.done_callback = None # Request state self.body = b"" self.more_body = True - self.disconnected = False self.receive_finished = False # Response state @@ -217,6 +240,8 @@ class RequestResponseCycle: self.protocol.transport.close() finally: self.protocol.state["total_requests"] += 1 + if self.done_callback is not None: + self.done_callback() async def send_500_response(self): await self.send( @@ -325,14 +350,14 @@ class RequestResponseCycle: raise RuntimeError(msg % message_type) async def receive(self): - protocol = self.protocol - if self.receive_finished: msg = "Receive channel fully consumed." raise RuntimeError(msg) + protocol = self.protocol + protocol.resume_reading() + if self.more_body and not self.body and not self.disconnected: - protocol.resume_reading() await protocol.client_event.wait() protocol.client_event.clear() @@ -347,6 +372,5 @@ class RequestResponseCycle: } self.receive_finished = not (self.more_body) self.body = b"" - protocol.resume_reading() return message
encode/uvicorn
870a8e24a6e9bda8be473e991b99ed7b172d5648
diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index 3b08fee..589ae9d 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -172,6 +172,32 @@ def test_close(protocol_cls): assert protocol.transport.is_closing() [email protected]("protocol_cls", [HttpToolsProtocol, H11Protocol]) +def test_pipelined_requests(protocol_cls): + def app(scope): + return Response("Hello, world", media_type="text/plain") + + protocol = get_connected_protocol(app, protocol_cls) + protocol.data_received(SIMPLE_GET_REQUEST) + protocol.data_received(SIMPLE_GET_REQUEST) + protocol.data_received(SIMPLE_GET_REQUEST) + + protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer + protocol.transport.buffer = b"" + + protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer + protocol.transport.buffer = b"" + + protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer + protocol.transport.buffer = b"" + + @pytest.mark.parametrize("protocol_cls", [HttpToolsProtocol, H11Protocol]) def test_undersized_request(protocol_cls): def app(scope): @@ -194,6 +220,16 @@ def test_oversized_request(protocol_cls): assert protocol.transport.is_closing() [email protected]("protocol_cls", [HttpToolsProtocol, H11Protocol]) +def test_invalid_http(protocol_cls): + def app(scope): + return Response("Hello, world", media_type="text/plain") + + protocol = get_connected_protocol(app, protocol_cls) + protocol.data_received(b'x' * 100000) + assert protocol.transport.is_closing() + + @pytest.mark.parametrize("protocol_cls", [HttpToolsProtocol, H11Protocol]) def test_app_exception(protocol_cls): class App:
Pipelining support in `httptools` implementation We've temporarily dropped pipelining support from the `httptools` implementation, although everythings in place in order to support it. Need to: Keep track of queued request/response cycles if a new cycle starts before the existing one has finished. Callback to the protocol to start the next cycle in the queue if needed.
0.0
[ "tests/protocols/test_http.py::test_pipelined_requests[H11Protocol]", "tests/protocols/test_http.py::test_invalid_http[H11Protocol]" ]
[ "tests/protocols/test_http.py::test_get_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_get_request[H11Protocol]", "tests/protocols/test_http.py::test_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_post_request[H11Protocol]", "tests/protocols/test_http.py::test_keepalive[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive[H11Protocol]", "tests/protocols/test_http.py::test_close[HttpToolsProtocol]", "tests/protocols/test_http.py::test_close[H11Protocol]", "tests/protocols/test_http.py::test_pipelined_requests[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[H11Protocol]", "tests/protocols/test_http.py::test_oversized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_oversized_request[H11Protocol]", "tests/protocols/test_http.py::test_invalid_http[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[H11Protocol]", "tests/protocols/test_http.py::test_app_init_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_init_exception[H11Protocol]", "tests/protocols/test_http.py::test_exception_during_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_exception_during_response[H11Protocol]", "tests/protocols/test_http.py::test_no_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_no_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_partial_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_partial_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_duplicate_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_duplicate_start_message[H11Protocol]", "tests/protocols/test_http.py::test_missing_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_missing_start_message[H11Protocol]", "tests/protocols/test_http.py::test_message_after_body_complete[HttpToolsProtocol]", "tests/protocols/test_http.py::test_message_after_body_complete[H11Protocol]", "tests/protocols/test_http.py::test_value_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_value_returned[H11Protocol]", "tests/protocols/test_http.py::test_early_disconnect[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_disconnect[H11Protocol]", "tests/protocols/test_http.py::test_http10_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[H11Protocol]" ]
2018-07-06 09:04:08+00:00
2,160
encode__uvicorn-1706
diff --git a/docs/settings.md b/docs/settings.md index c40905f..14b2882 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -67,7 +67,7 @@ Using Uvicorn with watchfiles will enable the following options (which are other * `--loop <str>` - Set the event loop implementation. The uvloop implementation provides greater performance, but is not compatible with Windows or PyPy. **Options:** *'auto', 'asyncio', 'uvloop'.* **Default:** *'auto'*. * `--http <str>` - Set the HTTP protocol implementation. The httptools implementation provides greater performance, but it not compatible with PyPy. **Options:** *'auto', 'h11', 'httptools'.* **Default:** *'auto'*. -* `--ws <str>` - Set the WebSockets protocol implementation. Either of the `websockets` and `wsproto` packages are supported. Use `'none'` to deny all websocket requests. **Options:** *'auto', 'none', 'websockets', 'wsproto'.* **Default:** *'auto'*. +* `--ws <str>` - Set the WebSockets protocol implementation. Either of the `websockets` and `wsproto` packages are supported. Use `'none'` to ignore all websocket requests. **Options:** *'auto', 'none', 'websockets', 'wsproto'.* **Default:** *'auto'*. * `--ws-max-size <int>` - Set the WebSockets max message size, in bytes. Please note that this can be used only with the default `websockets` protocol. * `--ws-ping-interval <float>` - Set the WebSockets ping interval, in seconds. Please note that this can be used only with the default `websockets` protocol. * `--ws-ping-timeout <float>` - Set the WebSockets ping timeout, in seconds. Please note that this can be used only with the default `websockets` protocol. diff --git a/scripts/install b/scripts/install index 58b6324..edd3009 100755 --- a/scripts/install +++ b/scripts/install @@ -12,8 +12,8 @@ if [ -z "$GITHUB_ACTIONS" ]; then "$PYTHON" -m venv "$VENV" PIP="$VENV/bin/pip" else - PIP="pip" + PIP="$PYTHON -m pip" fi -"$PIP" install -U pip -"$PIP" install -r "$REQUIREMENTS" +${PIP} install -U pip +${PIP} install -r "$REQUIREMENTS" diff --git a/uvicorn/config.py b/uvicorn/config.py index 589d72d..df91a6c 100644 --- a/uvicorn/config.py +++ b/uvicorn/config.py @@ -87,10 +87,8 @@ LOOP_SETUPS: Dict[LoopSetupType, Optional[str]] = { } INTERFACES: List[InterfaceType] = ["auto", "asgi3", "asgi2", "wsgi"] - SSL_PROTOCOL_VERSION: int = ssl.PROTOCOL_TLS_SERVER - LOGGING_CONFIG: Dict[str, Any] = { "version": 1, "disable_existing_loggers": False, @@ -159,7 +157,6 @@ def is_dir(path: Path) -> bool: def resolve_reload_patterns( patterns_list: List[str], directories_list: List[str] ) -> Tuple[List[str], List[Path]]: - directories: List[Path] = list(set(map(Path, directories_list.copy()))) patterns: List[str] = patterns_list.copy() diff --git a/uvicorn/protocols/http/h11_impl.py b/uvicorn/protocols/http/h11_impl.py index 5fff70b..9f6931e 100644 --- a/uvicorn/protocols/http/h11_impl.py +++ b/uvicorn/protocols/http/h11_impl.py @@ -92,7 +92,6 @@ class H11Protocol(asyncio.Protocol): self.server_state = server_state self.connections = server_state.connections self.tasks = server_state.tasks - self.default_headers = server_state.default_headers # Per-connection state self.transport: asyncio.Transport = None # type: ignore[assignment] @@ -155,6 +154,28 @@ class H11Protocol(asyncio.Protocol): self.timeout_keep_alive_task.cancel() self.timeout_keep_alive_task = None + def _get_upgrade(self) -> Optional[bytes]: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None + + def _should_upgrade_to_ws(self) -> bool: + if self.ws_protocol_class is None: + if self.config.ws == "auto": + msg = "Unsupported upgrade request." + self.logger.warning(msg) + msg = "No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + return False + return True + def data_received(self, data: bytes) -> None: self._unset_keepalive_if_required() @@ -204,12 +225,10 @@ class H11Protocol(asyncio.Protocol): "headers": self.headers, } - for name, value in self.headers: - if name == b"connection": - tokens = [token.lower().strip() for token in value.split(b",")] - if b"upgrade" in tokens: - self.handle_upgrade(event) - return + upgrade = self._get_upgrade() + if upgrade == b"websocket" and self._should_upgrade_to_ws(): + self.handle_websocket_upgrade(event) + return # Handle 503 responses when 'limit_concurrency' is exceeded. if self.limit_concurrency is not None and ( @@ -230,7 +249,7 @@ class H11Protocol(asyncio.Protocol): logger=self.logger, access_logger=self.access_logger, access_log=self.access_log, - default_headers=self.default_headers, + default_headers=self.server_state.default_headers, message_event=asyncio.Event(), on_response=self.on_response_complete, ) @@ -254,23 +273,7 @@ class H11Protocol(asyncio.Protocol): self.cycle.more_body = False self.cycle.message_event.set() - def handle_upgrade(self, event: H11Event) -> None: - upgrade_value = None - for name, value in self.headers: - if name == b"upgrade": - upgrade_value = value.lower() - - if upgrade_value != b"websocket" or self.ws_protocol_class is None: - msg = "Unsupported upgrade request." - self.logger.warning(msg) - from uvicorn.protocols.websockets.auto import AutoWebSocketsProtocol - - if AutoWebSocketsProtocol is None: # pragma: no cover - msg = "No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually." # noqa: E501 - self.logger.warning(msg) - self.send_400_response(msg) - return - + def handle_websocket_upgrade(self, event: H11Event) -> None: if self.logger.level <= TRACE_LOG_LEVEL: prefix = "%s:%d - " % self.client if self.client else "" self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) @@ -280,7 +283,7 @@ class H11Protocol(asyncio.Protocol): for name, value in self.headers: output += [name, b": ", value, b"\r\n"] output.append(b"\r\n") - protocol = self.ws_protocol_class( # type: ignore[call-arg] + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] config=self.config, server_state=self.server_state ) protocol.connection_made(self.transport) diff --git a/uvicorn/protocols/http/httptools_impl.py b/uvicorn/protocols/http/httptools_impl.py index f018c59..734e894 100644 --- a/uvicorn/protocols/http/httptools_impl.py +++ b/uvicorn/protocols/http/httptools_impl.py @@ -90,7 +90,6 @@ class HttpToolsProtocol(asyncio.Protocol): self.server_state = server_state self.connections = server_state.connections self.tasks = server_state.tasks - self.default_headers = server_state.default_headers # Per-connection state self.transport: asyncio.Transport = None # type: ignore[assignment] @@ -149,6 +148,32 @@ class HttpToolsProtocol(asyncio.Protocol): self.timeout_keep_alive_task.cancel() self.timeout_keep_alive_task = None + def _get_upgrade(self) -> Optional[bytes]: + connection = [] + upgrade = None + for name, value in self.headers: + if name == b"connection": + connection = [token.lower().strip() for token in value.split(b",")] + if name == b"upgrade": + upgrade = value.lower() + if b"upgrade" in connection: + return upgrade + return None + + def _should_upgrade_to_ws(self, upgrade: Optional[bytes]) -> bool: + if upgrade == b"websocket" and self.ws_protocol_class is not None: + return True + if self.config.ws == "auto": + msg = "Unsupported upgrade request." + self.logger.warning(msg) + msg = "No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually." # noqa: E501 + self.logger.warning(msg) + return False + + def _should_upgrade(self) -> bool: + upgrade = self._get_upgrade() + return self._should_upgrade_to_ws(upgrade) + def data_received(self, data: bytes) -> None: self._unset_keepalive_if_required() @@ -160,25 +185,11 @@ class HttpToolsProtocol(asyncio.Protocol): self.send_400_response(msg) return except httptools.HttpParserUpgrade: - self.handle_upgrade() - - def handle_upgrade(self) -> None: - upgrade_value = None - for name, value in self.headers: - if name == b"upgrade": - upgrade_value = value.lower() - - if upgrade_value != b"websocket" or self.ws_protocol_class is None: - msg = "Unsupported upgrade request." - self.logger.warning(msg) - from uvicorn.protocols.websockets.auto import AutoWebSocketsProtocol - - if AutoWebSocketsProtocol is None: # pragma: no cover - msg = "No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually." # noqa: E501 - self.logger.warning(msg) - self.send_400_response(msg) - return + upgrade = self._get_upgrade() + if self._should_upgrade_to_ws(upgrade): + self.handle_websocket_upgrade() + def handle_websocket_upgrade(self) -> None: if self.logger.level <= TRACE_LOG_LEVEL: prefix = "%s:%d - " % self.client if self.client else "" self.logger.log(TRACE_LOG_LEVEL, "%sUpgrading to WebSocket", prefix) @@ -189,7 +200,7 @@ class HttpToolsProtocol(asyncio.Protocol): for name, value in self.scope["headers"]: output += [name, b": ", value, b"\r\n"] output.append(b"\r\n") - protocol = self.ws_protocol_class( # type: ignore[call-arg] + protocol = self.ws_protocol_class( # type: ignore[call-arg, misc] config=self.config, server_state=self.server_state ) protocol.connection_made(self.transport) @@ -199,7 +210,7 @@ class HttpToolsProtocol(asyncio.Protocol): def send_400_response(self, msg: str) -> None: content = [STATUS_LINE[400]] - for name, value in self.default_headers: + for name, value in self.server_state.default_headers: content.extend([name, b": ", value, b"\r\n"]) content.extend( [ @@ -244,7 +255,7 @@ class HttpToolsProtocol(asyncio.Protocol): self.scope["method"] = method.decode("ascii") if http_version != "1.1": self.scope["http_version"] = http_version - if self.parser.should_upgrade(): + if self.parser.should_upgrade() and self._should_upgrade(): return parsed_url = httptools.parse_url(self.url) raw_path = parsed_url.path @@ -274,7 +285,7 @@ class HttpToolsProtocol(asyncio.Protocol): logger=self.logger, access_logger=self.access_logger, access_log=self.access_log, - default_headers=self.default_headers, + default_headers=self.server_state.default_headers, message_event=asyncio.Event(), expect_100_continue=self.expect_100_continue, keep_alive=http_version != "1.0", @@ -291,7 +302,9 @@ class HttpToolsProtocol(asyncio.Protocol): self.pipeline.appendleft((self.cycle, app)) def on_body(self, body: bytes) -> None: - if self.parser.should_upgrade() or self.cycle.response_complete: + if ( + self.parser.should_upgrade() and self._should_upgrade() + ) or self.cycle.response_complete: return self.cycle.body += body if len(self.cycle.body) > HIGH_WATER_LIMIT: @@ -299,7 +312,9 @@ class HttpToolsProtocol(asyncio.Protocol): self.cycle.message_event.set() def on_message_complete(self) -> None: - if self.parser.should_upgrade() or self.cycle.response_complete: + if ( + self.parser.should_upgrade() and self._should_upgrade() + ) or self.cycle.response_complete: return self.cycle.more_body = False self.cycle.message_event.set()
encode/uvicorn
a94781dcd122b9727b85f86fcc60318eed72d223
diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index 839b094..def8a3a 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -7,7 +7,7 @@ import pytest from tests.response import Response from uvicorn import Server -from uvicorn.config import Config +from uvicorn.config import WS_PROTOCOLS, Config from uvicorn.main import ServerState from uvicorn.protocols.http.h11_impl import H11Protocol @@ -18,6 +18,7 @@ except ImportError: # pragma: nocover HTTP_PROTOCOLS = [p for p in [H11Protocol, HttpToolsProtocol] if p is not None] +WEBSOCKET_PROTOCOLS = WS_PROTOCOLS.keys() SIMPLE_GET_REQUEST = b"\r\n".join([b"GET / HTTP/1.1", b"Host: example.org", b"", b""]) @@ -76,6 +77,18 @@ UPGRADE_REQUEST = b"\r\n".join( ] ) +UPGRADE_HTTP2_REQUEST = b"\r\n".join( + [ + b"GET / HTTP/1.1", + b"Host: example.org", + b"Connection: upgrade", + b"Upgrade: h2c", + b"Sec-WebSocket-Version: 11", + b"", + b"", + ] +) + INVALID_REQUEST_TEMPLATE = b"\r\n".join( [ b"%s", @@ -697,23 +710,61 @@ async def test_100_continue_not_sent_when_body_not_consumed(protocol_cls): @pytest.mark.anyio @pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS) -async def test_unsupported_upgrade_request(protocol_cls): +async def test_supported_upgrade_request(protocol_cls): + app = Response("Hello, world", media_type="text/plain") + + protocol = get_connected_protocol(app, protocol_cls, ws="wsproto") + protocol.data_received(UPGRADE_REQUEST) + assert b"HTTP/1.1 426 " in protocol.transport.buffer + + [email protected] [email protected]("protocol_cls", HTTP_PROTOCOLS) +async def test_unsupported_ws_upgrade_request(protocol_cls): app = Response("Hello, world", media_type="text/plain") protocol = get_connected_protocol(app, protocol_cls, ws="none") protocol.data_received(UPGRADE_REQUEST) - assert b"HTTP/1.1 400 Bad Request" in protocol.transport.buffer - assert b"Unsupported upgrade request." in protocol.transport.buffer + await protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer @pytest.mark.anyio @pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS) -async def test_supported_upgrade_request(protocol_cls): +async def test_unsupported_ws_upgrade_request_warn_on_auto( + caplog: pytest.LogCaptureFixture, protocol_cls +): app = Response("Hello, world", media_type="text/plain") - protocol = get_connected_protocol(app, protocol_cls, ws="wsproto") + protocol = get_connected_protocol(app, protocol_cls, ws="auto") + protocol.ws_protocol_class = None protocol.data_received(UPGRADE_REQUEST) - assert b"HTTP/1.1 426 " in protocol.transport.buffer + await protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer + warnings = [ + record.msg + for record in filter( + lambda record: record.levelname == "WARNING", caplog.records + ) + ] + assert "Unsupported upgrade request." in warnings + msg = "No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually." # noqa: E501 + assert msg in warnings + + [email protected] [email protected]("protocol_cls", HTTP_PROTOCOLS) [email protected]("ws", WEBSOCKET_PROTOCOLS) +async def test_http2_upgrade_request(protocol_cls, ws): + app = Response("Hello, world", media_type="text/plain") + + protocol = get_connected_protocol(app, protocol_cls, ws=ws) + protocol.data_received(UPGRADE_HTTP2_REQUEST) + await protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + assert b"Hello, world" in protocol.transport.buffer async def asgi3app(scope, receive, send):
"Date" header not changing between requests ### Discussed in https://github.com/encode/uvicorn/discussions/1610 <div type='discussions-op-text'> <sup>Originally posted by **arjwilliams** August 22, 2022</sup> I am testing out some cache-control headers in my web app, but the auto-generated "Date" header seems to only be changing when a new connection is established, rather than with each new request, which is preventing the browser from caching new responses, as it sees the response as being older than it actually is. I would expect that the "Date" header to change between requests, even when using an existing connection. I am testing on Python 3.10.5, with Uvicorn 0.18.2. Possible test case, which is currently failing for me: ```python import asyncio from email.utils import parsedate_to_datetime from contextlib import asynccontextmanager import httpx from uvicorn import Config, Server async def test_default_date_header_different(): config = Config(app=app, loop="asyncio", limit_max_requests=2) async with run_server(config): async with httpx.AsyncClient() as client: response1 = await client.get("http://127.0.0.1:8000") await asyncio.sleep(2) response2 = await client.get("http://127.0.0.1:8000") response1_date = parsedate_to_datetime(response1.headers["date"]) response2_date = parsedate_to_datetime(response2.headers["date"]) assert(response2_date > response1_date) async def app(scope, receive, send): assert scope["type"] == "http" await send({"type": "http.response.start", "status": 200, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) @asynccontextmanager async def run_server(config: Config): server = Server(config=config) cancel_handle = asyncio.ensure_future(server.serve()) await asyncio.sleep(0.1) try: yield server finally: await server.shutdown() cancel_handle.cancel() asyncio.run(test_date_header_different()) ```</div>
0.0
[ "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request[H11Protocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request_warn_on_auto[H11Protocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request_warn_on_auto[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[auto-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[auto-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[none-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[none-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[websockets-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[websockets-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[wsproto-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[wsproto-HttpToolsProtocol]" ]
[ "tests/protocols/test_http.py::test_get_request[H11Protocol]", "tests/protocols/test_http.py::test_get_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo=bar]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo=bar&baz=1]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo=bar]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo=bar&baz=1]", "tests/protocols/test_http.py::test_head_request[H11Protocol]", "tests/protocols/test_http.py::test_head_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_post_request[H11Protocol]", "tests/protocols/test_http.py::test_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive[H11Protocol]", "tests/protocols/test_http.py::test_keepalive[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive_timeout[H11Protocol]", "tests/protocols/test_http.py::test_keepalive_timeout[HttpToolsProtocol]", "tests/protocols/test_http.py::test_close[H11Protocol]", "tests/protocols/test_http.py::test_close[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding_empty_body[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding_empty_body[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding_head_request[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding_head_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_pipelined_requests[H11Protocol]", "tests/protocols/test_http.py::test_pipelined_requests[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[H11Protocol]", "tests/protocols/test_http.py::test_undersized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_oversized_request[H11Protocol]", "tests/protocols/test_http.py::test_oversized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_large_post_request[H11Protocol]", "tests/protocols/test_http.py::test_large_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_invalid_http[H11Protocol]", "tests/protocols/test_http.py::test_invalid_http[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[H11Protocol]", "tests/protocols/test_http.py::test_app_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_exception_during_response[H11Protocol]", "tests/protocols/test_http.py::test_exception_during_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_no_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_no_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_partial_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_partial_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_duplicate_start_message[H11Protocol]", "tests/protocols/test_http.py::test_duplicate_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_missing_start_message[H11Protocol]", "tests/protocols/test_http.py::test_missing_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_message_after_body_complete[H11Protocol]", "tests/protocols/test_http.py::test_message_after_body_complete[HttpToolsProtocol]", "tests/protocols/test_http.py::test_value_returned[H11Protocol]", "tests/protocols/test_http.py::test_value_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_disconnect[H11Protocol]", "tests/protocols/test_http.py::test_early_disconnect[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_response[H11Protocol]", "tests/protocols/test_http.py::test_early_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_read_after_response[H11Protocol]", "tests/protocols/test_http.py::test_read_after_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[H11Protocol]", "tests/protocols/test_http.py::test_http10_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_root_path[H11Protocol]", "tests/protocols/test_http.py::test_root_path[HttpToolsProtocol]", "tests/protocols/test_http.py::test_raw_path[H11Protocol]", "tests/protocols/test_http.py::test_raw_path[HttpToolsProtocol]", "tests/protocols/test_http.py::test_max_concurrency[H11Protocol]", "tests/protocols/test_http.py::test_max_concurrency[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_request[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_supported_upgrade_request[H11Protocol]", "tests/protocols/test_http.py::test_supported_upgrade_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_scopes[H11Protocol-asgi3app-expected_scopes0]", "tests/protocols/test_http.py::test_scopes[H11Protocol-asgi2app-expected_scopes1]", "tests/protocols/test_http.py::test_scopes[HttpToolsProtocol-asgi3app-expected_scopes0]", "tests/protocols/test_http.py::test_scopes[HttpToolsProtocol-asgi2app-expected_scopes1]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-method]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-path]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-http-version]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-method]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-path]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-http-version]", "tests/protocols/test_http.py::test_fragmentation", "tests/protocols/test_http.py::test_huge_headers_h11protocol_failure", "tests/protocols/test_http.py::test_huge_headers_httptools_will_pass", "tests/protocols/test_http.py::test_huge_headers_h11protocol_failure_with_setting", "tests/protocols/test_http.py::test_huge_headers_httptools", "tests/protocols/test_http.py::test_huge_headers_h11_max_incomplete" ]
2022-10-12 08:24:30+00:00
2,161
encode__uvicorn-1737
diff --git a/setup.cfg b/setup.cfg index 46f4e3b..ac52be5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -82,7 +82,7 @@ plugins = [coverage:report] precision = 2 -fail_under = 97.82 +fail_under = 97.92 show_missing = true skip_covered = true exclude_lines = diff --git a/uvicorn/config.py b/uvicorn/config.py index df91a6c..d2faf76 100644 --- a/uvicorn/config.py +++ b/uvicorn/config.py @@ -372,6 +372,9 @@ class Config: else: self.forwarded_allow_ips = forwarded_allow_ips + if self.reload and self.workers > 1: + logger.warning('"workers" flag is ignored when reloading is enabled.') + @property def asgi_version(self) -> Literal["2.0", "3.0"]: mapping: Dict[str, Literal["2.0", "3.0"]] = { diff --git a/uvicorn/protocols/websockets/websockets_impl.py b/uvicorn/protocols/websockets/websockets_impl.py index 01133b7..87e7baa 100644 --- a/uvicorn/protocols/websockets/websockets_impl.py +++ b/uvicorn/protocols/websockets/websockets_impl.py @@ -345,6 +345,8 @@ class WebSocketProtocol(WebSocketServerProtocol): data = await self.recv() except ConnectionClosed as exc: self.closed_event.set() + if self.ws_server.closing: + return {"type": "websocket.disconnect", "code": 1012} return {"type": "websocket.disconnect", "code": exc.code} msg: WebSocketReceiveEvent = { # type: ignore[typeddict-item] diff --git a/uvicorn/protocols/websockets/wsproto_impl.py b/uvicorn/protocols/websockets/wsproto_impl.py index 6e4f505..a97766f 100644 --- a/uvicorn/protocols/websockets/wsproto_impl.py +++ b/uvicorn/protocols/websockets/wsproto_impl.py @@ -87,11 +87,8 @@ class WSProtocol(asyncio.Protocol): try: self.conn.receive_data(data) except RemoteProtocolError as err: - if err.event_hint is not None: - self.transport.write(self.conn.send(err.event_hint)) - self.transport.close() - else: - self.handle_no_connect(events.CloseConnection()) + self.transport.write(self.conn.send(err.event_hint)) + self.transport.close() else: self.handle_events() @@ -125,9 +122,12 @@ class WSProtocol(asyncio.Protocol): self.writable.set() def shutdown(self): - self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) - output = self.conn.send(wsproto.events.CloseConnection(code=1012)) - self.transport.write(output) + if self.handshake_complete: + self.queue.put_nowait({"type": "websocket.disconnect", "code": 1012}) + output = self.conn.send(wsproto.events.CloseConnection(code=1012)) + self.transport.write(output) + else: + self.send_500_response() self.transport.close() def on_task_complete(self, task): @@ -222,9 +222,8 @@ class WSProtocol(asyncio.Protocol): async def run_asgi(self): try: result = await self.app(self.scope, self.receive, self.send) - except BaseException as exc: - msg = "Exception in ASGI application\n" - self.logger.error(msg, exc_info=exc) + except BaseException: + self.logger.exception("Exception in ASGI application\n") if not self.handshake_complete: self.send_500_response() self.transport.close() @@ -257,14 +256,15 @@ class WSProtocol(asyncio.Protocol): extensions = [] if self.config.ws_per_message_deflate: extensions.append(PerMessageDeflate()) - output = self.conn.send( - wsproto.events.AcceptConnection( - subprotocol=subprotocol, - extensions=extensions, - extra_headers=extra_headers, + if not self.transport.is_closing(): + output = self.conn.send( + wsproto.events.AcceptConnection( + subprotocol=subprotocol, + extensions=extensions, + extra_headers=extra_headers, + ) ) - ) - self.transport.write(output) + self.transport.write(output) elif message_type == "websocket.close": self.queue.put_nowait({"type": "websocket.disconnect", "code": None}) diff --git a/uvicorn/workers.py b/uvicorn/workers.py index c7d16ff..82b18e9 100644 --- a/uvicorn/workers.py +++ b/uvicorn/workers.py @@ -2,7 +2,7 @@ import asyncio import logging import signal import sys -from typing import Any +from typing import Any, Dict from gunicorn.arbiter import Arbiter from gunicorn.workers.base import Worker @@ -17,7 +17,7 @@ class UvicornWorker(Worker): rather than a WSGI callable. """ - CONFIG_KWARGS = {"loop": "auto", "http": "auto"} + CONFIG_KWARGS: Dict[str, Any] = {"loop": "auto", "http": "auto"} def __init__(self, *args: Any, **kwargs: Any) -> None: super(UvicornWorker, self).__init__(*args, **kwargs)
encode/uvicorn
3243f20c300eaad0c50f2707a5cb3fe80a284249
diff --git a/.github/workflows/test-suite.yml b/.github/workflows/test-suite.yml index 04c13b5..ff82ebd 100644 --- a/.github/workflows/test-suite.yml +++ b/.github/workflows/test-suite.yml @@ -13,7 +13,7 @@ jobs: runs-on: "${{ matrix.os }}" strategy: matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11-dev"] + python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] os: [windows-latest, ubuntu-latest, macos-latest] steps: - uses: "actions/checkout@v3" diff --git a/tests/protocols/test_websocket.py b/tests/protocols/test_websocket.py index a5fe93d..d495f51 100644 --- a/tests/protocols/test_websocket.py +++ b/tests/protocols/test_websocket.py @@ -528,7 +528,6 @@ async def test_client_connection_lost(ws_protocol_cls, http_protocol_cls): while True: message = await receive() if message["type"] == "websocket.connect": - print("accepted") await send({"type": "websocket.accept"}) elif message["type"] == "websocket.disconnect": break @@ -551,6 +550,66 @@ async def test_client_connection_lost(ws_protocol_cls, http_protocol_cls): assert got_disconnect_event_before_shutdown is True [email protected] [email protected]("ws_protocol_cls", WS_PROTOCOLS) [email protected]("http_protocol_cls", HTTP_PROTOCOLS) +async def test_not_accept_on_connection_lost(ws_protocol_cls, http_protocol_cls): + send_accept_task = asyncio.Event() + + async def app(scope, receive, send): + while True: + message = await receive() + if message["type"] == "websocket.connect": + await send_accept_task.wait() + await send({"type": "websocket.accept"}) + elif message["type"] == "websocket.disconnect": + break + + async def websocket_session(uri): + async with websockets.client.connect(uri): + while True: + await asyncio.sleep(0.1) + + config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") + async with run_server(config): + task = asyncio.create_task(websocket_session("ws://127.0.0.1:8000")) + await asyncio.sleep(0.1) + task.cancel() + send_accept_task.set() + + [email protected] [email protected]("ws_protocol_cls", WS_PROTOCOLS) [email protected]("http_protocol_cls", HTTP_PROTOCOLS) +async def test_send_close_on_server_shutdown(ws_protocol_cls, http_protocol_cls): + disconnect_message = {} + + async def app(scope, receive, send): + nonlocal disconnect_message + while True: + message = await receive() + if message["type"] == "websocket.connect": + await send({"type": "websocket.accept"}) + elif message["type"] == "websocket.disconnect": + disconnect_message = message + break + + async def websocket_session(uri): + async with websockets.client.connect(uri): + while True: + await asyncio.sleep(0.1) + + config = Config(app=app, ws=ws_protocol_cls, http=http_protocol_cls, lifespan="off") + async with run_server(config): + task = asyncio.create_task(websocket_session("ws://127.0.0.1:8000")) + await asyncio.sleep(0.1) + disconnect_message_before_shutdown = disconnect_message + + assert disconnect_message_before_shutdown == {} + assert disconnect_message == {"type": "websocket.disconnect", "code": 1012} + task.cancel() + + @pytest.mark.anyio @pytest.mark.parametrize("ws_protocol_cls", WS_PROTOCOLS) @pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS) diff --git a/tests/test_config.py b/tests/test_config.py index 403112f..d11c632 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -557,3 +557,12 @@ def test_config_use_subprocess(reload, workers, expected): config = Config(app=asgi_app, reload=reload, workers=workers) config.load() assert config.use_subprocess == expected + + +def test_warn_when_using_reload_and_workers(caplog: pytest.LogCaptureFixture) -> None: + Config(app=asgi_app, reload=True, workers=2) + assert len(caplog.records) == 1 + assert ( + '"workers" flag is ignored when reloading is enabled.' + in caplog.records[0].message + )
Handshaking may not be completed yet at `shutdown` in wsproto impl Traceback: ``` LocalProtocolError: Event CloseConnection(code=1012, reason=None) cannot be sent during the handshake File "gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "uvicorn/workers.py", line 57, in init_process super(UvicornWorker, self).init_process() File "gunicorn/workers/base.py", line 140, in init_process self.run() File "uvicorn/workers.py", line 66, in run loop.run_until_complete(server.serve(sockets=self.sockets)) File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete File "uvicorn/main.py", line 403, in serve await self.shutdown(sockets=sockets) File "uvicorn/main.py", line 539, in shutdown connection.shutdown() File "uvicorn/protocols/websockets/wsproto_impl.py", line 115, in shutdown output = self.conn.send(wsproto.events.CloseConnection(code=1012)) File "__init__.py", line 61, in send data += self.handshake.send(event) File "wsproto/handshake.py", line 101, in send "Event {} cannot be sent during the handshake".format(event) ```
0.0
[ "tests/protocols/test_websocket.py::test_not_accept_on_connection_lost[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_not_accept_on_connection_lost[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_not_accept_on_connection_lost[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_not_accept_on_connection_lost[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_close_on_server_shutdown[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_close_on_server_shutdown[HttpToolsProtocol-WebSocketProtocol]", "tests/test_config.py::test_warn_when_using_reload_and_workers" ]
[ "tests/protocols/test_websocket.py::test_invalid_upgrade[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_invalid_upgrade[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_invalid_upgrade[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_invalid_upgrade[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_accept_connection[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_accept_connection[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_accept_connection[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_accept_connection[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_supports_permessage_deflate_extension[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_supports_permessage_deflate_extension[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_supports_permessage_deflate_extension[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_supports_permessage_deflate_extension[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_can_disable_permessage_deflate_extension[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_can_disable_permessage_deflate_extension[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_can_disable_permessage_deflate_extension[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_can_disable_permessage_deflate_extension[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_close_connection[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_close_connection[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_close_connection[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_close_connection[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_headers[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_headers[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_headers[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_headers[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_extra_headers[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_extra_headers[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_extra_headers[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_extra_headers[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_path_and_raw_path[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_path_and_raw_path[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_path_and_raw_path[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_path_and_raw_path[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_client[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_client[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_client[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_client[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_client[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_client[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_client[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_client[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_and_close_connection[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_and_close_connection[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_and_close_connection[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_and_close_connection[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_server[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_server[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_server[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_text_data_to_server[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_server[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_server[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_server[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_server[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_after_protocol_close[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_after_protocol_close[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_after_protocol_close[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_after_protocol_close[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_missing_handshake[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_missing_handshake[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_missing_handshake[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_missing_handshake[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_before_handshake[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_before_handshake[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_before_handshake[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_before_handshake[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_duplicate_handshake[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_duplicate_handshake[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_duplicate_handshake[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_duplicate_handshake[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_asgi_return_value[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_asgi_return_value[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-None-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-None-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-None-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-None-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1000-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1000-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1000-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1000-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1001-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1001-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1001-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[none_as_reason-1001-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-None-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-None-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-None-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-None-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1000-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1000-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1000-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1000-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1001-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1001-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1001-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[normal_reason-1001-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-None-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-None-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-None-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-None-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1000-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1000-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1000-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1000-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1001-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1001-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1001-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_app_close[without_reason-1001-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_client_close[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_client_close[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_client_close[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_client_close[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_client_connection_lost[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_client_connection_lost[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_client_connection_lost[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_client_connection_lost[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_close_on_server_shutdown[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_send_close_on_server_shutdown[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto1-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto1-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto1-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto1-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto2-H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto2-H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto2-HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_subprotocols[proto2-HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_send_binary_data_to_server_bigger_than_default[max=defaults", "tests/protocols/test_websocket.py::test_send_binary_data_to_server_bigger_than_default[max=10", "tests/protocols/test_websocket.py::test_server_reject_connection[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_server_reject_connection[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_server_reject_connection[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_server_reject_connection[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_server_can_read_messages_in_buffer_after_close[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_server_can_read_messages_in_buffer_after_close[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_server_can_read_messages_in_buffer_after_close[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_server_can_read_messages_in_buffer_after_close[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_default_server_headers[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_default_server_headers[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_default_server_headers[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_default_server_headers[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_no_server_headers[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_no_server_headers[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_no_server_headers[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_no_server_headers[HttpToolsProtocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_no_date_header[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_no_date_header[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_multiple_server_header[H11Protocol-WSProtocol]", "tests/protocols/test_websocket.py::test_multiple_server_header[H11Protocol-WebSocketProtocol]", "tests/protocols/test_websocket.py::test_multiple_server_header[HttpToolsProtocol-WSProtocol]", "tests/protocols/test_websocket.py::test_multiple_server_header[HttpToolsProtocol-WebSocketProtocol]", "tests/test_config.py::test_config_should_reload_is_set[asgi_app-False]", "tests/test_config.py::test_config_should_reload_is_set[tests.test_config:asgi_app-True]", "tests/test_config.py::test_should_warn_on_invalid_reload_configuration", "tests/test_config.py::test_reload_dir_is_set", "tests/test_config.py::test_non_existant_reload_dir_is_not_set", "tests/test_config.py::test_reload_subdir_removal", "tests/test_config.py::test_reload_included_dir_is_added_to_reload_dirs", "tests/test_config.py::test_reload_dir_subdirectories_are_removed", "tests/test_config.py::test_reload_excluded_subdirectories_are_removed", "tests/test_config.py::test_reload_includes_exclude_dir_patterns_are_matched", "tests/test_config.py::test_wsgi_app", "tests/test_config.py::test_proxy_headers", "tests/test_config.py::test_app_unimportable_module", "tests/test_config.py::test_app_unimportable_other", "tests/test_config.py::test_app_factory", "tests/test_config.py::test_concrete_http_class", "tests/test_config.py::test_socket_bind", "tests/test_config.py::test_ssl_config", "tests/test_config.py::test_ssl_config_combined", "tests/test_config.py::test_asgi_version[asgi_app-3.0]", "tests/test_config.py::test_asgi_version[asgi2_app-2.0]", "tests/test_config.py::test_log_config_default[use_colors_not_provided]", "tests/test_config.py::test_log_config_default[use_colors_invalid_value]", "tests/test_config.py::test_log_config_default[use_colors_enabled]", "tests/test_config.py::test_log_config_default[use_colors_disabled]", "tests/test_config.py::test_log_config_json", "tests/test_config.py::test_log_config_yaml[log_config.yml]", "tests/test_config.py::test_log_config_yaml[log_config.yaml]", "tests/test_config.py::test_log_config_file", "tests/test_config.py::test_env_file[0-127.0.0.1]", "tests/test_config.py::test_env_file[0-127.0.0.2]", "tests/test_config.py::test_env_file[1-127.0.0.1]", "tests/test_config.py::test_env_file[1-127.0.0.2]", "tests/test_config.py::test_config_access_log[access", "tests/test_config.py::test_config_log_level[5]", "tests/test_config.py::test_config_log_level[10]", "tests/test_config.py::test_config_log_level[20]", "tests/test_config.py::test_config_log_level[30]", "tests/test_config.py::test_config_log_level[40]", "tests/test_config.py::test_config_log_level[50]", "tests/test_config.py::test_ws_max_size", "tests/test_config.py::test_bind_unix_socket_works_with_reload_or_workers[--reload=True", "tests/test_config.py::test_bind_unix_socket_works_with_reload_or_workers[--reload=False", "tests/test_config.py::test_bind_fd_works_with_reload_or_workers[--reload=True", "tests/test_config.py::test_bind_fd_works_with_reload_or_workers[--reload=False", "tests/test_config.py::test_config_use_subprocess[--reload=True", "tests/test_config.py::test_config_use_subprocess[--reload=False" ]
2022-10-28 13:04:02+00:00
2,162
encode__uvicorn-1782
diff --git a/uvicorn/protocols/http/h11_impl.py b/uvicorn/protocols/http/h11_impl.py index 9f6931e..c2764b0 100644 --- a/uvicorn/protocols/http/h11_impl.py +++ b/uvicorn/protocols/http/h11_impl.py @@ -468,10 +468,7 @@ class RequestResponseCycle: self.waiting_for_100_continue = False status_code = message["status"] - message_headers = cast( - List[Tuple[bytes, bytes]], message.get("headers", []) - ) - headers = self.default_headers + message_headers + headers = self.default_headers + list(message.get("headers", [])) if CLOSE_HEADER in self.scope["headers"] and CLOSE_HEADER not in headers: headers = headers + [CLOSE_HEADER]
encode/uvicorn
085f67be1d1eeb1546da6522fc4eb17751b62463
diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index 79946ad..8db2795 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -966,3 +966,17 @@ async def test_return_close_header(protocol_cls, close_header: bytes): assert b"content-type: text/plain" in protocol.transport.buffer assert b"content-length: 12" in protocol.transport.buffer assert close_header in protocol.transport.buffer + + [email protected] [email protected]("protocol_cls", HTTP_PROTOCOLS) +async def test_iterator_headers(protocol_cls): + async def app(scope, receive, send): + headers = iter([(b"x-test-header", b"test value")]) + await send({"type": "http.response.start", "status": 200, "headers": headers}) + await send({"type": "http.response.body", "body": b""}) + + protocol = get_connected_protocol(app, protocol_cls) + protocol.data_received(SIMPLE_GET_REQUEST) + await protocol.loop.run_one() + assert b"x-test-header: test value" in protocol.transport.buffer
Uvicorn assumes that `HTTPResponseStartEvent.headers` is a `List` ### Discussed in https://github.com/encode/uvicorn/discussions/1779 <div type='discussions-op-text'> <sup>Originally posted by **rijenkii** November 27, 2022</sup> According to the spec and asgiref, `HTTPResponseStartEvent.headers` is `Iterable[Tuple[bytes, bytes]]`. But, if `http.response.start` is sent like this: ```python headers: dict await send({ "type": "http.response.start", "status": status, "headers": headers.items(), }) ``` Uvicorn fails with ``` File ".../uvicorn/protocols/http/h11_impl.py", line 474, in send headers = self.default_headers + message_headers ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ TypeError: can only concatenate list (not "dict_items") to list ``` Relevant Uvicorn code: https://github.com/encode/uvicorn/blob/782f17e3855d5f36ce69d55427e74ca7f9b998c5/uvicorn/protocols/http/h11_impl.py#L471-L474 --- Potential fix may just be this: ```python message_headers = list(message.get("headers", [])) ```</div>
0.0
[ "tests/protocols/test_http.py::test_iterator_headers[H11Protocol]" ]
[ "tests/protocols/test_http.py::test_get_request[H11Protocol]", "tests/protocols/test_http.py::test_get_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo=bar]", "tests/protocols/test_http.py::test_request_logging[H11Protocol-/?foo=bar&baz=1]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo=bar]", "tests/protocols/test_http.py::test_request_logging[HttpToolsProtocol-/?foo=bar&baz=1]", "tests/protocols/test_http.py::test_head_request[H11Protocol]", "tests/protocols/test_http.py::test_head_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_post_request[H11Protocol]", "tests/protocols/test_http.py::test_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive[H11Protocol]", "tests/protocols/test_http.py::test_keepalive[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive_timeout[H11Protocol]", "tests/protocols/test_http.py::test_keepalive_timeout[HttpToolsProtocol]", "tests/protocols/test_http.py::test_close[H11Protocol]", "tests/protocols/test_http.py::test_close[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding_empty_body[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding_empty_body[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding_head_request[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding_head_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_pipelined_requests[H11Protocol]", "tests/protocols/test_http.py::test_pipelined_requests[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[H11Protocol]", "tests/protocols/test_http.py::test_undersized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_oversized_request[H11Protocol]", "tests/protocols/test_http.py::test_oversized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_large_post_request[H11Protocol]", "tests/protocols/test_http.py::test_large_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_invalid_http[H11Protocol]", "tests/protocols/test_http.py::test_invalid_http[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[H11Protocol]", "tests/protocols/test_http.py::test_app_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_exception_during_response[H11Protocol]", "tests/protocols/test_http.py::test_exception_during_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_no_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_no_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_partial_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_partial_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_duplicate_start_message[H11Protocol]", "tests/protocols/test_http.py::test_duplicate_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_missing_start_message[H11Protocol]", "tests/protocols/test_http.py::test_missing_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_message_after_body_complete[H11Protocol]", "tests/protocols/test_http.py::test_message_after_body_complete[HttpToolsProtocol]", "tests/protocols/test_http.py::test_value_returned[H11Protocol]", "tests/protocols/test_http.py::test_value_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_disconnect[H11Protocol]", "tests/protocols/test_http.py::test_early_disconnect[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_response[H11Protocol]", "tests/protocols/test_http.py::test_early_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_read_after_response[H11Protocol]", "tests/protocols/test_http.py::test_read_after_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[H11Protocol]", "tests/protocols/test_http.py::test_http10_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_root_path[H11Protocol]", "tests/protocols/test_http.py::test_root_path[HttpToolsProtocol]", "tests/protocols/test_http.py::test_raw_path[H11Protocol]", "tests/protocols/test_http.py::test_raw_path[HttpToolsProtocol]", "tests/protocols/test_http.py::test_max_concurrency[H11Protocol]", "tests/protocols/test_http.py::test_max_concurrency[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_request[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_supported_upgrade_request[H11Protocol]", "tests/protocols/test_http.py::test_supported_upgrade_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request[H11Protocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request_warn_on_auto[H11Protocol]", "tests/protocols/test_http.py::test_unsupported_ws_upgrade_request_warn_on_auto[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[auto-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[auto-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[none-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[none-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[websockets-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[websockets-HttpToolsProtocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[wsproto-H11Protocol]", "tests/protocols/test_http.py::test_http2_upgrade_request[wsproto-HttpToolsProtocol]", "tests/protocols/test_http.py::test_scopes[H11Protocol-asgi3app-expected_scopes0]", "tests/protocols/test_http.py::test_scopes[H11Protocol-asgi2app-expected_scopes1]", "tests/protocols/test_http.py::test_scopes[HttpToolsProtocol-asgi3app-expected_scopes0]", "tests/protocols/test_http.py::test_scopes[HttpToolsProtocol-asgi2app-expected_scopes1]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-method]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-path]", "tests/protocols/test_http.py::test_invalid_http_request[H11Protocol-invalid-http-version]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-method]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-path]", "tests/protocols/test_http.py::test_invalid_http_request[HttpToolsProtocol-invalid-http-version]", "tests/protocols/test_http.py::test_fragmentation", "tests/protocols/test_http.py::test_huge_headers_h11protocol_failure", "tests/protocols/test_http.py::test_huge_headers_httptools_will_pass", "tests/protocols/test_http.py::test_huge_headers_h11protocol_failure_with_setting", "tests/protocols/test_http.py::test_huge_headers_httptools", "tests/protocols/test_http.py::test_huge_headers_h11_max_incomplete", "tests/protocols/test_http.py::test_return_close_header[HttpToolsProtocol-connection:", "tests/protocols/test_http.py::test_return_close_header[H11Protocol-Connection:", "tests/protocols/test_http.py::test_iterator_headers[HttpToolsProtocol]" ]
2022-11-27 14:04:55+00:00
2,163
encode__uvicorn-227
diff --git a/uvicorn/middleware/message_logger.py b/uvicorn/middleware/message_logger.py index 3ddc9c9..a33736d 100644 --- a/uvicorn/middleware/message_logger.py +++ b/uvicorn/middleware/message_logger.py @@ -36,20 +36,27 @@ class MessageLoggerMiddleware: class MessageLoggerResponder: def __init__(self, scope, app, logger, task_counter): self.scope = scope - self.app = app self.logger = logger self.task_counter = task_counter self.client_addr = scope.get('client') + logged_scope = message_with_placeholders(scope) + log_text = '%s - ASGI [%d] Initialized %s' + self.logger.debug(log_text, self.client_addr, self.task_counter, logged_scope) + try: + self.inner = app(scope) + except: + log_text = '%s - ASGI [%d] Raised exception' + self.logger.debug(log_text, self.client_addr, self.task_counter) + raise + async def __call__(self, receive, send): self._receive = receive self._send = send - logged_scope = message_with_placeholders(self.scope) - log_text = '%s - ASGI [%d] Started %s' - self.logger.debug(log_text, self.client_addr, self.task_counter, logged_scope) + log_text = '%s - ASGI [%d] Started task' + self.logger.debug(log_text, self.client_addr, self.task_counter) try: - inner = self.app(self.scope) - await inner(self.receive, self.send) + await self.inner(self.receive, self.send) except: log_text = '%s - ASGI [%d] Raised exception' self.logger.debug(log_text, self.client_addr, self.task_counter)
encode/uvicorn
21494a0e7b4a063793ec1165c9e94b2c09ead2aa
diff --git a/tests/middleware/test_message_logger.py b/tests/middleware/test_message_logger.py index 2541dc0..1d07ed6 100644 --- a/tests/middleware/test_message_logger.py +++ b/tests/middleware/test_message_logger.py @@ -19,7 +19,8 @@ def test_message_logger(caplog): response = client.get("/") assert response.status_code == 200 messages = [record.msg % record.args for record in caplog.records] - assert sum(['ASGI [1] Started' in message for message in messages]) == 1 + assert sum(['ASGI [1] Initialized' in message for message in messages]) == 1 + assert sum(['ASGI [1] Started task' in message for message in messages]) == 1 assert sum(['ASGI [1] Sent' in message for message in messages]) == 1 assert sum(['ASGI [1] Received' in message for message in messages]) == 2 assert sum(['ASGI [1] Completed' in message for message in messages]) == 1 @@ -39,7 +40,26 @@ def test_message_logger_exc(caplog): with pytest.raises(RuntimeError): client.get("/") messages = [record.msg % record.args for record in caplog.records] - assert sum(['ASGI [1] Started' in message for message in messages]) == 1 + assert sum(['ASGI [1] Initialized' in message for message in messages]) == 1 + assert sum(['ASGI [1] Started task' in message for message in messages]) == 1 + assert sum(['ASGI [1] Sent' in message for message in messages]) == 0 + assert sum(['ASGI [1] Received' in message for message in messages]) == 0 + assert sum(['ASGI [1] Completed' in message for message in messages]) == 0 + assert sum(['ASGI [1] Raised exception' in message for message in messages]) == 1 + + +def test_message_logger_scope_exc(caplog): + def app(scope): + raise RuntimeError() + + caplog.set_level(logging.DEBUG) + app = MessageLoggerMiddleware(app) + client = TestClient(app) + with pytest.raises(RuntimeError): + client.get("/") + messages = [record.msg % record.args for record in caplog.records] + assert sum(['ASGI [1] Initialized' in message for message in messages]) == 1 + assert sum(['ASGI [1] Started task' in message for message in messages]) == 0 assert sum(['ASGI [1] Sent' in message for message in messages]) == 0 assert sum(['ASGI [1] Received' in message for message in messages]) == 0 assert sum(['ASGI [1] Completed' in message for message in messages]) == 0
Error integrating with Channels if 'lifespan' is not specified in router I'm not entirely sure if I should be posting this here or on `channels`. I'm using v0.3.12 which I believe has already introduced the new `lifespan` protocol defined in asgiref. But this causes an error with `channels`' router ```bash Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/uvicorn/lifespan.py", line 29, in run await self.asgi(self.receive, self.send) File "/usr/local/lib/python3.6/site-packages/uvicorn/middleware/message_logger.py", line 51, in __call__ inner = self.app(self.scope) File "/usr/local/lib/python3.6/site-packages/channels/routing.py", line 58, in __call__ raise ValueError("No application configured for scope type %r" % scope["type"]) ValueError: No application configured for scope type 'lifespan' ``` My `routing.py` file looks like this: ```python application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': JWTWebsocketMiddleware( URLRouter(urlpatterns) ) }) ``` **EDIT**: Sorry my workaround wasn't actually working as you'll need at least one `path` in the `URLRouter`, so I've removed it. To temporarily get around this, I had to downgrade to `v0.3.9`.
0.0
[ "tests/middleware/test_message_logger.py::test_message_logger", "tests/middleware/test_message_logger.py::test_message_logger_exc", "tests/middleware/test_message_logger.py::test_message_logger_scope_exc" ]
[]
2018-10-16 13:43:28+00:00
2,164
encode__uvicorn-228
diff --git a/uvicorn/protocols/http/h11_impl.py b/uvicorn/protocols/http/h11_impl.py index 0628a17..4ae0932 100644 --- a/uvicorn/protocols/http/h11_impl.py +++ b/uvicorn/protocols/http/h11_impl.py @@ -5,6 +5,7 @@ import logging import time import traceback from urllib.parse import unquote +from uvicorn.protocols.utils import get_local_addr, get_remote_addr, is_ssl import h11 @@ -136,9 +137,9 @@ class H11Protocol(asyncio.Protocol): self.transport = transport self.flow = FlowControl(transport) - self.server = transport.get_extra_info("sockname") - self.client = transport.get_extra_info("peername") - self.scheme = "https" if transport.get_extra_info("sslcontext") else "http" + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" if self.logger.level <= logging.DEBUG: self.logger.debug("%s - Connected", self.client) diff --git a/uvicorn/protocols/http/httptools_impl.py b/uvicorn/protocols/http/httptools_impl.py index 29dd27a..14a20f1 100644 --- a/uvicorn/protocols/http/httptools_impl.py +++ b/uvicorn/protocols/http/httptools_impl.py @@ -5,6 +5,7 @@ import logging import time import traceback from urllib.parse import unquote +from uvicorn.protocols.utils import get_local_addr, get_remote_addr, is_ssl import httptools @@ -140,9 +141,9 @@ class HttpToolsProtocol(asyncio.Protocol): self.transport = transport self.flow = FlowControl(transport) - self.server = transport.get_extra_info("sockname") - self.client = transport.get_extra_info("peername") - self.scheme = "https" if transport.get_extra_info("sslcontext") else "http" + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "https" if is_ssl(transport) else "http" if self.logger.level <= logging.DEBUG: self.logger.debug("%s - Connected", self.client) diff --git a/uvicorn/protocols/utils.py b/uvicorn/protocols/utils.py new file mode 100644 index 0000000..1792365 --- /dev/null +++ b/uvicorn/protocols/utils.py @@ -0,0 +1,16 @@ +def get_remote_addr(transport): + info = transport.get_extra_info("peername") + if info is not None and isinstance(info, (list, tuple)) and len(info) == 2: + return (str(info[0]), int(info[1])) + return None + + +def get_local_addr(transport): + info = transport.get_extra_info("sockname") + if info is not None and isinstance(info, (list, tuple)) and len(info) == 2: + return (str(info[0]), int(info[1])) + return None + + +def is_ssl(transport): + return bool(transport.get_extra_info("sslcontext")) diff --git a/uvicorn/protocols/websockets/websockets_impl.py b/uvicorn/protocols/websockets/websockets_impl.py index 37dd2e1..e8a1688 100644 --- a/uvicorn/protocols/websockets/websockets_impl.py +++ b/uvicorn/protocols/websockets/websockets_impl.py @@ -1,4 +1,5 @@ from urllib.parse import unquote +from uvicorn.protocols.utils import get_local_addr, get_remote_addr, is_ssl import asyncio import http import logging @@ -47,9 +48,9 @@ class WebSocketProtocol(websockets.WebSocketServerProtocol): def connection_made(self, transport): self.connections.add(self) self.transport = transport - self.server = transport.get_extra_info("sockname") - self.client = transport.get_extra_info("peername") - self.scheme = "wss" if transport.get_extra_info("sslcontext") else "ws" + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" super().connection_made(transport) def connection_lost(self, exc): diff --git a/uvicorn/protocols/websockets/wsproto_impl.py b/uvicorn/protocols/websockets/wsproto_impl.py index 141490b..e4bd9c9 100644 --- a/uvicorn/protocols/websockets/wsproto_impl.py +++ b/uvicorn/protocols/websockets/wsproto_impl.py @@ -1,4 +1,5 @@ from urllib.parse import unquote +from uvicorn.protocols.utils import get_local_addr, get_remote_addr, is_ssl import asyncio import h11 import logging @@ -47,9 +48,9 @@ class WSProtocol(asyncio.Protocol): def connection_made(self, transport): self.connections.add(self) self.transport = transport - self.server = transport.get_extra_info("sockname") - self.client = transport.get_extra_info("peername") - self.scheme = "wss" if transport.get_extra_info("sslcontext") else "ws" + self.server = get_local_addr(transport) + self.client = get_remote_addr(transport) + self.scheme = "wss" if is_ssl(transport) else "ws" def connection_lost(self, exc): self.connections.remove(self)
encode/uvicorn
aae22d8c63146e8634682ccf80cf1da74ca4eace
diff --git a/tests/protocols/test_utils.py b/tests/protocols/test_utils.py new file mode 100644 index 0000000..2b5ec63 --- /dev/null +++ b/tests/protocols/test_utils.py @@ -0,0 +1,25 @@ +from uvicorn.protocols.utils import get_local_addr, get_remote_addr + + +class MockTransport: + def __init__(self, info): + self.info = info + + def get_extra_info(self, info_type): + return self.info[info_type] + + +def test_get_local_addr(): + transport = MockTransport({"sockname": "path/to/unix-domain-socket"}) + assert get_local_addr(transport) == None + + transport = MockTransport({"sockname": ['123.45.6.7', 123]}) + assert get_local_addr(transport) == ('123.45.6.7', 123) + + +def test_get_remote_addr(): + transport = MockTransport({"peername": None}) + assert get_remote_addr(transport) == None + + transport = MockTransport({"peername": ['123.45.6.7', 123]}) + assert get_remote_addr(transport) == ('123.45.6.7', 123)
scope["server"] and scope["client"] must be a two-item iterable According to the [asgi spec](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) > both scope["server"] and scope["client"] must be either a two-item iterable of [host, port] or None (the default). The problems is that in certain configurations, where the socket is a unix domain socket (ex. with gunicorn), transport.get_extra_info("sockname") and "peername" will return a string with the unix domain socket. https://github.com/encode/uvicorn/blob/master/uvicorn/protocols/http/httptools_impl.py#L143-L144 This will break any apps correctly assuming scope["server"] and scope["client"] are two items.
0.0
[ "tests/protocols/test_utils.py::test_get_local_addr", "tests/protocols/test_utils.py::test_get_remote_addr" ]
[]
2018-10-16 14:03:46+00:00
2,165
encode__uvicorn-271
diff --git a/.travis.yml b/.travis.yml index 60f9f9b..43be62e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ python: - "3.7-dev" install: - - pip install -r requirements.txt + - pip install -U -r requirements.txt script: - scripts/test diff --git a/uvicorn/protocols/http/httptools_impl.py b/uvicorn/protocols/http/httptools_impl.py index 0b140b2..10af654 100644 --- a/uvicorn/protocols/http/httptools_impl.py +++ b/uvicorn/protocols/http/httptools_impl.py @@ -493,7 +493,10 @@ class RequestResponseCycle: if self.scope["method"] == "HEAD": self.expected_content_length = 0 elif self.chunked_encoding: - content = [b"%x\r\n" % len(body), body, b"\r\n"] + if body: + content = [b"%x\r\n" % len(body), body, b"\r\n"] + else: + content = [] if not more_body: content.append(b"0\r\n\r\n") self.transport.write(b"".join(content))
encode/uvicorn
f6f173c16887b4fceeec8ebf62808ea7a6111472
diff --git a/tests/protocols/test_http.py b/tests/protocols/test_http.py index c1cd9dc..f1b3ca1 100644 --- a/tests/protocols/test_http.py +++ b/tests/protocols/test_http.py @@ -240,6 +240,35 @@ def test_chunked_encoding(protocol_cls): assert not protocol.transport.is_closing() [email protected]("protocol_cls", [HttpToolsProtocol, H11Protocol]) +def test_chunked_encoding_empty_body(protocol_cls): + class App(): + def __init__(self, scope): + assert scope['type'] == 'http' + self.scope = scope + + async def __call__(self, receive, send): + await send({ + 'type': 'http.response.start', + 'status': 200, + 'headers': [ + [b'content-type', b'text/plain'], + ], + }) + await send({ + 'type': 'http.response.body', + 'body': b'', + }) + + protocol = get_connected_protocol(App, protocol_cls) + protocol.data_received(SIMPLE_GET_REQUEST) + protocol.loop.run_one() + assert b"HTTP/1.1 200 OK" in protocol.transport.buffer + print(protocol.transport.buffer) + assert protocol.transport.buffer.count(b'0\r\n\r\n') == 1 + assert not protocol.transport.is_closing() + + @pytest.mark.parametrize("protocol_cls", [HttpToolsProtocol, H11Protocol]) def test_pipelined_requests(protocol_cls): def app(scope):
Extra chunk when body is empty Using the example from the Readme, but returning an empty body: ```python class App(): def __init__(self, scope): assert scope['type'] == 'http' self.scope = scope async def __call__(self, receive, send): await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ], }) await send({ 'type': 'http.response.body', 'body': b'', # <- This is the only change from the example }) ``` Running: ```bash uvicorn app:App ``` Curl says: ```bash > curl http://127.0.0.1:8000 -v * Rebuilt URL to: http://127.0.0.1:8000/ * Trying 127.0.0.1... * Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0) > GET / HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: curl/7.47.0 > Accept: */* > < HTTP/1.1 200 OK < server: uvicorn < date: Thu, 17 Jan 2019 15:11:08 GMT < content-type: text/plain < transfer-encoding: chunked < * Leftovers after chunking: 5 bytes * Connection #0 to host 127.0.0.1 left intact ``` It sounds like those 5 bytes shouldn't be there. I think it's sending an extra chunk: there should be only 1 chunk with size 0. Maybe it's easier to see with telnet: ```bash > telnet 127.0.0.1 8000 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. GET / HTTP/1.1 HTTP/1.1 200 OK server: uvicorn date: Thu, 17 Jan 2019 15:13:32 GMT content-type: text/plain transfer-encoding: chunked 0 0 ``` I noticed it because it seems to break aiohttp's client. Any other UA seems to be happy with it. Any status code is affected too, so 301/302 redirects are "always" affected for example.
0.0
[ "tests/protocols/test_http.py::test_chunked_encoding_empty_body[HttpToolsProtocol]" ]
[ "tests/protocols/test_http.py::test_get_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_get_request[H11Protocol]", "tests/protocols/test_http.py::test_head_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_head_request[H11Protocol]", "tests/protocols/test_http.py::test_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_post_request[H11Protocol]", "tests/protocols/test_http.py::test_keepalive[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive[H11Protocol]", "tests/protocols/test_http.py::test_keepalive_timeout[HttpToolsProtocol]", "tests/protocols/test_http.py::test_keepalive_timeout[H11Protocol]", "tests/protocols/test_http.py::test_close[HttpToolsProtocol]", "tests/protocols/test_http.py::test_close[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding[HttpToolsProtocol]", "tests/protocols/test_http.py::test_chunked_encoding[H11Protocol]", "tests/protocols/test_http.py::test_chunked_encoding_empty_body[H11Protocol]", "tests/protocols/test_http.py::test_pipelined_requests[HttpToolsProtocol]", "tests/protocols/test_http.py::test_pipelined_requests[H11Protocol]", "tests/protocols/test_http.py::test_undersized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_undersized_request[H11Protocol]", "tests/protocols/test_http.py::test_oversized_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_oversized_request[H11Protocol]", "tests/protocols/test_http.py::test_large_post_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_large_post_request[H11Protocol]", "tests/protocols/test_http.py::test_invalid_http[HttpToolsProtocol]", "tests/protocols/test_http.py::test_invalid_http[H11Protocol]", "tests/protocols/test_http.py::test_app_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_exception[H11Protocol]", "tests/protocols/test_http.py::test_app_init_exception[HttpToolsProtocol]", "tests/protocols/test_http.py::test_app_init_exception[H11Protocol]", "tests/protocols/test_http.py::test_exception_during_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_exception_during_response[H11Protocol]", "tests/protocols/test_http.py::test_no_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_no_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_partial_response_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_partial_response_returned[H11Protocol]", "tests/protocols/test_http.py::test_duplicate_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_duplicate_start_message[H11Protocol]", "tests/protocols/test_http.py::test_missing_start_message[HttpToolsProtocol]", "tests/protocols/test_http.py::test_missing_start_message[H11Protocol]", "tests/protocols/test_http.py::test_message_after_body_complete[HttpToolsProtocol]", "tests/protocols/test_http.py::test_message_after_body_complete[H11Protocol]", "tests/protocols/test_http.py::test_value_returned[HttpToolsProtocol]", "tests/protocols/test_http.py::test_value_returned[H11Protocol]", "tests/protocols/test_http.py::test_early_disconnect[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_disconnect[H11Protocol]", "tests/protocols/test_http.py::test_early_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_early_response[H11Protocol]", "tests/protocols/test_http.py::test_read_after_response[HttpToolsProtocol]", "tests/protocols/test_http.py::test_read_after_response[H11Protocol]", "tests/protocols/test_http.py::test_http10_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_http10_request[H11Protocol]", "tests/protocols/test_http.py::test_root_path[HttpToolsProtocol]", "tests/protocols/test_http.py::test_root_path[H11Protocol]", "tests/protocols/test_http.py::test_max_concurrency[HttpToolsProtocol]", "tests/protocols/test_http.py::test_max_concurrency[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_request[H11Protocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[HttpToolsProtocol]", "tests/protocols/test_http.py::test_shutdown_during_idle[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_sent_when_body_consumed[H11Protocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[HttpToolsProtocol]", "tests/protocols/test_http.py::test_100_continue_not_sent_when_body_not_consumed[H11Protocol]", "tests/protocols/test_http.py::test_unsupported_upgrade_request[HttpToolsProtocol]", "tests/protocols/test_http.py::test_unsupported_upgrade_request[H11Protocol]" ]
2019-01-18 10:26:23+00:00
2,166
encode__uvicorn-646
diff --git a/CHANGELOG.md b/CHANGELOG.md index 15ffc8d..67020e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased * Use `watchgod`, if installed, for watching code changes. +* Reload application when any files in watched directories change, not just `.py` files. ## 0.11.3 diff --git a/uvicorn/supervisors/statreload.py b/uvicorn/supervisors/statreload.py index 3209c2c..03c96be 100644 --- a/uvicorn/supervisors/statreload.py +++ b/uvicorn/supervisors/statreload.py @@ -14,7 +14,7 @@ class StatReload(BaseReload): self.mtimes = {} def should_restart(self): - for filename in self.iter_py_files(): + for filename in self.iter_files(): try: mtime = os.path.getmtime(filename) except OSError: # pragma: nocover @@ -33,9 +33,9 @@ class StatReload(BaseReload): return True return False - def iter_py_files(self): + def iter_files(self): for reload_dir in self.config.reload_dirs: for subdir, dirs, files in os.walk(reload_dir): for file in files: - if file.endswith(".py"): + if not file.startswith("."): yield subdir + os.sep + file
encode/uvicorn
7e55554a9f32a127ea3511fa2f55d1b47b66029d
diff --git a/tests/supervisors/__init__.py b/tests/supervisors/__init__.py new file mode 100644 index 0000000..2def547 --- /dev/null +++ b/tests/supervisors/__init__.py @@ -0,0 +1,5 @@ +WATCHED_FILES = ( + "example.py", + "example.html", + "example.graphql", +) diff --git a/tests/supervisors/test_statreload.py b/tests/supervisors/test_statreload.py index 891a4fc..49a5ba3 100644 --- a/tests/supervisors/test_statreload.py +++ b/tests/supervisors/test_statreload.py @@ -3,9 +3,13 @@ import signal import time from pathlib import Path +import pytest + from uvicorn.config import Config from uvicorn.supervisors.statreload import StatReload +from . import WATCHED_FILES + def run(sockets): pass @@ -24,8 +28,9 @@ def test_statreload(): reloader.run() -def test_should_reload(tmpdir): - update_file = Path(os.path.join(str(tmpdir), "example.py")) [email protected]("filename", WATCHED_FILES) +def test_should_reload_when_watched_file_is_changed(tmpdir, filename): + update_file = Path(tmpdir) / filename update_file.touch() working_dir = os.getcwd() @@ -45,3 +50,26 @@ def test_should_reload(tmpdir): reloader.shutdown() finally: os.chdir(working_dir) + + +def test_should_not_reload_when_dot_file_is_changed(tmpdir): + update_file = Path(tmpdir) / ".dotted" + update_file.touch() + + working_dir = os.getcwd() + os.chdir(str(tmpdir)) + try: + config = Config(app=None, reload=True) + reloader = StatReload(config, target=run, sockets=[]) + reloader.signal_handler(sig=signal.SIGINT, frame=None) + reloader.startup() + + assert not reloader.should_restart() + time.sleep(0.1) + update_file.touch() + assert not reloader.should_restart() + + reloader.restart() + reloader.shutdown() + finally: + os.chdir(working_dir) diff --git a/tests/supervisors/test_watchgodreload.py b/tests/supervisors/test_watchgodreload.py index f8bc774..4bba1c2 100644 --- a/tests/supervisors/test_watchgodreload.py +++ b/tests/supervisors/test_watchgodreload.py @@ -3,9 +3,13 @@ import signal import time from pathlib import Path +import pytest + from uvicorn.config import Config from uvicorn.supervisors.watchgodreload import WatchGodReload +from . import WATCHED_FILES + def run(sockets): pass @@ -18,9 +22,9 @@ def test_watchgodreload(certfile_and_keyfile): reloader.run() -def test_should_reload_when_python_file_is_changed(tmpdir): - file = "example.py" - update_file = Path(os.path.join(str(tmpdir), file)) [email protected]("filename", WATCHED_FILES) +def test_should_reload_when_file_is_changed(tmpdir, filename): + update_file = Path(tmpdir) / filename update_file.touch() working_dir = os.getcwd() @@ -43,8 +47,7 @@ def test_should_reload_when_python_file_is_changed(tmpdir): def test_should_not_reload_when_dot_file_is_changed(tmpdir): - file = ".dotted" - update_file = Path(os.path.join(str(tmpdir), file)) + update_file = Path(tmpdir) / ".dotted" update_file.touch() working_dir = os.getcwd()
Add support for --reload to monitor additional file types. The "reload" process currently only monitors ".py" files in various directories. I have a changes that will pass in a list of additional "reload_suffixes" that the process will monitor. This allows the service to monitor data files in addition to code files. Any feedback on whether this is useful to others?
0.0
[ "tests/supervisors/test_statreload.py::test_should_reload_when_watched_file_is_changed[example.html]", "tests/supervisors/test_statreload.py::test_should_reload_when_watched_file_is_changed[example.graphql]" ]
[ "tests/supervisors/test_statreload.py::test_statreload", "tests/supervisors/test_statreload.py::test_should_reload_when_watched_file_is_changed[example.py]", "tests/supervisors/test_statreload.py::test_should_not_reload_when_dot_file_is_changed", "tests/supervisors/test_watchgodreload.py::test_watchgodreload", "tests/supervisors/test_watchgodreload.py::test_should_reload_when_file_is_changed[example.py]", "tests/supervisors/test_watchgodreload.py::test_should_reload_when_file_is_changed[example.html]", "tests/supervisors/test_watchgodreload.py::test_should_reload_when_file_is_changed[example.graphql]", "tests/supervisors/test_watchgodreload.py::test_should_not_reload_when_dot_file_is_changed" ]
2020-04-21 19:40:50+00:00
2,167
enowars__enochecker-79
diff --git a/src/enochecker/enochecker.py b/src/enochecker/enochecker.py index 831cb5b..fd98452 100644 --- a/src/enochecker/enochecker.py +++ b/src/enochecker/enochecker.py @@ -395,9 +395,6 @@ class BaseChecker(metaclass=_CheckerMeta): 1, ) - # def __format_internal_db_entry(name): - # return f"__Checker-Internals:{name}__" - # ---- Basic checker functionality ---- # def _run_method(self, method: Optional[str] = None) -> Optional[Result]: @@ -413,22 +410,6 @@ class BaseChecker(metaclass=_CheckerMeta): "Method {} not supported! Supported: {}".format(method, CHECKER_METHODS) ) - # handle the cases where the original putflag/putnoise wasn't successful - if method == "getflag": - key = f"__Checker-internals-RESULT:putflag,{self.flag_round},{self.flag_idx}__" - if key not in self.team_db or self.team_db[key] != "OK": - self.info( - f"original putflag did not return successfully -- ignoring getflag for flag_round:{self.flag_round}, index: {self.flag_idx}" - ) - return Result.OK - elif method == "getnoise": - key = f"__Checker-internals-RESULT:putnoise,{self.flag_round},{self.flag_idx}__" - if key not in self.team_db or self.team_db[key] != "OK": - self.info( - f"original putnoise did not return successfully -- ignoring getnoise for flag_round:{self.flag_round}, index: {self.flag_idx}" - ) - return Result.OK - return getattr(self, snake_caseify(method))() def run(self, method: Optional[str] = None) -> CheckerResult: @@ -455,17 +436,16 @@ class BaseChecker(metaclass=_CheckerMeta): # Better wrap this, in case somebody returns raw ints (?) ret = Result(ret) + if ret != Result.OK: + warnings.warn( + "Returning a non-ok status code is not recommended and will be removed in the future. Raise an Exception with additional text instead.", + DeprecationWarning, + ) self.info("Checker [{}] resulted in {}".format(self.method, ret.name)) - self.team_db[ - f"__Checker-internals-RESULT:{str(method)},{self.flag_round},{self.flag_idx}__" - ] = ret.name return CheckerResult(ret) # Returned Normally self.info("Checker [{}] executed successfully!".format(self.method)) - self.team_db[ - f"__Checker-internals-RESULT:{str(method)},{self.flag_round},{self.flag_idx}__" - ] = "OK" return CheckerResult(Result.OK) except EnoException as eno:
enowars/enochecker
e1ddd2c15096d22dd76321086ec7fd8687529d54
diff --git a/tests/test_run_method.py b/tests/test_run_method.py index d059e30..047b3df 100644 --- a/tests/test_run_method.py +++ b/tests/test_run_method.py @@ -87,54 +87,21 @@ def test_run_return_status(method, result, checker_cls): def meth(self): return result - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) - res = c.run() + with pytest.warns( + None + ): # ignore warnings caused by the deprecation of returning Results + res = c.run() assert isinstance(res, CheckerResult) assert res.result == result [email protected]("method", ["getflag", "getnoise"]) -def test_run_get_original_run_failed(method, checker_cls): - def meth(self): - assert False # this function should never be called - - setattr(checker_cls, method, meth) - c = checker_cls(method) - res = c.run() - assert isinstance(res, CheckerResult) - assert res.result == Result.OK - - @pytest.mark.parametrize("method", CHECKER_METHODS) def test_raise_broken_service_exception(method, checker_cls): def meth(self): raise BrokenServiceException("msg123") - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) res = c.run() @@ -148,18 +115,6 @@ def test_raise_offline_exception(method, checker_cls): def meth(self): raise OfflineException("msg123") - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) res = c.run() @@ -173,18 +128,6 @@ def test_raise_unhandled_exception(method, checker_cls): def meth(self): raise Exception("msg123") - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) res = c.run() @@ -200,18 +143,6 @@ def test_invalid_return(method, checker_cls): def meth(self): return "lolthisisinvalid" - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) res = c.run() @@ -236,18 +167,6 @@ def test_requests_mumble(method, exc, checker_cls): def meth(self): raise exc() - def ok(self): - return Result.OK - - if method == "getflag": - setattr(checker_cls, "putflag", ok) - c = checker_cls("putflag") - c.run() - elif method == "getnoise": - setattr(checker_cls, "putnoise", ok) - c = checker_cls("putnoise") - c.run() - setattr(checker_cls, method, meth) c = checker_cls(method) res = c.run() @@ -275,6 +194,21 @@ def test_offline_exceptions(method, exc, checker_cls): def meth(self): raise exc() + setattr(checker_cls, method, meth) + c = checker_cls(method) + res = c.run() + assert isinstance(res, CheckerResult) + assert res.result == Result.OFFLINE + assert res.message + + [email protected]( + "method", CHECKER_METHODS, +) +def test_no_warn_deprecated_return_ok(method, checker_cls): + def meth(self): + return Result.OK + def ok(self): return Result.OK @@ -289,7 +223,36 @@ def test_offline_exceptions(method, exc, checker_cls): setattr(checker_cls, method, meth) c = checker_cls(method) - res = c.run() + with pytest.warns(None) as record: + res = c.run() assert isinstance(res, CheckerResult) - assert res.result == Result.OFFLINE - assert res.message + assert res.result == Result.OK + assert len(record) == 0 + + [email protected]( + "method, ret", + product(CHECKER_METHODS, [Result.MUMBLE, Result.OFFLINE, Result.INTERNAL_ERROR]), +) +def test_warn_deprecated_return_value(method, ret, checker_cls): + def meth(self): + return ret + + def ok(self): + return Result.OK + + if method == "getflag": + setattr(checker_cls, "putflag", ok) + c = checker_cls("putflag") + c.run() + elif method == "getnoise": + setattr(checker_cls, "putnoise", ok) + c = checker_cls("putnoise") + c.run() + + setattr(checker_cls, method, meth) + c = checker_cls(method) + with pytest.deprecated_call(): + res = c.run() + assert isinstance(res, CheckerResult) + assert res.result == ret
Do not return OK when previous putflag/putnoise wasn't successful See https://github.com/enowars/enochecker/blob/master/src/enochecker/enochecker.py#L416
0.0
[ "tests/test_run_method.py::test_raise_broken_service_exception[getflag]", "tests/test_run_method.py::test_raise_broken_service_exception[getnoise]", "tests/test_run_method.py::test_raise_offline_exception[getflag]", "tests/test_run_method.py::test_raise_offline_exception[getnoise]", "tests/test_run_method.py::test_raise_unhandled_exception[getflag]", "tests/test_run_method.py::test_raise_unhandled_exception[getnoise]", "tests/test_run_method.py::test_invalid_return[getflag]", "tests/test_run_method.py::test_invalid_return[getnoise]", "tests/test_run_method.py::test_requests_mumble[getflag-HTTPError]", "tests/test_run_method.py::test_requests_mumble[getflag-EOFError]", "tests/test_run_method.py::test_requests_mumble[getnoise-HTTPError]", "tests/test_run_method.py::test_requests_mumble[getnoise-EOFError]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[getflag-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[getflag-timeout]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[getflag-OSError]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[getnoise-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-timeout]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[getnoise-OSError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionAbortedError]", "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.INTERNAL_ERROR]" ]
[ "tests/test_run_method.py::test_run_return_nothing[putflag]", "tests/test_run_method.py::test_run_return_nothing[getflag]", "tests/test_run_method.py::test_run_return_nothing[putnoise]", "tests/test_run_method.py::test_run_return_nothing[getnoise]", "tests/test_run_method.py::test_run_return_nothing[havoc]", "tests/test_run_method.py::test_run_return_nothing[exploit]", "tests/test_run_method.py::test_raise_broken_service_exception[putflag]", "tests/test_run_method.py::test_raise_broken_service_exception[putnoise]", "tests/test_run_method.py::test_raise_broken_service_exception[havoc]", "tests/test_run_method.py::test_raise_broken_service_exception[exploit]", "tests/test_run_method.py::test_raise_offline_exception[putflag]", "tests/test_run_method.py::test_raise_offline_exception[putnoise]", "tests/test_run_method.py::test_raise_offline_exception[havoc]", "tests/test_run_method.py::test_raise_offline_exception[exploit]", "tests/test_run_method.py::test_raise_unhandled_exception[putflag]", "tests/test_run_method.py::test_raise_unhandled_exception[putnoise]", "tests/test_run_method.py::test_raise_unhandled_exception[havoc]", "tests/test_run_method.py::test_raise_unhandled_exception[exploit]", "tests/test_run_method.py::test_invalid_return[putflag]", "tests/test_run_method.py::test_invalid_return[putnoise]", "tests/test_run_method.py::test_invalid_return[havoc]", "tests/test_run_method.py::test_invalid_return[exploit]", "tests/test_run_method.py::test_run_invalid_method", "tests/test_run_method.py::test_requests_mumble[putflag-HTTPError]", "tests/test_run_method.py::test_requests_mumble[putflag-EOFError]", "tests/test_run_method.py::test_requests_mumble[putnoise-HTTPError]", "tests/test_run_method.py::test_requests_mumble[putnoise-EOFError]", "tests/test_run_method.py::test_requests_mumble[havoc-HTTPError]", "tests/test_run_method.py::test_requests_mumble[havoc-EOFError]", "tests/test_run_method.py::test_requests_mumble[exploit-HTTPError]", "tests/test_run_method.py::test_requests_mumble[exploit-EOFError]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[putflag-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[putflag-timeout]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[putflag-OSError]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[putnoise-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-timeout]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[putnoise-OSError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[havoc-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[havoc-timeout]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[havoc-OSError]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[exploit-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[exploit-timeout]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[exploit-OSError]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionAbortedError]" ]
2020-07-22 16:16:47+00:00
2,168
enowars__enochecker-80
diff --git a/src/enochecker/enochecker.py b/src/enochecker/enochecker.py index 831cb5b..0e0e4ca 100644 --- a/src/enochecker/enochecker.py +++ b/src/enochecker/enochecker.py @@ -455,6 +455,11 @@ class BaseChecker(metaclass=_CheckerMeta): # Better wrap this, in case somebody returns raw ints (?) ret = Result(ret) + if ret != Result.OK: + warnings.warn( + "Returning a non-ok status code is not recommended and will be removed in the future. Raise an Exception with additional text instead.", + DeprecationWarning, + ) self.info("Checker [{}] resulted in {}".format(self.method, ret.name)) self.team_db[ f"__Checker-internals-RESULT:{str(method)},{self.flag_round},{self.flag_idx}__"
enowars/enochecker
e1ddd2c15096d22dd76321086ec7fd8687529d54
diff --git a/tests/test_run_method.py b/tests/test_run_method.py index d059e30..ecaa6af 100644 --- a/tests/test_run_method.py +++ b/tests/test_run_method.py @@ -101,7 +101,10 @@ def test_run_return_status(method, result, checker_cls): setattr(checker_cls, method, meth) c = checker_cls(method) - res = c.run() + with pytest.warns( + None + ): # ignore warnings caused by the deprecation of returning Results + res = c.run() assert isinstance(res, CheckerResult) assert res.result == result @@ -293,3 +296,59 @@ def test_offline_exceptions(method, exc, checker_cls): assert isinstance(res, CheckerResult) assert res.result == Result.OFFLINE assert res.message + + [email protected]( + "method", CHECKER_METHODS, +) +def test_no_warn_deprecated_return_ok(method, checker_cls): + def meth(self): + return Result.OK + + def ok(self): + return Result.OK + + if method == "getflag": + setattr(checker_cls, "putflag", ok) + c = checker_cls("putflag") + c.run() + elif method == "getnoise": + setattr(checker_cls, "putnoise", ok) + c = checker_cls("putnoise") + c.run() + + setattr(checker_cls, method, meth) + c = checker_cls(method) + with pytest.warns(None) as record: + res = c.run() + assert isinstance(res, CheckerResult) + assert res.result == Result.OK + assert len(record) == 0 + + [email protected]( + "method, ret", + product(CHECKER_METHODS, [Result.MUMBLE, Result.OFFLINE, Result.INTERNAL_ERROR]), +) +def test_warn_deprecated_return_value(method, ret, checker_cls): + def meth(self): + return ret + + def ok(self): + return Result.OK + + if method == "getflag": + setattr(checker_cls, "putflag", ok) + c = checker_cls("putflag") + c.run() + elif method == "getnoise": + setattr(checker_cls, "putnoise", ok) + c = checker_cls("putnoise") + c.run() + + setattr(checker_cls, method, meth) + c = checker_cls(method) + with pytest.deprecated_call(): + res = c.run() + assert isinstance(res, CheckerResult) + assert res.result == ret
Show warning when returning error status without accompanying message As mentioned in https://github.com/enowars/enochecker/pull/55 while returning Result.MUMBLE or Result.OFFLINE is supported it does not include details which would be necessary for e.g. https://github.com/enowars/enowars4-scoreboard/issues/2 The preferred and documented way should be using Exceptions instead
0.0
[ "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putflag-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getflag-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[putnoise-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[getnoise-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[havoc-Result.INTERNAL_ERROR]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.MUMBLE]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.OFFLINE]", "tests/test_run_method.py::test_warn_deprecated_return_value[exploit-Result.INTERNAL_ERROR]" ]
[ "tests/test_run_method.py::test_run_return_nothing[putflag]", "tests/test_run_method.py::test_run_return_nothing[getflag]", "tests/test_run_method.py::test_run_return_nothing[putnoise]", "tests/test_run_method.py::test_run_return_nothing[getnoise]", "tests/test_run_method.py::test_run_return_nothing[havoc]", "tests/test_run_method.py::test_run_return_nothing[exploit]", "tests/test_run_method.py::test_run_get_original_run_failed[getflag]", "tests/test_run_method.py::test_run_get_original_run_failed[getnoise]", "tests/test_run_method.py::test_raise_broken_service_exception[putflag]", "tests/test_run_method.py::test_raise_broken_service_exception[getflag]", "tests/test_run_method.py::test_raise_broken_service_exception[putnoise]", "tests/test_run_method.py::test_raise_broken_service_exception[getnoise]", "tests/test_run_method.py::test_raise_broken_service_exception[havoc]", "tests/test_run_method.py::test_raise_broken_service_exception[exploit]", "tests/test_run_method.py::test_raise_offline_exception[putflag]", "tests/test_run_method.py::test_raise_offline_exception[getflag]", "tests/test_run_method.py::test_raise_offline_exception[putnoise]", "tests/test_run_method.py::test_raise_offline_exception[getnoise]", "tests/test_run_method.py::test_raise_offline_exception[havoc]", "tests/test_run_method.py::test_raise_offline_exception[exploit]", "tests/test_run_method.py::test_raise_unhandled_exception[putflag]", "tests/test_run_method.py::test_raise_unhandled_exception[getflag]", "tests/test_run_method.py::test_raise_unhandled_exception[putnoise]", "tests/test_run_method.py::test_raise_unhandled_exception[getnoise]", "tests/test_run_method.py::test_raise_unhandled_exception[havoc]", "tests/test_run_method.py::test_raise_unhandled_exception[exploit]", "tests/test_run_method.py::test_invalid_return[putflag]", "tests/test_run_method.py::test_invalid_return[getflag]", "tests/test_run_method.py::test_invalid_return[putnoise]", "tests/test_run_method.py::test_invalid_return[getnoise]", "tests/test_run_method.py::test_invalid_return[havoc]", "tests/test_run_method.py::test_invalid_return[exploit]", "tests/test_run_method.py::test_run_invalid_method", "tests/test_run_method.py::test_requests_mumble[putflag-HTTPError]", "tests/test_run_method.py::test_requests_mumble[putflag-EOFError]", "tests/test_run_method.py::test_requests_mumble[getflag-HTTPError]", "tests/test_run_method.py::test_requests_mumble[getflag-EOFError]", "tests/test_run_method.py::test_requests_mumble[putnoise-HTTPError]", "tests/test_run_method.py::test_requests_mumble[putnoise-EOFError]", "tests/test_run_method.py::test_requests_mumble[getnoise-HTTPError]", "tests/test_run_method.py::test_requests_mumble[getnoise-EOFError]", "tests/test_run_method.py::test_requests_mumble[havoc-HTTPError]", "tests/test_run_method.py::test_requests_mumble[havoc-EOFError]", "tests/test_run_method.py::test_requests_mumble[exploit-HTTPError]", "tests/test_run_method.py::test_requests_mumble[exploit-EOFError]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[putflag-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[putflag-timeout]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[putflag-OSError]", "tests/test_run_method.py::test_offline_exceptions[putflag-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[getflag-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[getflag-timeout]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[getflag-OSError]", "tests/test_run_method.py::test_offline_exceptions[getflag-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[putnoise-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-timeout]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[putnoise-OSError]", "tests/test_run_method.py::test_offline_exceptions[putnoise-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[getnoise-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-timeout]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[getnoise-OSError]", "tests/test_run_method.py::test_offline_exceptions[getnoise-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[havoc-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[havoc-timeout]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[havoc-OSError]", "tests/test_run_method.py::test_offline_exceptions[havoc-ConnectionAbortedError]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionError0]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectTimeout]", "tests/test_run_method.py::test_offline_exceptions[exploit-TimeoutError]", "tests/test_run_method.py::test_offline_exceptions[exploit-timeout]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionError1]", "tests/test_run_method.py::test_offline_exceptions[exploit-OSError]", "tests/test_run_method.py::test_offline_exceptions[exploit-ConnectionAbortedError]" ]
2020-07-22 16:38:27+00:00
2,169
enowars__enochecker-82
diff --git a/src/enochecker/enochecker.py b/src/enochecker/enochecker.py index fc8dbbc..976688e 100644 --- a/src/enochecker/enochecker.py +++ b/src/enochecker/enochecker.py @@ -287,7 +287,6 @@ class BaseChecker(metaclass=_CheckerMeta): ) round_id = round_id or round self.round: Optional[int] = round_id - self.current_round: Optional[int] = round_id self.flag_round: Optional[int] = flag_round self.round_length: int = round_length self.flag: Optional[str] = flag @@ -359,6 +358,18 @@ class BaseChecker(metaclass=_CheckerMeta): self.error: Callable[..., None] = self.logger.error self.critical: Callable[..., None] = self.logger.critical + @property + def current_round(self) -> Optional[int]: + """ + Deprecated! Only for backwards compatibility! Use self.round instead. + + :return: current round + """ + warnings.warn( + "current_round is deprecated, use round instead", DeprecationWarning + ) + return self.round + @property def noise(self) -> Optional[str]: """
enowars/enochecker
575aecd3d737f50380bd14b220f02248c03ecd44
diff --git a/tests/test_enochecker.py b/tests/test_enochecker.py index 948b888..91009c1 100644 --- a/tests/test_enochecker.py +++ b/tests/test_enochecker.py @@ -267,6 +267,13 @@ def test_checker(): assert CheckerExampleImpl(method="havoc").run().result == Result.OFFLINE + c = CheckerExampleImpl(method="putflag", round_id=1337) + with pytest.deprecated_call(): + assert c.current_round == 1337 + c.round = 15 + with pytest.deprecated_call(): + assert c.current_round == c.round + @temp_storage_dir def test_useragents():
Deprecate self.round or self.current_round I'm not sure which one to keep, but I would replace the other one with: ``` @property def current_round(self): raise DeprecationWarning(...) return self.round ```
0.0
[ "tests/test_enochecker.py::test_checker" ]
[ "tests/test_enochecker.py::test_assert_equals", "tests/test_enochecker.py::test_conversions", "tests/test_enochecker.py::test_assert_in", "tests/test_enochecker.py::test_snake_caseify", "tests/test_enochecker.py::test_dict", "tests/test_enochecker.py::test_args", "tests/test_enochecker.py::test_checker_connections", "tests/test_enochecker.py::test_useragents", "tests/test_enochecker.py::test_exceptionHandling" ]
2020-07-22 17:51:19+00:00
2,170
enthought__okonomiyaki-358
diff --git a/.travis.yml b/.travis.yml index 9442174..ad8e40b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,7 +20,8 @@ cache: branches: only: - master - - maint/* + - /^maintenance\/.*$/ + - /^v\d+\.\d+\.\d+.*$/ install: - pip list diff --git a/okonomiyaki/runtimes/runtime_info.py b/okonomiyaki/runtimes/runtime_info.py index 5b20cdf..eb9a8e5 100644 --- a/okonomiyaki/runtimes/runtime_info.py +++ b/okonomiyaki/runtimes/runtime_info.py @@ -110,13 +110,16 @@ class IRuntimeInfoV1(IRuntimeInfo): variables = _compute_variables(metadata, prefix, name) - executable = substitute_variable(metadata.executable, variables) + executable = substitute_variable( + metadata.executable, variables, template='curly_braces_only' + ) paths = tuple( - substitute_variable(path, variables) for path in metadata.paths + substitute_variable(path, variables, template='curly_braces_only') + for path in metadata.paths ) post_install = tuple( - substitute_variable(part, variables) + substitute_variable(part, variables, template='curly_braces_only') for part in metadata.post_install ) @@ -157,9 +160,15 @@ class PythonRuntimeInfoV1(IRuntimeInfoV1): metadata, prefix, name ) variables = _compute_variables(metadata, prefix, name) - scriptsdir = substitute_variable(metadata.scriptsdir, variables) - site_packages = substitute_variable(metadata.site_packages, variables) - python_tag = substitute_variable(metadata.python_tag, variables) + scriptsdir = substitute_variable( + metadata.scriptsdir, variables, template='curly_braces_only' + ) + site_packages = substitute_variable( + metadata.site_packages, variables, template='curly_braces_only' + ) + python_tag = substitute_variable( + metadata.python_tag, variables, template='curly_braces_only' + ) return args + (scriptsdir, site_packages, python_tag) @@ -212,4 +221,6 @@ def _compute_variables(metadata, prefix, name): variables["prefix"] = prefix variables["name"] = name - return substitute_variables(variables, variables) + return substitute_variables( + variables, variables, template='curly_braces_only' + ) diff --git a/okonomiyaki/utils/misc.py b/okonomiyaki/utils/misc.py index bddffb1..b441357 100644 --- a/okonomiyaki/utils/misc.py +++ b/okonomiyaki/utils/misc.py @@ -1,5 +1,6 @@ import ast import contextlib +import re import shutil import string import tempfile @@ -64,14 +65,25 @@ def tempdir(): shutil.rmtree(d) -def substitute_variables(d, local_vars): - """Perform shell/Perl-style variable substitution. +def substitute_variables(d, local_vars, template='standard'): + """Perform repeated shell/Perl-style variable substitution to dict values - Every occurrence of '${name}' name is considered a variable, and variable - is substituted by the value found in the `local_vars' dictionary. Raise - ValueError for any variables not found in `local_vars'. + Every occurrence of '${name}' in the values of dict 'd' is considered a + variable, and the variable is substituted by the value found in the + 'local_vars' dictionary. A ValueError is raised for any variable not found + in 'local_vars'. This is applied repeatedly until all nested variables are + resolved. - '$' may be escaped by using '$$' + If the 'standard' template is used, $name will also be substituted. There + is a bug with escapes using the 'standard' template. This occurs because + substitution is applied repeatedly and after $$name is translated to $name, + variable substitution is performed on $name. + + With the 'curly_braces_only' template $name will not be substituted. Also + escapes using '$${name}' are ignored and not translated to '${name}'. This + allows the variable substitution to be applied repeatedly. The function + 'substitute_variable' should be applied to the data after this function + which does translate the escape '$${name}' to '${name}' by default. Parameters ---------- @@ -79,11 +91,18 @@ def substitute_variables(d, local_vars): (str: str) mapping, where each value will be substituted. local_vars: dict dict of variables + template: ('standard' | 'curly_braces_only') + whether to use 'standard' string.Template or RequireCurlyTemplate """ def _resolve(d): ret = {} for k, v in d.items(): - ret[k] = substitute_variable(v, local_vars) + # Ignoring the escape sequence with ignore_escape=True allows + # substitute_variable to be run repeatedly over the same data + # ignore_escape=True has no effect with the old 'standard' template + ret[k] = substitute_variable( + v, local_vars, template=template, ignore_escape=True + ) return ret ret = _resolve(d) @@ -93,5 +112,76 @@ def substitute_variables(d, local_vars): return ret -def substitute_variable(v, local_vars): - return string.Template(v).substitute(local_vars) +class RequireCurlyTemplate(string.Template): + """This class inheriting from Template requires curly braces. + A '$' without curly braces will not be substituted. + """ + delimiter = '$' + # named and escaped groups are always None + # This is because their patterns are a subset of the invalid group, + # i.e. the invalid group will always match first. + # According to the Python re documentation the "|" operator is never greedy, + # so the named and escaped groups will always be None. + ignore_escape_pattern_str = r""" + (?<!\$)\$(?: # Only match single dollar signs + {(?P<braced>[_a-z][_a-z0-9]*)} | # Delimiter and braced identifier + {(?P<invalid>[^}]*)} | # Other ill-formed delimiter expr + {(?P<named>)} | # named group is always None + {(?P<escaped>)} # escaped group is always None + ) + """ + ignore_escape_pattern = re.compile( + ignore_escape_pattern_str, re.IGNORECASE | re.VERBOSE + ) + pattern = r""" + \$(?: + (?P<escaped>\$)(?={[^}]*}) | # Extra delimiter followed by braces + {(?P<braced>[_a-z][_a-z0-9]*)} | # Delimiter and braced identifier + {(?P<invalid>[^}]*)} | # Other ill-formed delimiter expr + {(?P<named>)} # named group is always None + ) + """ + + def __init__(self, template, ignore_escape=False): + super(RequireCurlyTemplate, self).__init__(template) + if ignore_escape: + self.pattern = self.ignore_escape_pattern + + +def substitute_variable( + v, local_vars, template='standard', ignore_escape=False): + """Perform shell/Perl-style variable substitution to a string 'v' + + Every occurrence of '${name}' in the value of string 'v' is considered a + variable, and the variable is substituted by the value found in the + 'local_vars' dictionary. A ValueError is raised for any variable not found + in 'local_vars'. This is only applied once unlike 'substitute_variables', + so nested variables will not be resolved. + + If the 'standard' template is used, $name will also be substituted. + + Escapes using '$${name}' are translated to '${name}'. + + If the 'curly_braces_only' template is used and 'ignore_escape' is True, + escapes using '$${name}' will be ignored. + + Parameters + ---------- + v: string + string where each value will be substituted. + local_vars: dict + dict of variables + template: ('standard' | 'curly_braces_only') + whether to use 'standard' string.Template or RequireCurlyTemplate + ignore_escape: boolean + whether or not to ignore '$${name}' with RequireCurlyTemplate only + """ + if template == 'curly_braces_only': + template_substitute = RequireCurlyTemplate(v, ignore_escape).substitute + elif template == 'standard': + template_substitute = string.Template(v).substitute + else: + raise ValueError( + 'Template option must be "standard" or "curly_braces_only"' + ) + return template_substitute(local_vars)
enthought/okonomiyaki
5a755c35c254ec8a8b93d591b010d7255b957156
diff --git a/okonomiyaki/runtimes/tests/test_runtime_info.py b/okonomiyaki/runtimes/tests/test_runtime_info.py index 86ea23f..b074177 100644 --- a/okonomiyaki/runtimes/tests/test_runtime_info.py +++ b/okonomiyaki/runtimes/tests/test_runtime_info.py @@ -39,6 +39,30 @@ class TestPythonRuntimeInfoV1(unittest.TestCase): self.assertEqual(runtime_info.name, name) self.assertEqual(runtime_info.executable, r_executable) + def test_dollar_in_prefix(self): + # Given + name = u"test" + prefix = os.path.abspath(os.path.join(u"$foo", u"bar$")) + + if sys.platform == "win32": + path = PYTHON_CPYTHON_2_7_10_WIN_X86_64 + r_executable = os.path.join(prefix, "python.exe") + else: + path = PYTHON_CPYTHON_2_7_10_RH5_X86_64 + r_executable = os.path.join(prefix, "bin", "python") + + metadata = IRuntimeMetadata.factory_from_path(path) + + # When + runtime_info = IRuntimeInfo.factory_from_metadata( + metadata, prefix, name + ) + + # Then + self.assertEqual(runtime_info.prefix, prefix) + self.assertEqual(runtime_info.name, name) + self.assertEqual(runtime_info.executable, r_executable) + def test_json_round_trip(self): # Given path = PYTHON_CPYTHON_2_7_10_RH5_X86_64 diff --git a/okonomiyaki/utils/tests/test_misc.py b/okonomiyaki/utils/tests/test_misc.py index 305f2a5..8ba2ba6 100644 --- a/okonomiyaki/utils/tests/test_misc.py +++ b/okonomiyaki/utils/tests/test_misc.py @@ -2,7 +2,7 @@ import sys import textwrap from ...errors import OkonomiyakiError -from ..misc import parse_assignments, substitute_variables +from ..misc import parse_assignments, substitute_variables, substitute_variable from ..py3compat import StringIO if sys.version_info < (2, 7): @@ -46,10 +46,14 @@ class TestSubstitute(unittest.TestCase): } # When - rendered = substitute_variables(data, variables) + rendered_standard = substitute_variables(data, variables) + rendered_curly_only = substitute_variables( + data, variables, template='curly_braces_only' + ) # Then - self.assertEqual(rendered, r_data) + self.assertEqual(rendered_standard, r_data) + self.assertEqual(rendered_curly_only, r_data) def test_recursive(self): # Given @@ -69,8 +73,149 @@ class TestSubstitute(unittest.TestCase): } # When - variables = substitute_variables(variables, variables) - rendered = substitute_variables(data, variables) + variables_standard = substitute_variables(variables, variables) + variables_curly_only = substitute_variables( + variables, variables + ) + rendered_standard = substitute_variables(data, variables_standard) + rendered_curly_only = substitute_variables( + data, variables_curly_only, template='curly_braces_only' + ) + + # Then + self.assertEqual(rendered_standard, r_data) + self.assertEqual(rendered_curly_only, r_data) + + def test_escape(self): + # Given + data = { + "foo": "$${yolo}", + "bar": "$${foo}/bin", + } + + variables = { + "yolo": "/foo/bar", + } + variables.update(data) + + r_data = { + "foo": "$${yolo}", + "bar": "$${foo}/bin", + } + r_foo_ignore_escape = "$${yolo}" + r_foo_escape = "${yolo}" + + # When + variables = substitute_variables( + variables, variables, template="curly_braces_only" + ) + rendered = substitute_variables( + data, variables, template="curly_braces_only" + ) + render_foo_ignore_escape = substitute_variable( + data["foo"], variables, template="curly_braces_only", + ignore_escape=True + ) + render_foo_escape = substitute_variable( + data["foo"], variables, template="curly_braces_only" + ) # Then self.assertEqual(rendered, r_data) + self.assertEqual(render_foo_ignore_escape, r_foo_ignore_escape) + self.assertEqual(render_foo_escape, r_foo_escape) + + def test_without_curly_braces(self): + # Given + data = { + "foo": "$yolo", + "bar": "$foo/bin", + } + + variables = { + "yolo": "/foo/bar", + } + variables.update(data) + + r_data = { + "foo": "$yolo", + "bar": "$foo/bin", + } + + # When + variables = substitute_variables( + variables, variables, template="curly_braces_only" + ) + rendered = substitute_variables( + data, variables, template="curly_braces_only" + ) + + # Then + self.assertEqual(rendered, r_data) + + def test_empty_substitution(self): + # Given + # Empty variable name is invalid + data = { + "foo": "${}yolo", + "bar": "/bin", + } + + variables = { + "yolo": "/foo/bar", + } + variables.update(data) + + # When/Then + with self.assertRaises(ValueError): + variables = substitute_variables( + variables, variables, template="curly_braces_only" + ) + substitute_variables( + data, variables, template="curly_braces_only" + ) + + def test_invalid_substitution(self): + # Given + # idpattern = r'[_a-z][_a-z0-9]*' + # Characters not matching idpattern are invalid + data = { + "foo": "${yo-lo}", + "bar": "/bin", + } + + variables = { + "yo-lo": "/foo/bar", + } + variables.update(data) + + # When/Then + with self.assertRaises(ValueError): + variables = substitute_variables( + variables, variables, template="curly_braces_only" + ) + substitute_variables( + data, variables, template="curly_braces_only" + ) + + def test_key_error_substitution(self): + # Given + # Nonexistent variable name gives key error + data = { + "foo": "${nonexistent}yolo", + "bar": "/bin", + } + + variables = { + "yolo": "/foo/bar", + } + variables.update(data) + + # When/Then + with self.assertRaises(KeyError): + variables = substitute_variables( + variables, variables, template="curly_braces_only" + ) + substitute_variables( + data, variables, template="curly_braces_only" + )
Problem when setting up environment with User name beginning with $ A problem arises from the following sequence when setting up a runtime environment where the user name begins with $: https://github.com/enthought/okonomiyaki/blob/master/okonomiyaki/runtimes/runtime_info.py#L111 https://github.com/enthought/okonomiyaki/blob/master/okonomiyaki/runtimes/runtime_info.py#L204 https://github.com/enthought/okonomiyaki/blob/master/okonomiyaki/utils/misc.py#L67 A sample traceback is shown here: ``` 2018-03-29 14:25:01 ERROR 1156 Future-thread-1 [edm.utils.misc:154] All Installing runtime attempts failed 2018-03-29 14:25:01 ERROR 1156 Future-thread-1 [canopy.user_env.env_installer:207] Error installing runtime Traceback (most recent call last): File "build\bdist.win32\egg\canopy\user_env\env_installer.py", line 205, in do_install File "build\bdist.win32\egg\canopy_platform\runtimes_manager.py", line 375, in install_runtime_from_file File "build\bdist.win32\egg\canopy_platform\runtimes_manager.py", line 576, in _install_runtime File "build\bdist.win32\egg\canopy_platform\runtimes_manager.py", line 715, in _unpack_with_progress File "build\bdist.win32\egg\canopy_platform\edm_api.py", line 95, in wrapper File "build\bdist.win32\egg\canopy_platform\edm_api.py", line 338, in install_runtime File "build\bdist.win32\egg\edm\core\environments_manager.py", line 371, in install File "build\bdist.win32\egg\edm\runtimes\runtime_installer.py", line 282, in install File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 32, in factory_from_metadata return runtime_info_from_metadata(metadata, prefix, name) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 201, in runtime_info_from_metadata return klass._from_metadata(metadata, prefix, name) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 100, in _from_metadata return cls(*cls._from_metadata_impl(metadata, prefix, name)) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 157, in _from_metadata_impl metadata, prefix, name File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 111, in _from_metadata_impl variables = _compute_variables(metadata, prefix, name) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\runtimes\runtime_info.py", line 215, in _compute_variables return substitute_variables(variables, variables) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\utils\misc.py", line 89, in substitute_variables ret = _resolve(d) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\utils\misc.py", line 86, in _resolve ret[k] = substitute_variable(v, local_vars) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\Lib\site-packages\okonomiyaki\utils\misc.py", line 97, in substitute_variable return string.Template(v).substitute(local_vars) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\lib\string.py", line 176, in substitute return self.pattern.sub(convert, self.template) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-2.1.8.3709.win-x86\lib\string.py", line 166, in convert val = mapping[named] KeyError: u'xxxxxxxx ``` The KeyError is generated when the user name starts with $, for example $xxxxxxxx. The substitute_variable() function at https://github.com/enthought/okonomiyaki/blob/master/okonomiyaki/utils/misc.py#L96 uses ```string.Template().substitute()``` to perform Shell/Perl style variable substitution. In this case, a user name beginning with $ is treated as an environment variable and an attempt is made to substitute in the value, which then results in a KeyError since the user name is not present as an environment variable. A simple way to address this would be to use ```string.Template.safe_substitute()```. As shown here: https://gist.github.com/mgrady3/9bf677e4eb84c479095eca477b68f5ae However, it may be better to instead try and catch KeyErrors and perform some type of check to see where the substitution failed at. Insert some logic to allow paths with directories beginning with '$' to stay, but raise the error if there indeed should have been a substitution but this failed for some other reason.
0.0
[ "okonomiyaki/runtimes/tests/test_runtime_info.py::TestPythonRuntimeInfoV1::test_dollar_in_prefix", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_empty_substitution", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_escape", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_invalid_substitution", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_key_error_substitution", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_recursive", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_simple", "okonomiyaki/utils/tests/test_misc.py::TestSubstitute::test_without_curly_braces" ]
[ "okonomiyaki/runtimes/tests/test_runtime_info.py::TestPythonRuntimeInfoV1::test_json_round_trip", "okonomiyaki/runtimes/tests/test_runtime_info.py::TestPythonRuntimeInfoV1::test_simple", "okonomiyaki/runtimes/tests/test_runtime_info.py::TestJuliaRuntimeInfoV1::test_json_round_trip", "okonomiyaki/runtimes/tests/test_runtime_info.py::TestJuliaRuntimeInfoV1::test_simple", "okonomiyaki/utils/tests/test_misc.py::TestParseAssignments::test_parse_simple", "okonomiyaki/utils/tests/test_misc.py::TestParseAssignments::test_parse_simple_invalid_file" ]
2019-10-31 21:21:40+00:00
2,171
enthought__traits-futures-125
diff --git a/traits_futures/traits_executor.py b/traits_futures/traits_executor.py index 2cdb02d..04d3fd0 100644 --- a/traits_futures/traits_executor.py +++ b/traits_futures/traits_executor.py @@ -46,6 +46,20 @@ def _background_job_wrapper(background_job, sender): class TraitsExecutor(HasStrictTraits): """ Executor to initiate and manage background tasks. + + Parameters + ---------- + thread_pool : concurrent.futures.ThreadPoolExecutor, optional + If supplied, provides the underlying thread pool executor to use. In + this case, the creator of the TraitsExecutor is responsible for + shutting down the thread pool once it's no longer needed. If not + supplied, a new private thread pool will be created, and this object's + ``stop`` method will shut down that thread pool. + max_workers : int or None, optional + Maximum number of workers for the private thread pool. This parameter + is mutually exclusive with thread_pool. The default is ``None``, which + delegates the choice of number of workers to Python's + ``ThreadPoolExecutor``. """ #: Current state of this executor. state = ExecutorState @@ -58,14 +72,18 @@ class TraitsExecutor(HasStrictTraits): #: to dispose of related resources (like the thread pool). stopped = Property(Bool()) - def __init__(self, thread_pool=None, **traits): + def __init__(self, thread_pool=None, max_workers=None, **traits): super(TraitsExecutor, self).__init__(**traits) if thread_pool is None: self._thread_pool = concurrent.futures.ThreadPoolExecutor( - max_workers=4) + max_workers=max_workers) self._own_thread_pool = True else: + if max_workers is not None: + raise TypeError( + "at most one of 'thread_pool' and 'max_workers' " + "should be supplied") self._thread_pool = thread_pool self._own_thread_pool = False
enthought/traits-futures
90be7ad24df65405877602d35eb2c7e870457f6e
diff --git a/traits_futures/tests/test_traits_executor.py b/traits_futures/tests/test_traits_executor.py index 4a70743..1ad46d4 100644 --- a/traits_futures/tests/test_traits_executor.py +++ b/traits_futures/tests/test_traits_executor.py @@ -100,6 +100,17 @@ class TestTraitsExecutor(GuiTestAssistant, unittest.TestCase): del self.executor GuiTestAssistant.tearDown(self) + def test_max_workers(self): + executor = TraitsExecutor(max_workers=11) + self.assertEqual(executor._thread_pool._max_workers, 11) + executor.stop() + self.wait_until_stopped(executor) + + def test_max_workers_mutually_exclusive_with_thread_pool(self): + with self.temporary_thread_pool() as thread_pool: + with self.assertRaises(TypeError): + TraitsExecutor(thread_pool=thread_pool, max_workers=11) + def test_stop_method(self): executor = TraitsExecutor() listener = ExecutorListener(executor=executor)
Default number of workers in the `TraitsExecutor` should be configurable We have a hard-coded `max_workers=4` where the `TraitsExecutor` creates its underlying `concurrent.futures.ThreadPoolExecutor`. That's wrong! At the very least, that `4` should be a module-level constant, but it would be better to provide a way to create a `TraitsExecutor` that: - owns its underlying executor - allows the number of threads in that executor to be set in advance
0.0
[ "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_max_workers", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_max_workers_mutually_exclusive_with_thread_pool" ]
[ "traits_futures/tests/test_traits_executor.py::test_call", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_cant_submit_new_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_owned_thread_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once_no_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_shared_thread_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_states_consistent", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_cancels_running_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_raises_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_with_no_jobs", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_with_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stopped", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_call", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_iteration", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_progress" ]
2019-04-23 14:48:46+00:00
2,172
enthought__traits-futures-173
diff --git a/docs/source/guide/contexts.rst b/docs/source/guide/contexts.rst new file mode 100644 index 0000000..cac48a6 --- /dev/null +++ b/docs/source/guide/contexts.rst @@ -0,0 +1,59 @@ +.. + (C) Copyright 2018-2021 Enthought, Inc., Austin, TX + All rights reserved. + + This software is provided without warranty under the terms of the BSD + license included in LICENSE.txt and may be redistributed only under + the conditions described in the aforementioned license. The license + is also available online at http://www.enthought.com/licenses/BSD.txt + + Thanks for using Enthought open source! + +Contexts and multiprocessing +============================ + +By default, the |TraitsExecutor| submits its background tasks to a thread pool. +In some cases, for example in the case of multiple heavily CPU-bound background +tasks, it may be desirable to run the background tasks in separate processes +instead. For this to work, the Traits Futures code needs to know that it has to +work internally with multiprocessing-safe variants of the usual concurrency +primitives: events, queues, worker pools and the like. + +This can be achieved through use of a *context*, or more specifically, +an object implementing the |IParallelContext| interface. A context provides +the executor with a way of creating related and compatible +concurrency constructs. + +Traits Futures provides two different contexts: the |MultithreadingContext| +and the |MultiprocessingContext|. By default, the executor will use a +|MultithreadingContext|, but you can create and pass in your own context +instead. The context should be closed with the |close| method once it's +no longer needed. + +Here's an example ``main`` function that creates an executor that uses +a multiprocessing context:: + + def main(): + context = MultiprocessingContext() + traits_executor = TraitsExecutor(context=context) + try: + view = SquaringHelper(traits_executor=traits_executor) + view.configure_traits() + finally: + traits_executor.stop() + context.close() + +Here's a complete TraitsUI example that makes use of this. + +.. literalinclude:: examples/background_processes.py + + +.. + substitutions + + +.. |close| replace:: :meth:`~.IParallelContext.close` +.. |IParallelContext| replace:: :class:`~.IParallelContext` +.. |MultiprocessingContext| replace:: :class:`~.MultiprocessingContext` +.. |MultithreadingContext| replace:: :class:`~.MultithreadingContext` +.. |TraitsExecutor| replace:: :class:`~.TraitsExecutor` diff --git a/docs/source/guide/examples/background_processes.py b/docs/source/guide/examples/background_processes.py new file mode 100644 index 0000000..5fdc36a --- /dev/null +++ b/docs/source/guide/examples/background_processes.py @@ -0,0 +1,176 @@ +# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX +# All rights reserved. +# +# This software is provided without warranty under the terms of the BSD +# license included in LICENSE.txt and may be redistributed only under +# the conditions described in the aforementioned license. The license +# is also available online at http://www.enthought.com/licenses/BSD.txt +# +# Thanks for using Enthought open source! + +""" +Complete example showing how to use the MultiprocessingContext to execute +background jobs in separate processes instead of separate threads. + +The "jobs" in this case are slow, unreliable squaring operations. The +GUI allows multiple jobs to execute simultaneously, and shows the status +of each of the currently-running and completed jobs. + +Requires TraitsUI to run, in addition to the usual Traits Futures +dependencies. +""" + +import random +import time + +from traits.api import Button, Dict, Instance, List, Property, Range, Str +from traits_futures.api import ( + CallFuture, + CANCELLED, + CANCELLING, + COMPLETED, + EXECUTING, + FAILED, + MultiprocessingContext, + submit_call, + TraitsExecutor, + WAITING, +) +from traitsui.api import ( + Handler, + HGroup, + Item, + TabularAdapter, + TabularEditor, + UItem, + VGroup, + View, +) + + +def slow_square(n, timeout=5.0): + """ + Compute the square of an integer, slowly and unreliably. + + The input should be in the range 0-100. The larger + the input, the longer the expected time to complete the operation, + and the higher the likelihood of timeout. + """ + mean_time = (n + 5.0) / 5.0 + sleep_time = random.expovariate(1.0 / mean_time) + if sleep_time > timeout: + time.sleep(timeout) + raise RuntimeError("Calculation took too long.") + else: + time.sleep(sleep_time) + return n * n + + +class JobTabularAdapter(TabularAdapter): + columns = [ + ("Job State", "state"), + ] + + #: Row colors for the table. + colors = Dict( + { + CANCELLED: (255, 0, 0), + CANCELLING: (255, 128, 0), + EXECUTING: (128, 128, 255), + FAILED: (255, 192, 255), + COMPLETED: (128, 255, 128), + WAITING: (255, 255, 255), + } + ) + + #: Text to be displayed for the state column. + state_text = Property(Str()) + + def _get_bg_color(self): + return self.colors[self.item.state] + + def _get_state_text(self): + job = self.item + state = job.state + state_text = state.title() + if state == COMPLETED: + state_text += ": result={}".format(job.result) + elif state == FAILED: + state_text += ": {}".format(job.exception[1]) + return state_text + + +class SquaringHelper(Handler): + #: The Traits executor for the background jobs. + traits_executor = Instance(TraitsExecutor) + + #: List of the submitted jobs, for display purposes. + current_futures = List(Instance(CallFuture)) + + #: Start a new squaring operation. + square = Button() + + #: Cancel all currently executing jobs. + cancel_all = Button() + + #: Clear completed jobs from the list of current jobs. + clear_finished = Button() + + #: Value that we'll square. + input = Range(low=0, high=100) + + def _square_fired(self): + future = submit_call(self.traits_executor, slow_square, self.input) + self.current_futures.append(future) + + def _cancel_all_fired(self): + for future in self.current_futures: + if future.cancellable: + future.cancel() + + def _clear_finished_fired(self): + for future in list(self.current_futures): + if future.done: + self.current_futures.remove(future) + + def default_traits_view(self): + return View( + HGroup( + VGroup( + Item("input"), + UItem("square"), + UItem("cancel_all"), + UItem("clear_finished"), + ), + VGroup( + UItem( + "current_futures", + editor=TabularEditor( + adapter=JobTabularAdapter(), + auto_update=True, + ), + ), + ), + ), + width=1024, + height=768, + resizable=True, + ) + + +def main(): + """ + Demonstrate a GUI that hands off background tasks to a separate process. + """ + context = MultiprocessingContext() + traits_executor = TraitsExecutor(context=context) + try: + view = SquaringHelper(traits_executor=traits_executor) + view.configure_traits() + finally: + traits_executor.stop() + context.close() + + +if __name__ == "__main__": + main() diff --git a/docs/source/index.rst b/docs/source/index.rst index b7b913b..8e5e800 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -45,7 +45,6 @@ Limitations - By design, and unlike :mod:`concurrent.futures`, |traits_futures| requires the UI event loop to be running in order to process results. -- No multiprocessing support yet. Maybe one day. - Requires Python 3.6 or later. @@ -67,6 +66,7 @@ User Guide guide/intro.rst guide/cancel.rst + guide/contexts.rst guide/testing.rst guide/advanced.rst diff --git a/examples/slow_squares.py b/examples/slow_squares.py index 985ef70..44e0e59 100644 --- a/examples/slow_squares.py +++ b/examples/slow_squares.py @@ -11,7 +11,7 @@ import random import time -from traits.api import Button, Instance, List, Property, Range +from traits.api import Button, Dict, Instance, List, Property, Range, Str from traits_futures.api import ( CallFuture, CANCELLED, @@ -27,12 +27,12 @@ from traitsui.api import ( Handler, HGroup, Item, + TabularAdapter, TabularEditor, UItem, VGroup, View, ) -from traitsui.tabular_adapter import TabularAdapter def slow_square(n, timeout=5.0): @@ -59,17 +59,19 @@ class JobTabularAdapter(TabularAdapter): ] #: Row colors for the table. - colors = { - CANCELLED: (255, 0, 0), - CANCELLING: (255, 128, 0), - EXECUTING: (128, 128, 255), - FAILED: (255, 192, 255), - COMPLETED: (128, 255, 128), - WAITING: (255, 255, 255), - } + colors = Dict( + { + CANCELLED: (255, 0, 0), + CANCELLING: (255, 128, 0), + EXECUTING: (128, 128, 255), + FAILED: (255, 192, 255), + COMPLETED: (128, 255, 128), + WAITING: (255, 255, 255), + } + ) #: Text to be displayed for the state column. - state_text = Property + state_text = Property(Str()) def _get_bg_color(self): return self.colors[self.item.state] diff --git a/traits_futures/api.py b/traits_futures/api.py index e602d12..f5ec6ea 100644 --- a/traits_futures/api.py +++ b/traits_futures/api.py @@ -66,6 +66,7 @@ Parallelism contexts -------------------- - :class:`~.IParallelContext` +- :class:`~.MultiprocessingContext` - :class:`~.MultithreadingContext` """ @@ -88,6 +89,7 @@ from traits_futures.future_states import ( from traits_futures.i_future import IFuture from traits_futures.i_parallel_context import IParallelContext from traits_futures.i_task_specification import ITaskSpecification +from traits_futures.multiprocessing_context import MultiprocessingContext from traits_futures.multithreading_context import MultithreadingContext from traits_futures.traits_executor import ( ExecutorState, @@ -127,5 +129,6 @@ __all__ = [ "ITaskSpecification", # Contexts "IParallelContext", + "MultiprocessingContext", "MultithreadingContext", ]
enthought/traits-futures
a1b0f6bedeef815364206e3e361b22c2ea7ca164
diff --git a/traits_futures/tests/test_api.py b/traits_futures/tests/test_api.py index bfe524a..7fc2c83 100644 --- a/traits_futures/tests/test_api.py +++ b/traits_futures/tests/test_api.py @@ -27,6 +27,7 @@ class TestApi(unittest.TestCase): IParallelContext, ITaskSpecification, IterationFuture, + MultiprocessingContext, MultithreadingContext, ProgressFuture, RUNNING, diff --git a/traits_futures/tests/test_traits_process_executor.py b/traits_futures/tests/test_traits_process_executor.py new file mode 100644 index 0000000..135b302 --- /dev/null +++ b/traits_futures/tests/test_traits_process_executor.py @@ -0,0 +1,161 @@ +# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX +# All rights reserved. +# +# This software is provided without warranty under the terms of the BSD +# license included in LICENSE.txt and may be redistributed only under +# the conditions described in the aforementioned license. The license +# is also available online at http://www.enthought.com/licenses/BSD.txt +# +# Thanks for using Enthought open source! + +""" +Tests for the TraitsExecutor class. +""" +import contextlib +import unittest + +from traits_futures.api import ( + MultiprocessingContext, + MultithreadingContext, + TraitsExecutor, +) +from traits_futures.tests.traits_executor_tests import ( + ExecutorListener, + TraitsExecutorTests, +) +from traits_futures.toolkit_support import toolkit + +GuiTestAssistant = toolkit("gui_test_assistant:GuiTestAssistant") + + +class TestTraitsExecutorCreation(GuiTestAssistant, unittest.TestCase): + def setUp(self): + GuiTestAssistant.setUp(self) + self._context = MultiprocessingContext() + + def tearDown(self): + if hasattr(self, "executor"): + self.executor.stop() + self.wait_until_stopped(self.executor) + del self.executor + self._context.close() + GuiTestAssistant.tearDown(self) + + def test_max_workers(self): + executor = TraitsExecutor(max_workers=11, context=self._context) + self.assertEqual(executor._worker_pool._max_workers, 11) + executor.stop() + self.wait_until_stopped(executor) + + def test_max_workers_mutually_exclusive_with_worker_pool(self): + with self.temporary_worker_pool() as worker_pool: + with self.assertRaises(TypeError): + TraitsExecutor( + worker_pool=worker_pool, + max_workers=11, + context=self._context, + ) + + def test_default_context(self): + with self.temporary_executor() as executor: + self.assertIsInstance(executor._context, MultithreadingContext) + + def test_externally_supplied_context(self): + context = MultiprocessingContext() + try: + with self.temporary_executor(context=context) as executor: + self.assertIs(executor._context, context) + self.assertFalse(context.closed) + finally: + context.close() + + def test_owned_context_closed_at_executor_stop(self): + with self.temporary_executor() as executor: + context = executor._context + self.assertFalse(context.closed) + self.assertTrue(context.closed) + + def test_owned_worker_pool(self): + executor = TraitsExecutor(context=self._context) + worker_pool = executor._worker_pool + + executor.stop() + self.wait_until_stopped(executor) + + # Check that the internally-created worker pool has been shut down. + with self.assertRaises(RuntimeError): + worker_pool.submit(int) + + def test_thread_pool_argument_deprecated(self): + with self.temporary_worker_pool() as worker_pool: + with self.assertWarns(DeprecationWarning) as warning_info: + executor = TraitsExecutor( + thread_pool=worker_pool, context=self._context + ) + executor.stop() + self.wait_until_stopped(executor) + + # Check we're using the right stack level in the warning. + _, _, this_module = __name__.rpartition(".") + self.assertIn(this_module, warning_info.filename) + + def test_shared_worker_pool(self): + with self.temporary_worker_pool() as worker_pool: + executor = TraitsExecutor( + worker_pool=worker_pool, context=self._context + ) + executor.stop() + self.wait_until_stopped(executor) + + # Check that the the shared worker pool is still usable. + cf_future = worker_pool.submit(int) + self.assertEqual(cf_future.result(), 0) + + def wait_until_stopped(self, executor): + """ + Wait for the executor to reach STOPPED state. + """ + self.run_until(executor, "stopped", lambda executor: executor.stopped) + + @contextlib.contextmanager + def temporary_worker_pool(self): + """ + Create a worker pool that's shut down at the end of the with block. + """ + worker_pool = self._context.worker_pool(max_workers=4) + try: + yield worker_pool + finally: + worker_pool.shutdown() + + @contextlib.contextmanager + def temporary_executor(self, **kwds): + """ + Create a temporary TraitsExecutor, and shut it down properly after use. + """ + executor = TraitsExecutor(**kwds) + try: + yield executor + finally: + executor.stop() + self.wait_until_stopped(executor) + + +class TestTraitsExecutor( + GuiTestAssistant, TraitsExecutorTests, unittest.TestCase +): + def setUp(self): + GuiTestAssistant.setUp(self) + self._context = MultiprocessingContext() + self.executor = TraitsExecutor(context=self._context) + self.listener = ExecutorListener(executor=self.executor) + + def tearDown(self): + del self.listener + if not self.executor.stopped: + self.executor.stop() + self.wait_until_stopped(self.executor) + del self.executor + self._context.close() + del self._context + GuiTestAssistant.tearDown(self)
Add multiprocessing support The existing code is mostly threading / multiprocessing agnostic, but we're using `threading.Event` objects, for example. We should make it actually agnostic, and add tests with both threading and multiprocessing.
0.0
[ "traits_futures/tests/test_api.py::TestApi::test___all__", "traits_futures/tests/test_api.py::TestApi::test_imports", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_default_context", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_externally_supplied_context", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_max_workers", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_max_workers_mutually_exclusive_with_worker_pool", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_owned_context_closed_at_executor_stop", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_owned_worker_pool", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_shared_worker_pool", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutorCreation::test_thread_pool_argument_deprecated", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_cant_submit_new_unless_running", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_multiple_futures", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_running", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once_no_futures", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_states_consistent", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stop_cancels_running_futures", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stop_method", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stop_method_raises_unless_running", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stop_method_with_no_jobs", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stop_with_multiple_futures", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_stopped", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_submit_call_method", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_submit_iteration_method", "traits_futures/tests/test_traits_process_executor.py::TestTraitsExecutor::test_submit_progress_method" ]
[]
2020-07-11 13:02:20+00:00
2,173
enthought__traits-futures-187
diff --git a/traits_futures/traits_executor.py b/traits_futures/traits_executor.py index 4ca4183..43a6755 100644 --- a/traits_futures/traits_executor.py +++ b/traits_futures/traits_executor.py @@ -289,6 +289,9 @@ class TraitsExecutor(HasStrictTraits): #: and foreground futures. _message_router = Any() + #: True if we've created a message router, and need to shut it down. + _have_message_router = Bool(False) + #: Wrappers for currently-executing futures. _wrappers = Dict(Any(), Any()) @@ -315,6 +318,7 @@ class TraitsExecutor(HasStrictTraits): # Toolkit-specific message router. router = self._context.message_router() router.connect() + self._have_message_router = True return router def __context_default(self): @@ -338,8 +342,10 @@ class TraitsExecutor(HasStrictTraits): Go to STOPPED state, and shut down the worker pool if we own it. """ assert self.state == STOPPING - self._message_router.disconnect() - self._message_router = None + + if self._have_message_router: + self._message_router.disconnect() + self._message_router = None if self._own_worker_pool: self._worker_pool.shutdown()
enthought/traits-futures
344fdac05e79dfcea0302a49dcc38177bd7c0fd1
diff --git a/traits_futures/tests/test_traits_executor.py b/traits_futures/tests/test_traits_executor.py index 0bced3d..d7f5d35 100644 --- a/traits_futures/tests/test_traits_executor.py +++ b/traits_futures/tests/test_traits_executor.py @@ -7,6 +7,8 @@ Tests for the TraitsExecutor class. import contextlib import unittest +from traits.api import Bool + from traits_futures.api import MultithreadingContext, TraitsExecutor from traits_futures.tests.traits_executor_tests import ( ExecutorListener, @@ -17,6 +19,27 @@ from traits_futures.toolkit_support import toolkit GuiTestAssistant = toolkit("gui_test_assistant:GuiTestAssistant") +class TrackingTraitsExecutor(TraitsExecutor): + """ + Version of TraitsExecutor that keeps track of whether the default + methods have been called, for testing purposes. + """ + + #: Have we created a message router? + _message_router_created = Bool(False) + + def __message_router_default(self): + self._message_router_created = True + return TraitsExecutor._TraitsExecutor__message_router_default(self) + + #: Have we created a context? + _context_created = Bool(False) + + def __context_default(self): + self._context_created = True + return TraitsExecutor._TraitsExecutor__context_default(self) + + class TestTraitsExecutorCreation(GuiTestAssistant, unittest.TestCase): def setUp(self): GuiTestAssistant.setUp(self) @@ -100,6 +123,22 @@ class TestTraitsExecutorCreation(GuiTestAssistant, unittest.TestCase): cf_future = worker_pool.submit(int) self.assertEqual(cf_future.result(), 0) + def test_no_objects_created_at_shutdown(self): + # An executor that has no jobs submitted to it should not + # need to instantiate either the context or the message router. + with self.temporary_worker_pool() as worker_pool: + executor = TrackingTraitsExecutor(worker_pool=worker_pool) + executor.stop() + self.wait_until_stopped(executor) + + self.assertFalse( + executor._message_router_created, + msg="Message router unexpectedly created", + ) + self.assertFalse( + executor._context_created, msg="Context unexpectedly created", + ) + def wait_until_stopped(self, executor): """" Wait for the executor to reach STOPPED state.
stop method creates message router if it doesn't already exist The message router for the `TraitsExecutor` is created on first use. If no jobs are submitted, that first use is at executor `stop` time: the message router is instantiated only to call its `disconnect` method. It would be better to rearrange the logic so that the message router is either always created at `__init__` time, or not created at all if it's not used.
0.0
[ "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_no_objects_created_at_shutdown" ]
[ "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_default_context", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_externally_supplied_context", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_max_workers", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_max_workers_mutually_exclusive_with_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_owned_context_closed_at_executor_stop", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_owned_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_shared_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_thread_pool_argument_deprecated", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_cant_submit_new_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once_no_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_states_consistent", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_cancels_running_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_raises_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_with_no_jobs", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_with_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stopped", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_call_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_iteration_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_progress_method" ]
2020-07-30 16:10:07+00:00
2,174
enthought__traits-futures-203
diff --git a/docs/source/guide/advanced.rst b/docs/source/guide/advanced.rst index c6f9405..cbea979 100644 --- a/docs/source/guide/advanced.rst +++ b/docs/source/guide/advanced.rst @@ -163,7 +163,7 @@ background task type: substitutions .. |BaseFuture| replace:: :class:`~.BaseFuture` -.. |dispatch_message| replace:: :meth:`~.BaseFuture.dispatch_message` +.. |dispatch_message| replace:: :meth:`~.BaseFuture._dispatch_message` .. |exception| replace:: :attr:`~traits_futures.i_future.IFuture.exception` .. |HasStrictTraits| replace:: :class:`~traits.has_traits.HasStrictTraits` .. |IFuture| replace:: :class:`~.IFuture` diff --git a/traits_futures/base_future.py b/traits_futures/base_future.py index 6a44e4a..8eb52f7 100644 --- a/traits_futures/base_future.py +++ b/traits_futures/base_future.py @@ -17,9 +17,7 @@ from traits.api import ( Bool, Callable, Enum, - Event, HasStrictTraits, - on_trait_change, Property, provides, Str, @@ -116,12 +114,6 @@ class BaseFuture(HasStrictTraits): #: it will be consistent with the ``state``. done = Property(Bool()) - #: Event trait providing custom messages from the background task. - #: Subclasses of ``BaseFuture`` can listen to this trait and interpret - #: the messages in whatever way they like. Each message takes the - #: form ``(message_type, message_args)``. - message = Event(Tuple(Str(), Any())) - @property def result(self): """ @@ -142,11 +134,11 @@ class BaseFuture(HasStrictTraits): If the task is still executing, or was cancelled, or raised an exception instead of returning a result. """ - if self._state != COMPLETED: + if self.state != COMPLETED: raise AttributeError( "No result available. Task has not yet completed, " "or was cancelled, or failed with an exception. " - "Task state is {}".format(self._state) + "Task state is {}".format(self.state) ) return self._result @@ -171,7 +163,7 @@ class BaseFuture(HasStrictTraits): If the task is still executing, or was cancelled, or completed without raising an exception. """ - if self._state != FAILED: + if self.state != FAILED: raise AttributeError( "No exception information available. Task has " "not yet completed, or was cancelled, or completed " @@ -199,11 +191,15 @@ class BaseFuture(HasStrictTraits): "Can only cancel a waiting or executing task. " "Task state is {}".format(self.state) ) - self._cancel() self._user_cancelled() - @on_trait_change("message") - def dispatch_message(self, message): + # Semi-private methods #################################################### + + # These methods represent the state transitions in response to external + # events. They're used by the FutureWrapper, but are not intended for use + # by the users of Traits Futures. + + def _dispatch_message(self, message): """ Automate dispatch of different types of message. @@ -216,7 +212,14 @@ class BaseFuture(HasStrictTraits): If the future is already in ``CANCELLING`` state, no message is dispatched. + + Parameters + ---------- + message : tuple(str, object) + Message from the background task, in the form (message_type, + message_args). """ + if self._state == CANCELLING_AFTER_STARTED: # Ignore messages that arrive after a cancellation request. return @@ -229,12 +232,6 @@ class BaseFuture(HasStrictTraits): "Unexpected custom message in state {!r}".format(self._state) ) - # Semi-private methods #################################################### - - # These methods represent the state transitions in response to external - # events. They're used by the FutureWrapper, but are not intended for use - # by the users of Traits Futures. - def _task_started(self, none): """ Update state when the background task has started processing. @@ -290,9 +287,11 @@ class BaseFuture(HasStrictTraits): state. """ if self._state == INITIALIZED: + self._cancel() self._cancel = None self._state = CANCELLING_BEFORE_STARTED elif self._state == EXECUTING: + self._cancel() self._cancel = None self._state = CANCELLING_AFTER_STARTED else: diff --git a/traits_futures/i_parallel_context.py b/traits_futures/i_parallel_context.py index 81a5a7a..7b5da62 100644 --- a/traits_futures/i_parallel_context.py +++ b/traits_futures/i_parallel_context.py @@ -57,18 +57,6 @@ class IParallelContext(abc.ABC): the ``set`` and ``is_set`` methods from that API. """ - @abc.abstractmethod - def queue(self): - """ - Return a shareable queue suitable for this context. - - Returns - ------- - queue : queue-like - A queue that can be shared safely with workers. This package - relies only on the ``put`` and ``get`` methods of the queue. - """ - @abc.abstractmethod def message_router(self): """ diff --git a/traits_futures/multithreading_context.py b/traits_futures/multithreading_context.py index e2ad4e8..b1e2936 100644 --- a/traits_futures/multithreading_context.py +++ b/traits_futures/multithreading_context.py @@ -13,7 +13,6 @@ Context providing multithreading-friendly worker pools, events, and routers. """ import concurrent.futures -import queue import threading from traits_futures.i_parallel_context import IParallelContext @@ -55,17 +54,6 @@ class MultithreadingContext(IParallelContext): """ return threading.Event() - def queue(self): - """ - Return a shareable queue suitable for this context. - - Returns - ------- - queue : queue-like - A queue that can be shared safely with workers. - """ - return queue.Queue() - def message_router(self): """ Return a message router suitable for use in this context. diff --git a/traits_futures/wrappers.py b/traits_futures/wrappers.py index 7f30227..72f927b 100644 --- a/traits_futures/wrappers.py +++ b/traits_futures/wrappers.py @@ -72,15 +72,12 @@ class FutureWrapper(HasStrictTraits): message_kind, message = message if message_kind == CUSTOM: - self.future.message = message - elif message_kind == CONTROL: + self.future._dispatch_message(message) + else: + assert message_kind == CONTROL message_type, message_arg = message method_name = "_task_{}".format(message_type) getattr(self.future, method_name)(message_arg) - else: - raise RuntimeError( - "Unrecognised message kind: {}".format(message_kind) - ) class BackgroundTaskWrapper:
enthought/traits-futures
ff10fdb789681c7c843fdf267d90db2b2ac42112
diff --git a/traits_futures/tests/common_future_tests.py b/traits_futures/tests/common_future_tests.py index ebdd577..66f28e5 100644 --- a/traits_futures/tests/common_future_tests.py +++ b/traits_futures/tests/common_future_tests.py @@ -19,6 +19,12 @@ from traits_futures.exception_handling import marshal_exception from traits_futures.future_states import CANCELLABLE_STATES, DONE_STATES +def dummy_cancel_callback(): + """ + Dummy callback for cancellation, that does nothing. + """ + + class FutureListener(HasStrictTraits): """ Record state changes to a given future. """ @@ -55,7 +61,7 @@ class CommonFutureTests: # Record state when any of the three traits changes. future = self.future_class() - future._executor_initialized(lambda: None) + future._executor_initialized(dummy_cancel_callback) future.on_trait_change(record_states, "cancellable") future.on_trait_change(record_states, "done") @@ -74,7 +80,7 @@ class CommonFutureTests: def test_cancellable_and_done_success(self): future = self.future_class() - future._executor_initialized(lambda: None) + future._executor_initialized(dummy_cancel_callback) listener = FutureListener(future=future) @@ -86,7 +92,7 @@ class CommonFutureTests: def test_cancellable_and_done_failure(self): future = self.future_class() - future._executor_initialized(lambda: None) + future._executor_initialized(dummy_cancel_callback) listener = FutureListener(future=future) @@ -98,7 +104,7 @@ class CommonFutureTests: def test_cancellable_and_done_cancellation(self): future = self.future_class() - future._executor_initialized(lambda: None) + future._executor_initialized(dummy_cancel_callback) listener = FutureListener(future=future) @@ -111,7 +117,7 @@ class CommonFutureTests: def test_cancellable_and_done_early_cancellation(self): future = self.future_class() - future._executor_initialized(lambda: None) + future._executor_initialized(dummy_cancel_callback) listener = FutureListener(future=future) @@ -127,20 +133,24 @@ class CommonFutureTests: # The BaseFuture processes four different messages: started / raised / # returned messages from the task, and a possible cancellation message from # the user. We denote these with the letters S, X (for eXception), R and C, - # and add machinery to test various combinations. + # and add machinery to test various combinations. We also write I to + # denote initialization of the future. def test_invalid_message_sequences(self): - # A complete run must always involve "started, raised" or "started, - # returned" in that order. In addition, a single cancellation is - # possible at any time before the end of the sequence. + # A future must always be initialized before anything else happens, and + # then a complete run must always involve "started, raised" or + # "started, returned" in that order. In addition, a single cancellation + # is possible at any time before the end of the sequence. complete_valid_sequences = { - "SR", - "SX", - "CSR", - "CSX", - "SCR", - "SCX", + "ISR", + "ISX", + "ICSR", + "ICSX", + "ISCR", + "ISCX", } + + # Systematically generate invalid sequences of messages. valid_initial_sequences = { seq[:i] for seq in complete_valid_sequences @@ -150,30 +160,39 @@ class CommonFutureTests: seq[:i] + msg for seq in valid_initial_sequences for i in range(len(seq) + 1) - for msg in "CRSX" + for msg in "ICRSX" } invalid_sequences = continuations - valid_initial_sequences + + # Check that all invalid sequences raise StateTransitionError for sequence in invalid_sequences: with self.subTest(sequence=sequence): with self.assertRaises(StateTransitionError): self.send_message_sequence(sequence) + # Check all complete valid sequences. + for sequence in complete_valid_sequences: + with self.subTest(sequence=sequence): + future = self.send_message_sequence(sequence) + self.assertTrue(future.done) + def test_interface(self): future = self.future_class() self.assertIsInstance(future, IFuture) def send_message(self, future, message): """ Send a particular message to a future. """ - if message == "S": + if message == "I": + future._executor_initialized(dummy_cancel_callback) + elif message == "S": future._task_started(None) elif message == "X": future._task_raised(self.fake_exception()) elif message == "R": future._task_returned(23) - elif message == "C": - future._user_cancelled() else: - raise ValueError("Invalid message: {}".format(message)) + assert message == "C" + future._user_cancelled() def send_message_sequence(self, messages): """ Create a new future, and send the given message sequence to it. """ diff --git a/traits_futures/tests/test_base_future.py b/traits_futures/tests/test_base_future.py new file mode 100644 index 0000000..9cde384 --- /dev/null +++ b/traits_futures/tests/test_base_future.py @@ -0,0 +1,102 @@ +# (C) Copyright 2018-2020 Enthought, Inc., Austin, TX +# All rights reserved. +# +# This software is provided without warranty under the terms of the BSD +# license included in LICENSE.txt and may be redistributed only under +# the conditions described in the aforementioned license. The license +# is also available online at http://www.enthought.com/licenses/BSD.txt +# +# Thanks for using Enthought open source! + +""" +Tests for ability to subclass the BaseFuture base class. +""" + +import unittest + +from traits.api import Int, List + +from traits_futures.base_future import BaseFuture, StateTransitionError +from traits_futures.tests.common_future_tests import CommonFutureTests + + +def dummy_cancel_callback(): + """ + Dummy callback for cancellation, that does nothing. + """ + + +class PingFuture(BaseFuture): + """ + BaseFuture subclass that interpretes "ping" + messages from the background. + """ + #: Accumulate ping messages + pings = List(Int) + + def _process_ping(self, arg): + """ + Process a 'ping' message. + """ + self.pings.append(arg) + + +class TestBaseFuture(CommonFutureTests, unittest.TestCase): + def setUp(self): + self.future_class = PingFuture + + def test_normal_lifecycle(self): + future = self.future_class() + future._executor_initialized(dummy_cancel_callback) + future._task_started(None) + future._dispatch_message(("ping", 123)) + future._dispatch_message(("ping", 999)) + future._task_returned(1729) + + self.assertEqual(future.pings, [123, 999]) + + def test_ping_after_cancellation_is_ignored(self): + message = ("ping", 32) + + future = self.future_class() + future._executor_initialized(dummy_cancel_callback) + + future._task_started(None) + future._user_cancelled() + + future._dispatch_message(message) + future._task_returned(1729) + + self.assertEqual(future.pings, []) + + def test_impossible_ping(self): + # Custom messages should only ever arrive when a future is + # in EXECUTING or CANCELLING states. + message = ("ping", 32) + + future = self.future_class() + + with self.assertRaises(StateTransitionError): + future._dispatch_message(message) + + future._executor_initialized(dummy_cancel_callback) + + with self.assertRaises(StateTransitionError): + future._dispatch_message(message) + + future._task_started(None) + future._task_returned(1729) + + with self.assertRaises(StateTransitionError): + future._dispatch_message(message) + + def test_impossible_ping_cancelled_task(self): + message = ("ping", 32) + + future = self.future_class() + future._executor_initialized(dummy_cancel_callback) + + future._user_cancelled() + + with self.assertRaises(StateTransitionError): + future._dispatch_message(message) diff --git a/traits_futures/tests/test_traits_executor.py b/traits_futures/tests/test_traits_executor.py index 6a86ce6..a0dd162 100644 --- a/traits_futures/tests/test_traits_executor.py +++ b/traits_futures/tests/test_traits_executor.py @@ -53,10 +53,6 @@ class TestTraitsExecutorCreation(GuiTestAssistant, unittest.TestCase): self._context = MultithreadingContext() def tearDown(self): - if hasattr(self, "executor"): - self.executor.stop() - self.wait_until_stopped(self.executor) - del self.executor self._context.close() GuiTestAssistant.tearDown(self)
Check test coverage 0.1.0 had 100% test coverage, but a lot of code has moved around since then. We should check the coverage before the 0.2.0 release (partly just to check for any pieces of code that became unused but weren't deleted).
0.0
[ "traits_futures/tests/test_base_future.py::TestBaseFuture::test_impossible_ping", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_impossible_ping_cancelled_task", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_normal_lifecycle", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_ping_after_cancellation_is_ignored" ]
[ "traits_futures/tests/test_base_future.py::TestBaseFuture::test_cancellable_and_done_cancellation", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_cancellable_and_done_consistent_with_state", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_cancellable_and_done_early_cancellation", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_cancellable_and_done_failure", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_cancellable_and_done_success", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_interface", "traits_futures/tests/test_base_future.py::TestBaseFuture::test_invalid_message_sequences", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_default_context", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_externally_supplied_context", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_max_workers", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_max_workers_mutually_exclusive_with_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_no_objects_created_at_shutdown", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_owned_context_closed_at_executor_stop", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_owned_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_shared_worker_pool", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutorCreation::test_thread_pool_argument_deprecated", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_cant_submit_new_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_running_and_stopped_fired_only_once_no_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_states_consistent", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_cancels_running_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_raises_unless_running", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_method_with_no_jobs", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stop_with_multiple_futures", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_stopped", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_call_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_iteration_method", "traits_futures/tests/test_traits_executor.py::TestTraitsExecutor::test_submit_progress_method" ]
2020-09-18 19:18:18+00:00
2,175
enthought__traits-futures-255
diff --git a/traits_futures/message_router.py b/traits_futures/message_router.py index 9ca7d3f..b2e4db4 100644 --- a/traits_futures/message_router.py +++ b/traits_futures/message_router.py @@ -69,13 +69,15 @@ class MessageRouter(HasStrictTraits): """ Prepare router for routing. """ - pass + self._pingee = Pingee(on_ping=self._route_message) + self._pingee.connect() def disconnect(self): """ Undo any connections made by the ``connect`` call. """ - pass + self._pingee.disconnect() + self._pingee = None # Private traits ########################################################## @@ -110,6 +112,3 @@ class MessageRouter(HasStrictTraits): def __connection_ids_default(self): return itertools.count() - - def __pingee_default(self): - return Pingee(on_ping=self._route_message) diff --git a/traits_futures/null/pinger.py b/traits_futures/null/pinger.py index 59a1e15..8da4aed 100644 --- a/traits_futures/null/pinger.py +++ b/traits_futures/null/pinger.py @@ -22,26 +22,45 @@ class Pingee: """ Receiver for pings. + Whenever a ping is received from a linked Pingee, the receiver + calls the given fixed parameterless callable. + + The ping receiver must be connected (using the ``connect``) method + before use, and should call ``disconnect`` when it's no longer + expected to receive pings. + Parameters ---------- on_ping : callable - Zero-argument callable that's executed on the main thread as a - result of each ping. + Zero-argument callable that's called on the main thread + every time a ping is received. """ def __init__(self, on_ping): - self._event_loop = asyncio.get_event_loop() self._on_ping = on_ping + def connect(self): + """ + Prepare Pingee to receive pings. + """ + self._event_loop = asyncio.get_event_loop() + + def disconnect(self): + """ + Undo any connections made in the connect method. + """ + del self._event_loop + class Pinger: """ - Ping emitter, which can emit pings in a thread-safe manner. + Ping emitter, which can send pings to a receiver in a thread-safe manner. Parameters ---------- pingee : Pingee - The corresponding ping receiver. + The target receiver for the pings. The receiver must already be + connected. """ def __init__(self, pingee): diff --git a/traits_futures/qt/pinger.py b/traits_futures/qt/pinger.py index b510eeb..ef435a3 100644 --- a/traits_futures/qt/pinger.py +++ b/traits_futures/qt/pinger.py @@ -30,11 +30,18 @@ class Pingee(QObject): """ Receiver for pings. + Whenever a ping is received from a linked Pingee, the receiver + calls the given fixed parameterless callable. + + The ping receiver must be connected (using the ``connect``) method + before use, and should call ``disconnect`` when it's no longer + expected to receive pings. + Parameters ---------- on_ping : callable - Zero-argument callable that's executed on the main thread as a - result of each ping. + Zero-argument callable that's called on the main thread + every time a ping is received. """ def __init__(self, on_ping): @@ -45,15 +52,28 @@ class Pingee(QObject): def _execute_ping_callback(self): self._on_ping() + def connect(self): + """ + Prepare Pingee to receive pings. + """ + pass + + def disconnect(self): + """ + Undo any connections made in the connect method. + """ + pass + class Pinger: """ - Ping emitter, which can emit pings in a thread-safe manner. + Ping emitter, which can send pings to a receiver in a thread-safe manner. Parameters ---------- pingee : Pingee - The corresponding ping receiver. + The target receiver for the pings. The receiver must already be + connected. """ def __init__(self, pingee): diff --git a/traits_futures/wx/pinger.py b/traits_futures/wx/pinger.py index f1ed51b..df65e74 100644 --- a/traits_futures/wx/pinger.py +++ b/traits_futures/wx/pinger.py @@ -24,12 +24,13 @@ _PingEvent, _PingEventBinder = wx.lib.newevent.NewEvent() class Pinger: """ - Ping emitter, which can emit pings in a thread-safe manner. + Ping emitter, which can send pings to a receiver in a thread-safe manner. Parameters ---------- pingee : Pingee - The corresponding ping receiver. + The target receiver for the pings. The receiver must already be + connected. """ def __init__(self, pingee): @@ -60,6 +61,13 @@ class Pingee(wx.EvtHandler): """ Receiver for pings. + Whenever a ping is received from a linked Pingee, the receiver + calls the given fixed parameterless callable. + + The ping receiver must be connected (using the ``connect``) method + before use, and should call ``disconnect`` when it's no longer + expected to receive pings. + Parameters ---------- on_ping : callable @@ -69,11 +77,16 @@ class Pingee(wx.EvtHandler): def __init__(self, on_ping): wx.EvtHandler.__init__(self) - self._on_ping = on_ping - self.Bind(_PingEventBinder, self._on_ping_event) + self._on_ping = lambda event: on_ping() - def _on_ping_event(self, event): + def connect(self): + """ + Prepare Pingee to receive pings. + """ + self.Bind(_PingEventBinder, handler=self._on_ping) + + def disconnect(self): """ - Handler for events of type _PING_EVENT_TYPE. + Undo any connections made in the connect method. """ - self._on_ping() + self.Unbind(_PingEventBinder, handler=self._on_ping)
enthought/traits-futures
60efc6ca839fbcb235ebc886d64fa0ce4ce19fc5
diff --git a/traits_futures/tests/test_pinger.py b/traits_futures/tests/test_pinger.py index 3036953..91ec622 100644 --- a/traits_futures/tests/test_pinger.py +++ b/traits_futures/tests/test_pinger.py @@ -102,14 +102,24 @@ class PingListener(HasStrictTraits): #: Total number of pings received. ping_count = Int(0) + def __enter__(self): + self.connect() + return self + + def __exit__(self, *exc_info): + self.disconnect() + + def connect(self): + self.pingee = Pingee(on_ping=lambda: setattr(self, "ping", True)) + self.pingee.connect() + + def disconnect(self): + self.pingee.disconnect() + self.pingee = None + def _ping_fired(self): self.ping_count += 1 - def _pingee_default(self): - return Pingee( - on_ping=lambda: setattr(self, "ping", True), - ) - class MultipleListeners(HasStrictTraits): """ @@ -137,8 +147,10 @@ class TestPinger(GuiTestAssistant, unittest.TestCase): def setUp(self): GuiTestAssistant.setUp(self) self.listener = PingListener() + self.listener.connect() def tearDown(self): + self.listener.disconnect() del self.listener GuiTestAssistant.tearDown(self) @@ -178,18 +190,17 @@ class TestPinger(GuiTestAssistant, unittest.TestCase): self.assertEqual(self.listener.ping_count, 15) def test_multiple_pingees(self): - listener1 = PingListener() - listener2 = PingListener() - listeners = MultipleListeners(listeners=[listener1, listener2]) - - with BackgroundPinger(listener1.pingee) as pinger1: - with BackgroundPinger(listener2.pingee) as pinger2: - pinger1.ping(3) - pinger2.ping(4) - - self.run_until( - listeners, "ping", lambda obj: obj.ping_count >= 7 - ) + with PingListener() as listener1: + with PingListener() as listener2: + listeners = MultipleListeners(listeners=[listener1, listener2]) + with BackgroundPinger(listener1.pingee) as pinger1: + with BackgroundPinger(listener2.pingee) as pinger2: + pinger1.ping(3) + pinger2.ping(4) + + self.run_until( + listeners, "ping", lambda obj: obj.ping_count >= 7 + ) self.assertEqual(listener1.ping_count, 3) self.assertEqual(listener2.ping_count, 4)
Call Unbind in the wxPython Pingee implementation The wxPython `Pingee` implementation introduced in #246 has a `Bind` call without a matching `Unbind` call. While we don't have any evidence that this actually causes any problems, in general we probably want to provide an API for the `Pingee` to undo anything it's had to set up. Toolkits can then make use of this or not, as necessary.
0.0
[ "traits_futures/tests/test_pinger.py::TestPinger::test_background_threads_finish_before_event_loop_starts", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_background_pingers", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_background_pings", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_pingees", "traits_futures/tests/test_pinger.py::TestPinger::test_single_background_ping" ]
[]
2020-11-26 13:02:21+00:00
2,176
enthought__traits-futures-298
diff --git a/traits_futures/i_pingee.py b/traits_futures/i_pingee.py new file mode 100644 index 0000000..969f171 --- /dev/null +++ b/traits_futures/i_pingee.py @@ -0,0 +1,87 @@ +# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX +# All rights reserved. +# +# This software is provided without warranty under the terms of the BSD +# license included in LICENSE.txt and may be redistributed only under +# the conditions described in the aforementioned license. The license +# is also available online at http://www.enthought.com/licenses/BSD.txt +# +# Thanks for using Enthought open source! + +""" +Interface for the toolkit-specific pingee and pinger classes. +""" + +import abc + + +class IPingee(abc.ABC): + """ + Interface for toolkit-specific pingee classes. + + An IPingee instance provides a toolkit-specific cross-thread pinging + mechanism. The pingee is owned by the main thread, but may be shared + with background threads for the sole purpose of allowing those background + threads to create linked pingers. + + Whenever a ping is received from a linked ``IPinger`` instance, the pingee + ensures that under a running event loop, the ``on_ping`` callable is + eventually called. The ``on_ping`` callable will always be called on the + main thread. + + Parameters + ---------- + on_ping : callable + Zero-argument callable that's called on the main thread + every time a ping is received. + """ + + @abc.abstractmethod + def connect(self): + """ + Prepare pingee to receive pings. + + Not thread-safe. This method should only be called in the main thread. + """ + + @abc.abstractmethod + def disconnect(self): + """ + Undo any connections made in the connect method. + + Not thread-safe. This method should only be called in the main thread. + """ + + +class IPinger(abc.ABC): + """ + Interface for toolkit-specific pinger classes. + + An IPinger instance emits pings targeting a particular IPingee instance. + + Parameters + ---------- + pingee : IPingee + The target receiver for the pings. The receiver should already + be connected. + """ + + @abc.abstractmethod + def connect(self): + """ + Connect to the ping receiver. No pings should be sent before + this method is called. + """ + + @abc.abstractmethod + def disconnect(self): + """ + Disconnect from the ping receiver. No pings should be sent after + calling this method. + """ + + @abc.abstractmethod + def ping(self): + """ + Send a ping to the receiver. + """ diff --git a/traits_futures/multiprocessing_router.py b/traits_futures/multiprocessing_router.py index 58e4687..983eddc 100644 --- a/traits_futures/multiprocessing_router.py +++ b/traits_futures/multiprocessing_router.py @@ -73,6 +73,7 @@ from traits_futures.i_message_router import ( IMessageRouter, IMessageSender, ) +from traits_futures.i_pingee import IPingee from traits_futures.toolkit_support import toolkit logger = logging.getLogger(__name__) @@ -382,7 +383,7 @@ class MultiprocessingRouter(HasRequiredTraits): _receivers = Dict(Int(), Instance(MultiprocessingReceiver)) #: Receiver for the "message_sent" signal. - _pingee = Instance(Pingee) + _pingee = Instance(IPingee) #: Router status: True if running, False if stopped. _running = Bool(False) diff --git a/traits_futures/multithreading_router.py b/traits_futures/multithreading_router.py index 97c9433..1934621 100644 --- a/traits_futures/multithreading_router.py +++ b/traits_futures/multithreading_router.py @@ -34,6 +34,7 @@ from traits_futures.i_message_router import ( IMessageRouter, IMessageSender, ) +from traits_futures.i_pingee import IPingee from traits_futures.toolkit_support import toolkit logger = logging.getLogger(__name__) @@ -313,7 +314,7 @@ class MultithreadingRouter(HasStrictTraits): _receivers = Dict(Int(), Instance(MultithreadingReceiver)) #: Receiver for the "message_sent" signal. - _pingee = Instance(Pingee) + _pingee = Instance(IPingee) #: Router status: True if running, False if stopped. _running = Bool(False) diff --git a/traits_futures/null/pinger.py b/traits_futures/null/pinger.py index eee44a7..5efd880 100644 --- a/traits_futures/null/pinger.py +++ b/traits_futures/null/pinger.py @@ -17,12 +17,15 @@ the main thread execute a (fixed, parameterless) callback. import asyncio +from traits_futures.i_pingee import IPingee, IPinger + [email protected] class Pingee: """ Receiver for pings. - Whenever a ping is received from a linked Pingee, the receiver + Whenever a ping is received from a linked Pinger, the receiver calls the given fixed parameterless callable. The ping receiver must be connected (using the ``connect``) method @@ -52,6 +55,7 @@ class Pingee: del self._event_loop [email protected] class Pinger: """ Ping emitter, which can send pings to a receiver in a thread-safe manner. diff --git a/traits_futures/qt/pinger.py b/traits_futures/qt/pinger.py index a917150..caf307b 100644 --- a/traits_futures/qt/pinger.py +++ b/traits_futures/qt/pinger.py @@ -17,6 +17,8 @@ the main thread execute a (fixed, parameterless) callback. from pyface.qt.QtCore import QObject, Qt, Signal, Slot +from traits_futures.i_pingee import IPingee, IPinger + class _Signaller(QObject): """ @@ -26,11 +28,12 @@ class _Signaller(QObject): ping = Signal() [email protected] class Pingee(QObject): """ Receiver for pings. - Whenever a ping is received from a linked Pingee, the receiver + Whenever a ping is received from a linked Pinger, the receiver calls the given fixed parameterless callable. The ping receiver must be connected (using the ``connect``) method @@ -65,6 +68,7 @@ class Pingee(QObject): pass [email protected] class Pinger: """ Ping emitter, which can send pings to a receiver in a thread-safe manner. diff --git a/traits_futures/wx/pinger.py b/traits_futures/wx/pinger.py index 784d9c7..746b6f6 100644 --- a/traits_futures/wx/pinger.py +++ b/traits_futures/wx/pinger.py @@ -17,6 +17,8 @@ the main thread execute a (fixed, parameterless) callback. import wx.lib.newevent +from traits_futures.i_pingee import IPingee, IPinger + # Note: we're not using the more obvious spelling # _PingEvent, _PingEventBinder = wx.lib.newevent.NewEvent() # here because that confuses Sphinx's autodoc mocking. @@ -28,6 +30,7 @@ _PingEvent = _PingEventPair[0] _PingEventBinder = _PingEventPair[1] [email protected] class Pinger: """ Ping emitter, which can send pings to a receiver in a thread-safe manner. @@ -63,11 +66,12 @@ class Pinger: wx.PostEvent(self.pingee, _PingEvent()) [email protected] class Pingee(wx.EvtHandler): """ Receiver for pings. - Whenever a ping is received from a linked Pingee, the receiver + Whenever a ping is received from a linked Pinger, the receiver calls the given fixed parameterless callable. The ping receiver must be connected (using the ``connect``) method
enthought/traits-futures
66ecc55c4c474d0ec1176fd7e665f1217137e962
diff --git a/traits_futures/tests/test_pinger.py b/traits_futures/tests/test_pinger.py index cb582c9..a32cff1 100644 --- a/traits_futures/tests/test_pinger.py +++ b/traits_futures/tests/test_pinger.py @@ -22,6 +22,7 @@ from traits.api import ( on_trait_change, ) +from traits_futures.i_pingee import IPingee from traits_futures.toolkit_support import toolkit GuiTestAssistant = toolkit("gui_test_assistant:GuiTestAssistant") @@ -94,7 +95,7 @@ class PingListener(HasStrictTraits): """ #: The actual pingee as provided by Traits Futures. - pingee = Instance(Pingee) + pingee = Instance(IPingee) #: Event fired every time a ping is received. ping = Event()
Add `IPingee` interface #280 introduces some references to `IPingee` as a type in the "Parameters" section of docstrings; that was necessary because Sphinx warns about the ambiguity of references to `Pingee`. But `IPingee` doesn't yet exist; we should fix that.
0.0
[ "traits_futures/tests/test_pinger.py::TestPinger::test_background_threads_finish_before_event_loop_starts", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_background_pingers", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_background_pings", "traits_futures/tests/test_pinger.py::TestPinger::test_multiple_pingees", "traits_futures/tests/test_pinger.py::TestPinger::test_single_background_ping" ]
[]
2021-04-01 14:18:47+00:00
2,177
enthought__traits-futures-317
diff --git a/docs/source/guide/intro.rst b/docs/source/guide/intro.rst index 13c6274..2cff470 100644 --- a/docs/source/guide/intro.rst +++ b/docs/source/guide/intro.rst @@ -54,7 +54,9 @@ from ``traits_futures.api``: *must* have a parameter called "progress". A value for this parameter will be passed (by name) by the executor machinery. The value passed for the "progress" parameter can then be called to send progress reports to the - associated |ProgressFuture| object. + associated |ProgressFuture| object. If the future has been cancelled, the + next call to ``progress`` in the background task will raise a + |ProgressCancelled| exception. For example, your callable might look like this:: @@ -313,6 +315,7 @@ needed. .. |IterationFuture| replace:: :class:`~traits_futures.background_iteration.IterationFuture` .. |submit_iteration| replace:: :func:`~traits_futures.background_iteration.submit_iteration` +.. |ProgressCancelled| replace:: :exc:`~traits_futures.background_progress.ProgressCancelled` .. |ProgressFuture| replace:: :class:`~traits_futures.background_progress.ProgressFuture` .. |submit_progress| replace:: :func:`~traits_futures.background_progress.submit_progress` diff --git a/traits_futures/api.py b/traits_futures/api.py index f5ec6ea..b147f9b 100644 --- a/traits_futures/api.py +++ b/traits_futures/api.py @@ -28,6 +28,7 @@ Task submission functions - :func:`~.submit_call` - :func:`~.submit_iteration` - :func:`~.submit_progress` +- :exc:`~.ProgressCancelled` Types of futures ---------------- @@ -75,7 +76,11 @@ from traits_futures.background_iteration import ( IterationFuture, submit_iteration, ) -from traits_futures.background_progress import ProgressFuture, submit_progress +from traits_futures.background_progress import ( + ProgressCancelled, + ProgressFuture, + submit_progress, +) from traits_futures.base_future import BaseFuture from traits_futures.future_states import ( CANCELLED, @@ -105,6 +110,7 @@ __all__ = [ "CallFuture", "IterationFuture", "ProgressFuture", + "ProgressCancelled", # Future states "FutureState", "CANCELLED", diff --git a/traits_futures/background_progress.py b/traits_futures/background_progress.py index c79d6e6..84f5f66 100644 --- a/traits_futures/background_progress.py +++ b/traits_futures/background_progress.py @@ -32,7 +32,7 @@ from traits_futures.i_task_specification import ITaskSpecification PROGRESS = "progress" -class _ProgressCancelled(Exception): +class ProgressCancelled(Exception): """ Exception raised when progress reporting is interrupted by task cancellation. @@ -60,9 +60,16 @@ class ProgressReporter: progress_info : object An arbitrary object representing progress. Ideally, this should be immutable and pickleable. + + Raises + ------ + ProgressCancelled + If a cancellation request for this task has already been made. + In this case, the exception will be raised before any progress + information is sent. """ if self.cancelled(): - raise _ProgressCancelled("Task was cancelled") + raise ProgressCancelled("Task was cancelled") self.send(PROGRESS, progress_info) @@ -85,7 +92,7 @@ class ProgressBackgroundTask: try: return self.callable(*self.args, **self.kwargs) - except _ProgressCancelled: + except ProgressCancelled: return None
enthought/traits-futures
bc127deceb46ff468b058db23ebb97ac086a4e43
diff --git a/traits_futures/tests/background_progress_tests.py b/traits_futures/tests/background_progress_tests.py index 6683862..3dcd648 100644 --- a/traits_futures/tests/background_progress_tests.py +++ b/traits_futures/tests/background_progress_tests.py @@ -17,6 +17,7 @@ from traits_futures.api import ( EXECUTING, FAILED, FutureState, + ProgressCancelled, ProgressFuture, submit_progress, WAITING, @@ -80,7 +81,7 @@ def syncing_progress(test_ready, raised, progress): # so that we never get to the following code. try: progress("second") - except BaseException: + except ProgressCancelled: raised.set() raise diff --git a/traits_futures/tests/test_api.py b/traits_futures/tests/test_api.py index 7fc2c83..9e7a1b4 100644 --- a/traits_futures/tests/test_api.py +++ b/traits_futures/tests/test_api.py @@ -29,6 +29,7 @@ class TestApi(unittest.TestCase): IterationFuture, MultiprocessingContext, MultithreadingContext, + ProgressCancelled, ProgressFuture, RUNNING, STOPPED,
_ProgressCancelled should be in the api module The `_ProgressCancelled` exception type should be made public, and should be available in `traits_futures.api`. Target functions for `submit_progress` might legitimately want to access the exception that `progress` raises, and other runners that want to emulate the Traits Futures behaviour (for example in tests for such a target function) may want to raise that exception. If we wanted to go one step further: ideally, it would be possible to write a function intended as a target for `submit_progress` without even importing Traits Futures. That would involve making the exception class available from the `progress` argument passed to the function. That's not impossible, but it's not clear whether it's really a win.
0.0
[ "traits_futures/tests/test_api.py::TestApi::test___all__", "traits_futures/tests/test_api.py::TestApi::test_imports" ]
[]
2021-04-28 13:35:27+00:00
2,178
enthought__traits-futures-391
diff --git a/traits_futures/exception_handling.py b/traits_futures/exception_handling.py index c382978..1165b38 100644 --- a/traits_futures/exception_handling.py +++ b/traits_futures/exception_handling.py @@ -14,6 +14,34 @@ Support for transferring exception information from a background task. import traceback +def _qualified_type_name(class_): + """ + Compute a descriptive string representing a class, including + a module name where relevant. + + Example outputs are "RuntimeError" for the built-in RuntimeError + exception, or "struct.error" for the struct module exception class. + + Parameters + ---------- + class_ : type + + Returns + ------- + class_name : str + """ + # We're being extra conservative here and allowing for the possibility that + # the class doesn't have __module__ and/or __qualname__ attributes. This + # function is called during exception handling, so we want to minimise the + # possibility that it raises a new exception. + class_module = getattr(class_, "__module__", "<unknown>") + class_qualname = getattr(class_, "__qualname__", "<unknown>") + if class_module == "builtins": + return f"{class_qualname}" + else: + return f"{class_module}.{class_qualname}" + + def marshal_exception(exception): """ Turn exception details into something that can be safely @@ -31,7 +59,7 @@ def marshal_exception(exception): formatted traceback. """ return ( - str(type(exception)), + _qualified_type_name(type(exception)), str(exception), "".join( traceback.format_exception(
enthought/traits-futures
28cb7e9bbb1f174202b9b706b24eb5c4edd18a73
diff --git a/traits_futures/tests/background_call_tests.py b/traits_futures/tests/background_call_tests.py index 62661ed..d79c0e3 100644 --- a/traits_futures/tests/background_call_tests.py +++ b/traits_futures/tests/background_call_tests.py @@ -292,7 +292,7 @@ class BackgroundCallTests: future.result def assertException(self, future, exc_type): - self.assertEqual(future.exception[0], str(exc_type)) + self.assertIn(exc_type.__name__, future.exception[0]) def assertNoException(self, future): with self.assertRaises(AttributeError): diff --git a/traits_futures/tests/background_iteration_tests.py b/traits_futures/tests/background_iteration_tests.py index 754740f..bc78e8e 100644 --- a/traits_futures/tests/background_iteration_tests.py +++ b/traits_futures/tests/background_iteration_tests.py @@ -448,7 +448,7 @@ class BackgroundIterationTests: future.result def assertException(self, future, exc_type): - self.assertEqual(future.exception[0], str(exc_type)) + self.assertIn(exc_type.__name__, future.exception[0]) def assertNoException(self, future): with self.assertRaises(AttributeError): diff --git a/traits_futures/tests/background_progress_tests.py b/traits_futures/tests/background_progress_tests.py index 9f8c5a6..9d11bd6 100644 --- a/traits_futures/tests/background_progress_tests.py +++ b/traits_futures/tests/background_progress_tests.py @@ -332,4 +332,4 @@ class BackgroundProgressTests: future.exception def assertException(self, future, exc_type): - self.assertEqual(future.exception[0], str(exc_type)) + self.assertIn(exc_type.__name__, future.exception[0]) diff --git a/traits_futures/tests/test_exception_handling.py b/traits_futures/tests/test_exception_handling.py index 6de33ed..894e4c1 100644 --- a/traits_futures/tests/test_exception_handling.py +++ b/traits_futures/tests/test_exception_handling.py @@ -13,6 +13,10 @@ import unittest from traits_futures.exception_handling import marshal_exception +class CustomException(Exception): + """Custom exception for testing purposes.""" + + class TestExceptionHandling(unittest.TestCase): def test_marshal_exception(self): try: @@ -25,7 +29,7 @@ class TestExceptionHandling(unittest.TestCase): self.assertIsInstance(exc_value, str) self.assertIsInstance(exc_traceback, str) - self.assertEqual(exc_type, str(RuntimeError)) + self.assertEqual(exc_type, "RuntimeError") self.assertIn("something went wrong", exc_value) self.assertIn("test_marshal_exception", exc_traceback) @@ -41,7 +45,7 @@ class TestExceptionHandling(unittest.TestCase): self.assertIsInstance(exc_value, str) self.assertIsInstance(exc_traceback, str) - self.assertEqual(exc_type, str(ValueError)) + self.assertEqual(exc_type, "ValueError") self.assertIn(message, exc_value) self.assertIn("test_marshal_exception", exc_traceback) @@ -59,6 +63,41 @@ class TestExceptionHandling(unittest.TestCase): self.assertIsInstance(exc_value, str) self.assertIsInstance(exc_traceback, str) - self.assertEqual(exc_type, str(RuntimeError)) + self.assertEqual(exc_type, "RuntimeError") self.assertIn("something went wrong", exc_value) self.assertIn("test_marshal_exception", exc_traceback) + + def test_marshal_exception_non_builtin(self): + message = "printer on fire" + try: + raise CustomException(message) + except BaseException as exception: + marshalled = marshal_exception(exception) + + exc_type, exc_value, exc_traceback = marshalled + self.assertIsInstance(exc_type, str) + self.assertIsInstance(exc_value, str) + self.assertIsInstance(exc_traceback, str) + + self.assertEqual( + exc_type, + f"{__name__}.CustomException", + ) + self.assertIn(message, exc_value) + self.assertIn("test_marshal_exception", exc_traceback) + + def test_marshal_exception_nested_exception(self): + class NestedException(Exception): + pass + + try: + raise NestedException() + except BaseException as exception: + marshalled = marshal_exception(exception) + + exc_type, exc_value, exc_traceback = marshalled + self.assertEqual( + exc_type, + f"{__name__}.TestExceptionHandling." + "test_marshal_exception_nested_exception.<locals>.NestedException", + )
Consider using `type.__name__` instead of `str(type)` in `marshal_exception()` Consider using `type.__name__` instead of `str(type)` in `marshal_exception()` for better use of that string. In my opinion, `'ZeroDivisionError'` is more useful than `"<class 'ZeroDivisionError'>"`. https://github.com/enthought/traits-futures/blob/main/traits_futures/exception_handling.py#L22 https://github.com/enthought/traits-futures/blob/839a775285ee0b28be81672734b0f196bfb596c5/traits_futures/exception_handling.py#L17-L25
0.0
[ "traits_futures/tests/test_exception_handling.py::TestExceptionHandling::test_marshal_exception", "traits_futures/tests/test_exception_handling.py::TestExceptionHandling::test_marshal_exception_nested_exception", "traits_futures/tests/test_exception_handling.py::TestExceptionHandling::test_marshal_exception_non_builtin", "traits_futures/tests/test_exception_handling.py::TestExceptionHandling::test_marshal_exception_with_unicode_message", "traits_futures/tests/test_exception_handling.py::TestExceptionHandling::test_marshal_exception_works_outside_except" ]
[]
2021-07-09 13:55:57+00:00
2,179
enthought__traits-futures-449
diff --git a/docs/source/changes.rst b/docs/source/changes.rst index 56404d1..ffabb7b 100644 --- a/docs/source/changes.rst +++ b/docs/source/changes.rst @@ -91,7 +91,7 @@ Fixes queue. Instead, it will fail fast with a ``QueueError`` exception. This situation should never happen in normal use; please report it if you ever witness it. -* The ``ProgressCancelled`` exception used by the background task submitted +* The ``TaskCancelled`` exception used by the background task submitted via ``submit_progress`` is now public, in case that task needs to catch the exception. * The marshal_exception function has been fixed not to rely on the global diff --git a/docs/source/guide/intro.rst b/docs/source/guide/intro.rst index a6a3b76..4d613bf 100644 --- a/docs/source/guide/intro.rst +++ b/docs/source/guide/intro.rst @@ -56,7 +56,7 @@ from |traits_futures.api|: "progress" parameter can then be called to send progress reports to the associated |ProgressFuture| object. If the future has been cancelled, the next call to ``progress`` in the background task will raise a - |ProgressCancelled| exception. + |TaskCancelled| exception. For example, your callable might look like this:: @@ -393,7 +393,7 @@ needed. .. |submit_iteration| replace:: :func:`~traits_futures.background_iteration.submit_iteration` .. |result_event| replace:: :attr:`~traits_futures.background_iteration.IterationFuture.result_event` -.. |ProgressCancelled| replace:: :exc:`~traits_futures.background_progress.ProgressCancelled` +.. |TaskCancelled| replace:: :exc:`~traits_futures.base_future.TaskCancelled` .. |ProgressFuture| replace:: :class:`~traits_futures.background_progress.ProgressFuture` .. |submit_progress| replace:: :func:`~traits_futures.background_progress.submit_progress` .. |progress| replace:: :attr:`~traits_futures.background_progress.ProgressFuture.progress` diff --git a/traits_futures/api.py b/traits_futures/api.py index 914b21b..9d00855 100644 --- a/traits_futures/api.py +++ b/traits_futures/api.py @@ -28,7 +28,6 @@ Task submission functions - :func:`~.submit_call` - :func:`~.submit_iteration` - :func:`~.submit_progress` -- :exc:`~.ProgressCancelled` Types of futures ---------------- @@ -36,6 +35,7 @@ Types of futures - :class:`~.CallFuture` - :class:`~.IterationFuture` - :class:`~.ProgressFuture` +- :exc:`~.TaskCancelled` Future states ------------- @@ -85,12 +85,8 @@ from traits_futures.background_iteration import ( IterationFuture, submit_iteration, ) -from traits_futures.background_progress import ( - ProgressCancelled, - ProgressFuture, - submit_progress, -) -from traits_futures.base_future import BaseFuture, BaseTask +from traits_futures.background_progress import ProgressFuture, submit_progress +from traits_futures.base_future import BaseFuture, BaseTask, TaskCancelled from traits_futures.ets_event_loop import ETSEventLoop from traits_futures.executor_states import ( ExecutorState, @@ -119,7 +115,7 @@ __all__ = [ "CallFuture", "IterationFuture", "ProgressFuture", - "ProgressCancelled", + "TaskCancelled", # Future states "FutureState", "CANCELLED", diff --git a/traits_futures/background_progress.py b/traits_futures/background_progress.py index 774f3c1..73b1dc3 100644 --- a/traits_futures/background_progress.py +++ b/traits_futures/background_progress.py @@ -21,7 +21,7 @@ be cancelled. from traits.api import Callable, Dict, Event, HasStrictTraits, Str, Tuple -from traits_futures.base_future import BaseFuture, BaseTask +from traits_futures.base_future import BaseFuture, BaseTask, TaskCancelled from traits_futures.i_task_specification import ITaskSpecification # Message types for messages from ProgressTask @@ -32,13 +32,6 @@ from traits_futures.i_task_specification import ITaskSpecification PROGRESS = "progress" -class ProgressCancelled(Exception): - """ - Exception raised when progress reporting is interrupted by - task cancellation. - """ - - class ProgressReporter: """ Object used by the target callable to report progress. @@ -63,13 +56,13 @@ class ProgressReporter: Raises ------ - ProgressCancelled + TaskCancelled If a cancellation request for this task has already been made. In this case, the exception will be raised before any progress information is sent. """ if self.cancelled(): - raise ProgressCancelled("Task was cancelled") + raise TaskCancelled("Task was cancelled") self.send(PROGRESS, progress_info) @@ -94,7 +87,7 @@ class ProgressTask(BaseTask): **self.kwargs, progress=progress.report, ) - except ProgressCancelled: + except TaskCancelled: return None diff --git a/traits_futures/base_future.py b/traits_futures/base_future.py index f425aae..578cbc7 100644 --- a/traits_futures/base_future.py +++ b/traits_futures/base_future.py @@ -125,6 +125,12 @@ _CANCELLABLE_INTERNAL_STATES = { } +class TaskCancelled(Exception): + """ + Exception raised within the background task on cancellation. + """ + + class _StateTransitionError(Exception): """ Exception used to indicate a bad state transition.
enthought/traits-futures
965a34e6fb981cf4f06c74ed833ccfc32fbe97be
diff --git a/traits_futures/tests/background_progress_tests.py b/traits_futures/tests/background_progress_tests.py index 99d1fce..a7812bd 100644 --- a/traits_futures/tests/background_progress_tests.py +++ b/traits_futures/tests/background_progress_tests.py @@ -17,9 +17,9 @@ from traits_futures.api import ( EXECUTING, FAILED, FutureState, - ProgressCancelled, ProgressFuture, submit_progress, + TaskCancelled, WAITING, ) @@ -81,7 +81,7 @@ def syncing_progress(test_ready, raised, progress): # so that we never get to the following code. try: progress("second") - except ProgressCancelled: + except TaskCancelled: raised.set() raise diff --git a/traits_futures/tests/test_api.py b/traits_futures/tests/test_api.py index e388319..3474bff 100644 --- a/traits_futures/tests/test_api.py +++ b/traits_futures/tests/test_api.py @@ -33,7 +33,6 @@ class TestApi(unittest.TestCase): IterationFuture, MultiprocessingContext, MultithreadingContext, - ProgressCancelled, ProgressFuture, RUNNING, STOPPED, @@ -41,6 +40,7 @@ class TestApi(unittest.TestCase): submit_call, submit_iteration, submit_progress, + TaskCancelled, TraitsExecutor, WAITING, )
Rename ProgressCancelled exception (related: #437, #317) The `ProgressCancelled` exception is generally useful, and should be renamed to `Cancelled` and moved into `base_future.py`. The renaming would be best done before the 0.3.0 release, since `ProgressCancelled` hasn't yet been made available in any released version of the library.
0.0
[ "traits_futures/tests/test_api.py::TestApi::test___all__", "traits_futures/tests/test_api.py::TestApi::test_imports" ]
[]
2021-07-21 07:32:04+00:00
2,180
enthought__traits-futures-492
diff --git a/docs/source/changes.rst b/docs/source/changes.rst index 674089b..4480ebc 100644 --- a/docs/source/changes.rst +++ b/docs/source/changes.rst @@ -20,6 +20,8 @@ Features * Support Qt6-based toolkits PyQt6 and PySide6. (This is dependent on corresponding support in Pyface.) (#488) +* Allow an ``asyncio`` event loop to be specified when creating an + instance of ``AsyncioEventLoop``. (#492) Changes ~~~~~~~ @@ -28,6 +30,14 @@ Changes entry point group have been removed. Their behaviour was ill-defined, and dependent on ``asyncio.get_event_loop``, which is deprecated in Python. (#490) +* ``AsyncioEventLoop`` now creates a new ``asyncio`` event loop using + ``asyncio.new_event_loop`` if no event loop is explicitly passed in, instead + of trying to get the currently-set event loop using the (now deprecated) + ``asyncio.get_event_loop`` function. A new ``AsyncioEventLoop.close`` method + is available to close the event loop owned by ``AsyncioEventLoop``. + Moreover, in a future version of Traits Futures it will be required to + pass an explicit event loop. Instantiating an ``AsyncioEventLoop`` without + an ``asyncio`` event loop is deprecated. (#492) Documentation ~~~~~~~~~~~~~ diff --git a/docs/source/guide/examples/headless.py b/docs/source/guide/examples/headless.py index ad9b983..136b318 100644 --- a/docs/source/guide/examples/headless.py +++ b/docs/source/guide/examples/headless.py @@ -14,6 +14,7 @@ Running Traits Futures without a GUI, using the asyncio event loop. import asyncio import random +import sys from traits_futures.api import ( AsyncioEventLoop, @@ -47,9 +48,13 @@ async def future_wrapper(traits_future): traits_future = event.object asyncio_future.set_result(traits_future.result) - # Once we can assume a minimum Python version of 3.7, this should - # be changed to use get_running_event_loop instead of get_event_loop. - asyncio_future = asyncio.get_event_loop().create_future() + if sys.version_info < (3, 7): + # We want to use get_running_loop, but it's new in Python 3.7. + # This branch can be dropped once we can assume a minimum Python + # version of 3.7. + asyncio_future = asyncio.get_event_loop().create_future() + else: + asyncio_future = asyncio.get_running_loop().create_future() traits_future.observe(set_result, "done") @@ -64,9 +69,11 @@ def print_progress(event): if __name__ == "__main__": - traits_executor = TraitsExecutor(event_loop=AsyncioEventLoop()) + asyncio_event_loop = asyncio.new_event_loop() + traits_executor = TraitsExecutor( + event_loop=AsyncioEventLoop(event_loop=asyncio_event_loop) + ) traits_future = submit_iteration(traits_executor, approximate_pi) traits_future.observe(print_progress, "result_event") - # For Python 3.7 and later, just use asyncio.run. - asyncio.get_event_loop().run_until_complete(future_wrapper(traits_future)) + asyncio_event_loop.run_until_complete(future_wrapper(traits_future)) diff --git a/traits_futures/asyncio/event_loop.py b/traits_futures/asyncio/event_loop.py index ee2f981..3830d7e 100644 --- a/traits_futures/asyncio/event_loop.py +++ b/traits_futures/asyncio/event_loop.py @@ -9,9 +9,10 @@ # Thanks for using Enthought open source! """ -IEventLoop implementation for the main-thread asyncio event loop. +IEventLoop implementation wrapping an asyncio event loop. """ import asyncio +import warnings from traits_futures.asyncio.event_loop_helper import EventLoopHelper from traits_futures.asyncio.pingee import Pingee @@ -21,11 +22,36 @@ from traits_futures.i_event_loop import IEventLoop @IEventLoop.register class AsyncioEventLoop: """ - IEventLoop implementation for the main-thread asyncio event loop. + IEventLoop implementation wrapping an asyncio event loop. + + Parameters + ---------- + event_loop : asyncio.AbstractEventLoop, optional + The asyncio event loop to wrap. If not provided, a new + event loop will be created and used. """ - def __init__(self): - self._event_loop = asyncio.get_event_loop() + def __init__(self, *, event_loop=None): + own_event_loop = event_loop is None + if own_event_loop: + warnings.warn( + ( + "The event_loop parameter to AsyncioEventLoop will " + "become required in a future version of Traits Futures" + ), + DeprecationWarning, + ) + event_loop = asyncio.new_event_loop() + + self._own_event_loop = own_event_loop + self._event_loop = event_loop + + def close(self): + """ + Free any resources allocated by this object. + """ + if self._own_event_loop: + self._event_loop.close() def pingee(self, on_ping): """
enthought/traits-futures
b4a837bbb02d3ed80b4c5c12a61983084021620d
diff --git a/traits_futures/asyncio/tests/test_asyncio_event_loop.py b/traits_futures/asyncio/tests/test_asyncio_event_loop.py index 03f8468..8265ed8 100644 --- a/traits_futures/asyncio/tests/test_asyncio_event_loop.py +++ b/traits_futures/asyncio/tests/test_asyncio_event_loop.py @@ -12,7 +12,7 @@ Tests for the asyncio event loop. """ - +import asyncio import unittest from traits_futures.asyncio.event_loop import AsyncioEventLoop @@ -20,6 +20,35 @@ from traits_futures.tests.i_event_loop_tests import IEventLoopTests class TestAsyncioEventLoop(IEventLoopTests, unittest.TestCase): + def event_loop_factory(self): + """ + Factory for the event loop. + + Returns + ------- + event_loop: IEventLoop + """ + asyncio_event_loop = asyncio.new_event_loop() + self.addCleanup(asyncio_event_loop.close) + return AsyncioEventLoop(event_loop=asyncio_event_loop) + + def test_asyncio_event_loop_closed(self): + with self.assertWarns(DeprecationWarning): + event_loop = AsyncioEventLoop() + # Dig out the underlying asyncio event loop. + asyncio_event_loop = event_loop._event_loop + self.assertFalse(asyncio_event_loop.is_closed()) + event_loop.close() + self.assertTrue(asyncio_event_loop.is_closed()) - #: Factory for instances of the event loop. - event_loop_factory = AsyncioEventLoop + def test_creation_from_asyncio_event_loop(self): + asyncio_event_loop = asyncio.new_event_loop() + event_loop = AsyncioEventLoop(event_loop=asyncio_event_loop) + self.assertEqual(event_loop._event_loop, asyncio_event_loop) + try: + self.assertFalse(asyncio_event_loop.is_closed()) + # Closing our wrapper shouldn't close the asyncio event loop. + event_loop.close() + self.assertFalse(asyncio_event_loop.is_closed()) + finally: + asyncio_event_loop.close() diff --git a/traits_futures/asyncio/tests/test_event_loop_helper.py b/traits_futures/asyncio/tests/test_event_loop_helper.py index 5c5e3d3..3525223 100644 --- a/traits_futures/asyncio/tests/test_event_loop_helper.py +++ b/traits_futures/asyncio/tests/test_event_loop_helper.py @@ -12,6 +12,7 @@ Tests for the asyncio implementation of IEventLoopHelper. """ +import asyncio import unittest from traits_futures.asyncio.event_loop import AsyncioEventLoop @@ -21,6 +22,14 @@ from traits_futures.tests.i_event_loop_helper_tests import ( class TestEventLoopHelper(IEventLoopHelperTests, unittest.TestCase): + def event_loop_factory(self): + """ + Factory for the event loop. - #: Zero-parameter callable that creates a suitable IEventLoop instance. - event_loop_factory = AsyncioEventLoop + Returns + ------- + event_loop: IEventLoop + """ + asyncio_event_loop = asyncio.new_event_loop() + self.addCleanup(asyncio_event_loop.close) + return AsyncioEventLoop(event_loop=asyncio_event_loop) diff --git a/traits_futures/asyncio/tests/test_pingee.py b/traits_futures/asyncio/tests/test_pingee.py index bdfd3cf..302cdb1 100644 --- a/traits_futures/asyncio/tests/test_pingee.py +++ b/traits_futures/asyncio/tests/test_pingee.py @@ -12,6 +12,7 @@ Tests for the asyncio implementations of IPingee and IPinger. """ +import asyncio import unittest from traits_futures.asyncio.event_loop import AsyncioEventLoop @@ -20,5 +21,14 @@ from traits_futures.tests.i_pingee_tests import IPingeeTests class TestPingee(TestAssistant, IPingeeTests, unittest.TestCase): + def event_loop_factory(self): + """ + Factory for the event loop. - event_loop_factory = AsyncioEventLoop + Returns + ------- + event_loop: IEventLoop + """ + asyncio_event_loop = asyncio.new_event_loop() + self.addCleanup(asyncio_event_loop.close) + return AsyncioEventLoop(event_loop=asyncio_event_loop) diff --git a/traits_futures/testing/test_assistant.py b/traits_futures/testing/test_assistant.py index 97495c5..06af3d4 100644 --- a/traits_futures/testing/test_assistant.py +++ b/traits_futures/testing/test_assistant.py @@ -13,6 +13,8 @@ Test support, providing the ability to run the event loop from within tests. """ +import asyncio + from traits.api import Bool, HasStrictTraits from traits_futures.asyncio.event_loop import AsyncioEventLoop @@ -44,10 +46,17 @@ class TestAssistant: Most of the logic is devolved to a toolkit-specific EventLoopHelper class. """ - #: Factory for the event loop. This should be a zero-argument callable - #: that provides an IEventLoop instance. Override in subclasses to - #: run tests with a particular toolkit. - event_loop_factory = AsyncioEventLoop + def event_loop_factory(self): + """ + Factory for the event loop. + + Returns + ------- + event_loop: IEventLoop + """ + asyncio_event_loop = asyncio.new_event_loop() + self.addCleanup(asyncio_event_loop.close) + return AsyncioEventLoop(event_loop=asyncio_event_loop) def setUp(self): self._event_loop = self.event_loop_factory()
Allow event_loop to be specified when creating AsyncioContext Currently the `AsyncioContext` uses `asyncio.get_event_loop` to get the event loop to use. Instead, it should be possible to pass in an event loop (and use `asyncio.get_event_loop` as a fallback if no event loop is specified). This would also allow us to go back to avoiding test interactions via the event loop (see #330), but in a cleaner way than before: we can create a dedicated event loop for each test and avoid touching the global state at all - we wouldn't use `set_event_loop` to set the event loop associated to the thread.
0.0
[ "traits_futures/asyncio/tests/test_asyncio_event_loop.py::TestAsyncioEventLoop::test_asyncio_event_loop_closed", "traits_futures/asyncio/tests/test_asyncio_event_loop.py::TestAsyncioEventLoop::test_creation_from_asyncio_event_loop", "traits_futures/asyncio/tests/test_asyncio_event_loop.py::TestAsyncioEventLoop::test_event_loop_helper", "traits_futures/asyncio/tests/test_asyncio_event_loop.py::TestAsyncioEventLoop::test_implements_i_event_loop", "traits_futures/asyncio/tests/test_asyncio_event_loop.py::TestAsyncioEventLoop::test_pingee", "traits_futures/asyncio/tests/test_event_loop_helper.py::TestEventLoopHelper::test_instance_of_i_event_loop_helper", "traits_futures/asyncio/tests/test_event_loop_helper.py::TestEventLoopHelper::test_run_until_when_condition_already_true", "traits_futures/asyncio/tests/test_event_loop_helper.py::TestEventLoopHelper::test_run_until_when_condition_becomes_true", "traits_futures/asyncio/tests/test_event_loop_helper.py::TestEventLoopHelper::test_run_until_when_condition_never_true", "traits_futures/asyncio/tests/test_event_loop_helper.py::TestEventLoopHelper::test_run_until_with_nontrivial_condition", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_background_threads_finish_before_event_loop_starts", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_disconnect_removes_callback_reference", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_multiple_background_pingers", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_multiple_background_pings", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_multiple_pingees", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_ping_after_pingee_closed", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_pinger_disconnect_removes_pingee_reference", "traits_futures/asyncio/tests/test_pingee.py::TestPingee::test_single_background_ping" ]
[]
2021-12-16 16:13:17+00:00
2,181
epikulski__digitalarchive-29
diff --git a/digitalarchive/exceptions.py b/digitalarchive/exceptions.py index 8f0f3da..94f222d 100644 --- a/digitalarchive/exceptions.py +++ b/digitalarchive/exceptions.py @@ -14,3 +14,6 @@ class NoSuchResourceError(Exception): class APIServerError(Exception): """DA API returned a non-200 code for attempted operation.""" + +class MalformedLanguageSearch(InvalidSearchFieldError): + """User passed a langauge search term that was not an instance of models.Language or an ISO 639-2/B string.""" diff --git a/digitalarchive/models.py b/digitalarchive/models.py index d887150..bb8a4b7 100644 --- a/digitalarchive/models.py +++ b/digitalarchive/models.py @@ -663,7 +663,8 @@ class Document(_MatchableResource, _HydrateableResource, _TimestampedResource): authors include all of the passed contributors. donors (list(:class:`digitalarchive.models.Donor`)) Restrict results to Documents who were obtained or translated with support from all of the passed donors. - language (:class:`digitalarchive.models.Language`) Restrict results to Documents by original language. + languages (:class:`digitalarchive.models.Language` or str) Restrict results to Documents by language of + original document. If passing a string, you must pass an ISO 639-2/B language code. translation (:class:`digitalarchive.models.Translation`) Restrict results to Documents for which there is a translation available in the passed Language. theme (:class:`digitalarchive.models.Theme`) Restrict results to Documents belonging to the passed Theme. @@ -693,6 +694,10 @@ class Document(_MatchableResource, _HydrateableResource, _TimestampedResource): if any(key in kwargs.keys() for key in ["start_date", "end_date"]): kwargs = Document._process_date_searches(kwargs) + # Process language searches if they are present. + if "languages" in kwargs.keys(): + kwargs = Document._process_language_search(kwargs) + # Process any related model searches. if any( key in kwargs.keys() @@ -896,6 +901,35 @@ class Document(_MatchableResource, _HydrateableResource, _TimestampedResource): # Return the reformatted query. return query + @staticmethod + def _process_language_search(query: dict) -> dict: + """ + Process a language search + + Looks up the DA's language ID# for user provided ISO 639-2/B language codes and updates the query. + + Args: + query (dict): A ResourceMatcher query. + + Returns: + dict: A query dict with a ISO 639-2/B string replaced with appropriate Language object. + """ + parsed_languages = [] + for language in query["languages"]: + # Check if ID# is instance of language, bail on yes. + if isinstance(language, Language): + parsed_languages.append(language) + + # If str, lookup ID# of language + elif isinstance(language, str) and len(language) == 3: + parsed_languages.append(Language(id=language)) + + else: + raise exceptions.MalformedLanguageSearch + + # Replace kwarg with Langauge object. + query["languages"] = parsed_languages + return query @dataclass(eq=False) class Theme(_HydrateableResource):
epikulski/digitalarchive
79b1fade4d73015969d4496b82fab4ed8796358d
diff --git a/tests/integration/test_models.py b/tests/integration/test_models.py index 144d889..8ae297a 100644 --- a/tests/integration/test_models.py +++ b/tests/integration/test_models.py @@ -260,6 +260,12 @@ class TestDocument: for doc in docs.all(): assert language in doc.languages + def test_search_by_language_by_iso_code(self): + all_docs = digitalarchive.Document.match() + german_docs = digitalarchive.Document.match(languages=["ger"]) + assert german_docs.count > 0 + assert german_docs.count < all_docs.count + def test_search_by_translation(self): language = digitalarchive.models.Language(id="chi") docs = digitalarchive.Document.match(translations=[language]) diff --git a/tests/unit/test_models.py b/tests/unit/test_models.py index c943d72..fb84a01 100644 --- a/tests/unit/test_models.py +++ b/tests/unit/test_models.py @@ -192,6 +192,10 @@ class TestDocument: # mock_matching.assert_called_with(models.Document, collection[]= mock_collections, model="Record"}) assert "collection[]" in mock_matching.call_args[1].keys() + def test_invalid_language_search(self): + with pytest.raises(exceptions.MalformedLanguageSearch): + models.Document.match(languages=["invalid"]) + @unittest.mock.patch("digitalarchive.models.api") def test_process_date_search_only_end_date(self, mock_api): test_date = date(1989, 4, 15)
Accept ISO 639-3 language codes when searching for documents by language Currently, users must pass an entire language object to limit searches by language. Adding the ability to simply pass a 639-3 language string would make searches easier.
0.0
[ "tests/unit/test_models.py::TestDocument::test_invalid_language_search" ]
[ "tests/unit/test_models.py::TestMatchableResource::test_match_name", "tests/unit/test_models.py::TestMatchableResource::test_match_value", "tests/unit/test_models.py::TestMatchableResource::test_match_handle_term_and_name", "tests/unit/test_models.py::TestHydrateableResource::test_pull", "tests/unit/test_models.py::TestHydrateableResource::test_hydrate", "tests/unit/test_models.py::TestCollection::test_match", "tests/unit/test_models.py::TestCollection::test_datetime_parsing", "tests/unit/test_models.py::TestDocument::test_match", "tests/unit/test_models.py::TestDocument::test_match_date_search_handling", "tests/unit/test_models.py::TestDocument::test_match_q_field_construction", "tests/unit/test_models.py::TestDocument::test_related_model_searches", "tests/unit/test_models.py::TestDocument::test_process_date_search_only_end_date", "tests/unit/test_models.py::TestDocument::test_valid_eq", "tests/unit/test_models.py::TestDocument::test_invalid_eq", "tests/unit/test_models.py::TestDocument::test_invalid_eq_class", "tests/unit/test_models.py::TestDocument::test_hash", "tests/unit/test_models.py::TestDocument::test_date_parsing", "tests/unit/test_models.py::TestDocument::test_hydrate", "tests/unit/test_models.py::TestDocument::test_hydrate_recursive", "tests/unit/test_models.py::TestDocument::test_parse_child_records", "tests/unit/test_models.py::TestDocument::test_parse_child_records_empty", "tests/unit/test_models.py::TestDocument::test_process_related_model_searches_languages", "tests/unit/test_models.py::TestDocument::test_match_invalid_field", "tests/unit/test_models.py::TestDocument::test_process_date_search_invalid_date_str", "tests/unit/test_models.py::TestDocument::test_process_date_search_invalid_date_obj", "tests/unit/test_models.py::TestDocument::test_process_related_model_searches_too_many_params", "tests/unit/test_models.py::TestAsset::test_init", "tests/unit/test_models.py::TestTranscript::test_hydrate", "tests/unit/test_models.py::TestTranscript::test_hydrate_html", "tests/unit/test_models.py::TestTranscript::test_hydrate_pdf", "tests/unit/test_models.py::TestTranscript::test_hydrate_bad_extension", "tests/unit/test_models.py::TestTranscript::test_hydrate_server_error", "tests/unit/test_models.py::TestTranslation::test_init", "tests/unit/test_models.py::TestMediaFile::test_init", "tests/unit/test_models.py::TestCoverage::test_init_no_parent", "tests/unit/test_models.py::TestCoverage::test_init_parent_parsing", "tests/unit/test_models.py::TestCoverage::test_init_children_parsing", "tests/unit/test_models.py::TestTheme::test_init_collections", "tests/unit/test_models.py::TestTheme::test_pull" ]
2019-11-12 23:42:47+00:00
2,182
epogrebnyak__weo-reader-12
diff --git a/weo/dataframe.py b/weo/dataframe.py index 2715367..5fed1c7 100644 --- a/weo/dataframe.py +++ b/weo/dataframe.py @@ -29,8 +29,11 @@ def convert(x): return np.nan -def read_csv(filename): +def read_csv(filename): # October 2020 and later files use UTF-16 LE encoding df = pd.read_csv(filename, delimiter="\t", encoding="iso-8859-1") + if df.isnull().iloc[0, 0]: + df = pd.read_csv(filename, delimiter="\t", encoding="UTF-16 LE") + df.dropna(how="all", axis=1, inplace=True) ix = df["Country"].isna() return df[~ix], df[ix] @@ -58,7 +61,7 @@ def accept_year(func): # FIXME: make accept a country if arg: year = arg[0] if year: - ts = df[str(year)].transpose().iloc[:, 0] + ts = df.transpose()[str(year)] return ts else: return df @@ -325,7 +328,7 @@ class WEO: if year is None: return _df else: - _df = _df[str(year)].transpose() + _df = _df.transpose()[str(year)] _df["Description"] = _df.index.map(lambda c: " - ".join(self.from_code(c))) return _df diff --git a/weo/download.py b/weo/download.py index 471a55e..c854b22 100644 --- a/weo/download.py +++ b/weo/download.py @@ -1,11 +1,11 @@ """Download dataset from IMF WEO website. from weo import download - download("2019-Oct', 'weo.csv') + download("2020-Oct', 'weo.csv') Equivalent to: - curl -o weo.csv https://www.imf.org/external/pubs/ft/weo/2019/02/weodata/WEOOct2019all.xls + curl -o weo.csv https://www.imf.org/-/media/Files/Publications/WEO/WEO-Database/2020/02/WEOOct2020all.xls """ @@ -48,15 +48,23 @@ def make_url(r, prefix): Data in other formats goes back to 2000. Landing page with URLs: - https://www.imf.org/external/pubs/ft/weo/2011/02/weodata/download.aspx + https://www.imf.org/en/Publications/SPROLLs/world-economic-outlook-databases """ + + base_url = "https://www.imf.org/-/media/Files/Publications/WEO/WEO-Database" + year = r.year month = r.month_string() period_marker = r.period_string() - return ( - "https://www.imf.org/external/pubs/ft/weo/" - f"{year}/{period_marker}" - f"/weodata/WEO{month}{year}{prefix}.xls" + + if year > 2020 or (year == 2020 and month == "Oct"): # New URL format + return ( + f"{base_url}/{year}/{period_marker}" + f"/WEO{month}{year}{prefix}.xls" + ) + return ( # Old URL format + f"{base_url}/{year}" + f"/WEO{month}{year}{prefix}.xls" )
epogrebnyak/weo-reader
dfe8fa0b55adea01c523a08e414b333098d3fb53
diff --git a/tests/test_weo_dates.py b/tests/test_weo_dates.py index 9cc2679..acd740f 100644 --- a/tests/test_weo_dates.py +++ b/tests/test_weo_dates.py @@ -4,7 +4,7 @@ from weo import dates, all_dates def test_dates(): assert dates(2007) == ["2007-Oct"] assert dates(2011) == ["2011-Apr", "2011-Sep"] - assert dates(2020) == ["2020-Apr"] + assert dates(2020) == ["2020-Apr", "2020-Oct"] def test_all_dates(): diff --git a/tests/test_weo_download.py b/tests/test_weo_download.py index f5ac762..5af1f78 100644 --- a/tests/test_weo_download.py +++ b/tests/test_weo_download.py @@ -16,14 +16,14 @@ def test_from_date_fails(): def test_make_countries_url(): assert ( make_url_countries(from_date("2020-04")) - == "https://www.imf.org/external/pubs/ft/weo/2020/01/weodata/WEOApr2020all.xls" + == "https://www.imf.org/-/media/Files/Publications/WEO/WEO-Database/2020/WEOApr2020all.xls" ) def test_url_september(): assert ( make_url_countries(from_date("2011-Sep")) - == "https://www.imf.org/external/pubs/ft/weo/2011/02/weodata/WEOSep2011all.xls" + == "https://www.imf.org/-/media/Files/Publications/WEO/WEO-Database/2011/WEOSep2011all.xls" )
doesn't work for 2020-October database weo package doesn't seem to work for 2020-October database. running this code: ``` from weo import download from weo import WEO download("2020-Oct", path='weo.csv', overwrite=True) w = WEO("weo.csv") ``` gives the following error: --------------------------------------------------------------------------- ParserError Traceback (most recent call last) <ipython-input-14-90829dcd1cb0> in <module> ----> 1 w = WEO("weo.csv") ~/.local/lib/python3.7/site-packages/weo/dataframe.py in __init__(self, filename) 111 112 def __init__(self, filename): --> 113 self.df, _ = read_csv(filename) 114 115 @property ~/.local/lib/python3.7/site-packages/weo/dataframe.py in read_csv(filename) 31 32 def read_csv(filename): ---> 33 df = pd.read_csv(filename, delimiter="\t", encoding="iso-8859-1") 34 ix = df["Country"].isna() 35 return df[~ix], df[ix] ~/.local/lib/python3.7/site-packages/pandas/io/parsers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision) 686 ) 687 --> 688 return _read(filepath_or_buffer, kwds) 689 690 ~/.local/lib/python3.7/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds) 458 459 try: --> 460 data = parser.read(nrows) 461 finally: 462 parser.close() ~/.local/lib/python3.7/site-packages/pandas/io/parsers.py in read(self, nrows) 1196 def read(self, nrows=None): 1197 nrows = _validate_integer("nrows", nrows) -> 1198 ret = self._engine.read(nrows) 1199 1200 # May alter columns / col_dict ~/.local/lib/python3.7/site-packages/pandas/io/parsers.py in read(self, nrows) 2155 def read(self, nrows=None): 2156 try: -> 2157 data = self._reader.read(nrows) 2158 except StopIteration: 2159 if self._first_chunk: pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows() pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error() ParserError: Error tokenizing data. C error: Expected 1 fields in line 48, saw 2
0.0
[ "tests/test_weo_download.py::test_make_countries_url", "tests/test_weo_download.py::test_url_september" ]
[ "tests/test_weo_dates.py::test_dates", "tests/test_weo_dates.py::test_all_dates", "tests/test_weo_download.py::test_from_date", "tests/test_weo_download.py::test_from_date_fails", "tests/test_weo_download.py::test_download_raises_on_wrong_year", "tests/test_weo_download.py::test_download_raises_on_wrong_period" ]
2021-01-03 05:17:33+00:00
2,183
equinor__webviz-config-275
diff --git a/CHANGELOG.md b/CHANGELOG.md index a50fc8c..46eed1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] - YYYY-MM-DD ### Added - [#269](https://github.com/equinor/webviz-config/pull/269) - Added an optional argument `screenshot_filename` to `WebvizPluginABC`. Can be used to let plugin authors specify filename used when screenshots of the plugin are saved. +- [#275](https://github.com/equinor/webviz-config/pull/275) - Indented docstrings are now supported by `webviz docs`. ## [0.1.0] - 2020-08-24 ### Added diff --git a/webviz_config/_docs/_build_docs.py b/webviz_config/_docs/_build_docs.py index 93e3050..541d5ea 100644 --- a/webviz_config/_docs/_build_docs.py +++ b/webviz_config/_docs/_build_docs.py @@ -16,7 +16,7 @@ import inspect import pathlib from importlib import import_module from collections import defaultdict -from typing import Any, Dict, Optional, Tuple +from typing import Any, Dict, Optional, Tuple, List import pkg_resources import jinja2 @@ -52,7 +52,7 @@ def _document_plugin(plugin: Tuple[str, Any]) -> PluginInfo: name, reference = plugin docstring = reference.__doc__ if reference.__doc__ is not None else "" - docstring_parts = docstring.strip().split("\n---\n") + docstring_parts = _split_docstring(docstring) argspec = inspect.getfullargspec(reference.__init__) module = inspect.getmodule(reference) subpackage = inspect.getmodule(module).__package__ # type: ignore @@ -162,3 +162,20 @@ def build_docs(build_directory: pathlib.Path) -> None: (build_directory / "sidebar.md").write_text( template.render({"packages": plugin_documentation.keys()}) ) + + +def _split_docstring(docstring: str) -> List[str]: + """Divides docstring by splitting on ---, also unindents + first in case of indented docstrings (similar to this one) + """ + lines = docstring.strip().split("\n") + + try: + indent_spaces = min( + [len(line) - len(line.lstrip()) for line in lines[1:] if line.strip() != ""] + ) + except ValueError: # In the case of no original newline (\n) + indent_spaces = 0 + + unindented_lines = [lines[0]] + [line[indent_spaces:] for line in lines[1:]] + return "\n".join(unindented_lines).split("\n---\n") diff --git a/webviz_config/plugins/_markdown.py b/webviz_config/plugins/_markdown.py index 7fb0998..efcee81 100644 --- a/webviz_config/plugins/_markdown.py +++ b/webviz_config/plugins/_markdown.py @@ -93,12 +93,12 @@ class Markdown(WebvizPluginABC): Images are supported, and should in the markdown file be given as either relative paths to the markdown file itself, or as absolute paths. -> The markdown syntax for images has been extended to support \ -providing width and/or height for individual images (optional). \ -To specify the dimensions write e.g. -> ```markdown -> ![width=40%,height=300px](./example_banner.png "Some caption") -> ``` + > The markdown syntax for images has been extended to support \ + providing width and/or height for individual images (optional). \ + To specify the dimensions write e.g. + > ```markdown + > ![width=40%,height=300px](./example_banner.png "Some caption") + > ``` """
equinor/webviz-config
3aa0e6d26886020655aa385f8040c6318bb73678
diff --git a/tests/test_docstring.py b/tests/test_docstring.py new file mode 100644 index 0000000..399bccc --- /dev/null +++ b/tests/test_docstring.py @@ -0,0 +1,76 @@ +from webviz_config._docs._build_docs import _split_docstring + + +def test_split_docstring(): + tests = [ + ( + "This is a test with only description.", + ["This is a test with only description."], + ), + ( + ( + " This is a test with only description, " + "but which has leading and trailing spaces. " + ), + [ + ( + "This is a test with only description, " + "but which has leading and trailing spaces." + ) + ], + ), + ( + "Test with some newlines\n\n \n and a 4 space indent", + ["Test with some newlines\n\n\nand a 4 space indent"], + ), + ( + "Test with a \n 4 space and a \n 2 space indent\n", + ["Test with a \n 4 space and a \n2 space indent"], + ), + ( + "Test with a \n 4 space and a \n 2 space indent\n", + ["Test with a \n 4 space and a \n2 space indent"], + ), + ( + ( + " This is a test with description, arguments and data input." + "\n\n ---\n\n The docstring is indented by 4 spaces:\n " + "* The argument list has a sub list indented by 8 spaces\n like this." + "\n ---\n The data input section is not very interesting." + ), + [ + "This is a test with description, arguments and data input.\n", + ( + "\nThe docstring is indented by 4 spaces:\n" + "* The argument list has a sub list indented by 8 spaces\n like this." + ), + "The data input section is not very interesting.", + ], + ), + ( + ( + "\tThis is a test with description, arguments and data input," + " where indents are made with tabs and not spaces-" + "\n\n\t---\n\n\tThe docstring is indented by 1 tab:\n" + "\t* The argument list has a sub list indented by 2 tabs\n\t\tlike this." + "\n\t---\n\tThe data input section is not very interesting." + ), + [ + ( + "This is a test with description, arguments and data input," + " where indents are made with tabs and not spaces-\n" + ), + ( + "\nThe docstring is indented by 1 tab:\n" + "* The argument list has a sub list indented by 2 tabs\n\tlike this." + ), + "The data input section is not very interesting.", + ], + ), + ( + "This is a test with only description, which includes a linebreak.\n", + ["This is a test with only description, which includes a linebreak."], + ), + ] + for test in tests: + assert _split_docstring(test[0]) == test[1]
Generated documentation does not support indented docstrings If the docstring is indented, like ```python class Markdown(WebvizPluginABC): """Renders and includes the content from a Markdown file. --- * **`markdown_file`:** Path to the markdown file to render and include. \ Either absolute path or relative to the configuration file. --- Images are supported, and should in the markdown file be given as either relative paths to the markdown file itself, or as absolute paths. > The markdown syntax for images has been extended to support \ providing width and/or height for individual images (optional). \ To specify the dimensions write e.g. > ```markdown > ![width=40%,height=300px](./example_banner.png "Some caption") > ``` """ ``` the "special section" with `>` is not rendered correctly. Some plugins might want to consistently indent docstring lines. Remove all "consistent" indentation in docstring lines before giving it further to the documentation machinery?
0.0
[ "tests/test_docstring.py::test_split_docstring" ]
[]
2020-08-28 13:22:12+00:00
2,184
equinor__webviz-config-333
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0faa365..7b43905 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#337](https://github.com/equinor/webviz-config/pull/337) - New generic plugin to generate a [Pivot table](https://en.wikipedia.org/wiki/Pivot_table) based on [Dash Pivottable](https://github.com/plotly/dash-pivottable). +- [#333](https://github.com/equinor/webviz-config/pull/333) - Warning is now raised +if more than one plugin project provides a plugin with the same name. ## [0.2.2] - 2020-11-16 diff --git a/webviz_config/plugins/__init__.py b/webviz_config/plugins/__init__.py index fd3a4af..b22bb5d 100644 --- a/webviz_config/plugins/__init__.py +++ b/webviz_config/plugins/__init__.py @@ -2,45 +2,16 @@ the utility itself. """ -import inspect from typing import Optional try: # Python 3.8+ - # pylint: disable=ungrouped-imports from importlib.metadata import distributions # type: ignore - from typing import TypedDict # type: ignore except ModuleNotFoundError: # Python < 3.8 from importlib_metadata import distributions # type: ignore - from typing_extensions import TypedDict # type: ignore +from ._utils import load_webviz_plugins_with_metadata, PluginDistInfo -class PluginDistInfo(TypedDict): - dist_name: str - dist_version: str - documentation_url: Optional[str] - download_url: Optional[str] - issue_url: Optional[str] - -metadata = {} - -for dist in distributions(): - for entry_point in dist.entry_points: - if entry_point.group == "webviz_config_plugins": - project_urls = { - value.split(",")[0]: value.split(",")[1].strip() - for (key, value) in dist.metadata.items() - if key == "Project-URL" - } - - metadata[entry_point.name] = { - "dist_name": dist.metadata["name"], - "dist_version": dist.version, - "documentation_url": project_urls.get("Documentation"), - "download_url": project_urls.get("Download"), - "tracker_url": project_urls.get("Tracker"), - } - - globals()[entry_point.name] = entry_point.load() +metadata = load_webviz_plugins_with_metadata(distributions(), globals()) diff --git a/webviz_config/plugins/_utils.py b/webviz_config/plugins/_utils.py new file mode 100644 index 0000000..fbb19bf --- /dev/null +++ b/webviz_config/plugins/_utils.py @@ -0,0 +1,59 @@ +import warnings +from typing import Any, Dict, Iterable, Optional + +try: + # Python 3.8+ + # pylint: disable=ungrouped-imports + from typing import TypedDict # type: ignore +except ImportError: + # Python < 3.8 + from typing_extensions import TypedDict # type: ignore + + +class PluginDistInfo(TypedDict): + dist_name: str + dist_version: str + documentation_url: Optional[str] + download_url: Optional[str] + tracker_url: Optional[str] + + +def load_webviz_plugins_with_metadata( + distributions: Iterable, loaded_plugins: Dict[str, Any] +) -> Dict[str, PluginDistInfo]: + """Loads the given distributions, finds entry points corresponding to webviz-config + plugins, and put them into the mutable input dictionary loaded_plugins + (key is plugin name string, value is reference to plugin class). + Also returns a dictionary of plugin metadata. + """ + + metadata: Dict[str, PluginDistInfo] = {} + + for dist in distributions: + for entry_point in dist.entry_points: + if entry_point.group == "webviz_config_plugins": + project_urls = { + value.split(",")[0]: value.split(",")[1].strip() + for (key, value) in dist.metadata.items() + if key == "Project-URL" + } + + if entry_point.name in metadata: + warnings.warn( + f"Multiple versions of plugin with name {entry_point.name}. " + f"Already loaded from project {metadata[entry_point.name]['dist_name']}. " + f"Overwriting using plugin with from project {dist.metadata['name']}", + RuntimeWarning, + ) + + metadata[entry_point.name] = { + "dist_name": dist.metadata["name"], + "dist_version": dist.version, + "documentation_url": project_urls.get("Documentation"), + "download_url": project_urls.get("Download"), + "tracker_url": project_urls.get("Tracker"), + } + + loaded_plugins[entry_point.name] = entry_point.load() + + return metadata
equinor/webviz-config
8011920d7c56042c8e5653bb27aa95ce077063b6
diff --git a/tests/test_plugin_init.py b/tests/test_plugin_init.py new file mode 100644 index 0000000..011df9a --- /dev/null +++ b/tests/test_plugin_init.py @@ -0,0 +1,60 @@ +import warnings + +import mock + +from webviz_config.plugins._utils import load_webviz_plugins_with_metadata + + +class DistMock: + # pylint: disable=too-few-public-methods + def __init__(self, entry_points, name): + self.metadata = {"name": name} + + self.entry_points = entry_points + self.version = "123" + + +plugin_entrypoint_mock1 = mock.Mock() +plugin_entrypoint_mock1.group = "webviz_config_plugins" +plugin_entrypoint_mock1.name = "SomePlugin1" + +plugin_entrypoint_mock2 = mock.Mock() +plugin_entrypoint_mock2.group = "webviz_config_plugins" +plugin_entrypoint_mock2.name = "SomePlugin2" + +dist_mock1 = DistMock([plugin_entrypoint_mock1], "dist_mock1") +dist_mock2 = DistMock([plugin_entrypoint_mock1], "dist_mock2") +dist_mock3 = DistMock([plugin_entrypoint_mock2], "dist_mock3") + + +def test_no_warning(): + globals_mock = {} + with warnings.catch_warnings(record=True) as warn: + metadata = load_webviz_plugins_with_metadata( + [dist_mock1, dist_mock3], globals_mock + ) + assert len(warn) == 0, "Too many warnings" + + assert len(metadata) == 2, "Wrong number of items in metadata" + assert "SomePlugin1" in globals_mock + assert "SomePlugin2" in globals_mock + + +def test_warning_multiple(): + globals_mock = {} + with warnings.catch_warnings(record=True) as warn: + metadata = load_webviz_plugins_with_metadata( + [dist_mock1, dist_mock2], globals_mock + ) + + assert len(warn) == 1 + assert issubclass(warn[-1].category, RuntimeWarning) + assert str(warn[-1].message) == ( + "Multiple versions of plugin with name SomePlugin1. " + "Already loaded from project dist_mock1. " + "Overwriting using plugin with from project dist_mock2" + ) + + assert len(metadata) == 1, "Wrong number of items in metadata" + assert metadata["SomePlugin1"]["dist_name"] == "dist_mock2", "Wrong dist name" + assert "SomePlugin1" in globals_mock
Raise a warning if multiple plugins exist with same name Since we are a plugin framework, there might be plugin projects creating plugins with the same name. Raise a warning during runtime to give attention to name conflict. This could be done in https://github.com/equinor/webviz-config/blob/623ab6fbabf85dd658be1d668d9f6e216939fdd2/webviz_config/plugins/__init__.py#L37-L39 by simply checking if a plugin with name is already in `__all__`. The warning should probably include package name of both plugins in order to make it easy for the user to understand where they come from (one way of getting package name from the plugin reference is to use `inspect` from std.lib).
0.0
[ "tests/test_plugin_init.py::test_no_warning", "tests/test_plugin_init.py::test_warning_multiple" ]
[]
2020-10-23 14:01:36+00:00
2,185
equinor__webviz-config-626
diff --git a/webviz_config/generic_plugins/_example_wlf_plugin/_shared_settings/_shared_settings.py b/webviz_config/generic_plugins/_example_wlf_plugin/_shared_settings/_shared_settings.py index c0bb990..b497bde 100644 --- a/webviz_config/generic_plugins/_example_wlf_plugin/_shared_settings/_shared_settings.py +++ b/webviz_config/generic_plugins/_example_wlf_plugin/_shared_settings/_shared_settings.py @@ -52,7 +52,7 @@ class SharedSettingsGroup(SettingsGroupABC): "value": 3, }, ], - value="2", + value=2, ), ] ) diff --git a/webviz_config/generic_plugins/_example_wlf_plugin/_views/_plot/_view.py b/webviz_config/generic_plugins/_example_wlf_plugin/_views/_plot/_view.py index d286f0d..aea5033 100644 --- a/webviz_config/generic_plugins/_example_wlf_plugin/_views/_plot/_view.py +++ b/webviz_config/generic_plugins/_example_wlf_plugin/_views/_plot/_view.py @@ -16,10 +16,8 @@ from webviz_config.webviz_plugin_subclasses import ( ViewABC, ViewElementABC, SettingsGroupABC, - callback_typecheck, ) - -from webviz_config.utils import StrEnum +from webviz_config.utils import callback_typecheck, StrEnum from webviz_config.generic_plugins._example_wlf_plugin._shared_view_elements import ( TextViewElement, diff --git a/webviz_config/generic_plugins/_example_wlf_plugin/_views/_table/_view.py b/webviz_config/generic_plugins/_example_wlf_plugin/_views/_table/_view.py index 3e6ad1e..6231ee1 100644 --- a/webviz_config/generic_plugins/_example_wlf_plugin/_views/_table/_view.py +++ b/webviz_config/generic_plugins/_example_wlf_plugin/_views/_table/_view.py @@ -10,14 +10,13 @@ import pandas as pd import webviz_core_components as wcc -from webviz_config.utils import StrEnum +from webviz_config.utils import callback_typecheck, StrEnum from webviz_config import WebvizPluginABC, EncodedFile from webviz_config.webviz_plugin_subclasses import ( ViewABC, ViewElementABC, SettingsGroupABC, - callback_typecheck, ) from webviz_config.generic_plugins._example_wlf_plugin._shared_view_elements import ( diff --git a/webviz_config/utils/__init__.py b/webviz_config/utils/__init__.py index 980c8b8..7c3aa5e 100644 --- a/webviz_config/utils/__init__.py +++ b/webviz_config/utils/__init__.py @@ -6,3 +6,4 @@ from ._deprecate_webviz_settings_attribute_in_dash_app import ( deprecate_webviz_settings_attribute_in_dash_app, ) from ._str_enum import StrEnum +from ._callback_typecheck import callback_typecheck, ConversionError diff --git a/webviz_config/webviz_plugin_subclasses/_callback_typecheck.py b/webviz_config/utils/_callback_typecheck.py similarity index 53% rename from webviz_config/webviz_plugin_subclasses/_callback_typecheck.py rename to webviz_config/utils/_callback_typecheck.py index 99f45e1..f9b011a 100644 --- a/webviz_config/webviz_plugin_subclasses/_callback_typecheck.py +++ b/webviz_config/utils/_callback_typecheck.py @@ -1,7 +1,6 @@ # pylint: disable=line-too-long -from typing import Any, Callable, get_origin, TypeVar +from typing import Any, Callable, get_origin, _TypedDictMeta, TypeVar, Union # type: ignore[attr-defined] import inspect -from enum import Enum T = TypeVar("T") @@ -11,17 +10,35 @@ class ConversionError(Exception): def convert(arg: Any, convert_to: T) -> T: - # pylint: disable=too-many-return-statements + # pylint: disable=too-many-return-statements, too-many-branches additional_error_message: str = "" try: - if inspect.isclass(convert_to) and issubclass(convert_to, Enum): - return convert_to(arg) # type: ignore[return-value] - if convert_to is int: - return int(arg) # type: ignore[return-value] - if convert_to is float: - return float(arg) # type: ignore[return-value] - if convert_to is str: - return str(arg) # type: ignore[return-value] + if convert_to is None and arg is None: + return None + if inspect.isclass(convert_to) and not isinstance(convert_to, _TypedDictMeta): + return convert_to(arg) + if ( + isinstance(convert_to, _TypedDictMeta) + and "__annotations__" in dir(convert_to) + and isinstance(arg, dict) + ): + new_dict = convert_to() + for key, value in arg.items(): + if key in list(convert_to.__annotations__.keys()): + new_dict[key] = convert(value, convert_to.__annotations__[key]) + else: + raise Exception( + f""" + Key '{key}' not allowed in '{convert_to}'.\n + Allowed keys are: {', '.join(list(convert_to.__annotations__.keys()))} + """ + ) + + if not convert_to.__total__ or len(new_dict.keys()) == len( + convert_to.__annotations__.keys() + ): + return new_dict + if convert_to is list and isinstance(arg, list): return arg # type: ignore[return-value] if get_origin(convert_to) is list and isinstance(arg, list): @@ -37,6 +54,16 @@ def convert(arg: Any, convert_to: T) -> T: ) for key, value in arg.items() } + if get_origin(convert_to) is Union: + if "__args__" in dir(convert_to): + for convert_type in convert_to.__args__: # type: ignore[attr-defined] + if isinstance(arg, convert_type): + return arg + for convert_type in convert_to.__args__: # type: ignore[attr-defined] + try: + return convert(arg, convert_type) + except ConversionError: + pass # pylint: disable=broad-except except Exception as exception: diff --git a/webviz_config/webviz_plugin_subclasses/__init__.py b/webviz_config/webviz_plugin_subclasses/__init__.py index f27b57a..5819415 100644 --- a/webviz_config/webviz_plugin_subclasses/__init__.py +++ b/webviz_config/webviz_plugin_subclasses/__init__.py @@ -2,4 +2,3 @@ from ._settings_group_abc import SettingsGroupABC from ._views import ViewABC, ViewElementABC, ViewLayoutElement, LayoutElementType from ._layout_base_abc import LayoutBaseABC from ._layout_unique_id import LayoutUniqueId -from ._callback_typecheck import callback_typecheck
equinor/webviz-config
55f78d9f86990d6d816a82b162d4bd65e04edd75
diff --git a/tests/test_callback_typecheck.py b/tests/test_callback_typecheck.py new file mode 100644 index 0000000..027fc84 --- /dev/null +++ b/tests/test_callback_typecheck.py @@ -0,0 +1,133 @@ +from typing import ( + Dict, + List, + Optional, + TypedDict, + Union, +) +from enum import Enum +from webviz_config.utils import callback_typecheck, ConversionError + + +def test_callback_typecheck() -> None: + class MyEnum(str, Enum): + VALUE_1 = "value-1" + + class MyTypedDict(TypedDict): + name: str + year: int + + class DeepTypedDict(TypedDict): + value: MyTypedDict + + ############################################################ + + def expect_none(arg: None) -> None: + assert arg is None + + callback_typecheck(expect_none)(None) + + ############################################################ + + def expect_enum(arg: MyEnum) -> None: + assert isinstance(arg, MyEnum) + + callback_typecheck(expect_enum)("value-1") + + ############################################################ + + def expect_typed_dict(arg: MyTypedDict) -> None: + types = [type(value) for value in arg.values()] + assert ( + isinstance(arg, dict) + and set(arg.keys()) + == set(MyTypedDict.__annotations__.keys()) # pylint: disable=no-member + and set(types) + == set(MyTypedDict.__annotations__.values()) # pylint: disable=no-member + ) + + callback_typecheck(expect_typed_dict)({"name": "Name", "year": 1990}) + + # If any invalid key is given to a `TypedDict`, assert that a `ConversionError` is raised + try: + callback_typecheck(expect_typed_dict)({"name": "Name", "year2": 1990}) + assert False + except ConversionError: + pass + except Exception: # pylint: disable=broad-except + assert False + + ############################################################ + + def expect_deep_typed_dict(arg: DeepTypedDict) -> None: + types = [type(value) for value in arg.values()] + assert ( + isinstance(arg, dict) + and set(arg.keys()) + == set(DeepTypedDict.__annotations__.keys()) # pylint: disable=no-member + # NOTE: A `TypedDict` is a `dict` at runtime + and set(types) == set([dict]) + and set(arg["value"].keys()) + == set(MyTypedDict.__annotations__.keys()) # pylint: disable=no-member + ) + + callback_typecheck(expect_deep_typed_dict)( + {"value": {"name": "Name", "year": 1990}} + ) + + ############################################################ + + def expect_int(arg: int) -> None: + assert isinstance(arg, int) + + callback_typecheck(expect_int)("1") + + ############################################################ + + def expect_float(arg: float) -> None: + assert isinstance(arg, float) + + callback_typecheck(expect_float)("1.5") + + ############################################################ + + def expect_str(arg: str) -> None: + assert isinstance(arg, str) + + callback_typecheck(expect_str)(1) + + ############################################################ + + def expect_list(arg: List[str]) -> None: + assert isinstance(arg, list) + assert isinstance(arg[0], str) + + callback_typecheck(expect_list)([1, 2, 3]) + + ############################################################ + + def expect_dict(arg: Dict[str, int]) -> None: + assert isinstance(arg, dict) + assert isinstance(list(arg.values())[0], int) + assert isinstance(list(arg.keys())[0], str) + + callback_typecheck(expect_dict)({"1": 1}) + + ############################################################ + + def expect_optional(arg: Optional[str]) -> Optional[str]: + return arg + + assert callback_typecheck(expect_optional)(None) is None + assert isinstance(callback_typecheck(expect_optional)("string"), str) + + ############################################################ + + def expect_union(arg: Union[str, int]) -> Union[str, int]: + return arg + + assert isinstance(callback_typecheck(expect_union)("1"), str) + assert isinstance(callback_typecheck(expect_union)(1), int) + assert isinstance(callback_typecheck(expect_union)(1.5), str) + + ############################################################
Support `Optional` in `callback_typecheck` **Is your feature request related to a problem? Please describe.** The `callback_typecheck` decorator cannot be used with `Optional` arguments yet. **Describe the solution you'd like** Include a convert mechanism for `Optional` types in `callback_typecheck`'s `convert` function.
0.0
[ "tests/test_callback_typecheck.py::test_callback_typecheck" ]
[]
2022-09-12 14:27:44+00:00
2,186
equinor__webviz-config-656
diff --git a/CHANGELOG.md b/CHANGELOG.md index ee81118..40f207d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#648](https://github.com/equinor/webviz-config/pull/648) - Allow `blob:` in `script-src` CSP in order to enable web worker usage in Dash components. - [#652](https://github.com/equinor/webviz-config/pull/652) - Enabled support for LaTeX math/equations in markdown. - [#653](https://github.com/equinor/webviz-config/pull/653) - Reduce time for running `webviz --help` by lazy importing top level entrypoints. +- [#656](https://github.com/equinor/webviz-config/pull/656) - Further reduce startup time by only loading plugin entrypoints used in the application. ### Added - [#644](https://github.com/equinor/webviz-config/pull/644) - Added option to download tables in `DataTable` and `PivotTable`. diff --git a/webviz_config/_config_parser.py b/webviz_config/_config_parser.py index b64b6d7..c8fd588 100644 --- a/webviz_config/_config_parser.py +++ b/webviz_config/_config_parser.py @@ -9,7 +9,6 @@ import yaml import webviz_config.plugins from .utils import terminal_colors -from .utils._get_webviz_plugins import _get_webviz_plugins from . import _deprecation_store as _ds SPECIAL_ARGS = ["self", "app", "webviz_settings", "_call_signature"] @@ -211,9 +210,7 @@ class ParserError(Exception): class ConfigParser: - STANDARD_PLUGINS = [ - name for (name, _) in _get_webviz_plugins(webviz_config.plugins) - ] + INSTALLED_PLUGINS = webviz_config.plugins.__all__ def __init__(self, yaml_file: pathlib.Path): @@ -436,13 +433,13 @@ class ConfigParser: plugin_variables = next(iter(plugin.values())) kwargs = {} if plugin_variables is None else {**plugin_variables} - if plugin_name not in ConfigParser.STANDARD_PLUGINS: + if plugin_name not in ConfigParser.INSTALLED_PLUGINS: raise ParserError( f"{terminal_colors.RED}{terminal_colors.BOLD}" "You have included a plugin with " f"name `{plugin_name}` in your " - "configuration file. This is not a " - "standard plugin." + "configuration file. This is not an " + "installed plugin." f"{terminal_colors.END}" ) diff --git a/webviz_config/_docs/_build_docs.py b/webviz_config/_docs/_build_docs.py index 6313ebd..2439d8c 100644 --- a/webviz_config/_docs/_build_docs.py +++ b/webviz_config/_docs/_build_docs.py @@ -23,7 +23,6 @@ import jinja2 import webviz_config.plugins from webviz_config.plugins import PLUGIN_METADATA, PLUGIN_PROJECT_METADATA from .._config_parser import SPECIAL_ARGS -from ..utils._get_webviz_plugins import _get_webviz_plugins from .. import _deprecation_store as _ds @@ -119,17 +118,17 @@ def _extract_init_arguments_and_check_for_deprecation( return (bool(deprecated_arguments), result, deprecation_check_code) -def _document_plugin(plugin: Tuple[str, Any]) -> PluginInfo: - """Takes in a tuple (from e.g. inspect.getmembers), and returns +def _document_plugin(plugin_name: str) -> PluginInfo: + """Takes in plugin name as string and returns a dictionary according to the type definition PluginInfo. """ - name, reference = plugin + reference = webviz_config.plugins.__getattr__(plugin_name) docstring = reference.__doc__ if reference.__doc__ is not None else "" docstring_parts = _split_docstring(docstring) module = inspect.getmodule(reference) subpackage = inspect.getmodule(module).__package__ # type: ignore - dist_name = PLUGIN_METADATA[name]["dist_name"] + dist_name = PLUGIN_METADATA[plugin_name]["dist_name"] ( has_deprecated_arguments, arguments, @@ -144,7 +143,7 @@ def _document_plugin(plugin: Tuple[str, Any]) -> PluginInfo: else None, "data_input": docstring_parts[2] if len(docstring_parts) > 2 else None, "description": docstring_parts[0] if docstring != "" else None, - "name": name, + "name": plugin_name, "package_doc": import_module(subpackage).__doc__, # type: ignore "dist_name": dist_name, "dist_version": PLUGIN_PROJECT_METADATA[dist_name]["dist_version"], @@ -165,8 +164,8 @@ def get_plugin_documentation() -> defaultdict: plugin_doc = [ _document_plugin(plugin) - for plugin in _get_webviz_plugins(webviz_config.plugins) - if not plugin[0].startswith("Example") + for plugin in webviz_config.plugins.__all__ + if not plugin.startswith("Example") ] # Sort the plugins by package: diff --git a/webviz_config/_docs/_create_schema.py b/webviz_config/_docs/_create_schema.py index 07e4fe8..3257145 100644 --- a/webviz_config/_docs/_create_schema.py +++ b/webviz_config/_docs/_create_schema.py @@ -186,7 +186,8 @@ def create_schema() -> dict: "type": "object", "properties": { plugin_doc["name"]: { - "description": plugin_doc["description"], + "description": plugin_doc["description"] + or " PLUGIN MISSING DESCRIPTION ", "type": "object", "properties": { **{ diff --git a/webviz_config/plugins/__init__.py b/webviz_config/plugins/__init__.py index 89333bc..9ad9c47 100644 --- a/webviz_config/plugins/__init__.py +++ b/webviz_config/plugins/__init__.py @@ -2,11 +2,24 @@ the utility itself. """ +import abc from importlib.metadata import distributions from ._utils import load_webviz_plugins_with_metadata, PluginProjectMetaData -PLUGIN_METADATA, PLUGIN_PROJECT_METADATA = load_webviz_plugins_with_metadata( - distributions(), globals() -) +( + PLUGIN_METADATA, + PLUGIN_PROJECT_METADATA, + plugin_entrypoints, +) = load_webviz_plugins_with_metadata(distributions()) + +__all__ = list(plugin_entrypoints.keys()) + + +def __getattr__(name: str) -> abc.ABC: + """Lazy load plugins, i.e. only import/load when a given plugin is requested.""" + + if name in __all__: + return plugin_entrypoints[name].load() + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/webviz_config/plugins/_utils.py b/webviz_config/plugins/_utils.py index 53971fb..58723b3 100644 --- a/webviz_config/plugins/_utils.py +++ b/webviz_config/plugins/_utils.py @@ -1,8 +1,8 @@ import re import warnings -from typing import Any, Dict, Iterable, Optional, Tuple, TypedDict +from typing import Dict, Iterable, Optional, Tuple, TypedDict -from importlib.metadata import requires, version, PackageNotFoundError +from importlib.metadata import requires, version, PackageNotFoundError, EntryPoint class PluginProjectMetaData(TypedDict): @@ -51,29 +51,24 @@ def _plugin_dist_dependencies(plugin_dist_name: str) -> Dict[str, str]: def load_webviz_plugins_with_metadata( - distributions: Iterable, loaded_plugins: Dict[str, Any] -) -> Tuple[Dict[str, dict], Dict[str, PluginProjectMetaData]]: - """Loads the given distributions, finds entry points corresponding to webviz-config - plugins, and put them into the mutable input dictionary loaded_plugins - (key is plugin name string, value is reference to plugin class). + distributions: Iterable, +) -> Tuple[Dict[str, dict], Dict[str, PluginProjectMetaData], Dict[str, EntryPoint]]: + """Finds entry points corresponding to webviz-config plugins, + and returns them as a dictionary (key is plugin name string, + value is reference to entrypoint). + Also returns a dictionary of plugin metadata. """ plugin_project_metadata: Dict[str, PluginProjectMetaData] = {} plugin_metadata: Dict[str, dict] = {} + plugin_entrypoints: Dict[str, EntryPoint] = {} for dist in distributions: for entry_point in dist.entry_points: if entry_point.group == "webviz_config_plugins": - dist_name = dist.metadata["name"] - project_urls = { - value.split(",")[0]: value.split(",")[1].strip() - for (key, value) in dist.metadata.items() - if key == "Project-URL" - } - if ( entry_point.name in plugin_metadata and dist_name not in plugin_project_metadata @@ -86,6 +81,12 @@ def load_webviz_plugins_with_metadata( ) if dist_name not in plugin_project_metadata: + project_urls = { + value.split(",")[0]: value.split(",")[1].strip() + for (key, value) in dist.metadata.items() + if key == "Project-URL" + } + plugin_project_metadata[dist_name] = PluginProjectMetaData( { "dist_version": dist.version, @@ -101,6 +102,6 @@ def load_webviz_plugins_with_metadata( "dist_name": dist.metadata["name"], } - loaded_plugins[entry_point.name] = entry_point.load() + plugin_entrypoints[entry_point.name] = entry_point - return (plugin_metadata, plugin_project_metadata) + return (plugin_metadata, plugin_project_metadata, plugin_entrypoints) diff --git a/webviz_config/utils/_get_webviz_plugins.py b/webviz_config/utils/_get_webviz_plugins.py deleted file mode 100644 index ab1efbb..0000000 --- a/webviz_config/utils/_get_webviz_plugins.py +++ /dev/null @@ -1,20 +0,0 @@ -import types -import typing -import inspect - -from .._plugin_abc import WebvizPluginABC - - -def _get_webviz_plugins(module: types.ModuleType) -> list: - """Returns a list of all Webviz plugins - in the module given as input. - """ - - def _is_webviz_plugin(obj: typing.Any) -> bool: - return ( - inspect.isclass(obj) - and issubclass(obj, WebvizPluginABC) - and obj is not WebvizPluginABC - ) - - return inspect.getmembers(module, _is_webviz_plugin)
equinor/webviz-config
3209912a2b060d6c943fea84cf0d7d60e3ba3086
diff --git a/tests/test_plugin_init.py b/tests/test_plugin_init.py index 3098e84..fa235d0 100644 --- a/tests/test_plugin_init.py +++ b/tests/test_plugin_init.py @@ -33,16 +33,19 @@ def test_no_warning(monkeypatch): monkeypatch.setattr(importlib.metadata, "requires", lambda x: []) importlib.reload(webviz_config.plugins._utils) - globals_mock = {} with warnings.catch_warnings(record=True) as warn: - metadata, _ = webviz_config.plugins._utils.load_webviz_plugins_with_metadata( - [dist_mock1, dist_mock3], globals_mock + ( + metadata, + _, + plugin_entrypoints, + ) = webviz_config.plugins._utils.load_webviz_plugins_with_metadata( + [dist_mock1, dist_mock3] ) assert len(warn) == 0, "Too many warnings" assert len(metadata) == 2, "Wrong number of items in metadata" - assert "SomePlugin1" in globals_mock - assert "SomePlugin2" in globals_mock + assert "SomePlugin1" in plugin_entrypoints + assert "SomePlugin2" in plugin_entrypoints def test_warning_multiple(monkeypatch): @@ -50,10 +53,13 @@ def test_warning_multiple(monkeypatch): monkeypatch.setattr(importlib.metadata, "requires", lambda x: []) importlib.reload(webviz_config.plugins._utils) - globals_mock = {} with warnings.catch_warnings(record=True) as warn: - metadata, _ = webviz_config.plugins._utils.load_webviz_plugins_with_metadata( - [dist_mock1, dist_mock2], globals_mock + ( + metadata, + _, + plugin_entrypoints, + ) = webviz_config.plugins._utils.load_webviz_plugins_with_metadata( + [dist_mock1, dist_mock2] ) assert len(warn) == 1 @@ -67,4 +73,4 @@ def test_warning_multiple(monkeypatch): assert len(metadata) == 1, "Wrong number of items in metadata" assert metadata["SomePlugin1"]["dist_name"] == "dist_mock2", "Wrong dist name" - assert "SomePlugin1" in globals_mock + assert "SomePlugin1" in plugin_entrypoints
Intelligent loading of plugins through entry_points `webviz-config` is using a quite standard way of discovering and loading plugins, i.e. https://github.com/equinor/webviz-config/blob/5139c3039f0198ba23b55ec2ca9e7019ae6dd54d/webviz_config/plugins/__init__.py#L51-L53 However, we could change this slightly to easily improve loading time on systems where many plugins are installed (but only a small subset of them are used in an actual user configuration file) by only loading the modules / `entry_points` related to plugins used in the given `yaml` file. Related to #185.
0.0
[ "tests/test_plugin_init.py::test_no_warning", "tests/test_plugin_init.py::test_warning_multiple" ]
[]
2022-11-25 11:38:02+00:00
2,187
erikrose__parsimonious-202
diff --git a/README.rst b/README.rst index b27ecfd..c0ba2ae 100644 --- a/README.rst +++ b/README.rst @@ -236,6 +236,14 @@ Syntax Reference conventions for "raw" and Unicode strings help support fiddly characters. +``b"some literal"`` A bytes literal. Using bytes literals and regular + expressions allows your grammar to parse binary files. + Note that all literals and regular expressions must be + of the same type within a grammar. In grammars that + process bytestrings, you should make the grammar string + an ``r"""string"""`` so that byte literals like ``\xff`` + work correctly. + [space] Sequences are made out of space- or tab-delimited things. ``a b c`` matches spots where those 3 terms appear in that order. @@ -269,6 +277,9 @@ Syntax Reference them out of simpler primitives. Parsimonious uses the regex_ library instead of the built-in re module. +``~br"regex"`` A bytes regex; required if your grammar parses + bytestrings. + ``(things)`` Parentheses are used for grouping, like in every other language. ==================== ======================================================== @@ -421,6 +432,11 @@ Niceties Version History =============== +(Next release) + * Add support for grammars on bytestrings (lucaswiman) + * Fix precedence of string literal modifiers u/r/b. + This will break grammars with no spaces between a + reference and a string literal. (lucaswiman) 0.9.0 * Add support for Python 3.7, 3.8, 3.9, 3.10 (righthandabacus, Lonnen) diff --git a/parsimonious/grammar.py b/parsimonious/grammar.py index c1e324a..617f4d1 100644 --- a/parsimonious/grammar.py +++ b/parsimonious/grammar.py @@ -6,6 +6,7 @@ by hand. """ from collections import OrderedDict +from textwrap import dedent from parsimonious.exceptions import BadGrammar, UndefinedLabel from parsimonious.expressions import (Literal, Regex, Sequence, OneOf, @@ -226,8 +227,8 @@ rule_syntax = (r''' literal = spaceless_literal _ # So you can't spell a regex like `~"..." ilm`: - spaceless_literal = ~"u?r?\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""is / - ~"u?r?'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"is + spaceless_literal = ~"u?r?b?\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""is / + ~"u?r?b?'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"is expression = ored / sequence / term or_term = "/" _ term @@ -246,7 +247,7 @@ rule_syntax = (r''' # A subsequent equal sign is the only thing that distinguishes a label # (which begins a new rule) from a reference (which is just a pointer to a # rule defined somewhere else): - label = ~"[a-zA-Z_][a-zA-Z_0-9]*" _ + label = ~"[a-zA-Z_][a-zA-Z_0-9]*(?![\"'])" _ # _ = ~r"\s*(?:#[^\r\n]*)?\s*" _ = meaninglessness* @@ -286,6 +287,7 @@ class RuleVisitor(NodeVisitor): """ self.custom_rules = custom_rules or {} + self._last_literal_node_and_type = None def visit_parenthesized(self, node, parenthesized): """Treat a parenthesized subexpression as just its contents. @@ -368,7 +370,19 @@ class RuleVisitor(NodeVisitor): def visit_spaceless_literal(self, spaceless_literal, visited_children): """Turn a string literal into a ``Literal`` that recognizes it.""" - return Literal(evaluate_string(spaceless_literal.text)) + literal_value = evaluate_string(spaceless_literal.text) + if self._last_literal_node_and_type: + last_node, last_type = self._last_literal_node_and_type + if last_type != type(literal_value): + raise BadGrammar(dedent(f"""\ + Found {last_node.text} ({last_type}) and {spaceless_literal.text} ({type(literal_value)}) string literals. + All strings in a single grammar must be of the same type. + """) + ) + + self._last_literal_node_and_type = spaceless_literal, type(literal_value) + + return Literal(literal_value) def visit_literal(self, node, literal): """Pick just the literal out of a literal-and-junk combo.""" diff --git a/parsimonious/utils.py b/parsimonious/utils.py index 3dc27cc..7c7e863 100644 --- a/parsimonious/utils.py +++ b/parsimonious/utils.py @@ -12,9 +12,11 @@ class StrAndRepr(object): def evaluate_string(string): """Piggyback on Python's string support so we can have backslash escaping - and niceties like \n, \t, etc. string.decode('string_escape') would have - been a lower-level possibility. + and niceties like \n, \t, etc. + This also supports: + 1. b"strings", allowing grammars to parse bytestrings, in addition to str. + 2. r"strings" to simplify regexes. """ return ast.literal_eval(string)
erikrose/parsimonious
e98dd3342c1405c5021b0a7169e25f16b294f884
diff --git a/parsimonious/tests/test_grammar.py b/parsimonious/tests/test_grammar.py index f495f81..c9f0aa3 100644 --- a/parsimonious/tests/test_grammar.py +++ b/parsimonious/tests/test_grammar.py @@ -4,8 +4,9 @@ from sys import version_info from unittest import TestCase import sys +import pytest -from parsimonious.exceptions import UndefinedLabel, ParseError +from parsimonious.exceptions import BadGrammar, UndefinedLabel, ParseError, VisitationError from parsimonious.expressions import Literal, Lookahead, Regex, Sequence, TokenMatcher, is_callable from parsimonious.grammar import rule_grammar, RuleVisitor, Grammar, TokenGrammar, LazyReference from parsimonious.nodes import Node @@ -493,3 +494,59 @@ class TokenGrammarTests(TestCase): self.assertEqual(u'<Token "πŸ’£">'.encode('utf-8'), t.__repr__()) else: self.assertEqual(u'<Token "πŸ’£">', t.__repr__()) + + +def test_precedence_of_string_modifiers(): + # r"strings", etc. should be parsed as a single literal, not r followed + # by a string literal. + g = Grammar(r""" + escaped_bell = r"\b" + r = "irrelevant" + """) + assert isinstance(g["escaped_bell"], Literal) + assert g["escaped_bell"].literal == "\\b" + with pytest.raises(ParseError): + g.parse("irrelevant\b") + + g2 = Grammar(r""" + escaped_bell = r"\b" + """) + assert g2.parse("\\b") + + +def test_binary_grammar(): + g = Grammar(r""" + file = header body terminator + header = b"\xFF" length b"~" + length = ~rb"\d+" + body = ~b"[^\xFF]*" + terminator = b"\xFF" + """) + length = 22 + assert g.parse(b"\xff22~" + (b"a" * 22) + b"\xff") is not None + + +def test_inconsistent_string_types_in_grammar(): + with pytest.raises(VisitationError) as e: + Grammar(r""" + foo = b"foo" + bar = "bar" + """) + assert e.value.original_class is BadGrammar + with pytest.raises(VisitationError) as e: + Grammar(r""" + foo = ~b"foo" + bar = "bar" + """) + assert e.value.original_class is BadGrammar + + # The following should parse without errors because they use the same + # string types: + Grammar(r""" + foo = b"foo" + bar = b"bar" + """) + Grammar(r""" + foo = "foo" + bar = "bar" + """)
incorrect precedence for modifiers of string literals The precedence of literal modifiers like `r"string"` is wrong. `r` gets parsed as a rule reference, and the string literal is interpreted as-is. I discovered this while trying to add support for binary grammars. I hope to fix this as part of that project, but wanted to note it in an issue in case I don't get around to it. ## How to reproduce: ``` >>> g = Grammar(""" default = r"\b" r = "something" """) >>> g.parse("something\b") s = 'something\x08' Node(<Sequence default = r '\x08'>, s, 0, 10, children=[Node(<Literal r = 'something'>, s, 0, 9), Node(<Literal '\x08'>, s, 9, 10)]) >>> g.parse(r"\b") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 113, in parse return self.default_rule.parse(text, pos=pos) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/expressions.py", line 130, in parse node = self.match(text, pos=pos) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/expressions.py", line 147, in match raise error parsimonious.exceptions.ParseError: Rule 'default' didn't match at '\b' (line 1, column 1). ``` If the `r` rule is omitted: ``` >>> from parsimonious.grammar import Grammar >>> Grammar(""" default = r"\b" """) Traceback (most recent call last): File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 413, in _resolve_refs reffed_expr = rule_map[label] KeyError: 'r' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 67, in __init__ exprs, first = self._expressions_from_rules(rules, decorated_custom_rules) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 104, in _expressions_from_rules return RuleVisitor(custom_rules).visit(tree) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/nodes.py", line 213, in visit return method(node, [self.visit(n) for n in node]) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 452, in visit_rules rule_map = OrderedDict((expr.name, self._resolve_refs(rule_map, expr, done)) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 452, in <genexpr> rule_map = OrderedDict((expr.name, self._resolve_refs(rule_map, expr, done)) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 423, in _resolve_refs expr.members = tuple(self._resolve_refs(rule_map, member, done) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 423, in <genexpr> expr.members = tuple(self._resolve_refs(rule_map, member, done) File "/Users/lucaswiman/opensource/parsimonious/parsimonious/grammar.py", line 415, in _resolve_refs raise UndefinedLabel(expr) parsimonious.exceptions.UndefinedLabel: The label "r" was never defined. ```
0.0
[ "parsimonious/tests/test_grammar.py::test_precedence_of_string_modifiers", "parsimonious/tests/test_grammar.py::test_binary_grammar", "parsimonious/tests/test_grammar.py::test_inconsistent_string_types_in_grammar" ]
[ "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_quantifier", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_regex", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_spaceless_literal", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_successes", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_optional", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_round_trip", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_undefined_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_bad_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_of_routines", "parsimonious/tests/test_grammar.py::GrammarTests::test_comments", "parsimonious/tests/test_grammar.py::GrammarTests::test_complex_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_expressions_from_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_immutable_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_infinite_loop", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_default_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_lookahead", "parsimonious/tests/test_grammar.py::GrammarTests::test_match", "parsimonious/tests/test_grammar.py::GrammarTests::test_multi_line", "parsimonious/tests/test_grammar.py::GrammarTests::test_not", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens_with_leading_whitespace", "parsimonious/tests/test_grammar.py::GrammarTests::test_repr", "parsimonious/tests/test_grammar.py::GrammarTests::test_resolve_refs_order", "parsimonious/tests/test_grammar.py::GrammarTests::test_right_recursive", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved_on_shallow_copies", "parsimonious/tests/test_grammar.py::GrammarTests::test_simple_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_single_quoted_literals", "parsimonious/tests/test_grammar.py::GrammarTests::test_unconnected_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_unicode", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_failure", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_success", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_token_repr" ]
2022-03-31 02:18:37+00:00
2,188
erikrose__parsimonious-203
diff --git a/README.rst b/README.rst index a6c8e07..8955b3d 100644 --- a/README.rst +++ b/README.rst @@ -282,6 +282,15 @@ Syntax Reference ``(things)`` Parentheses are used for grouping, like in every other language. + +``thing{n}`` Exactly ``n`` repetitions of ``thing``. + +``thing{n,m}`` Between ``n`` and ``m`` repititions (inclusive.) + +``thing{,m}`` At most ``m`` repetitions of ``thing``. + +``thing{n,}`` At least ``n`` repetitions of ``thing``. + ==================== ======================================================== .. _flags: https://docs.python.org/3/howto/regex.html#compilation @@ -434,7 +443,11 @@ Version History =============== (Next release) + * Add support for range ``{min,max}`` repetition expressions (righthandabacus) + * Fix bug in ``*`` and ``+`` for token grammars (lucaswiman) * Add support for grammars on bytestrings (lucaswiman) + * Fix LazyReference resolution bug #134 (righthandabacus) + .. warning:: This release makes backward-incompatible changes: diff --git a/parsimonious/exceptions.py b/parsimonious/exceptions.py index b51c336..29cdef9 100644 --- a/parsimonious/exceptions.py +++ b/parsimonious/exceptions.py @@ -30,14 +30,17 @@ class ParseError(StrAndRepr, Exception): match.""" # This is a method rather than a property in case we ever wanted to # pass in which line endings we want to use. - return self.text.count('\n', 0, self.pos) + 1 + if isinstance(self.text, list): # TokenGrammar + return None + else: + return self.text.count('\n', 0, self.pos) + 1 def column(self): """Return the 1-based column where the expression ceased to match.""" # We choose 1-based because that's what Python does with SyntaxErrors. try: return self.pos - self.text.rindex('\n', 0, self.pos) - except ValueError: + except (ValueError, AttributeError): return self.pos + 1 diff --git a/parsimonious/expressions.py b/parsimonious/expressions.py index 0679527..bf10656 100644 --- a/parsimonious/expressions.py +++ b/parsimonious/expressions.py @@ -375,105 +375,71 @@ class Lookahead(Compound): """An expression which consumes nothing, even if its contained expression succeeds""" - # TODO: Merge this and Not for better cache hit ratios and less code. - # Downside: pretty-printed grammars might be spelled differently than what - # went in. That doesn't bother me. + __slots__ = ['negativity'] - def _uncached_match(self, text, pos, cache, error): - node = self.members[0].match_core(text, pos, cache, error) - if node is not None: - return Node(self, text, pos, pos) - - def _as_rhs(self): - return u'&%s' % self._unicode_members()[0] + def __init__(self, member, *, negative=False, **kwargs): + super(Lookahead, self).__init__(member, **kwargs) + self.negativity = bool(negative) - -class Not(Compound): - """An expression that succeeds only if the expression within it doesn't - - In any case, it never consumes any characters; it's a negative lookahead. - - """ def _uncached_match(self, text, pos, cache, error): - # FWIW, the implementation in Parsing Techniques in Figure 15.29 does - # not bother to cache NOTs directly. node = self.members[0].match_core(text, pos, cache, error) - if node is None: + if (node is None) == self.negativity: # negative lookahead == match only if not found return Node(self, text, pos, pos) def _as_rhs(self): - # TODO: Make sure this parenthesizes the member properly if it's an OR - # or AND. - return u'!%s' % self._unicode_members()[0] + return u'%s%s' % ('!' if self.negativity else '&', self._unicode_members()[0]) +def Not(term): + return Lookahead(term, negative=True) # Quantifiers. None of these is strictly necessary, but they're darn handy. -class Optional(Compound): - """An expression that succeeds whether or not the contained one does - - If the contained expression succeeds, it goes ahead and consumes what it - consumes. Otherwise, it consumes nothing. - - """ - def _uncached_match(self, text, pos, cache, error): - node = self.members[0].match_core(text, pos, cache, error) - return (Node(self, text, pos, pos) if node is None else - Node(self, text, pos, node.end, children=[node])) - - def _as_rhs(self): - return u'%s?' % self._unicode_members()[0] +class Quantifier(Compound): + """An expression wrapper like the */+/?/{n,m} quantifier in regexes.""" + __slots__ = ['min', 'max'] -# TODO: Merge with OneOrMore. -class ZeroOrMore(Compound): - """An expression wrapper like the * quantifier in regexes.""" - - def _uncached_match(self, text, pos, cache, error): - new_pos = pos - children = [] - while True: - node = self.members[0].match_core(text, new_pos, cache, error) - if node is None or not (node.end - node.start): - # Node was None or 0 length. 0 would otherwise loop infinitely. - return Node(self, text, pos, new_pos, children) - children.append(node) - new_pos += node.end - node.start - - def _as_rhs(self): - return u'%s*' % self._unicode_members()[0] - - -class OneOrMore(Compound): - """An expression wrapper like the + quantifier in regexes. - - You can also pass in an alternate minimum to make this behave like "2 or - more", "3 or more", etc. - - """ - __slots__ = ['min'] - - # TODO: Add max. It should probably succeed if there are more than the max - # --just not consume them. - - def __init__(self, member, name='', min=1): - super(OneOrMore, self).__init__(member, name=name) + def __init__(self, member, *, min=0, max=float('inf'), name='', **kwargs): + super(Quantifier, self).__init__(member, name=name, **kwargs) self.min = min + self.max = max def _uncached_match(self, text, pos, cache, error): new_pos = pos children = [] - while True: + size = len(text) + while new_pos < size and len(children) < self.max: node = self.members[0].match_core(text, new_pos, cache, error) if node is None: - break + break # no more matches children.append(node) length = node.end - node.start - if length == 0: # Don't loop infinitely. + if len(children) >= self.min and length == 0: # Don't loop infinitely break new_pos += length if len(children) >= self.min: return Node(self, text, pos, new_pos, children) def _as_rhs(self): - return u'%s+' % self._unicode_members()[0] + if self.min == 0 and self.max == 1: + qualifier = '?' + elif self.min == 0 and self.max == float('inf'): + qualifier = '*' + elif self.min == 1 and self.max == float('inf'): + qualifier = '+' + elif self.max == float('inf'): + qualifier = '{%d,}' % self.min + elif self.min == 0: + qualifier = '{,%d}' % self.max + else: + qualifier = '{%d,%d}' % (self.min, self.max) + return '%s%s' % (self._unicode_members()[0], qualifier) + +def ZeroOrMore(member, name=''): + return Quantifier(member, name=name, min=0, max=float('inf')) + +def OneOrMore(member, name='', min=1): + return Quantifier(member, name=name, min=min, max=float('inf')) + +def Optional(member, name=''): + return Quantifier(member, name=name, min=0, max=1) diff --git a/parsimonious/grammar.py b/parsimonious/grammar.py index 617f4d1..ff4739f 100644 --- a/parsimonious/grammar.py +++ b/parsimonious/grammar.py @@ -10,7 +10,7 @@ from textwrap import dedent from parsimonious.exceptions import BadGrammar, UndefinedLabel from parsimonious.expressions import (Literal, Regex, Sequence, OneOf, - Lookahead, Optional, ZeroOrMore, OneOrMore, Not, TokenMatcher, + Lookahead, Quantifier, Optional, ZeroOrMore, OneOrMore, Not, TokenMatcher, expression, is_callable) from parsimonious.nodes import NodeVisitor from parsimonious.utils import evaluate_string @@ -241,7 +241,7 @@ rule_syntax = (r''' atom = reference / literal / regex / parenthesized regex = "~" spaceless_literal ~"[ilmsuxa]*"i _ parenthesized = "(" _ expression ")" _ - quantifier = ~"[*+?]" _ + quantifier = ~r"[*+?]|\{\d*,\d+\}|\{\d+,\d*\}|\{\d+\}" _ reference = label !equals # A subsequent equal sign is the only thing that distinguishes a label @@ -305,7 +305,17 @@ class RuleVisitor(NodeVisitor): def visit_quantified(self, node, quantified): atom, quantifier = quantified - return self.quantifier_classes[quantifier.text](atom) + try: + return self.quantifier_classes[quantifier.text](atom) + except KeyError: + # This should pass: assert re.full_match("\{(\d*)(,(\d*))?\}", quantifier) + quantifier = quantifier.text[1:-1].split(",") + if len(quantifier) == 1: + min_match = max_match = int(quantifier[0]) + else: + min_match = int(quantifier[0]) if quantifier[0] else 0 + max_match = int(quantifier[1]) if quantifier[1] else float('inf') + return Quantifier(atom, min=min_match, max=max_match) def visit_lookahead_term(self, node, lookahead_term): ampersand, term, _ = lookahead_term @@ -405,7 +415,7 @@ class RuleVisitor(NodeVisitor): """ return visited_children or node # should semantically be a tuple - def _resolve_refs(self, rule_map, expr, done): + def _resolve_refs(self, rule_map, expr, resolved): """Return an expression with all its lazy references recursively resolved. @@ -415,24 +425,42 @@ class RuleVisitor(NodeVisitor): :arg done: The set of Expressions that have already been or are currently being resolved, to ward off redundant work and prevent infinite recursion for circular refs - """ - if isinstance(expr, LazyReference): + if expr in resolved: + newref = resolved[expr] + elif isinstance(expr, LazyReference): label = str(expr) try: reffed_expr = rule_map[label] except KeyError: raise UndefinedLabel(expr) - return self._resolve_refs(rule_map, reffed_expr, done) + newref = resolved[expr] = self._resolve_refs(rule_map, reffed_expr, resolved) else: - if getattr(expr, 'members', ()) and expr not in done: + if getattr(expr, 'members', ()) and expr not in resolved: # Prevents infinite recursion for circular refs. At worst, one # of `expr.members` can refer back to `expr`, but it can't go # any farther. - done.add(expr) - expr.members = tuple(self._resolve_refs(rule_map, member, done) + resolved[expr] = expr + expr.members = tuple(self._resolve_refs(rule_map, member, resolved) for member in expr.members) - return expr + newref = expr + return newref + + def _find_unresolved(self, rules): + """Recursively find all LazyReference objects and return them as a set""" + seen = set() + to_resolve = set() + def _find_referenced_rules(rulelist): + for expr in rulelist: + if expr in seen: + continue + seen.add(expr) + if isinstance(expr, LazyReference): + to_resolve.add(expr) + elif getattr(expr, 'members', None): + _find_referenced_rules(expr.members) + _find_referenced_rules(rules) + return to_resolve def visit_rules(self, node, rules_list): """Collate all the rules into a map. Return (map, default rule). @@ -458,9 +486,18 @@ class RuleVisitor(NodeVisitor): rule_map.update(self.custom_rules) # Resolve references. This tolerates forward references. - done = set() - rule_map = OrderedDict((expr.name, self._resolve_refs(rule_map, expr, done)) - for expr in rule_map.values()) + # We use a job pool `to_resolve` to remember all rules to resolve. It is + # initialized with all existing rules in `rule_map` and all + # LazyReference rules found later will be added as well. + to_resolve = set(rule_map.values()) + resolved = {} + while to_resolve: + expr = to_resolve.pop() + newexpr = self._resolve_refs(rule_map, expr, resolved) + if getattr(expr, 'name', None): + rule_map[expr.name] = newexpr + if getattr(newexpr, 'members', ()): + to_resolve.update(self._find_unresolved(newexpr.members)) # isinstance() is a temporary hack around the fact that * rules don't # always get transformed into lists by NodeVisitor. We should fix that;
erikrose/parsimonious
aa032364ffac8b0c1893f9c29dfdca7dd70298f6
diff --git a/parsimonious/tests/test_expressions.py b/parsimonious/tests/test_expressions.py index 01b7e5d..dbf8af9 100644 --- a/parsimonious/tests/test_expressions.py +++ b/parsimonious/tests/test_expressions.py @@ -3,7 +3,7 @@ from unittest import TestCase from parsimonious.exceptions import ParseError, IncompleteParseError from parsimonious.expressions import (Literal, Regex, Sequence, OneOf, Not, - Optional, ZeroOrMore, OneOrMore, Expression) + Quantifier, Optional, ZeroOrMore, OneOrMore, Expression) from parsimonious.grammar import Grammar, rule_grammar from parsimonious.nodes import Node @@ -24,7 +24,7 @@ class LengthTests(TestCase): """ node_length = None if node is None else node.end - node.start - self.assertTrue(node_length == length) + assert node_length == length def test_regex(self): self.len_eq(Literal('hello').match('ehello', 1), 5) # simple @@ -50,6 +50,8 @@ class LengthTests(TestCase): def test_optional(self): self.len_eq(Sequence(Optional(Literal('a')), Literal('b')).match('b'), 1) # contained expr fails self.len_eq(Sequence(Optional(Literal('a')), Literal('b')).match('ab'), 2) # contained expr succeeds + self.len_eq(Optional(Literal('a')).match('aa'), 1) + self.len_eq(Optional(Literal('a')).match('bb'), 0) def test_zero_or_more(self): self.len_eq(ZeroOrMore(Literal('b')).match(''), 0) # zero @@ -64,7 +66,10 @@ class LengthTests(TestCase): self.len_eq(OneOrMore(Literal('b')).match('b'), 1) # one self.len_eq(OneOrMore(Literal('b')).match('bbb'), 3) # more self.len_eq(OneOrMore(Literal('b'), min=3).match('bbb'), 3) # with custom min; success + self.len_eq(Quantifier(Literal('b'), min=3, max=5).match('bbbb'), 4) # with custom min and max; success + self.len_eq(Quantifier(Literal('b'), min=3, max=5).match('bbbbbb'), 5) # with custom min and max; success self.assertRaises(ParseError, OneOrMore(Literal('b'), min=3).match, 'bb') # with custom min; failure + self.assertRaises(ParseError, Quantifier(Literal('b'), min=3, max=5).match, 'bb') # with custom min and max; failure self.len_eq(OneOrMore(Regex('^')).match('bb'), 0) # attempt infinite loop @@ -267,6 +272,20 @@ class RepresentationTests(TestCase): self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs")* "spam"')), u"foo = 'bar' ('baz' 'eggs')* 'spam'") + # Quantifiers + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){2,4} "spam"')), + "foo = 'bar' ('baz' 'eggs'){2,4} 'spam'") + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){2,} "spam"')), + "foo = 'bar' ('baz' 'eggs'){2,} 'spam'") + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){1,} "spam"')), + "foo = 'bar' ('baz' 'eggs')+ 'spam'") + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){,4} "spam"')), + "foo = 'bar' ('baz' 'eggs'){,4} 'spam'") + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){0,1} "spam"')), + "foo = 'bar' ('baz' 'eggs')? 'spam'") + self.assertEqual(str(Grammar('foo = "bar" ("baz" "eggs"){0,} "spam"')), + "foo = 'bar' ('baz' 'eggs')* 'spam'") + # OneOf self.assertEqual(str(Grammar('foo = "bar" ("baz" / "eggs") "spam"')), u"foo = 'bar' ('baz' / 'eggs') 'spam'") @@ -305,7 +324,7 @@ class SlotsTests(TestCase): But it does. """ - class Smoo(Optional): + class Smoo(Quantifier): __slots__ = ['smoo'] def __init__(self): diff --git a/parsimonious/tests/test_grammar.py b/parsimonious/tests/test_grammar.py index c9f0aa3..e982d61 100644 --- a/parsimonious/tests/test_grammar.py +++ b/parsimonious/tests/test_grammar.py @@ -3,8 +3,8 @@ from sys import version_info from unittest import TestCase -import sys import pytest +import sys from parsimonious.exceptions import BadGrammar, UndefinedLabel, ParseError, VisitationError from parsimonious.expressions import Literal, Lookahead, Regex, Sequence, TokenMatcher, is_callable @@ -286,6 +286,31 @@ class GrammarTests(TestCase): """) grammar.parse('(34)') + def test_resolve_refs_completeness(self): + """Smoke-test another circumstance where lazy references don't get resolved.""" + grammar = Grammar(r""" + block = "{" _ item* "}" _ + + # An item is an element of a block. + item = number / word / block / paren + + # Parens are for delimiting subexpressions. + paren = "(" _ item* ")" _ + + # Words are barewords, unquoted things, other than literals, that can live + # in lists. We may renege on some of these chars later, especially ".". We + # may add Unicode. + word = spaceless_word _ + spaceless_word = ~r"[-a-z`~!@#$%^&*_+=|\\;<>,.?][-a-z0-9`~!@#$%^&*_+=|\\;<>,.?]*"i + + number = ~r"[0-9]+" _ # There are decimals and strings and other stuff back on the "parsing" branch, once you get this working. + + _ = meaninglessness* + meaninglessness = whitespace + whitespace = ~r"\s+" + """) + grammar.parse('{log (add 3 to 5)}') + def test_infinite_loop(self): """Smoke-test a grammar that was causing infinite loops while building. @@ -462,6 +487,43 @@ class GrammarTests(TestCase): list(grammar.keys()), ['r%s' % i for i in range(100)]) + def test_repetitions(self): + grammar = Grammar(r''' + left_missing = "a"{,5} + right_missing = "a"{5,} + exact = "a"{5} + range = "a"{2,5} + optional = "a"? + plus = "a"+ + star = "a"* + ''') + should_parse = [ + ("left_missing", ["a" * i for i in range(6)]), + ("right_missing", ["a" * i for i in range(5, 8)]), + ("exact", ["a" * 5]), + ("range", ["a" * i for i in range(2, 6)]), + ("optional", ["", "a"]), + ("plus", ["a", "aa"]), + ("star", ["", "a", "aa"]), + ] + for rule, examples in should_parse: + for example in examples: + assert grammar[rule].parse(example) + + should_not_parse = [ + ("left_missing", ["a" * 6]), + ("right_missing", ["a" * i for i in range(5)]), + ("exact", ["a" * i for i in list(range(5)) + list(range(6, 10))]), + ("range", ["a" * i for i in list(range(2)) + list(range(6, 10))]), + ("optional", ["aa"]), + ("plus", [""]), + ("star", ["b"]), + ] + for rule, examples in should_not_parse: + for example in examples: + with pytest.raises(ParseError): + grammar[rule].parse(example) + class TokenGrammarTests(TestCase): """Tests for the TokenGrammar class and associated machinery""" @@ -483,17 +545,36 @@ class TokenGrammarTests(TestCase): grammar = TokenGrammar(""" foo = "token1" "token2" """) - self.assertRaises(ParseError, - grammar.parse, - [Token('tokenBOO'), Token('token2')]) + with pytest.raises(ParseError) as e: + grammar.parse([Token('tokenBOO'), Token('token2')]) + assert "Rule 'foo' didn't match at" in str(e.value) def test_token_repr(self): t = Token(u'πŸ’£') self.assertTrue(isinstance(t.__repr__(), str)) - if sys.version_info < (3, 0): - self.assertEqual(u'<Token "πŸ’£">'.encode('utf-8'), t.__repr__()) - else: - self.assertEqual(u'<Token "πŸ’£">', t.__repr__()) + self.assertEqual(u'<Token "πŸ’£">', t.__repr__()) + + def test_token_star_plus_expressions(self): + a = Token("a") + b = Token("b") + grammar = TokenGrammar(""" + foo = "a"* + bar = "a"+ + """) + assert grammar["foo"].parse([]) is not None + assert grammar["foo"].parse([a]) is not None + assert grammar["foo"].parse([a, a]) is not None + + with pytest.raises(ParseError): + grammar["foo"].parse([a, b]) + with pytest.raises(ParseError): + grammar["foo"].parse([b]) + + assert grammar["bar"].parse([a]) is not None + with pytest.raises(ParseError): + grammar["bar"].parse([a, b]) + with pytest.raises(ParseError): + grammar["bar"].parse([b]) def test_precedence_of_string_modifiers():
TokenMatcher exception _TokenMatcher.\_uncached\_match_ has different behavior than _Literal.\_uncached\_match_ regarding overread. _Literal_'s one returns None on overread thanks to its use of _startswith_. _TokenMatcher_'s one generates an `IndexError: list index out of range`. To reproduce the exception the example below uses a _OneOrMore_ expr that calls _TokenMatcher.\_uncached\_match_ with pos >= len(token_list): ``` py s = [Token('token1'), Token('token2')] grammar = TokenGrammar(""" foo = token1 "token2"+ token1 = "token1" """) grammar.parse(s) ``` Simple fix is to check pos < len(token_list): ``` py def _uncached_match(self, token_list, pos, cache, error): if pos < len(token_list) and token_list[pos].type == self.literal: return Node(self, token_list, pos, pos + 1) ```
0.0
[ "parsimonious/tests/test_expressions.py::LengthTests::test_not", "parsimonious/tests/test_expressions.py::LengthTests::test_one_of", "parsimonious/tests/test_expressions.py::LengthTests::test_one_or_more", "parsimonious/tests/test_expressions.py::LengthTests::test_optional", "parsimonious/tests/test_expressions.py::LengthTests::test_regex", "parsimonious/tests/test_expressions.py::LengthTests::test_sequence", "parsimonious/tests/test_expressions.py::LengthTests::test_zero_or_more", "parsimonious/tests/test_expressions.py::TreeTests::test_one_of", "parsimonious/tests/test_expressions.py::TreeTests::test_one_or_more_one", "parsimonious/tests/test_expressions.py::TreeTests::test_optional", "parsimonious/tests/test_expressions.py::TreeTests::test_sequence_nodes", "parsimonious/tests/test_expressions.py::TreeTests::test_simple_node", "parsimonious/tests/test_expressions.py::TreeTests::test_zero_or_more_zero", "parsimonious/tests/test_expressions.py::ParseTests::test_parse_success", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_favoring_named_rules", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_inner_rule_succeeding", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_line_and_column", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_no_named_rule_succeeding", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_parse_with_leftovers", "parsimonious/tests/test_expressions.py::ErrorReportingTests::test_rewinding", "parsimonious/tests/test_expressions.py::RepresentationTests::test_unicode", "parsimonious/tests/test_expressions.py::RepresentationTests::test_unicode_crash", "parsimonious/tests/test_expressions.py::RepresentationTests::test_unicode_keep_parens", "parsimonious/tests/test_expressions.py::RepresentationTests::test_unicode_surrounding_parens", "parsimonious/tests/test_expressions.py::SlotsTests::test_subclassing", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_quantifier", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_regex", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_spaceless_literal", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_successes", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_optional", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_round_trip", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_undefined_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_bad_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_of_routines", "parsimonious/tests/test_grammar.py::GrammarTests::test_comments", "parsimonious/tests/test_grammar.py::GrammarTests::test_complex_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_expressions_from_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_immutable_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_infinite_loop", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_default_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_lookahead", "parsimonious/tests/test_grammar.py::GrammarTests::test_match", "parsimonious/tests/test_grammar.py::GrammarTests::test_multi_line", "parsimonious/tests/test_grammar.py::GrammarTests::test_not", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens_with_leading_whitespace", "parsimonious/tests/test_grammar.py::GrammarTests::test_repetitions", "parsimonious/tests/test_grammar.py::GrammarTests::test_repr", "parsimonious/tests/test_grammar.py::GrammarTests::test_resolve_refs_completeness", "parsimonious/tests/test_grammar.py::GrammarTests::test_resolve_refs_order", "parsimonious/tests/test_grammar.py::GrammarTests::test_right_recursive", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved_on_shallow_copies", "parsimonious/tests/test_grammar.py::GrammarTests::test_simple_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_single_quoted_literals", "parsimonious/tests/test_grammar.py::GrammarTests::test_unconnected_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_unicode", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_failure", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_success", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_token_repr", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_token_star_plus_expressions", "parsimonious/tests/test_grammar.py::test_precedence_of_string_modifiers", "parsimonious/tests/test_grammar.py::test_binary_grammar", "parsimonious/tests/test_grammar.py::test_inconsistent_string_types_in_grammar" ]
[]
2022-04-11 06:25:42+00:00
2,189
erikrose__parsimonious-211
diff --git a/README.rst b/README.rst index afa55a6..fab1b16 100644 --- a/README.rst +++ b/README.rst @@ -443,6 +443,7 @@ Version History =============== (Next release) + * Improve error message in left-recursive rules. (lucaswiman) * Add support for range ``{min,max}`` repetition expressions (righthandabacus) * Fix bug in ``*`` and ``+`` for token grammars (lucaswiman) * Add support for grammars on bytestrings (lucaswiman) diff --git a/parsimonious/exceptions.py b/parsimonious/exceptions.py index d0f9375..a03a549 100644 --- a/parsimonious/exceptions.py +++ b/parsimonious/exceptions.py @@ -1,3 +1,4 @@ +from textwrap import dedent from parsimonious.utils import StrAndRepr @@ -44,6 +45,20 @@ class ParseError(StrAndRepr, Exception): return self.pos + 1 +class LeftRecursionError(ParseError): + def __str__(self): + rule_name = self.expr.name if self.expr.name else str(self.expr) + window = self.text[self.pos:self.pos + 20] + return dedent(f""" + Left recursion in rule {rule_name!r} at {window!r} (line {self.line()}, column {self.column()}). + + Parsimonious is a packrat parser, so it can't handle left recursion. + See https://en.wikipedia.org/wiki/Parsing_expression_grammar#Indirect_left_recursion + for how to rewrite your grammar into a rule that does not use left-recursion. + """ + ).strip() + + class IncompleteParseError(ParseError): """A call to ``parse()`` matched a whole Expression but did not consume the entire text.""" diff --git a/parsimonious/expressions.py b/parsimonious/expressions.py index 9200365..f93f2c6 100644 --- a/parsimonious/expressions.py +++ b/parsimonious/expressions.py @@ -10,7 +10,7 @@ from collections import defaultdict from inspect import getfullargspec, isfunction, ismethod, ismethoddescriptor import regex as re -from parsimonious.exceptions import ParseError, IncompleteParseError +from parsimonious.exceptions import ParseError, IncompleteParseError, LeftRecursionError from parsimonious.nodes import Node, RegexNode from parsimonious.utils import StrAndRepr @@ -96,6 +96,9 @@ def expression(callable, rule_name, grammar): return AdHocExpression(name=rule_name) +IN_PROGRESS = object() + + class Expression(StrAndRepr): """A thing that can be matched against a piece of text""" @@ -186,10 +189,10 @@ class Expression(StrAndRepr): node = expr_cache[pos] else: # TODO: Set default value to prevent infinite recursion in left-recursive rules. - node = expr_cache[pos] = self._uncached_match(text, - pos, - cache, - error) + expr_cache[pos] = IN_PROGRESS # Mark as in progress + node = expr_cache[pos] = self._uncached_match(text, pos, cache, error) + if node is IN_PROGRESS: + raise LeftRecursionError(text, pos=-1, expr=self) # Record progress for error reporting: if node is None and pos >= error.pos and (
erikrose/parsimonious
69d8ab8ddfcaf67a35a3cc0f8738a5b0d47e3689
diff --git a/parsimonious/tests/test_grammar.py b/parsimonious/tests/test_grammar.py index b4ac7f7..2f979f6 100644 --- a/parsimonious/tests/test_grammar.py +++ b/parsimonious/tests/test_grammar.py @@ -4,9 +4,8 @@ from sys import version_info from unittest import TestCase import pytest -import sys -from parsimonious.exceptions import BadGrammar, UndefinedLabel, ParseError, VisitationError +from parsimonious.exceptions import BadGrammar, LeftRecursionError, ParseError, UndefinedLabel, VisitationError from parsimonious.expressions import Literal, Lookahead, Regex, Sequence, TokenMatcher, is_callable from parsimonious.grammar import rule_grammar, RuleVisitor, Grammar, TokenGrammar, LazyReference from parsimonious.nodes import Node @@ -649,3 +648,20 @@ def test_inconsistent_string_types_in_grammar(): foo = "foo" bar = "bar" """) + + +def test_left_associative(): + # Regression test for https://github.com/erikrose/parsimonious/issues/209 + language_grammar = r""" + expression = operator_expression / non_operator_expression + non_operator_expression = number_expression + + operator_expression = expression "+" non_operator_expression + + number_expression = ~"[0-9]+" + """ + + grammar = Grammar(language_grammar) + with pytest.raises(LeftRecursionError) as e: + grammar["operator_expression"].parse("1+2") + assert "Parsimonious is a packrat parser, so it can't handle left recursion." in str(e.value)
Don't allow recursion if no characters are being used up. I was trying to write left associative operators in grammar, but an issue that kept coming up was infinite recursion. This could be solved by making every operator right associative, because the parser would cut out the option of just going down the same node over and over. Making it so that the parser can only visit one node twice if characters have been used up would completely solve this issue.
0.0
[ "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_quantifier", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_regex", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_spaceless_literal", "parsimonious/tests/test_grammar.py::BootstrappingGrammarTests::test_successes", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_optional", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_round_trip", "parsimonious/tests/test_grammar.py::RuleVisitorTests::test_undefined_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_bad_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_callability_of_routines", "parsimonious/tests/test_grammar.py::GrammarTests::test_circular_toplevel_reference", "parsimonious/tests/test_grammar.py::GrammarTests::test_comments", "parsimonious/tests/test_grammar.py::GrammarTests::test_complex_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_expressions_from_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_immutable_grammar", "parsimonious/tests/test_grammar.py::GrammarTests::test_infinite_loop", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_lazy_default_rule", "parsimonious/tests/test_grammar.py::GrammarTests::test_lookahead", "parsimonious/tests/test_grammar.py::GrammarTests::test_match", "parsimonious/tests/test_grammar.py::GrammarTests::test_multi_line", "parsimonious/tests/test_grammar.py::GrammarTests::test_not", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens", "parsimonious/tests/test_grammar.py::GrammarTests::test_parens_with_leading_whitespace", "parsimonious/tests/test_grammar.py::GrammarTests::test_repetitions", "parsimonious/tests/test_grammar.py::GrammarTests::test_repr", "parsimonious/tests/test_grammar.py::GrammarTests::test_resolve_refs_completeness", "parsimonious/tests/test_grammar.py::GrammarTests::test_resolve_refs_order", "parsimonious/tests/test_grammar.py::GrammarTests::test_right_recursive", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved", "parsimonious/tests/test_grammar.py::GrammarTests::test_rule_ordering_is_preserved_on_shallow_copies", "parsimonious/tests/test_grammar.py::GrammarTests::test_simple_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_single_quoted_literals", "parsimonious/tests/test_grammar.py::GrammarTests::test_unconnected_custom_rules", "parsimonious/tests/test_grammar.py::GrammarTests::test_unicode", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_failure", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_parse_success", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_token_repr", "parsimonious/tests/test_grammar.py::TokenGrammarTests::test_token_star_plus_expressions", "parsimonious/tests/test_grammar.py::test_precedence_of_string_modifiers", "parsimonious/tests/test_grammar.py::test_binary_grammar", "parsimonious/tests/test_grammar.py::test_inconsistent_string_types_in_grammar", "parsimonious/tests/test_grammar.py::test_left_associative" ]
[]
2022-05-07 20:59:50+00:00
2,190
esi-neuroscience__syncopy-457
diff --git a/CHANGELOG.md b/CHANGELOG.md index 86c2a0bc..ca535c2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to this project will be documented in this file. - fix bug #394 'Copying a spy.StructDict returns a dict'. - serializable `.cfg` #392 - single trial cross-corr bug #446 +- fix bug #457, Syncopy does not warn about temp storage dir size exceeding reporting threshold at startup + ## [2022.12] diff --git a/syncopy/__init__.py b/syncopy/__init__.py index 8becb36e..8f27f3a0 100644 --- a/syncopy/__init__.py +++ b/syncopy/__init__.py @@ -36,13 +36,14 @@ except PackageNotFoundError: # --- Greeting --- -def startup_print_once(message): - """Print message once: do not spam message n times during all n worker imports.""" +def startup_print_once(message, force=False): + """Print message once: do not spam message n times during all n worker imports. + """ try: dd.get_client() except ValueError: silence_file = os.path.join(os.path.expanduser("~"), ".spy", "silentstartup") - if os.getenv("SPYSILENTSTARTUP") is None and not os.path.isfile(silence_file): + if force or (os.getenv("SPYSILENTSTARTUP") is None and not os.path.isfile(silence_file)): print(message) @@ -141,23 +142,28 @@ from .statistics import * from .plotting import * from .preproc import * -from .datatype.util import setup_storage +from .datatype.util import setup_storage, get_dir_size storage_tmpdir_size_gb, storage_tmpdir_numfiles = setup_storage() # Creates the storage dir if needed and computes size and number of files in there if any. +spydir_size_gb, spydir_numfiles = get_dir_size(spydir, out="GB") from .shared.log import setup_logging __logdir__ = None # Gets set in setup_logging() call below. setup_logging(spydir=spydir, session=__sessionid__) # Sets __logdir__. startup_print_once(f"Logging to log directory '{__logdir__}'.\nTemporary storage directory set to '{__storage__}'.\n") +storage_msg = ( + "\nSyncopy <core> WARNING: {folder_desc}:s '{tmpdir:s}' " + + "contains {nfs:d} files taking up a total of {sze:4.2f} GB on disk. \n" + + "Please run `spy.cleanup()` and/or manually free up disk space." + ) if storage_tmpdir_size_gb > __storagelimit__: - msg = ( - "\nSyncopy <core> WARNING: Temporary storage folder {tmpdir:s} " - + "contains {nfs:d} files taking up a total of {sze:4.2f} GB on disk. \n" - + "Consider running `spy.cleanup()` to free up disk space." - ) - msg_formatted = msg.format(tmpdir=__storage__, nfs=storage_tmpdir_numfiles, sze=storage_tmpdir_size_gb) - startup_print_once(msg_formatted) - + msg_formatted = storage_msg.format(folder_desc="Temporary storage folder", tmpdir=__storage__, nfs=storage_tmpdir_numfiles, sze=storage_tmpdir_size_gb) + startup_print_once(msg_formatted, force=True) +else: + # We also check the size of the whole Syncopy cfg folder, as older Syncopy versions placed files directly into it. + if spydir_size_gb > __storagelimit__: + msg_formatted = storage_msg.format(folder_desc="User config folder", tmpdir=spydir, nfs=spydir_numfiles, sze=spydir_size_gb) + startup_print_once(msg_formatted, force=True) # Override default traceback (differentiate b/w Jupyter/iPython and regular Python) from .shared.errors import SPYExceptionHandler diff --git a/syncopy/datatype/base_data.py b/syncopy/datatype/base_data.py index c6e5b1e8..6f05555a 100644 --- a/syncopy/datatype/base_data.py +++ b/syncopy/datatype/base_data.py @@ -1255,7 +1255,7 @@ class BaseData(ABC): prop.file.close() # can happen if the file was deleted elsewhere # or we exit un-gracefully from some undefined state - except (ValueError, ImportError): + except (ValueError, ImportError, TypeError): pass # remove from file system diff --git a/syncopy/datatype/util.py b/syncopy/datatype/util.py index 6411737e..dac7dc99 100644 --- a/syncopy/datatype/util.py +++ b/syncopy/datatype/util.py @@ -58,9 +58,35 @@ class TrialIndexer: return "{} element iterable".format(self._len) -def setup_storage(): +def get_dir_size(start_path = '.', out="byte"): """ - Create temporary storage dir and report on its size. + Compute size of all files in directory (and its subdirectories), in bytes or GB. + """ + total_size_bytes = 0 + num_files = 0 + for dirpath, _, filenames in os.walk(start_path): + for f in filenames: + fp = os.path.join(dirpath, f) + # skip if it is symbolic link + try: + if not os.path.islink(fp): + total_size_bytes += os.path.getsize(fp) + num_files += 1 + except Exception as ex: # Ignore issues from several parallel cleanup processes. + pass + + if out == "GB": + total_size = total_size_bytes / 1e9 + elif out == "byte": + total_size = total_size_bytes + else: + raise ValueError("Invalid 'out' unit: '{}', expected one of 'byte' or 'GB'".format(out)) + return total_size, num_files + + +def setup_storage(storage_dir=__storage__): + """ + Create temporary storage dir if needed, and report on its size. Returns ------- @@ -69,29 +95,17 @@ def setup_storage(): """ # Create package-wide tmp directory if not already present - if not os.path.exists(__storage__): + if not os.path.exists(storage_dir): try: - os.mkdir(__storage__) + os.mkdir(storage_dir) except Exception as exc: err = ( "Syncopy core: cannot create temporary storage directory {}. " + "Original error message below\n{}" ) - raise IOError(err.format(__storage__, str(exc))) - - # Check for upper bound of temp directory size - with os.scandir(__storage__) as scan: - storage_size = 0.0 - storage_num_files = 0 - for fle in scan: - try: - storage_size += fle.stat().st_size / 1024 ** 3 - storage_num_files += 1 - # this catches a cleanup by another process - except FileNotFoundError: - continue + raise IOError(err.format(storage_dir, str(exc))) - return storage_size, storage_num_files + return get_dir_size(storage_dir, out="GB")
esi-neuroscience/syncopy
de079999a12c2f365bacebdd89439e6257272825
diff --git a/syncopy/tests/test_datatype_util.py b/syncopy/tests/test_datatype_util.py new file mode 100644 index 00000000..25823bcf --- /dev/null +++ b/syncopy/tests/test_datatype_util.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# +# Test proper functionality of Syncopy's `ContinuousData` class + subclasses +# + +# Builtin/3rd party package imports +import os +import tempfile + +# Local imports +from syncopy.datatype.util import get_dir_size + + +class TestDirSize(): + + def test_dirsize(self): + with tempfile.TemporaryDirectory() as tdir: + fname = "tmpfile" + for file_idx in range(20): + tf = os.path.join(tdir, fname + str(file_idx)) + with open(tf, "w") as f: + f.write(f"This is a dummy file {file_idx}.") + dir_size_byte, num_files = get_dir_size(tdir, out="byte") + assert num_files == 20 + assert dir_size_byte > 200 + assert dir_size_byte < 2000 + assert dir_size_byte == 470 + dir_size_gb, num_files = get_dir_size(tdir, out="GB") + assert dir_size_gb < 1e-6 + + + + +if __name__ == '__main__': + + T1 = TestDirSize() + diff --git a/syncopy/tests/test_statistics.py b/syncopy/tests/test_statistics.py index e25256c4..f2f5a134 100644 --- a/syncopy/tests/test_statistics.py +++ b/syncopy/tests/test_statistics.py @@ -230,7 +230,8 @@ class TestSumStatistics: adata = sd.white_noise(100, nSamples=1000, nChannels=2, - samplerate=500) + samplerate=500, + seed=42) # add simple 60Hz armonic adata += sd.harmonic(100,
Syncopy does not keep track of its temp storage **Describe the bug** Syncopy does not correctly compute the size of its temporary storage directory. **To Reproduce** ```python import syncopy as spy Syncopy 2022.12 See https://syncopy.org for the online documentation. For bug reports etc. please send an email to [email protected] Logging to log directory '/cs/home/kajald/.spy/logs'. Temporary storage directory set to '/cs/home/kajald/.spy/tmp_storage' from syncopy.datatype.util import setup_storage setup_storage() (1.9789702035486698, 8) ``` However, ```bash du -h --max-depth=1 /cs/home/kajald/.spy/tmp_storage/ 1.5G /cs/home/kajald/.spy/tmp_storage/spy_fe54_7bb8e9a9 14G /cs/home/kajald/.spy/tmp_storage/spy_ca09_b73e54ff 512 /cs/home/kajald/.spy/tmp_storage/spy_fe54_bf55d6f2 281G /cs/home/kajald/.spy/tmp_storage/spy_fe54_6d6399c5 512 /cs/home/kajald/.spy/tmp_storage/spy_fe54_deffa14a 512 /cs/home/kajald/.spy/tmp_storage/spy_fe54_41496fd4 512 /cs/home/kajald/.spy/tmp_storage/spy_fe54_194bcf7e 301G /cs/home/kajald/.spy/tmp_storage/ ``` **Expected behavior** Print a warning message if the size of the storage directory exceeds the pre-set limit (of 10GB, I think). **System Profile:** - OS: Linux (RHEL 8.2)
0.0
[ "syncopy/tests/test_datatype_util.py::TestDirSize::test_dirsize", "syncopy/tests/test_statistics.py::TestSumStatistics::test_dim_statistics", "syncopy/tests/test_statistics.py::TestSumStatistics::test_trial_statistics", "syncopy/tests/test_statistics.py::TestSumStatistics::test_selections", "syncopy/tests/test_statistics.py::TestSumStatistics::test_exceptions", "syncopy/tests/test_statistics.py::TestSumStatistics::test_stat_parallel", "syncopy/tests/test_statistics.py::TestSumStatistics::test_itc", "syncopy/tests/test_statistics.py::TestJackknife::test_jk_avg", "syncopy/tests/test_statistics.py::TestJackknife::test_jk_csd", "syncopy/tests/test_statistics.py::TestJackknife::test_jk_coh", "syncopy/tests/test_statistics.py::TestJackknife::test_jk_frontend", "syncopy/tests/test_statistics.py::TestJackknife::test_jk_granger" ]
[]
2023-03-29 13:57:46+00:00
2,191
espdev__csaps-3
diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d405cbf --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# v0.4.2 + +* FIX: "smooth" value is 0.0 was not used + +# v0.4.1 + +* First PyPI release diff --git a/csaps.py b/csaps.py index c838584..e5d82e2 100644 --- a/csaps.py +++ b/csaps.py @@ -281,10 +281,10 @@ class UnivariateCubicSmoothingSpline: # Solve linear system for the 2nd derivatives qtwq = qtw @ qtw.T - if self._smooth: - p = self._smooth - else: + if self._smooth is None: p = self._compute_smooth(r, qtwq) + else: + p = self._smooth a = (6. * (1. - p)) * qtwq + p * r b = np.diff(divdydx, axis=self._axis).T diff --git a/setup.py b/setup.py index 34d524a..b2f82e4 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ from setuptools import setup NAME = 'csaps' -VERSION = '0.4.1' +VERSION = '0.4.2' ROOT_DIR = pathlib.Path(__file__).parent
espdev/csaps
6b73408ecd9d39f5f3c292a8b0446601353e6bac
diff --git a/tests/test_csaps.py b/tests/test_csaps.py index 61172dc..7eb3260 100644 --- a/tests/test_csaps.py +++ b/tests/test_csaps.py @@ -252,5 +252,21 @@ def test_surface_smoothing(): _ = sp(xdata) +def test_zero_smooth(): + x = [1., 2., 4., 6.] + y = [2., 4., 5., 7.] + + sp = csaps.UnivariateCubicSmoothingSpline(x, y, smooth=0.) + + assert sp.smooth == pytest.approx(0.) + + ys = sp(x) + + assert ys == pytest.approx([2.440677966101695, + 3.355932203389830, + 5.186440677966102, + 7.016949152542373]) + + if __name__ == '__main__': pytest.main()
results of UnivariateCubicSmoothingSpline for smooth = 0 @espdev Thank you for writing this library. it is awesome and very useful. I noticed that when I use UnivariateCubicSmoothingSpline with smooth = 0, I don't get a straight line, instead, it does "auto smooth". using the example you gave with smooth = 0 I get: ![image](https://user-images.githubusercontent.com/32917209/58765859-1e01cb00-852c-11e9-914d-ef9cb454ebfe.png) what I expected to get is the following: ![image](https://user-images.githubusercontent.com/32917209/58765836-e3982e00-852b-11e9-9f22-7e2c0ea624ca.png) I believe the root cause for this is that the following if statement in the code would be false for self._smooth = 0: `if self._smooth:` ` p = self._smooth` ` else:` ` p = self._compute_smooth(r, qtwq)` proposed correction: `if (self._smooth or self._smooth==0):` ` p = self._smooth` ` else:` ` p = self._compute_smooth(r, qtwq)`
0.0
[ "tests/test_csaps.py::test_zero_smooth" ]
[ "tests/test_csaps.py::test_univariate_invalid_data[x0-y0-None]", "tests/test_csaps.py::test_univariate_invalid_data[x1-y1-None]", "tests/test_csaps.py::test_univariate_invalid_data[x2-y2-None]", "tests/test_csaps.py::test_univariate_invalid_data[x3-y3-w3]", "tests/test_csaps.py::test_univariate_invalid_data[x4-y4-w4]", "tests/test_csaps.py::test_univariate_invalid_data[x5-y5-w5]", "tests/test_csaps.py::test_univariate_invalid_data[x6-y6-None]", "tests/test_csaps.py::test_univariate_invalid_data[x7-y7-None]", "tests/test_csaps.py::test_univariate_invalid_data[x8-y8-w8]", "tests/test_csaps.py::test_univariate_invalid_data[x9-y9-w9]", "tests/test_csaps.py::test_univariate_invalid_data[x10-y10-w10]", "tests/test_csaps.py::test_univariate_vectorize[y0]", "tests/test_csaps.py::test_univariate_vectorize[y1]", "tests/test_csaps.py::test_univariate_vectorize[y2]", "tests/test_csaps.py::test_univariate_vectorize[y3]", "tests/test_csaps.py::test_univariate_vectorize[y4]", "tests/test_csaps.py::test_univariate_vectorize[y5]", "tests/test_csaps.py::test_univariate_vectorize[y6]", "tests/test_csaps.py::test_univariate_vectorize[y7]", "tests/test_csaps.py::test_univariate_vectorize[y8]", "tests/test_csaps.py::test_univariate_vectorize[y9]", "tests/test_csaps.py::test_univariate_vectorize[y10]", "tests/test_csaps.py::test_univariate_vectorize[y11]", "tests/test_csaps.py::test_univariate_vectorize[y12]", "tests/test_csaps.py::test_univariate_vectorize[y13]", "tests/test_csaps.py::test_univariate_vectorize[y14]", "tests/test_csaps.py::test_univariate_vectorize[y15]", "tests/test_csaps.py::test_univariate_vectorize[y16]", "tests/test_csaps.py::test_univariate_vectorize[y17]", "tests/test_csaps.py::test_univariate_vectorize[y18]", "tests/test_csaps.py::test_univariate_auto_smooth", "tests/test_csaps.py::test_univariate_npoints[x0-y0-xi0-yid0]", "tests/test_csaps.py::test_univariate_npoints[x1-y1-xi1-yid1]", "tests/test_csaps.py::test_univariate_npoints[x2-y2-xi2-yid2]", "tests/test_csaps.py::test_univariate_weighted[w0-yid0]", "tests/test_csaps.py::test_multivariate_auto_tdata", "tests/test_csaps.py::test_grid_invalid_data[x0-y0-None-None]", "tests/test_csaps.py::test_grid_invalid_data[x1-y1-None-None]", "tests/test_csaps.py::test_grid_invalid_data[x2-y2-None-None]", "tests/test_csaps.py::test_grid_invalid_data[x3-y3-None-None]", "tests/test_csaps.py::test_grid_invalid_data[x4-y4-w4-None]", "tests/test_csaps.py::test_grid_invalid_data[x5-y5-w5-None]", "tests/test_csaps.py::test_grid_invalid_data[x6-y6-w6-None]", "tests/test_csaps.py::test_grid_invalid_data[x7-y7-None-p7]", "tests/test_csaps.py::test_surface_smoothing" ]
2019-06-07 01:16:41+00:00
2,192