instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
marshmallow-code__apispec-442
|
diff --git a/docs/using_plugins.rst b/docs/using_plugins.rst
index ad9007b..b9bed1b 100644
--- a/docs/using_plugins.rst
+++ b/docs/using_plugins.rst
@@ -232,35 +232,36 @@ apispec will respect schema modifiers such as ``exclude`` and ``partial`` in the
Custom Fields
***************
-By default, apispec only knows how to set the type of
-built-in marshmallow fields. If you want to generate definitions for
-schemas with custom fields, use the
-`apispec.ext.marshmallow.MarshmallowPlugin.map_to_openapi_type` decorator.
+By default, apispec knows how to map class of the provided marshmallow fields to the
+correct OpenAPI type. If your custom field sub-classes a standard marshmallow field
+class then it will inherit the default mapping. If you want to override the OpenAPI
+type in the generated definitions for schemas with custom fields, use the
+`apispec.ext.marshmallow.MarshmallowPlugin.map_to_openapi_type` decorator. This can
+be invoked with either a pair of strings which provide the OpenAPI type, or a
+marshmallow field that has the same target mapping.
.. code-block:: python
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
- from marshmallow.fields import Integer
+ from marshmallow.fields import Integer, Field
ma_plugin = MarshmallowPlugin()
- spec = APISpec(
- title="Gisty",
- version="1.0.0",
- openapi_version="3.0.2",
- info=dict(description="A minimal gist API"),
- plugins=[ma_plugin],
- )
+
+ # Inherits Integer mapping of ('integer', 'int32')
+ class MyCustomInteger(Integer):
+ pass
+ # Override Integer mapping
@ma_plugin.map_to_openapi_type("string", "uuid")
class MyCustomField(Integer):
pass
@ma_plugin.map_to_openapi_type(Integer) # will map to ('integer', 'int32')
- class MyCustomFieldThatsKindaLikeAnInteger(Integer):
+ class MyCustomFieldThatsKindaLikeAnInteger(Field):
pass
diff --git a/src/apispec/ext/marshmallow/__init__.py b/src/apispec/ext/marshmallow/__init__.py
index d96537a..230b674 100644
--- a/src/apispec/ext/marshmallow/__init__.py
+++ b/src/apispec/ext/marshmallow/__init__.py
@@ -36,6 +36,7 @@ from __future__ import absolute_import
import warnings
from apispec import BasePlugin
+from apispec.compat import itervalues
from .common import resolve_schema_instance, make_schema_key
from .openapi import OpenAPIConverter
@@ -123,11 +124,11 @@ class MarshmallowPlugin(BasePlugin):
# OAS 3 component except header
if self.openapi_version.major >= 3:
if "content" in data:
- for content_type in data["content"]:
- schema = data["content"][content_type]["schema"]
- data["content"][content_type][
- "schema"
- ] = self.openapi.resolve_schema_dict(schema)
+ for content in itervalues(data["content"]):
+ if "schema" in content:
+ content["schema"] = self.openapi.resolve_schema_dict(
+ content["schema"]
+ )
def map_to_openapi_type(self, *args):
"""Decorator to set mapping for custom fields.
|
marshmallow-code/apispec
|
e92ceffd12b2e392b8d199ed314bd2a7e6512dff
|
diff --git a/tests/test_ext_marshmallow.py b/tests/test_ext_marshmallow.py
index c1f2d0e..bac008e 100644
--- a/tests/test_ext_marshmallow.py
+++ b/tests/test_ext_marshmallow.py
@@ -245,6 +245,13 @@ class TestComponentResponseHelper:
assert resolved_schema["properties"]["name"]["type"] == "string"
assert resolved_schema["properties"]["password"]["type"] == "string"
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_content_without_schema(self, spec):
+ resp = {"content": {"application/json": {"example": {"name": "Example"}}}}
+ spec.components.response("GetPetOk", resp)
+ response = get_responses(spec)["GetPetOk"]
+ assert response == resp
+
class TestCustomField:
def test_can_use_custom_field_decorator(self, spec_fixture):
|
Update Custom Fields docs for #435
https://github.com/marshmallow-code/apispec/pull/435#issuecomment-486654039
|
0.0
|
e92ceffd12b2e392b8d199ed314bd2a7e6512dff
|
[
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_content_without_schema[3.0.0]"
] |
[
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[AnalysisWithListSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_nested_schema_many_true_resolver_return_none",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[2.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v2",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[3.0.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[2.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[3.0.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[2.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[3.0.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[2.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[3.0.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[3.0.0]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-01 15:36:11+00:00
|
mit
| 3,735 |
|
marshmallow-code__apispec-495
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index d30d8db..18cb18c 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -6,6 +6,9 @@ Changelog
Features:
+- *Backwards-incompatible* Marshmallow ``fields.Raw`` and ``fields.Field`` are
+ now represented by OpenAPI `Any Type <https://swagger.io/docs/specification/data-models/data-types/#any>`_.
+ (:pr:`495`)
- Add support for generating user defined OpenAPI properties for custom field
classes via an ``add_attribute_function`` method. (:pr:`478`)
- *Backwards-incompatible*: The ``schema_name_resolver`` function now receives
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index 1340ca3..8069eb3 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -37,9 +37,8 @@ DEFAULT_FIELD_MAPPING = {
marshmallow.fields.Email: ("string", "email"),
marshmallow.fields.URL: ("string", "url"),
marshmallow.fields.Dict: ("object", None),
- # Assume base Field and Raw are strings
- marshmallow.fields.Field: ("string", None),
- marshmallow.fields.Raw: ("string", None),
+ marshmallow.fields.Field: (None, None),
+ marshmallow.fields.Raw: (None, None),
marshmallow.fields.List: ("array", None),
}
@@ -183,8 +182,9 @@ class FieldConverterMixin:
)
type_, fmt = "string", None
- ret = {"type": type_}
-
+ ret = {}
+ if type_:
+ ret["type"] = type_
if fmt:
ret["format"] = fmt
@@ -413,7 +413,6 @@ class FieldConverterMixin:
:rtype: dict
"""
if isinstance(field, marshmallow.fields.Nested):
- del ret["type"]
schema_dict = self.resolve_nested_schema(field.schema)
if ret and "$ref" in schema_dict:
ret.update({"allOf": [schema_dict]})
|
marshmallow-code/apispec
|
7016ebc7550780a54277f40959b1686774be08f9
|
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index dd520d4..63d9514 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -34,9 +34,6 @@ def test_field2choices_preserving_order(openapi):
(fields.Time, "string"),
(fields.Email, "string"),
(fields.URL, "string"),
- # Assume base Field and Raw are strings
- (fields.Field, "string"),
- (fields.Raw, "string"),
# Custom fields inherit types from their parents
(CustomStringField, "string"),
(CustomIntegerField, "integer"),
@@ -48,6 +45,13 @@ def test_field2property_type(FieldClass, jsontype, spec_fixture):
assert res["type"] == jsontype
[email protected]("FieldClass", [fields.Field, fields.Raw])
+def test_field2property_no_type_(FieldClass, spec_fixture):
+ field = FieldClass()
+ res = spec_fixture.openapi.field2property(field)
+ assert "type" not in res
+
+
@pytest.mark.parametrize("ListClass", [fields.List, CustomList])
def test_formatted_field_translates_to_array(ListClass, spec_fixture):
field = ListClass(fields.String)
|
Representing openapi's "Any Type"
I am trying to use `marshmallow.fields.Raw` to represent a "arbitrary json" field. Currently I do not see a way to represent a field in marshmallow that will produce a openapi property that is empty when passed through apispec.
The code in `apispec.marshmallow.openapi.OpenAPIConverter.field2type_and_format` (see https://github.com/marshmallow-code/apispec/blob/dev/apispec/ext/marshmallow/openapi.py#L159-L173) unconditionally sets the key `type` in the property object. However it seems that it is legal in openapi to have an empty schema (without the `type` key) which permits any type (see the "Any Type" section at the bottom of https://swagger.io/docs/specification/data-models/data-types/)
Please advise if this is possible with the current codebase or if I will need to implement a custom solution. Thanks.
|
0.0
|
7016ebc7550780a54277f40959b1686774be08f9
|
[
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]"
] |
[
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Integer-int32]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Float-float]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Integer-int32]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Float-float]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-04 02:49:59+00:00
|
mit
| 3,736 |
|
marshmallow-code__apispec-539
|
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 1ad3e9a..84c119e 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -62,3 +62,4 @@ Contributors (chronological)
- Bastien Gerard `@bagerard <https://github.com/bagerard>`_
- Ashutosh Chaudhary `@codeasashu <https://github.com/codeasashu>`_
- Fedor Fominykh `@fedorfo <https://github.com/fedorfo>`_
+- Colin Bounouar `@Colin-b <https://github.com/colin-b>`_
diff --git a/src/apispec/core.py b/src/apispec/core.py
index 77b876c..e878321 100644
--- a/src/apispec/core.py
+++ b/src/apispec/core.py
@@ -190,19 +190,19 @@ class APISpec:
self.version = version
self.openapi_version = OpenAPIVersion(openapi_version)
self.options = options
+ self.plugins = plugins
# Metadata
self._tags = []
self._paths = OrderedDict()
+ # Components
+ self.components = Components(self.plugins, self.openapi_version)
+
# Plugins
- self.plugins = plugins
for plugin in self.plugins:
plugin.init_spec(self)
- # Components
- self.components = Components(self.plugins, self.openapi_version)
-
def to_dict(self):
ret = {
"paths": self._paths,
|
marshmallow-code/apispec
|
20b5ed34366c720fc5a0f50e0b7546cd526cb178
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 3978632..ce9348f 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -276,6 +276,21 @@ class TestComponents:
spec.components.schema("Pet", properties=self.properties, enum=enum)
assert spec.to_dict() == yaml.safe_load(spec.to_yaml())
+ def test_components_can_be_accessed_by_plugin_in_init_spec(self):
+ class TestPlugin(BasePlugin):
+ def init_spec(self, spec):
+ spec.components.schema(
+ "TestSchema",
+ {"properties": {"key": {"type": "string"}}, "type": "object"},
+ )
+
+ spec = APISpec(
+ "Test API", version="0.0.1", openapi_version="2.0", plugins=[TestPlugin()]
+ )
+ assert get_schemas(spec) == {
+ "TestSchema": {"properties": {"key": {"type": "string"}}, "type": "object"}
+ }
+
class TestPath:
paths = {
|
Ability to access APISpec.components in plugin init_spec method
Is there a specific reason why components is initialized after plugins init_spec methods are called?
If not, then I am willing to open a PR to solve this issue.
|
0.0
|
20b5ed34366c720fc5a0f50e0b7546cd526cb178
|
[
"tests/test_core.py::TestComponents::test_components_can_be_accessed_by_plugin_in_init_spec"
] |
[
"tests/test_core.py::TestAPISpecInit::test_raises_wrong_apispec_version",
"tests/test_core.py::TestMetadata::test_openapi_metadata[2.0]",
"tests/test_core.py::TestMetadata::test_openapi_metadata[3.0.0]",
"tests/test_core.py::TestMetadata::test_openapi_metadata_merge_v3[3.0.0]",
"tests/test_core.py::TestTags::test_tag[2.0]",
"tests/test_core.py::TestTags::test_tag[3.0.0]",
"tests/test_core.py::TestTags::test_tag_is_chainable[2.0]",
"tests/test_core.py::TestTags::test_tag_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_schema[2.0]",
"tests/test_core.py::TestComponents::test_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_schema_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_description[2.0]",
"tests/test_core.py::TestComponents::test_schema_description[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_stores_enum[2.0]",
"tests/test_core.py::TestComponents::test_schema_stores_enum[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_discriminator[2.0]",
"tests/test_core.py::TestComponents::test_schema_discriminator[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_schema_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_response[2.0]",
"tests/test_core.py::TestComponents::test_response[3.0.0]",
"tests/test_core.py::TestComponents::test_response_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_response_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_response_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_response_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter[2.0]",
"tests/test_core.py::TestComponents::test_parameter[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_parameter_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_parameter_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_example[3.0.0]",
"tests/test_core.py::TestComponents::test_example_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_example_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_to_yaml[2.0]",
"tests/test_core.py::TestComponents::test_to_yaml[3.0.0]",
"tests/test_core.py::TestPath::test_path[2.0]",
"tests/test_core.py::TestPath::test_path[3.0.0]",
"tests/test_core.py::TestPath::test_paths_maintain_order[2.0]",
"tests/test_core.py::TestPath::test_paths_maintain_order[3.0.0]",
"tests/test_core.py::TestPath::test_paths_is_chainable[2.0]",
"tests/test_core.py::TestPath::test_paths_is_chainable[3.0.0]",
"tests/test_core.py::TestPath::test_methods_maintain_order[2.0]",
"tests/test_core.py::TestPath::test_methods_maintain_order[3.0.0]",
"tests/test_core.py::TestPath::test_path_merges_paths[2.0]",
"tests/test_core.py::TestPath::test_path_merges_paths[3.0.0]",
"tests/test_core.py::TestPath::test_path_called_twice_with_same_operations_parameters[2.0]",
"tests/test_core.py::TestPath::test_path_called_twice_with_same_operations_parameters[3.0.0]",
"tests/test_core.py::TestPath::test_path_ensures_path_parameters_required[2.0]",
"tests/test_core.py::TestPath::test_path_ensures_path_parameters_required[3.0.0]",
"tests/test_core.py::TestPath::test_path_with_no_path_raises_error[2.0]",
"tests/test_core.py::TestPath::test_path_with_no_path_raises_error[3.0.0]",
"tests/test_core.py::TestPath::test_path_summary_description[2.0]",
"tests/test_core.py::TestPath::test_path_summary_description[3.0.0]",
"tests/test_core.py::TestPath::test_parameter[2.0]",
"tests/test_core.py::TestPath::test_parameter[3.0.0]",
"tests/test_core.py::TestPath::test_invalid_parameter[2.0-parameters0]",
"tests/test_core.py::TestPath::test_invalid_parameter[2.0-parameters1]",
"tests/test_core.py::TestPath::test_invalid_parameter[3.0.0-parameters0]",
"tests/test_core.py::TestPath::test_invalid_parameter[3.0.0-parameters1]",
"tests/test_core.py::TestPath::test_parameter_duplicate[2.0]",
"tests/test_core.py::TestPath::test_parameter_duplicate[3.0.0]",
"tests/test_core.py::TestPath::test_global_parameters[2.0]",
"tests/test_core.py::TestPath::test_global_parameters[3.0.0]",
"tests/test_core.py::TestPath::test_global_parameter_duplicate[2.0]",
"tests/test_core.py::TestPath::test_global_parameter_duplicate[3.0.0]",
"tests/test_core.py::TestPath::test_response[2.0]",
"tests/test_core.py::TestPath::test_response[3.0.0]",
"tests/test_core.py::TestPath::test_response_with_HTTPStatus_code[2.0]",
"tests/test_core.py::TestPath::test_response_with_HTTPStatus_code[3.0.0]",
"tests/test_core.py::TestPath::test_response_with_status_code_range[2.0]",
"tests/test_core.py::TestPath::test_response_with_status_code_range[3.0.0]",
"tests/test_core.py::TestPath::test_path_check_invalid_http_method[2.0]",
"tests/test_core.py::TestPath::test_path_check_invalid_http_method[3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_factory",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_operation_helper_is_used[2.0]",
"tests/test_core.py::TestPlugins::test_plugin_operation_helper_is_used[3.0.0]",
"tests/test_core.py::TestPluginsOrder::test_plugins_order"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-12 16:51:55+00:00
|
mit
| 3,737 |
|
marshmallow-code__apispec-568
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index d24fdd5..475e50c 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,16 @@
Changelog
---------
+3.3.1 (unreleased)
+******************
+
+Bug fixes:
+
+- Fix ``MarshmallowPlugin`` crash when ``resolve_schema_dict`` is passed a
+ schema as string and ``schema_name_resolver`` returns ``None``
+ (:issue:`566`). Thanks :user:`black3r` for reporting and thanks
+ :user:`Bangterm` for the PR.
+
3.3.0 (2020-02-14)
******************
diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py
index 8cf3460..a79172d 100644
--- a/src/apispec/ext/marshmallow/openapi.py
+++ b/src/apispec/ext/marshmallow/openapi.py
@@ -93,7 +93,7 @@ class OpenAPIConverter(FieldConverterMixin):
name = self.schema_name_resolver(schema)
if not name:
try:
- json_schema = self.schema2jsonschema(schema)
+ json_schema = self.schema2jsonschema(schema_instance)
except RuntimeError:
raise APISpecError(
"Name resolver returned None for schema {schema} which is "
|
marshmallow-code/apispec
|
8ec05f8686a199f6fcf537d7fbd94953a22cc48b
|
diff --git a/tests/test_ext_marshmallow.py b/tests/test_ext_marshmallow.py
index a5a91bd..4755ad7 100644
--- a/tests/test_ext_marshmallow.py
+++ b/tests/test_ext_marshmallow.py
@@ -558,6 +558,55 @@ class TestOperationHelper:
"schema"
] == build_ref(spec, "schema", "Pet")
+ @pytest.mark.parametrize(
+ "pet_schema", (PetSchema, PetSchema(), "tests.schemas.PetSchema"),
+ )
+ def test_schema_name_resolver_returns_none_v2(self, pet_schema):
+ def resolver(schema):
+ return None
+
+ spec = APISpec(
+ title="Test resolver returns None",
+ version="0.1",
+ openapi_version="2.0",
+ plugins=(MarshmallowPlugin(schema_name_resolver=resolver),),
+ )
+ spec.path(
+ path="/pet",
+ operations={"get": {"responses": {200: {"schema": pet_schema}}}},
+ )
+ get = get_paths(spec)["/pet"]["get"]
+ assert "properties" in get["responses"]["200"]["schema"]
+
+ @pytest.mark.parametrize(
+ "pet_schema", (PetSchema, PetSchema(), "tests.schemas.PetSchema"),
+ )
+ def test_schema_name_resolver_returns_none_v3(self, pet_schema):
+ def resolver(schema):
+ return None
+
+ spec = APISpec(
+ title="Test resolver returns None",
+ version="0.1",
+ openapi_version="3.0.0",
+ plugins=(MarshmallowPlugin(schema_name_resolver=resolver),),
+ )
+ spec.path(
+ path="/pet",
+ operations={
+ "get": {
+ "responses": {
+ 200: {"content": {"application/json": {"schema": pet_schema}}}
+ }
+ }
+ },
+ )
+ get = get_paths(spec)["/pet"]["get"]
+ assert (
+ "properties"
+ in get["responses"]["200"]["content"]["application/json"]["schema"]
+ )
+
@pytest.mark.parametrize("spec_fixture", ("2.0",), indirect=True)
def test_schema_uses_ref_in_parameters_and_request_body_if_available_v2(
self, spec_fixture
|
Marshmallow plugin bug with string schema ref and schema_name_resolver
`resolve_schema_dict` claims to support `string` as its schema parameter type. It can get there for example when you are parsing schema from docstring using the provided yaml util, or using FlaskPlugin to do it for you.
But, when `schema_name_resolver` returns `None` for this case, the schema gets forwarded to `schema2jsonschema` which expects a `marshmallow.Schema` instance and crashes.
Test case is a slightly modified "example application":
<details>
<summary>Show example test case</summary>
```python
import uuid
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from flask import Flask, jsonify
from marshmallow import fields, Schema
def schema_name_resolver(schema):
if schema == "PetSchema":
return None
# Create an APISpec
spec = APISpec(
title="Swagger Petstore",
version="1.0.0",
openapi_version="3.0.2",
plugins=[
FlaskPlugin(),
MarshmallowPlugin(schema_name_resolver=schema_name_resolver),
],
)
# Optional marshmallow support
class CategorySchema(Schema):
id = fields.Int()
name = fields.Str(required=True)
class PetSchema(Schema):
categories = fields.List(fields.Nested(CategorySchema))
name = fields.Str()
# Optional Flask support
app = Flask(__name__)
@app.route("/random")
def random_pet():
"""A cute furry animal endpoint.
---
get:
description: Get a random pet
responses:
200:
description: Return a pet
content:
application/json:
schema: PetSchema
"""
# Hardcoded example data
pet_data = {
"name": "sample_pet_" + str(uuid.uuid1()),
"categories": [{"id": 1, "name": "sample_category"}],
}
return PetSchema().dump(pet_data)
# Register the path and the entities within it
with app.test_request_context():
spec.path(view=random_pet)
@app.route("/spec.json")
def get_spec():
return jsonify(spec.to_dict())
```
</details>
<details>
<summary>Show example stacktrace</summary>
```
Traceback (most recent call last):
File "/home//PycharmProjects/test-apispec/main.py", line 62, in <module>
spec.path(view=random_pet)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/core.py", line 280, in path
plugin.operation_helper(path=path, operations=operations, **kwargs)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/__init__.py", line 202, in operation_helper
self.resolver.resolve_response(response)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/schema_resolver.py", line 113, in resolve_response
self.resolve_schema(response)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/schema_resolver.py", line 161, in resolve_schema
content["schema"] = self.resolve_schema_dict(content["schema"])
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/schema_resolver.py", line 218, in resolve_schema_dict
return self.converter.resolve_nested_schema(schema)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/openapi.py", line 96, in resolve_nested_schema
json_schema = self.schema2jsonschema(schema)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/openapi.py", line 261, in schema2jsonschema
fields = get_fields(schema)
File "/home//.local/share/virtualenvs/test-apispec-HubT4B3L/lib/python3.8/site-packages/apispec/ext/marshmallow/common.py", line 63, in get_fields
raise ValueError(
ValueError: 'PetSchema' doesn't have either `fields` or `_declared_fields`.
```
</details>
I think it should be enough to just pass `schema_instance` instead of `schema` to `self.schema2jsonschema` in `resolve_nested_schema`
|
0.0
|
8ec05f8686a199f6fcf537d7fbd94953a22cc48b
|
[
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[tests.schemas.PetSchema]"
] |
[
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[AnalysisWithListSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_nested_schema_many_true_resolver_return_none",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_content_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[2.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v2",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[3.0.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[2.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[3.0.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[2.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[3.0.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[2.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[3.0.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[3.0.0]"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-22 17:00:31+00:00
|
mit
| 3,738 |
|
marshmallow-code__apispec-616
|
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index 0b3798a..8583ec0 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -83,6 +83,8 @@ class FieldConverterMixin:
def init_attribute_functions(self):
self.attribute_functions = [
+ # self.field2type_and_format should run first
+ # as other functions may rely on its output
self.field2type_and_format,
self.field2default,
self.field2choices,
@@ -272,7 +274,7 @@ class FieldConverterMixin:
] = True
return attributes
- def field2range(self, field, **kwargs):
+ def field2range(self, field, ret):
"""Return the dictionary of OpenAPI field attributes for a set of
:class:`Range <marshmallow.validators.Range>` validators.
@@ -289,19 +291,12 @@ class FieldConverterMixin:
)
]
- attributes = {}
- for validator in validators:
- if validator.min is not None:
- if hasattr(attributes, "minimum"):
- attributes["minimum"] = max(attributes["minimum"], validator.min)
- else:
- attributes["minimum"] = validator.min
- if validator.max is not None:
- if hasattr(attributes, "maximum"):
- attributes["maximum"] = min(attributes["maximum"], validator.max)
- else:
- attributes["maximum"] = validator.max
- return attributes
+ min_attr, max_attr = (
+ ("minimum", "maximum")
+ if ret.get("type") in {"number", "integer"}
+ else ("x-minimum", "x-maximum")
+ )
+ return make_min_max_attributes(validators, min_attr, max_attr)
def field2length(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a set of
@@ -310,8 +305,6 @@ class FieldConverterMixin:
:param Field field: A marshmallow field.
:rtype: dict
"""
- attributes = {}
-
validators = [
validator
for validator in field.validators
@@ -328,23 +321,13 @@ class FieldConverterMixin:
min_attr = "minItems" if is_array else "minLength"
max_attr = "maxItems" if is_array else "maxLength"
- for validator in validators:
- if validator.min is not None:
- if hasattr(attributes, min_attr):
- attributes[min_attr] = max(attributes[min_attr], validator.min)
- else:
- attributes[min_attr] = validator.min
- if validator.max is not None:
- if hasattr(attributes, max_attr):
- attributes[max_attr] = min(attributes[max_attr], validator.max)
- else:
- attributes[max_attr] = validator.max
-
- for validator in validators:
- if validator.equal is not None:
- attributes[min_attr] = validator.equal
- attributes[max_attr] = validator.equal
- return attributes
+ equal_list = [
+ validator.equal for validator in validators if validator.equal is not None
+ ]
+ if equal_list:
+ return {min_attr: equal_list[0], max_attr: equal_list[0]}
+
+ return make_min_max_attributes(validators, min_attr, max_attr)
def field2pattern(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a set of
@@ -449,3 +432,23 @@ class FieldConverterMixin:
if value_field:
ret["additionalProperties"] = self.field2property(value_field)
return ret
+
+
+def make_min_max_attributes(validators, min_attr, max_attr):
+ """Return a dictionary of minimum and maximum attributes based on a list
+ of validators. If either minimum or maximum values are not present in any
+ of the validator objects that attribute will be omitted.
+
+ :param validators list: A list of `Marshmallow` validator objects. Each
+ objct is inspected for a minimum and maximum values
+ :param min_attr string: The OpenAPI attribute for the minimum value
+ :param max_attr string: The OpenAPI attribute for the maximum value
+ """
+ attributes = {}
+ min_list = [validator.min for validator in validators if validator.min is not None]
+ max_list = [validator.max for validator in validators if validator.max is not None]
+ if min_list:
+ attributes[min_attr] = max(min_list)
+ if max_list:
+ attributes[max_attr] = min(max_list)
+ return attributes
|
marshmallow-code/apispec
|
5762c831fccf9d8dedcdfb901d106c02addc278b
|
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 5879073..36c6ad0 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -1,4 +1,5 @@
import pytest
+from datetime import datetime
from marshmallow import fields, Schema, validate
@@ -498,6 +499,7 @@ class TestFieldValidation:
class ValidationSchema(Schema):
id = fields.Int(dump_only=True)
range = fields.Int(validate=validate.Range(min=1, max=10))
+ range_no_upper = fields.Float(validate=validate.Range(min=1))
multiple_ranges = fields.Int(
validate=[
validate.Range(min=1),
@@ -523,11 +525,13 @@ class TestFieldValidation:
equal_length = fields.Str(
validate=[validate.Length(equal=5), validate.Length(min=1, max=10)]
)
+ date_range = fields.DateTime(validate=validate.Range(min=datetime(1900, 1, 1),))
@pytest.mark.parametrize(
("field", "properties"),
[
("range", {"minimum": 1, "maximum": 10}),
+ ("range_no_upper", {"minimum": 1}),
("multiple_ranges", {"minimum": 3, "maximum": 7}),
("list_length", {"minItems": 1, "maxItems": 10}),
("custom_list_length", {"minItems": 1, "maxItems": 10}),
@@ -535,6 +539,7 @@ class TestFieldValidation:
("custom_field_length", {"minLength": 1, "maxLength": 10}),
("multiple_lengths", {"minLength": 3, "maxLength": 7}),
("equal_length", {"minLength": 5, "maxLength": 5}),
+ ("date_range", {"x-minimum": datetime(1900, 1, 1)}),
],
)
def test_properties(self, field, properties, spec):
|
Minimum/maximum date is not jsonschema compliant
I'm using flask-apispec (but I think that the issue is related to apispec) to generate a swagger 2.0 schema from webargs/marshmallow models that include datetimes with min/max boundaries like this:
```
mydate = fields.DateTime(
required=True,
validate=validate.Range(
max=datetime.now(pytz.utc).replace(hour=23, minute=59, second=59),
min=datetime(1900, 1, 1, tzinfo=pytz.utc),
max_inclusive=True
)
)
```
The generated json shema is:
```
"mydate": {
"format": "date-time",
"maximum": "Tue, 08 Dec 2020 23:59:59 GMT",
"minimum": "Mon, 01 Jan 1900 00:00:00 GMT",
"type": "string"
},
```
But when I run schemathesis on the generated schema I obtain a validation error
```
E jsonschema.exceptions.ValidationError: 'Tue, 08 Dec 2020 23:59:59 GMT' is not of type 'number'
E
E Failed validating 'type' in schema['properties']['definitions']['additionalProperties']['properties']['properties']['additionalProperties']['properties']['maximum']:
E {'type': 'number'}
E
E On instance['definitions']['Input']['properties']['mydate']['maximum']:
E 'Tue, 08 Dec 2020 23:59:59 GMT'
```
Schemathesis is right, because minimum and maximum values are expected to be "JSON numbers" (https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3) and not datetimes
On the other side having min and max date validation is a very appreciated feature, so the option to avoid to set these boundaries on the models is not really feasible for my use cases. Furthermore the use of schemathesis is very helpful for my test suite and I would like to continue to use it.
Is there something that I can modify / configure to obtain jsonschema compliant models from webargs/marshmallow schema with datetimes min/max values?
Or maybe is there something that apispec could fix to obtain the result? (for example convert min/max datetimes into timestamps? Having a number should be adherent to the schema specification)
If not possible, I could try to open an issue on schemathesis to ask for some compatibility fixes. They already include [compatibility fixes for fastapi](https://schemathesis.readthedocs.io/en/stable/compatibility.html#using-fastapi) (that by using pydantic produces Draft 7 compatible schemas, while schemathesis validates against Draft 4 and Wright Draft 00) so maybe they would be interested in adding some compatibility fixes also for apispec. But in this case I would like to ask for your help to support the request by providing your motivations for not meeting the specifications or other information that they could ask to me.
I really thank you for your help
|
0.0
|
5762c831fccf9d8dedcdfb901d106c02addc278b
|
[
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v2",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v3",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-11 23:02:05+00:00
|
mit
| 3,739 |
|
marshmallow-code__apispec-671
|
diff --git a/docs/special_topics.rst b/docs/special_topics.rst
index 892d4a0..43170a1 100644
--- a/docs/special_topics.rst
+++ b/docs/special_topics.rst
@@ -53,14 +53,29 @@ JSON
Documenting Top-level Components
--------------------------------
-The ``APISpec`` object contains helpers to add top-level components.
-
-To add a schema (f.k.a. "definition" in OAS v2), use
-`spec.components.schema <apispec.core.Components.schema>`.
-
-Likewise, parameters and responses can be added using
-`spec.components.parameter <apispec.core.Components.parameter>` and
-`spec.components.response <apispec.core.Components.response>`.
+The ``APISpec`` object contains helpers to add top-level components:
+
+.. list-table::
+ :header-rows: 1
+
+ * - Component type
+ - Helper method
+ - OpenAPI version
+ * - Schema (f.k.a. "definition" in OAS v2)
+ - `spec.components.schema <apispec.core.Components.schema>`
+ - 2, 3
+ * - Parameter
+ - `spec.components.parameter <apispec.core.Components.parameter>`
+ - 2, 3
+ * - Reponse
+ - `spec.components.response <apispec.core.Components.response>`
+ - 2, 3
+ * - Header
+ - `spec.components.response <apispec.core.Components.header>`
+ - 3
+ * - Example
+ - `spec.components.response <apispec.core.Components.example>`
+ - 3
To add other top-level objects, pass them to the ``APISpec`` as keyword arguments.
@@ -134,3 +149,18 @@ to document `Security Scheme Objects <https://github.com/OAI/OpenAPI-Specificati
pprint(spec.to_dict()["components"]["securitySchemes"], indent=2)
# { 'api_key': {'in': 'header', 'name': 'X-API-Key', 'type': 'apiKey'},
# 'jwt': {'bearerFormat': 'JWT', 'scheme': 'bearer', 'type': 'http'}}
+
+Referencing Top-level Components
+--------------------------------
+
+On OpenAPI, top-level component are meant to be referenced using a ``$ref``,
+as in ``{$ref: '#/components/schemas/Pet'}`` (OpenAPI v3) or
+``{$ref: '#/definitions/Pet'}`` (OpenAPI v2).
+
+APISpec automatically resolves references in paths and in components themselves
+when a string is provided while a dict is expected. Passing a fully-resolved
+reference is not supported. In other words, rather than passing
+``{"schema": {$ref: '#/components/schemas/Pet'}}``, the user must pass
+``{"schema": "Pet"}``. APISpec assumes a schema reference named ``"Pet"`` has
+been defined and builds the reference using the components location
+corresponding to the OpenAPI version.
diff --git a/src/apispec/core.py b/src/apispec/core.py
index 54bb7e3..3aa7029 100644
--- a/src/apispec/core.py
+++ b/src/apispec/core.py
@@ -86,6 +86,7 @@ class Components:
ret.update(plugin.schema_helper(name, component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
+ self._resolve_refs_in_schema(ret)
self.schemas[name] = ret
return self
@@ -110,6 +111,7 @@ class Components:
ret.update(plugin.response_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
+ self._resolve_refs_in_response(ret)
self.responses[component_id] = ret
return self
@@ -142,6 +144,7 @@ class Components:
ret.update(plugin.parameter_helper(component, **kwargs) or {})
except PluginMethodNotImplementedError:
continue
+ self._resolve_refs_in_parameter_or_header(ret)
self.parameters[component_id] = ret
return self
@@ -157,6 +160,7 @@ class Components:
raise DuplicateComponentNameError(
f'Another header with name "{component_id}" is already registered.'
)
+ self._resolve_refs_in_parameter_or_header(component)
self.headers[component_id] = component
return self
@@ -205,44 +209,66 @@ class Components:
return build_reference(obj_type, self.openapi_version.major, obj)
def _resolve_schema(self, obj):
- """Replace schema reference as string with a $ref if needed."""
- if not isinstance(obj, dict):
- return
- if self.openapi_version.major < 3:
- if "schema" in obj:
- obj["schema"] = self.get_ref("schema", obj["schema"])
- else:
- if "content" in obj:
- for content in obj["content"].values():
- if "schema" in content:
- content["schema"] = self.get_ref("schema", content["schema"])
+ """Replace schema reference as string with a $ref if needed
+
+ Also resolve references in the schema
+ """
+ if "schema" in obj:
+ obj["schema"] = self.get_ref("schema", obj["schema"])
+ self._resolve_refs_in_schema(obj["schema"])
def _resolve_examples(self, obj):
"""Replace example reference as string with a $ref"""
for name, example in obj.get("examples", {}).items():
obj["examples"][name] = self.get_ref("example", example)
- def _resolve_refs_in_parameter(self, parameter):
- self._resolve_examples(parameter)
+ def _resolve_refs_in_schema(self, schema):
+ if "properties" in schema:
+ for key in schema["properties"]:
+ schema["properties"][key] = self.get_ref(
+ "schema", schema["properties"][key]
+ )
+ self._resolve_refs_in_schema(schema["properties"][key])
+ if "items" in schema:
+ schema["items"] = self.get_ref("schema", schema["items"])
+ self._resolve_refs_in_schema(schema["items"])
+ for key in ("allOf", "oneOf", "anyOf"):
+ if key in schema:
+ schema[key] = [self.get_ref("schema", s) for s in schema[key]]
+ for sch in schema[key]:
+ self._resolve_refs_in_schema(sch)
+ if "not" in schema:
+ schema["not"] = self.get_ref("schema", schema["not"])
+ self._resolve_refs_in_schema(schema["not"])
+
+ def _resolve_refs_in_parameter_or_header(self, parameter_or_header):
+ self._resolve_schema(parameter_or_header)
+ self._resolve_examples(parameter_or_header)
def _resolve_refs_in_request_body(self, request_body):
- self._resolve_schema(request_body)
+ # requestBody is OpenAPI v3+
for media_type in request_body["content"].values():
+ self._resolve_schema(media_type)
self._resolve_examples(media_type)
def _resolve_refs_in_response(self, response):
- self._resolve_schema(response)
- for name, header in response.get("headers", {}).items():
- response["headers"][name] = self.get_ref("header", header)
- for media_type in response.get("content", {}).values():
- self._resolve_examples(media_type)
+ if self.openapi_version.major < 3:
+ self._resolve_schema(response)
+ else:
+ for media_type in response.get("content", {}).values():
+ self._resolve_schema(media_type)
+ self._resolve_examples(media_type)
+ for name, header in response.get("headers", {}).items():
+ response["headers"][name] = self.get_ref("header", header)
+ self._resolve_refs_in_parameter_or_header(response["headers"][name])
+ # TODO: Resolve link refs when Components supports links
def _resolve_refs_in_operation(self, operation):
if "parameters" in operation:
parameters = []
for parameter in operation["parameters"]:
parameter = self.get_ref("parameter", parameter)
- self._resolve_refs_in_parameter(parameter)
+ self._resolve_refs_in_parameter_or_header(parameter)
parameters.append(parameter)
operation["parameters"] = parameters
if "requestBody" in operation:
@@ -260,7 +286,7 @@ class Components:
parameters = []
for parameter in path["parameters"]:
parameter = self.get_ref("parameter", parameter)
- self._resolve_refs_in_parameter(parameter)
+ self._resolve_refs_in_parameter_or_header(parameter)
parameters.append(parameter)
path["parameters"] = parameters
for method in (
|
marshmallow-code/apispec
|
4c84e22b010512e3dbb443a0a8e9fb53d56a9c07
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 94bd5cb..66e2ff8 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,3 +1,4 @@
+import copy
from collections import OrderedDict
from http import HTTPStatus
@@ -30,6 +31,69 @@ description = "This is a sample Petstore server. You can find out more "
'key "special-key" to test the authorization filters'
+class RefsSchemaTestMixin:
+ REFS_SCHEMA = {
+ "properties": {
+ "nested": "NestedSchema",
+ "deep_nested": {"properties": {"nested": "NestedSchema"}},
+ "nested_list": {"items": "DeepNestedSchema"},
+ "deep_nested_list": {
+ "items": {"properties": {"nested": "DeepNestedSchema"}}
+ },
+ "allof": {
+ "allOf": [
+ "AllOfSchema",
+ {"properties": {"nested": "AllOfSchema"}},
+ ]
+ },
+ "oneof": {
+ "oneOf": [
+ "OneOfSchema",
+ {"properties": {"nested": "OneOfSchema"}},
+ ]
+ },
+ "anyof": {
+ "anyOf": [
+ "AnyOfSchema",
+ {"properties": {"nested": "AnyOfSchema"}},
+ ]
+ },
+ "not": "NotSchema",
+ "deep_not": {"properties": {"nested": "DeepNotSchema"}},
+ }
+ }
+
+ @staticmethod
+ def assert_schema_refs(spec, schema):
+ props = schema["properties"]
+ assert props["nested"] == build_ref(spec, "schema", "NestedSchema")
+ assert props["deep_nested"]["properties"]["nested"] == build_ref(
+ spec, "schema", "NestedSchema"
+ )
+ assert props["nested_list"]["items"] == build_ref(
+ spec, "schema", "DeepNestedSchema"
+ )
+ assert props["deep_nested_list"]["items"]["properties"]["nested"] == build_ref(
+ spec, "schema", "DeepNestedSchema"
+ )
+ assert props["allof"]["allOf"][0] == build_ref(spec, "schema", "AllOfSchema")
+ assert props["allof"]["allOf"][1]["properties"]["nested"] == build_ref(
+ spec, "schema", "AllOfSchema"
+ )
+ assert props["oneof"]["oneOf"][0] == build_ref(spec, "schema", "OneOfSchema")
+ assert props["oneof"]["oneOf"][1]["properties"]["nested"] == build_ref(
+ spec, "schema", "OneOfSchema"
+ )
+ assert props["anyof"]["anyOf"][0] == build_ref(spec, "schema", "AnyOfSchema")
+ assert props["anyof"]["anyOf"][1]["properties"]["nested"] == build_ref(
+ spec, "schema", "AnyOfSchema"
+ )
+ assert props["not"] == build_ref(spec, "schema", "NotSchema")
+ assert props["deep_not"]["properties"]["nested"] == build_ref(
+ spec, "schema", "DeepNotSchema"
+ )
+
+
@pytest.fixture(params=("2.0", "3.0.0"))
def spec(request):
openapi_version = request.param
@@ -132,7 +196,7 @@ class TestTags:
assert spec.to_dict()["tags"] == [{"name": "tag1"}, {"name": "tag2"}]
-class TestComponents:
+class TestComponents(RefsSchemaTestMixin):
properties = {
"id": {"type": "integer", "format": "int64"},
@@ -321,8 +385,138 @@ class TestComponents:
"TestSchema": {"properties": {"key": {"type": "string"}}, "type": "object"}
}
+ def test_components_resolve_refs_in_schema(self, spec):
+ spec.components.schema("refs_schema", copy.deepcopy(self.REFS_SCHEMA))
+ self.assert_schema_refs(spec, get_schemas(spec)["refs_schema"])
-class TestPath:
+ def test_components_resolve_response_schema(self, spec):
+ schema = {"schema": "PetSchema"}
+ if spec.openapi_version.major >= 3:
+ schema = {"content": {"application/json": schema}}
+ spec.components.response("Response", schema)
+ resp = get_responses(spec)["Response"]
+ if spec.openapi_version.major < 3:
+ schema = resp["schema"]
+ else:
+ schema = resp["content"]["application/json"]["schema"]
+ assert schema == build_ref(spec, "schema", "PetSchema")
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_response_header(self, spec):
+ response = {"headers": {"header_1": "Header_1"}}
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ header_1 = resp["headers"]["header_1"]
+ assert header_1 == build_ref(spec, "header", "Header_1")
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_response_header_schema(self, spec):
+ response = {"headers": {"header_1": {"name": "Pet", "schema": "PetSchema"}}}
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ header_1 = resp["headers"]["header_1"]
+ assert header_1["schema"] == build_ref(spec, "schema", "PetSchema")
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_response_header_examples(self, spec):
+ response = {
+ "headers": {
+ "header_1": {"name": "Pet", "examples": {"example_1": "Example_1"}}
+ }
+ }
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ header_1 = resp["headers"]["header_1"]
+ assert header_1["examples"]["example_1"] == build_ref(
+ spec, "example", "Example_1"
+ )
+
+ # "examples" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_response_examples(self, spec):
+ response = {
+ "content": {"application/json": {"examples": {"example_1": "Example_1"}}}
+ }
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ example_1 = resp["content"]["application/json"]["examples"]["example_1"]
+ assert example_1 == build_ref(spec, "example", "Example_1")
+
+ def test_components_resolve_refs_in_response_schema(self, spec):
+ schema = copy.deepcopy(self.REFS_SCHEMA)
+ if spec.openapi_version.major >= 3:
+ response = {"content": {"application/json": {"schema": schema}}}
+ else:
+ response = {"schema": schema}
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ if spec.openapi_version.major < 3:
+ schema = resp["schema"]
+ else:
+ schema = resp["content"]["application/json"]["schema"]
+ self.assert_schema_refs(spec, schema)
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_refs_in_response_header_schema(self, spec):
+ header = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
+ response = {"headers": {"header": header}}
+ spec.components.response("Response", response)
+ resp = get_responses(spec)["Response"]
+ self.assert_schema_refs(spec, resp["headers"]["header"]["schema"])
+
+ # "examples" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_parameter_examples(self, spec):
+ parameter = {
+ "examples": {"example_1": "Example_1"},
+ }
+ spec.components.parameter("param", "path", parameter)
+ param = get_parameters(spec)["param"]
+ example_1 = param["examples"]["example_1"]
+ assert example_1 == build_ref(spec, "example", "Example_1")
+
+ def test_components_resolve_parameter_schemas(self, spec):
+ parameter = {"schema": "PetSchema"}
+ spec.components.parameter("param", "path", parameter)
+ param = get_parameters(spec)["param"]
+ assert param["schema"] == build_ref(spec, "schema", "PetSchema")
+
+ def test_components_resolve_refs_in_parameter_schema(self, spec):
+ parameter = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
+ spec.components.parameter("param", "path", parameter)
+ self.assert_schema_refs(spec, get_parameters(spec)["param"]["schema"])
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_header_schema(self, spec):
+ header = {"name": "Pet", "schema": "PetSchema"}
+ spec.components.header("header", header)
+ header = get_headers(spec)["header"]
+ assert header["schema"] == build_ref(spec, "schema", "PetSchema")
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_header_examples(self, spec):
+ header = {"name": "Pet", "examples": {"example_1": "Example_1"}}
+ spec.components.header("header", header)
+ header = get_headers(spec)["header"]
+ assert header["examples"]["example_1"] == build_ref(
+ spec, "example", "Example_1"
+ )
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_components_resolve_refs_in_header_schema(self, spec):
+ header = {"schema": copy.deepcopy(self.REFS_SCHEMA)}
+ spec.components.header("header", header)
+ self.assert_schema_refs(spec, get_headers(spec)["header"]["schema"])
+
+
+class TestPath(RefsSchemaTestMixin):
paths = {
"/pet/{petId}": {
"get": {
@@ -390,11 +584,11 @@ class TestPath:
"/path4",
]
- def test_paths_is_chainable(self, spec):
+ def test_path_is_chainable(self, spec):
spec.path(path="/path1").path("/path2")
assert list(spec.to_dict()["paths"].keys()) == ["/path1", "/path2"]
- def test_methods_maintain_order(self, spec):
+ def test_path_methods_maintain_order(self, spec):
methods = ["get", "post", "put", "patch", "delete", "head", "options"]
for method in methods:
spec.path(path="/path", operations=OrderedDict({method: {}}))
@@ -492,34 +686,20 @@ class TestPath:
assert p["summary"] == summary
assert p["description"] == description
- def test_parameter(self, spec):
+ def test_path_resolves_parameter(self, spec):
route_spec = self.paths["/pet/{petId}"]["get"]
-
spec.components.parameter("test_parameter", "path", route_spec["parameters"][0])
-
spec.path(
path="/pet/{petId}", operations={"get": {"parameters": ["test_parameter"]}}
)
-
- metadata = spec.to_dict()
p = get_paths(spec)["/pet/{petId}"]["get"]
-
assert p["parameters"][0] == build_ref(spec, "parameter", "test_parameter")
- if spec.openapi_version.major < 3:
- assert (
- route_spec["parameters"][0] == metadata["parameters"]["test_parameter"]
- )
- else:
- assert (
- route_spec["parameters"][0]
- == metadata["components"]["parameters"]["test_parameter"]
- )
@pytest.mark.parametrize(
"parameters",
([{"name": "petId"}], [{"in": "path"}]), # missing "in" # missing "name"
)
- def test_invalid_parameter(self, spec, parameters):
+ def test_path_invalid_parameter(self, spec, parameters):
path = "/pet/{petId}"
with pytest.raises(InvalidParameterError):
@@ -594,31 +774,17 @@ class TestPath:
],
)
- def test_response(self, spec):
+ def test_path_resolves_response(self, spec):
route_spec = self.paths["/pet/{petId}"]["get"]
-
spec.components.response("test_response", route_spec["responses"]["200"])
-
spec.path(
path="/pet/{petId}",
operations={"get": {"responses": {"200": "test_response"}}},
)
-
- metadata = spec.to_dict()
p = get_paths(spec)["/pet/{petId}"]["get"]
-
assert p["responses"]["200"] == build_ref(spec, "response", "test_response")
- if spec.openapi_version.major < 3:
- assert (
- route_spec["responses"]["200"] == metadata["responses"]["test_response"]
- )
- else:
- assert (
- route_spec["responses"]["200"]
- == metadata["components"]["responses"]["test_response"]
- )
- def test_response_with_HTTPStatus_code(self, spec):
+ def test_path_response_with_HTTPStatus_code(self, spec):
code = HTTPStatus(200)
spec.path(
path="/pet/{petId}",
@@ -627,7 +793,7 @@ class TestPath:
assert "200" in get_paths(spec)["/pet/{petId}"]["get"]["responses"]
- def test_response_with_status_code_range(self, spec, recwarn):
+ def test_path_response_with_status_code_range(self, spec, recwarn):
status_code = "2XX"
spec.path(
@@ -686,6 +852,30 @@ class TestPath:
header_1 = resp["headers"]["header_1"]
assert header_1 == build_ref(spec, "header", "Header_1")
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_path_resolve_response_header_schema(self, spec):
+ response = {"headers": {"header_1": {"name": "Pet", "schema": "PetSchema"}}}
+ spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
+ resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
+ header_1 = resp["headers"]["header_1"]
+ assert header_1["schema"] == build_ref(spec, "schema", "PetSchema")
+
+ # "headers" components section only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_path_resolve_response_header_examples(self, spec):
+ response = {
+ "headers": {
+ "header_1": {"name": "Pet", "examples": {"example_1": "Example_1"}}
+ }
+ }
+ spec.path("/pet/{petId}", operations={"get": {"responses": {"200": response}}})
+ resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
+ header_1 = resp["headers"]["header_1"]
+ assert header_1["examples"]["example_1"] == build_ref(
+ spec, "example", "Example_1"
+ )
+
# "examples" components section only exists in OAS 3
@pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
def test_path_resolve_response_examples(self, spec):
@@ -721,6 +911,42 @@ class TestPath:
example_1 = param["examples"]["example_1"]
assert example_1 == build_ref(spec, "example", "Example_1")
+ def test_path_resolve_parameter_schemas(self, spec):
+ parameter = {"name": "test", "in": "query", "schema": "PetSchema"}
+ spec.path("/pet/{petId}", operations={"get": {"parameters": [parameter]}})
+ param = get_paths(spec)["/pet/{petId}"]["get"]["parameters"][0]
+ assert param["schema"] == build_ref(spec, "schema", "PetSchema")
+
+ def test_path_resolve_refs_in_response_schema(self, spec):
+ if spec.openapi_version.major >= 3:
+ schema = {"content": {"application/json": {"schema": self.REFS_SCHEMA}}}
+ else:
+ schema = {"schema": self.REFS_SCHEMA}
+ spec.path("/pet/{petId}", operations={"get": {"responses": {"200": schema}}})
+ resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
+ if spec.openapi_version.major < 3:
+ schema = resp["schema"]
+ else:
+ schema = resp["content"]["application/json"]["schema"]
+ self.assert_schema_refs(spec, schema)
+
+ def test_path_resolve_refs_in_parameter_schema(self, spec):
+ schema = copy.copy({"schema": self.REFS_SCHEMA})
+ schema["in"] = "query"
+ schema["name"] = "test"
+ spec.path("/pet/{petId}", operations={"get": {"parameters": [schema]}})
+ schema = get_paths(spec)["/pet/{petId}"]["get"]["parameters"][0]["schema"]
+ self.assert_schema_refs(spec, schema)
+
+ # requestBody only exists in OAS 3
+ @pytest.mark.parametrize("spec", ("3.0.0",), indirect=True)
+ def test_path_resolve_refs_in_request_body_schema(self, spec):
+ schema = {"content": {"application/json": {"schema": self.REFS_SCHEMA}}}
+ spec.path("/pet/{petId}", operations={"get": {"responses": {"200": schema}}})
+ resp = get_paths(spec)["/pet/{petId}"]["get"]["responses"]["200"]
+ schema = resp["content"]["application/json"]["schema"]
+ self.assert_schema_refs(spec, schema)
+
class TestPlugins:
@staticmethod
|
Resolve components references in components
Currently, we resolve component references in operations but not in components themselves.
It could be nice to do it there as well to allow a user to pass references as strings inside components.
There should be an opportunity for factorization with the code that resolves refs in operations.
Let's finish the refactor in #655 first.
|
0.0
|
4c84e22b010512e3dbb443a0a8e9fb53d56a9c07
|
[
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_schema[2.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_schema[2.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_header[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_header_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_header_examples[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_response_examples[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_response_schema[2.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_response_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_response_header_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_parameter_examples[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_parameter_schemas[2.0]",
"tests/test_core.py::TestComponents::test_components_resolve_parameter_schemas[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_parameter_schema[2.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_parameter_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_header_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_header_examples[3.0.0]",
"tests/test_core.py::TestComponents::test_components_resolve_refs_in_header_schema[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_header_schema[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_header_examples[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_parameter_schemas[2.0]",
"tests/test_core.py::TestPath::test_path_resolve_parameter_schemas[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_refs_in_response_schema[2.0]",
"tests/test_core.py::TestPath::test_path_resolve_refs_in_response_schema[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_refs_in_parameter_schema[2.0]",
"tests/test_core.py::TestPath::test_path_resolve_refs_in_parameter_schema[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_refs_in_request_body_schema[3.0.0]"
] |
[
"tests/test_core.py::TestAPISpecInit::test_raises_wrong_apispec_version",
"tests/test_core.py::TestMetadata::test_openapi_metadata[2.0]",
"tests/test_core.py::TestMetadata::test_openapi_metadata[3.0.0]",
"tests/test_core.py::TestMetadata::test_openapi_metadata_merge_v3[3.0.0]",
"tests/test_core.py::TestTags::test_tag[2.0]",
"tests/test_core.py::TestTags::test_tag[3.0.0]",
"tests/test_core.py::TestTags::test_tag_is_chainable[2.0]",
"tests/test_core.py::TestTags::test_tag_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_schema[2.0]",
"tests/test_core.py::TestComponents::test_schema[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_schema_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_description[2.0]",
"tests/test_core.py::TestComponents::test_schema_description[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_stores_enum[2.0]",
"tests/test_core.py::TestComponents::test_schema_stores_enum[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_discriminator[2.0]",
"tests/test_core.py::TestComponents::test_schema_discriminator[3.0.0]",
"tests/test_core.py::TestComponents::test_schema_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_schema_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_response[2.0]",
"tests/test_core.py::TestComponents::test_response[3.0.0]",
"tests/test_core.py::TestComponents::test_response_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_response_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_response_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_response_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter[2.0]",
"tests/test_core.py::TestComponents::test_parameter[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_parameter_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_parameter_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_parameter_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_header[3.0.0]",
"tests/test_core.py::TestComponents::test_header_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_header_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_example[3.0.0]",
"tests/test_core.py::TestComponents::test_example_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_example_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme_is_chainable[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme_is_chainable[3.0.0]",
"tests/test_core.py::TestComponents::test_security_scheme_duplicate_name[2.0]",
"tests/test_core.py::TestComponents::test_security_scheme_duplicate_name[3.0.0]",
"tests/test_core.py::TestComponents::test_to_yaml[2.0]",
"tests/test_core.py::TestComponents::test_to_yaml[3.0.0]",
"tests/test_core.py::TestComponents::test_components_can_be_accessed_by_plugin_in_init_spec",
"tests/test_core.py::TestPath::test_path[2.0]",
"tests/test_core.py::TestPath::test_path[3.0.0]",
"tests/test_core.py::TestPath::test_paths_maintain_order[2.0]",
"tests/test_core.py::TestPath::test_paths_maintain_order[3.0.0]",
"tests/test_core.py::TestPath::test_path_is_chainable[2.0]",
"tests/test_core.py::TestPath::test_path_is_chainable[3.0.0]",
"tests/test_core.py::TestPath::test_path_methods_maintain_order[2.0]",
"tests/test_core.py::TestPath::test_path_methods_maintain_order[3.0.0]",
"tests/test_core.py::TestPath::test_path_merges_paths[2.0]",
"tests/test_core.py::TestPath::test_path_merges_paths[3.0.0]",
"tests/test_core.py::TestPath::test_path_called_twice_with_same_operations_parameters[2.0]",
"tests/test_core.py::TestPath::test_path_called_twice_with_same_operations_parameters[3.0.0]",
"tests/test_core.py::TestPath::test_path_ensures_path_parameters_required[2.0]",
"tests/test_core.py::TestPath::test_path_ensures_path_parameters_required[3.0.0]",
"tests/test_core.py::TestPath::test_path_with_no_path_raises_error[2.0]",
"tests/test_core.py::TestPath::test_path_with_no_path_raises_error[3.0.0]",
"tests/test_core.py::TestPath::test_path_summary_description[2.0]",
"tests/test_core.py::TestPath::test_path_summary_description[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolves_parameter[2.0]",
"tests/test_core.py::TestPath::test_path_resolves_parameter[3.0.0]",
"tests/test_core.py::TestPath::test_path_invalid_parameter[2.0-parameters0]",
"tests/test_core.py::TestPath::test_path_invalid_parameter[2.0-parameters1]",
"tests/test_core.py::TestPath::test_path_invalid_parameter[3.0.0-parameters0]",
"tests/test_core.py::TestPath::test_path_invalid_parameter[3.0.0-parameters1]",
"tests/test_core.py::TestPath::test_parameter_duplicate[2.0]",
"tests/test_core.py::TestPath::test_parameter_duplicate[3.0.0]",
"tests/test_core.py::TestPath::test_global_parameters[2.0]",
"tests/test_core.py::TestPath::test_global_parameters[3.0.0]",
"tests/test_core.py::TestPath::test_global_parameter_duplicate[2.0]",
"tests/test_core.py::TestPath::test_global_parameter_duplicate[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolves_response[2.0]",
"tests/test_core.py::TestPath::test_path_resolves_response[3.0.0]",
"tests/test_core.py::TestPath::test_path_response_with_HTTPStatus_code[2.0]",
"tests/test_core.py::TestPath::test_path_response_with_HTTPStatus_code[3.0.0]",
"tests/test_core.py::TestPath::test_path_response_with_status_code_range[2.0]",
"tests/test_core.py::TestPath::test_path_response_with_status_code_range[3.0.0]",
"tests/test_core.py::TestPath::test_path_check_invalid_http_method[2.0]",
"tests/test_core.py::TestPath::test_path_check_invalid_http_method[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_schema[2.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_schema[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_request_body[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_header[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_response_examples[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_request_body_examples[3.0.0]",
"tests/test_core.py::TestPath::test_path_resolve_parameter_examples[3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_factory",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_schema_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_parameter_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_response_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[True-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[True-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[False-2.0]",
"tests/test_core.py::TestPlugins::test_plugin_path_helper_is_used[False-3.0.0]",
"tests/test_core.py::TestPlugins::test_plugin_operation_helper_is_used[2.0]",
"tests/test_core.py::TestPlugins::test_plugin_operation_helper_is_used[3.0.0]",
"tests/test_core.py::TestPluginsOrder::test_plugins_order"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-05-30 21:49:19+00:00
|
mit
| 3,740 |
|
marshmallow-code__apispec-672
|
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index b5e6ba2..620ffc7 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -261,7 +261,7 @@ class FieldConverterMixin:
attributes["writeOnly"] = True
return attributes
- def field2nullable(self, field, **kwargs):
+ def field2nullable(self, field, ret):
"""Return the dictionary of OpenAPI field attributes for a nullable field.
:param Field field: A marshmallow field.
@@ -269,9 +269,12 @@ class FieldConverterMixin:
"""
attributes = {}
if field.allow_none:
- attributes[
- "x-nullable" if self.openapi_version.major < 3 else "nullable"
- ] = True
+ if self.openapi_version.major < 3:
+ attributes["x-nullable"] = True
+ elif self.openapi_version.minor < 1:
+ attributes["nullable"] = True
+ else:
+ attributes["type"] = make_type_list(ret.get("type")) + ["'null'"]
return attributes
def field2range(self, field, ret):
@@ -293,7 +296,7 @@ class FieldConverterMixin:
min_attr, max_attr = (
("minimum", "maximum")
- if ret.get("type") in {"number", "integer"}
+ if set(make_type_list(ret.get("type"))) & {"number", "integer"}
else ("x-minimum", "x-maximum")
)
return make_min_max_attributes(validators, min_attr, max_attr)
@@ -437,6 +440,21 @@ class FieldConverterMixin:
return ret
+def make_type_list(types):
+ """Return a list of types from a type attribute
+
+ Since OpenAPI 3.1.0, "type" can be a single type as string or a list of
+ types, including 'null'. This function takes a "type" attribute as input
+ and returns it as a list, be it an empty or single-element list.
+ This is useful to factorize type-conditional code or code adding a type.
+ """
+ if types is None:
+ return []
+ if isinstance(types, str):
+ return [types]
+ return types
+
+
def make_min_max_attributes(validators, min_attr, max_attr):
"""Return a dictionary of minimum and maximum attributes based on a list
of validators. If either minimum or maximum values are not present in any
|
marshmallow-code/apispec
|
e95cdd4641e12727fc7cd63dca9ad6ac66864f4a
|
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index 5f26c55..cd5b201 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -162,13 +162,60 @@ def test_field_with_additional_metadata(spec_fixture):
assert res["minLength"] == 6
[email protected]("spec_fixture", ("2.0", "3.0.0", "3.1.0"), indirect=True)
def test_field_with_allow_none(spec_fixture):
field = fields.Str(allow_none=True)
res = spec_fixture.openapi.field2property(field)
if spec_fixture.openapi.openapi_version.major < 3:
assert res["x-nullable"] is True
- else:
+ elif spec_fixture.openapi.openapi_version.minor < 1:
assert res["nullable"] is True
+ else:
+ assert "nullable" not in res
+ assert res["type"] == ["string", "'null'"]
+
+
+def test_field_with_range_no_type(spec_fixture):
+ field = fields.Field(validate=validate.Range(min=1, max=10))
+ res = spec_fixture.openapi.field2property(field)
+ assert res["x-minimum"] == 1
+ assert res["x-maximum"] == 10
+ assert "type" not in res
+
+
[email protected]("field", (fields.Number, fields.Integer))
+def test_field_with_range_string_type(spec_fixture, field):
+ field = field(validate=validate.Range(min=1, max=10))
+ res = spec_fixture.openapi.field2property(field)
+ assert res["minimum"] == 1
+ assert res["maximum"] == 10
+ assert isinstance(res["type"], str)
+
+
[email protected]("spec_fixture", ("3.1.0",), indirect=True)
+def test_field_with_range_type_list_with_number(spec_fixture):
+ @spec_fixture.openapi.map_to_openapi_type(["integer", "'null'"], None)
+ class NullableInteger(fields.Field):
+ """Nullable integer"""
+
+ field = NullableInteger(validate=validate.Range(min=1, max=10))
+ res = spec_fixture.openapi.field2property(field)
+ assert res["minimum"] == 1
+ assert res["maximum"] == 10
+ assert res["type"] == ["integer", "'null'"]
+
+
[email protected]("spec_fixture", ("3.1.0",), indirect=True)
+def test_field_with_range_type_list_without_number(spec_fixture):
+ @spec_fixture.openapi.map_to_openapi_type(["string", "'null'"], None)
+ class NullableInteger(fields.Field):
+ """Nullable integer"""
+
+ field = NullableInteger(validate=validate.Range(min=1, max=10))
+ res = spec_fixture.openapi.field2property(field)
+ assert res["x-minimum"] == 1
+ assert res["x-maximum"] == 10
+ assert res["type"] == ["string", "'null'"]
def test_field_with_str_regex(spec_fixture):
|
OpenAPI 3.1 support
There's been a 3.1.0 RC release and they decided to make breaking changes.
https://github.com/OAI/OpenAPI-Specification/releases
It didn't go through all the changes yet to see if and how we are impacted.
At least, since they don't follow semver anymore and things can change in minor versions, we may have to modify some functions to pass the version object or string rather than just the major version as int.
Also I did a quick search to find an EOL for OAS v2 and I didn't find anything. Maybe there is no need for an EOL on a spec, as opposed to a code library.
|
0.0
|
e95cdd4641e12727fc7cd63dca9ad6ac66864f4a
|
[
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]"
] |
[
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-05-31 15:44:41+00:00
|
mit
| 3,741 |
|
marshmallow-code__apispec-674
|
diff --git a/src/apispec/ext/marshmallow/common.py b/src/apispec/ext/marshmallow/common.py
index 9f773a8..7f757f1 100644
--- a/src/apispec/ext/marshmallow/common.py
+++ b/src/apispec/ext/marshmallow/common.py
@@ -43,14 +43,12 @@ def get_fields(schema, *, exclude_dump_only=False):
:param bool exclude_dump_only: whether to filter fields in Meta.dump_only
:rtype: dict, of field name field object pairs
"""
- if hasattr(schema, "fields"):
+ if isinstance(schema, marshmallow.Schema):
fields = schema.fields
- elif hasattr(schema, "_declared_fields"):
+ elif isinstance(schema, type) and issubclass(schema, marshmallow.Schema):
fields = copy.deepcopy(schema._declared_fields)
else:
- raise ValueError(
- f"{schema!r} doesn't have either `fields` or `_declared_fields`."
- )
+ raise ValueError(f"{schema!r} is neither a Schema class nor a Schema instance.")
Meta = getattr(schema, "Meta", None)
warn_if_fields_defined_in_meta(fields, Meta)
return filter_excluded_fields(fields, Meta, exclude_dump_only=exclude_dump_only)
|
marshmallow-code/apispec
|
490948cbcf36e6da081e5f6f746fb3957208fea8
|
diff --git a/tests/test_ext_marshmallow_common.py b/tests/test_ext_marshmallow_common.py
index 8b1f192..5ce03d1 100644
--- a/tests/test_ext_marshmallow_common.py
+++ b/tests/test_ext_marshmallow_common.py
@@ -79,3 +79,12 @@ class TestGetFields:
assert list(get_fields(ExcludeSchema, exclude_dump_only=True).keys()) == [
"field5"
]
+
+ # regression test for https://github.com/marshmallow-code/apispec/issues/673
+ def test_schema_with_field_named_fields(self):
+ class TestSchema(Schema):
+ fields = fields.Int()
+
+ schema_fields = get_fields(TestSchema)
+ assert list(schema_fields.keys()) == ["fields"]
+ assert isinstance(schema_fields["fields"], fields.Int)
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 7e27845..121401c 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -200,9 +200,7 @@ class TestMarshmallowSchemaToModelDefinition:
pass
expected_error = (
- "{!r} doesn't have either `fields` or `_declared_fields`.".format(
- NotASchema
- )
+ f"{NotASchema!r} is neither a Schema class nor a Schema instance."
)
with pytest.raises(ValueError, match=expected_error):
openapi.schema2jsonschema(NotASchema)
@@ -346,7 +344,7 @@ class TestMarshmallowSchemaToParameters:
pass
expected_error = (
- f"{NotASchema!r} doesn't have either `fields` or `_declared_fields`"
+ f"{NotASchema!r} is neither a Schema class nor a Schema instance."
)
with pytest.raises(ValueError, match=expected_error):
openapi.schema2jsonschema(NotASchema)
|
Marshmallow 3.12 schema with `fields` property produce error
Marshmallow added Fields be accessed by name as Schema attributes
I have a schema like this
```python
import marshmallow as ma
class Schema(ma.Schema):
fields = ma.fields.List(ma.fields.Int)
```
Produces error
```
File "/venv/lib/python3.9/site-packages/apispec/ext/marshmallow/openapi.py", line 127, in schema2parameters
fields = get_fields(schema, exclude_dump_only=True)
File "/venv/lib/python3.9/site-packages/apispec/ext/marshmallow/common.py", line 56, in get_fields
return filter_excluded_fields(fields, Meta, exclude_dump_only=exclude_dump_only)
File "/venv/lib/python3.9/site-packages/apispec/ext/marshmallow/common.py", line 90, in filter_excluded_fields
for key, value in fields.items()
AttributeError: 'List' object has no attribute 'items'
```
https://marshmallow.readthedocs.io/en/stable/changelog.html#id2
`get_fields` function gets `fields` schema attribute:
https://github.com/marshmallow-code/apispec/blob/dev/src/apispec/ext/marshmallow/common.py#L46
Can we eliminate this?
|
0.0
|
490948cbcf36e6da081e5f6f746fb3957208fea8
|
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]"
] |
[
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_raise_if_schema_class_passed",
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_same_schemas_instances_equal",
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_same_schemas_instances_unhashable_modifiers_equal[list]",
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_same_schemas_instances_unhashable_modifiers_equal[set]",
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_different_schemas_not_equal",
"tests/test_ext_marshmallow_common.py::TestMakeSchemaKey::test_instances_with_different_modifiers_not_equal",
"tests/test_ext_marshmallow_common.py::TestUniqueName::test_unique_name[2.0]",
"tests/test_ext_marshmallow_common.py::TestUniqueName::test_unique_name[3.0.0]",
"tests/test_ext_marshmallow_common.py::TestGetFields::test_get_fields_meta_exclude_dump_only_as_list_and_tuple[tuple-tuple]",
"tests/test_ext_marshmallow_common.py::TestGetFields::test_get_fields_meta_exclude_dump_only_as_list_and_tuple[tuple-list]",
"tests/test_ext_marshmallow_common.py::TestGetFields::test_get_fields_meta_exclude_dump_only_as_list_and_tuple[list-tuple]",
"tests/test_ext_marshmallow_common.py::TestGetFields::test_get_fields_meta_exclude_dump_only_as_list_and_tuple[list-list]",
"tests/test_ext_marshmallow_common.py::TestGetFields::test_schema_with_field_named_fields",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v2",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v3",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-03 14:15:49+00:00
|
mit
| 3,742 |
|
marshmallow-code__apispec-677
|
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index 620ffc7..b1e4de8 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -96,6 +96,7 @@ class FieldConverterMixin:
self.field2pattern,
self.metadata2properties,
self.nested2properties,
+ self.pluck2properties,
self.list2properties,
self.dict2properties,
]
@@ -402,7 +403,11 @@ class FieldConverterMixin:
:param Field field: A marshmallow field.
:rtype: dict
"""
- if isinstance(field, marshmallow.fields.Nested):
+ # Pluck is a subclass of Nested but is in essence a single field; it
+ # is treated separately by pluck2properties.
+ if isinstance(field, marshmallow.fields.Nested) and not isinstance(
+ field, marshmallow.fields.Pluck
+ ):
schema_dict = self.resolve_nested_schema(field.schema)
if ret and "$ref" in schema_dict:
ret.update({"allOf": [schema_dict]})
@@ -410,6 +415,21 @@ class FieldConverterMixin:
ret.update(schema_dict)
return ret
+ def pluck2properties(self, field, **kwargs):
+ """Return a dictionary of properties from :class:`Pluck <marshmallow.fields.Pluck` fields.
+
+ Pluck effectively trans-includes a field from another schema into this,
+ possibly wrapped in an array (`many=True`).
+
+ :param Field field: A marshmallow field.
+ :rtype: dict
+ """
+ if isinstance(field, marshmallow.fields.Pluck):
+ plucked_field = field.schema.fields[field.field_name]
+ ret = self.field2property(plucked_field)
+ return {"type": "array", "items": ret} if field.many else ret
+ return {}
+
def list2properties(self, field, **kwargs):
"""Return a dictionary of properties from :class:`List <marshmallow.fields.List>` fields.
|
marshmallow-code/apispec
|
f64ff702646375120320a09a85753a3be6e4995c
|
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index cd5b201..084b343 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -5,7 +5,7 @@ import pytest
from marshmallow import fields, validate
from .schemas import CategorySchema, CustomList, CustomStringField, CustomIntegerField
-from .utils import build_ref
+from .utils import build_ref, get_schemas
def test_field2choices_preserving_order(openapi):
@@ -318,6 +318,52 @@ def test_nested_field_with_property(spec_fixture):
}
+class TestField2PropertyPluck:
+ @pytest.fixture(autouse=True)
+ def _setup(self, spec_fixture):
+ self.field2property = spec_fixture.openapi.field2property
+
+ self.spec = spec_fixture.spec
+ self.spec.components.schema("Category", schema=CategorySchema)
+ self.unplucked = get_schemas(self.spec)["Category"]["properties"]["breed"]
+
+ def test_spec(self, spec_fixture):
+ breed = fields.Pluck(CategorySchema, "breed")
+ assert self.field2property(breed) == self.unplucked
+
+ def test_with_property(self):
+ breed = fields.Pluck(CategorySchema, "breed", dump_only=True)
+ assert self.field2property(breed) == {**self.unplucked, "readOnly": True}
+
+ def test_metadata(self):
+ breed = fields.Pluck(
+ CategorySchema,
+ "breed",
+ metadata={
+ "description": "Category breed",
+ "invalid_property": "not in the result",
+ "x_extension": "A great extension",
+ },
+ )
+ assert self.field2property(breed) == {
+ **self.unplucked,
+ "description": "Category breed",
+ "x-extension": "A great extension",
+ }
+
+ def test_many(self):
+ breed = fields.Pluck(CategorySchema, "breed", many=True)
+ assert self.field2property(breed) == {"type": "array", "items": self.unplucked}
+
+ def test_many_with_property(self):
+ breed = fields.Pluck(CategorySchema, "breed", many=True, dump_only=True)
+ assert self.field2property(breed) == {
+ "items": self.unplucked,
+ "type": "array",
+ "readOnly": True,
+ }
+
+
def test_custom_properties_for_custom_fields(spec_fixture):
def custom_string2properties(self, field, **kwargs):
ret = {}
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 4df2aaa..72ab8c6 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -391,6 +391,16 @@ class TestNesting:
assert ("i" in props) == (modifier == "only")
assert ("j" not in props) == (modifier == "only")
+ def test_schema2jsonschema_with_plucked_field(self, spec_fixture):
+ class PetSchema(Schema):
+ breed = fields.Pluck(CategorySchema, "breed")
+
+ category_schema = spec_fixture.openapi.schema2jsonschema(CategorySchema)
+ pet_schema = spec_fixture.openapi.schema2jsonschema(PetSchema)
+ assert (
+ pet_schema["properties"]["breed"] == category_schema["properties"]["breed"]
+ )
+
def test_schema2jsonschema_with_nested_fields_with_adhoc_changes(
self, spec_fixture
):
@@ -414,6 +424,20 @@ class TestNesting:
CategorySchema
)
+ def test_schema2jsonschema_with_plucked_fields_with_adhoc_changes(
+ self, spec_fixture
+ ):
+ category_schema = CategorySchema()
+ category_schema.fields["breed"].dump_only = True
+
+ class PetSchema(Schema):
+ breed = fields.Pluck(category_schema, "breed", many=True)
+
+ spec_fixture.spec.components.schema("Pet", schema=PetSchema)
+ props = get_schemas(spec_fixture.spec)["Pet"]["properties"]
+
+ assert props["breed"]["items"]["readOnly"] is True
+
def test_schema2jsonschema_with_nested_excluded_fields(self, spec):
category_schema = CategorySchema(exclude=("breed",))
|
Marshmallow Pluck type not supported correctly?
Hi guys,
I was just trying to use Marshmallow 3 "nesting" via Pluck field (example taken from docs https://marshmallow.readthedocs.io/en/3.0/nesting.html) and swagger documentation rendered via `apispec` shows nested object in an array instead of flat array.
When using this example:
```
class UserSchema(Schema):
name = fields.String()
email = fields.Email()
friends = fields.Pluck('self', 'name', many=True)
# ... create ``user`` ...
serialized_data = UserSchema().dump(user)
pprint(serialized_data)
# {
# "name": "Steve",
# "email": "[email protected]",
# "friends": ["Mike", "Joe"]
# }
deserialized_data = UserSchema().load(result)
pprint(deserialized_data)
# {
# "name": "Steve",
# "email": "[email protected]",
# "friends": [{"name": "Mike"}, {"name": "Joe"}]
# }
```
`apispec`-generated documentation says that ` "friends": ["Mike", "Joe"]` is in fact ` "friends": [{"name": "Mike"}, {"name": "Joe"}]`. So documentation is generated as for a normal nested object (without flattening it).
Is it just not supported yet or is there a bug?
Is there a plan to support this?
|
0.0
|
f64ff702646375120320a09a85753a3be6e4995c
|
[
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[3.0.0]"
] |
[
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_missing_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v2",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v3",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-08 17:01:39+00:00
|
mit
| 3,743 |
|
marshmallow-code__apispec-678
|
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index b1e4de8..470ed07 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -29,6 +29,7 @@ DEFAULT_FIELD_MAPPING = {
marshmallow.fields.DateTime: ("string", "date-time"),
marshmallow.fields.Date: ("string", "date"),
marshmallow.fields.Time: ("string", None),
+ marshmallow.fields.TimeDelta: ("integer", None),
marshmallow.fields.Email: ("string", "email"),
marshmallow.fields.URL: ("string", "url"),
marshmallow.fields.Dict: ("object", None),
@@ -99,6 +100,7 @@ class FieldConverterMixin:
self.pluck2properties,
self.list2properties,
self.dict2properties,
+ self.timedelta2properties,
]
def map_to_openapi_type(self, *args):
@@ -459,6 +461,19 @@ class FieldConverterMixin:
ret["additionalProperties"] = self.field2property(value_field)
return ret
+ def timedelta2properties(self, field, **kwargs):
+ """Return a dictionary of properties from :class:`TimeDelta <marshmallow.fields.TimeDelta>` fields.
+
+ Adds a `x-unit` vendor property based on the field's `precision` attribute
+
+ :param Field field: A marshmallow field.
+ :rtype: dict
+ """
+ ret = {}
+ if isinstance(field, marshmallow.fields.TimeDelta):
+ ret["x-unit"] = field.precision
+ return ret
+
def make_type_list(types):
"""Return a list of types from a type attribute
|
marshmallow-code/apispec
|
63aa0af6c40687e6b0834c2f9b0b234829f4d815
|
diff --git a/tests/test_ext_marshmallow.py b/tests/test_ext_marshmallow.py
index 162a4b6..7833484 100644
--- a/tests/test_ext_marshmallow.py
+++ b/tests/test_ext_marshmallow.py
@@ -2,7 +2,7 @@ import json
import pytest
-from marshmallow.fields import Field, DateTime, Dict, String, Nested, List
+from marshmallow.fields import Field, DateTime, Dict, String, Nested, List, TimeDelta
from marshmallow import Schema
from apispec import APISpec
@@ -1197,3 +1197,21 @@ class TestList:
result = get_schemas(spec)["SchemaWithList"]["properties"]["list_field"]
assert result == {"items": build_ref(spec, "schema", "Pet"), "type": "array"}
+
+
+class TestTimeDelta:
+ def test_timedelta_x_unit(self, spec):
+ class SchemaWithTimeDelta(Schema):
+ sec = TimeDelta("seconds")
+ day = TimeDelta("days")
+
+ spec.components.schema("SchemaWithTimeDelta", schema=SchemaWithTimeDelta)
+
+ assert (
+ get_schemas(spec)["SchemaWithTimeDelta"]["properties"]["sec"]["x-unit"]
+ == "seconds"
+ )
+ assert (
+ get_schemas(spec)["SchemaWithTimeDelta"]["properties"]["day"]["x-unit"]
+ == "days"
+ )
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index 084b343..d2a33a7 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -28,6 +28,7 @@ def test_field2choices_preserving_order(openapi):
(fields.DateTime, "string"),
(fields.Date, "string"),
(fields.Time, "string"),
+ (fields.TimeDelta, "integer"),
(fields.Email, "string"),
(fields.URL, "string"),
# Custom fields inherit types from their parents
|
TimeDelta fields not generating useful documentation
Documentation for `marshmallow.fields.TimeDelta` is not capturing anything about the field type except the description. Under the hood, Marshmallow treats it as an `int` that gets converted to a `datetime.timedelta` on deserialization.
Here is the line from the schema declaration:
```py
uptime = fields.TimeDelta(precision="minutes", required=False, metadata={"description":"running time"})
```
Example output of "uptime" field (type TimeDelta) from openapi.json generated by flask-smorest:
```json
{
"uptime": {
"description": "running time"
}
}
```
And here is a screen grab of the Swagger UI:

I think it should be treated as an number, with the precision string spelled out in the documentation. Is there a way to add this?
|
0.0
|
63aa0af6c40687e6b0834c2f9b0b234829f4d815
|
[
"tests/test_ext_marshmallow.py::TestTimeDelta::test_timedelta_x_unit[2.0]",
"tests/test_ext_marshmallow.py::TestTimeDelta::test_timedelta_x_unit[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-TimeDelta-integer]"
] |
[
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[AnalysisWithListSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_nested_schema_many_true_resolver_return_none",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_content_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[2.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v2",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[3.0.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[2.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[3.0.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[2.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[3.0.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[2.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[3.0.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_media"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-14 08:56:52+00:00
|
mit
| 3,744 |
|
marshmallow-code__apispec-690
|
diff --git a/setup.py b/setup.py
index 527a956..77301e0 100644
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,7 @@ EXTRAS_REQUIRE = {
"docs": [
"marshmallow>=3.0.0",
"pyyaml==5.4.1",
- "sphinx==4.0.2",
+ "sphinx==4.0.3",
"sphinx-issues==1.2.0",
"sphinx-rtd-theme==0.5.2",
],
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index c1304a9..7db713a 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -280,7 +280,7 @@ class FieldConverterMixin:
elif self.openapi_version.minor < 1:
attributes["nullable"] = True
else:
- attributes["type"] = make_type_list(ret.get("type")) + ["'null'"]
+ attributes["type"] = [*make_type_list(ret.get("type")), "null"]
return attributes
def field2range(self, field, ret):
|
marshmallow-code/apispec
|
aeb0ee556534cb1862129fd1ad98b28728bc80ce
|
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index 04f70f1..3569e04 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -173,7 +173,7 @@ def test_field_with_allow_none(spec_fixture):
assert res["nullable"] is True
else:
assert "nullable" not in res
- assert res["type"] == ["string", "'null'"]
+ assert res["type"] == ["string", "null"]
def test_field_with_dump_only(spec_fixture):
@@ -211,7 +211,7 @@ def test_field_with_range_string_type(spec_fixture, field):
@pytest.mark.parametrize("spec_fixture", ("3.1.0",), indirect=True)
def test_field_with_range_type_list_with_number(spec_fixture):
- @spec_fixture.openapi.map_to_openapi_type(["integer", "'null'"], None)
+ @spec_fixture.openapi.map_to_openapi_type(["integer", "null"], None)
class NullableInteger(fields.Field):
"""Nullable integer"""
@@ -219,12 +219,12 @@ def test_field_with_range_type_list_with_number(spec_fixture):
res = spec_fixture.openapi.field2property(field)
assert res["minimum"] == 1
assert res["maximum"] == 10
- assert res["type"] == ["integer", "'null'"]
+ assert res["type"] == ["integer", "null"]
@pytest.mark.parametrize("spec_fixture", ("3.1.0",), indirect=True)
def test_field_with_range_type_list_without_number(spec_fixture):
- @spec_fixture.openapi.map_to_openapi_type(["string", "'null'"], None)
+ @spec_fixture.openapi.map_to_openapi_type(["string", "null"], None)
class NullableInteger(fields.Field):
"""Nullable integer"""
@@ -232,7 +232,7 @@ def test_field_with_range_type_list_without_number(spec_fixture):
res = spec_fixture.openapi.field2property(field)
assert res["x-minimum"] == 1
assert res["x-maximum"] == 10
- assert res["type"] == ["string", "'null'"]
+ assert res["type"] == ["string", "null"]
def test_field_with_str_regex(spec_fixture):
|
Nullable in OAS 3.1 rendered as "'null'" string instead of "null"
Nullable fields should be rendered as `"type": ["fieldType", "null"]`, not `["fieldType", "'null'"]`.
The field converter currently includes quotes around `null` _in the literal string value_, see https://github.com/marshmallow-code/apispec/blob/5cf763e04df42afddc2480991c878da928558417/src/apispec/ext/marshmallow/field_converter.py#L283
which results in JSON like this:
```json
"created_at": {
"type": [
"string",
"'null'"
],
"format": "date-time",
"readOnly": true
},
```
or as YAML:
```yaml
created_at:
type:
- string
- '''null'''
format: date-time
readOnly: true
```
While the type string should be a string (and not `None` in Python, `null` in JSON or YAML), the extra quotes there are an error.
To fix, please drop the extra quotes in the value:
```python
attributes["type"] = make_type_list(ret.get("type")) + ["null"]
```
Also see
- [Understanding JSON Schema: null](https://json-schema.org/understanding-json-schema/reference/null.html)
- this specific [valid specification test](https://github.com/OAI/OpenAPI-Specification/blob/54edcf039c9854dcbc4feac1b1990c21972f3ca5/tests/v3.1/pass/mega.yaml#L45) in the OpenAPI specification repository.
|
0.0
|
aeb0ee556534cb1862129fd1ad98b28728bc80ce
|
[
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]"
] |
[
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_missing_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_doc_default_and_missing[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-07-02 16:29:40+00:00
|
mit
| 3,745 |
|
marshmallow-code__apispec-716
|
diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py
index 273af20..24866c2 100644
--- a/src/apispec/ext/marshmallow/openapi.py
+++ b/src/apispec/ext/marshmallow/openapi.py
@@ -177,7 +177,7 @@ class OpenAPIConverter(FieldConverterMixin):
fields = get_fields(schema)
Meta = getattr(schema, "Meta", None)
partial = getattr(schema, "partial", None)
- ordered = getattr(schema, "ordered", False)
+ ordered = getattr(Meta, "ordered", False)
jsonschema = self.fields2jsonschema(fields, partial=partial, ordered=ordered)
|
marshmallow-code/apispec
|
64d3718a998f843a1f0dbd171f6ce507084f698f
|
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 83ea7ad..f417377 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -1,4 +1,5 @@
import pytest
+from collections import OrderedDict
from datetime import datetime
from marshmallow import EXCLUDE, fields, INCLUDE, RAISE, Schema, validate
@@ -102,6 +103,21 @@ class TestMarshmallowSchemaToModelDefinition:
res = openapi.schema2jsonschema(BandSchema(partial=("drummer",)))
assert res["required"] == ["bassist"]
+ @pytest.mark.parametrize("ordered_schema", (True, False))
+ def test_ordered(self, openapi, ordered_schema):
+ class BandSchema(Schema):
+ class Meta:
+ ordered = ordered_schema
+
+ drummer = fields.Str()
+ bassist = fields.Str()
+
+ res = openapi.schema2jsonschema(BandSchema)
+ assert isinstance(res["properties"], OrderedDict) == ordered_schema
+
+ res = openapi.schema2jsonschema(BandSchema())
+ assert isinstance(res["properties"], OrderedDict) == ordered_schema
+
def test_no_required_fields(self, openapi):
class BandSchema(Schema):
drummer = fields.Str()
|
ordered is part of the Meta of a schema
ordered is part of Meta see https://marshmallow.readthedocs.io/en/stable/marshmallow.schema.html#marshmallow.schema.Schema.Meta, however it is currently pulled from the schema see https://github.com/marshmallow-code/apispec/blob/dev/src/apispec/ext/marshmallow/openapi.py#L180
Work around
```python
import marshmallow
class Foo(marshmallow.Schema):
class Meta:
ordered = True
ordered = True
```
|
0.0
|
64d3718a998f843a1f0dbd171f6ce507084f698f
|
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_ordered[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_ordered[3.0.0-True]"
] |
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_ordered[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_ordered[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_multiple[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v2",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v3",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-27 09:44:33+00:00
|
mit
| 3,746 |
|
marshmallow-code__apispec-778
|
diff --git a/docs/conf.py b/docs/conf.py
index 368fd52..c0fd839 100755
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -18,8 +18,9 @@ primary_domain = "py"
default_role = "py:obj"
intersphinx_mapping = {
- "python": ("http://python.readthedocs.io/en/latest/", None),
- "marshmallow": ("http://marshmallow.readthedocs.io/en/latest/", None),
+ "python": ("https://python.readthedocs.io/en/latest/", None),
+ "marshmallow": ("https://marshmallow.readthedocs.io/en/latest/", None),
+ "webargs": ("https://webargs.readthedocs.io/en/latest/", None),
}
issues_github_path = "marshmallow-code/apispec"
diff --git a/docs/using_plugins.rst b/docs/using_plugins.rst
index 2c794b8..0f02be9 100644
--- a/docs/using_plugins.rst
+++ b/docs/using_plugins.rst
@@ -295,6 +295,32 @@ method. Continuing from the example above:
The function passed to `add_attribute_function` will be bound to the converter.
It must accept the converter instance as first positional argument.
+In some rare cases, typically with container fields such as fields derived from
+:class:`List <marshmallow.fields.List>`, documenting the parameters using this
+field require some more customization.
+This can be achieved using the `add_parameter_attribute_function
+<apispec.ext.marshmallow.openapi.OpenAPIConverter.add_parameter_attribute_function>`
+method.
+
+For instance, when documenting webargs's
+:class:`DelimitedList <webargs.fields.DelimitedList>` field, one may register
+this function:
+
+.. code-block:: python
+
+ def delimited_list2param(self, field, **kwargs):
+ ret: dict = {}
+ if isinstance(field, DelimitedList):
+ if self.openapi_version.major < 3:
+ ret["collectionFormat"] = "csv"
+ else:
+ ret["explode"] = False
+ ret["style"] = "form"
+ return ret
+
+
+ ma_plugin.converter.add_parameter_attribute_function(delimited_list2param)
+
Next Steps
----------
diff --git a/setup.py b/setup.py
index 49bf24c..70b9b56 100644
--- a/setup.py
+++ b/setup.py
@@ -7,15 +7,15 @@ EXTRAS_REQUIRE = {
"validation": ["prance[osv]>=0.11", "openapi_spec_validator<0.5"],
"lint": [
"flake8==5.0.4",
- "flake8-bugbear==22.9.11",
+ "flake8-bugbear==22.9.23",
"pre-commit~=2.4",
- "mypy==0.971",
+ "mypy==0.982",
"types-PyYAML",
],
"docs": [
"marshmallow>=3.13.0",
"pyyaml==6.0",
- "sphinx==5.1.1",
+ "sphinx==5.2.3",
"sphinx-issues==3.0.1",
"sphinx-rtd-theme==1.0.0",
],
diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py
index ea76955..94da0b2 100644
--- a/src/apispec/ext/marshmallow/openapi.py
+++ b/src/apispec/ext/marshmallow/openapi.py
@@ -8,6 +8,7 @@ marshmallow :class:`Schemas <marshmallow.Schema>` and :class:`Fields <marshmallo
"""
from __future__ import annotations
+import typing
import marshmallow
from marshmallow.utils import is_collection
@@ -59,9 +60,37 @@ class OpenAPIConverter(FieldConverterMixin):
self.schema_name_resolver = schema_name_resolver
self.spec = spec
self.init_attribute_functions()
+ self.init_parameter_attribute_functions()
# Schema references
self.refs: dict = {}
+ def init_parameter_attribute_functions(self) -> None:
+ self.parameter_attribute_functions = [
+ self.field2required,
+ self.list2param,
+ ]
+
+ def add_parameter_attribute_function(self, func) -> None:
+ """Method to add a field parameter function to the list of field
+ parameter functions that will be called on a field to convert it to a
+ field parameter.
+
+ :param func func: the field parameter function to add
+ The attribute function will be bound to the
+ `OpenAPIConverter <apispec.ext.marshmallow.openapi.OpenAPIConverter>`
+ instance.
+ It will be called for each field in a schema with
+ `self <apispec.ext.marshmallow.openapi.OpenAPIConverter>` and a
+ `field <marshmallow.fields.Field>` instance
+ positional arguments and `ret <dict>` keyword argument.
+ May mutate `ret`.
+ User added field parameter functions will be called after all built-in
+ field parameter functions in the order they were added.
+ """
+ bound_func = func.__get__(self)
+ setattr(self, func.__name__, bound_func)
+ self.parameter_attribute_functions.append(bound_func)
+
def resolve_nested_schema(self, schema):
"""Return the OpenAPI representation of a marshmallow Schema.
@@ -150,7 +179,7 @@ class OpenAPIConverter(FieldConverterMixin):
def _field2parameter(
self, field: marshmallow.fields.Field, *, name: str, location: str
- ):
+ ) -> dict:
"""Return an OpenAPI parameter as a `dict`, given a marshmallow
:class:`Field <marshmallow.Field>`.
@@ -158,26 +187,49 @@ class OpenAPIConverter(FieldConverterMixin):
"""
ret: dict = {"in": location, "name": name}
+ prop = self.field2property(field)
+ if self.openapi_version.major < 3:
+ ret.update(prop)
+ else:
+ if "description" in prop:
+ ret["description"] = prop.pop("description")
+ ret["schema"] = prop
+
+ for param_attr_func in self.parameter_attribute_functions:
+ ret.update(param_attr_func(field, ret=ret))
+
+ return ret
+
+ def field2required(
+ self, field: marshmallow.fields.Field, **kwargs: typing.Any
+ ) -> dict:
+ """Return the dictionary of OpenAPI parameter attributes for a required field.
+
+ :param Field field: A marshmallow field.
+ :rtype: dict
+ """
+ ret = {}
partial = getattr(field.parent, "partial", False)
ret["required"] = field.required and (
not partial
or (is_collection(partial) and field.name not in partial) # type:ignore
)
+ return ret
- prop = self.field2property(field)
- multiple = isinstance(field, marshmallow.fields.List)
+ def list2param(self, field: marshmallow.fields.Field, **kwargs: typing.Any) -> dict:
+ """Return a dictionary of parameter properties from
+ :class:`List <marshmallow.fields.List` fields.
- if self.openapi_version.major < 3:
- if multiple:
+ :param Field field: A marshmallow field.
+ :rtype: dict
+ """
+ ret: dict = {}
+ if isinstance(field, marshmallow.fields.List):
+ if self.openapi_version.major < 3:
ret["collectionFormat"] = "multi"
- ret.update(prop)
- else:
- if multiple:
+ else:
ret["explode"] = True
ret["style"] = "form"
- if prop.get("description", None):
- ret["description"] = prop.pop("description")
- ret["schema"] = prop
return ret
def schema2jsonschema(self, schema):
|
marshmallow-code/apispec
|
cbcff0d7d7a3539df57e5f80fe32642314493e91
|
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 83ea7ad..6ec99ce 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -207,20 +207,36 @@ class TestMarshmallowSchemaToModelDefinition:
class TestMarshmallowSchemaToParameters:
- @pytest.mark.parametrize("ListClass", [fields.List, CustomList])
- def test_field_multiple(self, ListClass, openapi):
- field = ListClass(fields.Str)
- res = openapi._field2parameter(field, name="field", location="query")
- assert res["in"] == "query"
- if openapi.openapi_version.major < 3:
- assert res["type"] == "array"
- assert res["items"]["type"] == "string"
- assert res["collectionFormat"] == "multi"
+ def test_custom_properties_for_custom_fields(self, spec_fixture):
+ class DelimitedList(fields.List):
+ """Delimited list field"""
+
+ def delimited_list2param(self, field, **kwargs):
+ ret: dict = {}
+ if isinstance(field, DelimitedList):
+ if self.openapi_version.major < 3:
+ ret["collectionFormat"] = "csv"
+ else:
+ ret["explode"] = False
+ ret["style"] = "form"
+ return ret
+
+ spec_fixture.marshmallow_plugin.converter.add_parameter_attribute_function(
+ delimited_list2param
+ )
+
+ class MySchema(Schema):
+ delimited_list = DelimitedList(fields.Int)
+
+ param = spec_fixture.marshmallow_plugin.converter.schema2parameters(
+ MySchema(), location="query"
+ )[0]
+
+ if spec_fixture.openapi.openapi_version.major < 3:
+ assert param["collectionFormat"] == "csv"
else:
- assert res["schema"]["type"] == "array"
- assert res["schema"]["items"]["type"] == "string"
- assert res["style"] == "form"
- assert res["explode"] is True
+ assert param["explode"] is False
+ assert param["style"] == "form"
def test_field_required(self, openapi):
field = fields.Str(required=True)
@@ -252,6 +268,21 @@ class TestMarshmallowSchemaToParameters:
param = next(p for p in res_nodump if p["name"] == "partial_field")
assert param["required"] is False
+ @pytest.mark.parametrize("ListClass", [fields.List, CustomList])
+ def test_field_list(self, ListClass, openapi):
+ field = ListClass(fields.Str)
+ res = openapi._field2parameter(field, name="field", location="query")
+ assert res["in"] == "query"
+ if openapi.openapi_version.major < 3:
+ assert res["type"] == "array"
+ assert res["items"]["type"] == "string"
+ assert res["collectionFormat"] == "multi"
+ else:
+ assert res["schema"]["type"] == "array"
+ assert res["schema"]["items"]["type"] == "string"
+ assert res["style"] == "form"
+ assert res["explode"] is True
+
# json/body is invalid for OpenAPI 3
@pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
def test_schema_body(self, openapi):
|
explode and style are hardcoded in OpenAPIConverter.property2parameter
I've been trying to document webargs's `DelimitedList` (child class of `List`) and I'm stuck because I'd need to override hardcoded stuff.
```py
def field2parameter(self, field, name, default_in):
location = field.metadata.get("location", None)
prop = self.field2property(field)
return self.property2parameter(
prop,
name=name,
required=field.required,
multiple=isinstance(field, marshmallow.fields.List), # <--- List
location=location,
default_in=default_in,
)
def property2parameter(self, prop, name, required, multiple, location, default_in):
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {"type": "object", "properties": {name: prop}}
if required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple: # <--- when List, set explode and style
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret
```
To document `DelimitedList`, we'd need to set `explode` to False. That's assuming we use default `,` as delimiter. Using space or pipe would require to also modify `style`.
To make this more generic, we could remove `multiple` and create an extensible mechanism to allow custom post-processings after `property2parameter`. And add a post-processor for `List` to do what's currently done with `multiple`.
Kinda like what's been done with attribute_functions in `FieldConverter`.
(Maybe we could separate the property2bodyparameter case as right now it does not involve a specific `List` case.)
|
0.0
|
cbcff0d7d7a3539df57e5f80fe32642314493e91
|
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[3.0.0]"
] |
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-13 13:36:12+00:00
|
mit
| 3,747 |
|
marshmallow-code__apispec-804
|
diff --git a/docs/using_plugins.rst b/docs/using_plugins.rst
index 0f02be9..8dd2b4b 100644
--- a/docs/using_plugins.rst
+++ b/docs/using_plugins.rst
@@ -243,7 +243,7 @@ custom field subclasses a standard marshmallow `Field` class then it will
inherit the default mapping. If you want to override the OpenAPI type and format
for custom fields, use the
`map_to_openapi_type <apispec.ext.marshmallow.MarshmallowPlugin.map_to_openapi_type>`
-decorator. It can be invoked with either a pair of strings providing the
+method. It can be invoked with either a pair of strings providing the
OpenAPI type and format, or a marshmallow `Field` that has the desired target mapping.
.. code-block:: python
@@ -258,21 +258,26 @@ OpenAPI type and format, or a marshmallow `Field` that has the desired target ma
title="Demo", version="0.1", openapi_version="3.0.0", plugins=(ma_plugin,)
)
- # Inherits Integer mapping of ('integer', 'int32')
- class MyCustomInteger(Integer):
+ # Inherits Integer mapping of ('integer', None)
+ class CustomInteger(Integer):
pass
# Override Integer mapping
- @ma_plugin.map_to_openapi_type("string", "uuid")
- class MyCustomField(Integer):
+ class Int32(Integer):
pass
- @ma_plugin.map_to_openapi_type(Integer) # will map to ('integer', 'int32')
- class MyCustomFieldThatsKindaLikeAnInteger(Field):
+ ma_plugin.map_to_openapi_type(Int32, "string", "int32")
+
+
+ # Map to ('integer', None) like Integer
+ class IntegerLike(Field):
pass
+
+ ma_plugin.map_to_openapi_type(IntegerLike, Integer)
+
In situations where greater control of the properties generated for a custom field
is desired, users may add custom logic to the conversion of fields to OpenAPI properties
through the use of the `add_attribute_function
diff --git a/src/apispec/ext/marshmallow/__init__.py b/src/apispec/ext/marshmallow/__init__.py
index c08cb87..2595581 100644
--- a/src/apispec/ext/marshmallow/__init__.py
+++ b/src/apispec/ext/marshmallow/__init__.py
@@ -137,8 +137,10 @@ class MarshmallowPlugin(BasePlugin):
openapi_version=spec.openapi_version, converter=self.converter
)
- def map_to_openapi_type(self, *args):
- """Decorator to set mapping for custom fields.
+ def map_to_openapi_type(self, field_cls, *args):
+ """Set mapping for custom field class.
+
+ :param type field_cls: Field class to set mapping for.
``*args`` can be:
@@ -147,15 +149,19 @@ class MarshmallowPlugin(BasePlugin):
Examples: ::
- @ma_plugin.map_to_openapi_type('string', 'uuid')
- class MyCustomField(Integer):
+ # Override Integer mapping
+ class Int32(Integer):
# ...
- @ma_plugin.map_to_openapi_type(Integer) # will map to ('integer', None)
- class MyCustomFieldThatsKindaLikeAnInteger(Integer):
+ ma_plugin.map_to_openapi_type(Int32, 'string', 'int32')
+
+ # Map to ('integer', None) like Integer
+ class IntegerLike(Integer):
# ...
+
+ ma_plugin.map_to_openapi_type(IntegerLike, Integer)
"""
- return self.converter.map_to_openapi_type(*args)
+ return self.converter.map_to_openapi_type(field_cls, *args)
def schema_helper(self, name, _, schema=None, **kwargs):
"""Definition helper that allows using a marshmallow
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index 2a5beaa..5c9abc5 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -113,8 +113,10 @@ class FieldConverterMixin:
self.timedelta2properties,
]
- def map_to_openapi_type(self, *args):
- """Decorator to set mapping for custom fields.
+ def map_to_openapi_type(self, field_cls, *args):
+ """Set mapping for custom field class.
+
+ :param type field_cls: Field class to set mapping for.
``*args`` can be:
@@ -128,11 +130,7 @@ class FieldConverterMixin:
else:
raise TypeError("Pass core marshmallow field type or (type, fmt) pair.")
- def inner(field_type):
- self.field_mapping[field_type] = openapi_type_field
- return field_type
-
- return inner
+ self.field_mapping[field_cls] = openapi_type_field
def add_attribute_function(self, func):
"""Method to add an attribute function to the list of attribute functions
|
marshmallow-code/apispec
|
c084e1c4078231ac9423d30553350426a6b7b862
|
diff --git a/tests/test_ext_marshmallow.py b/tests/test_ext_marshmallow.py
index 5e8a61c..07d83fa 100644
--- a/tests/test_ext_marshmallow.py
+++ b/tests/test_ext_marshmallow.py
@@ -314,19 +314,25 @@ class TestComponentHeaderHelper:
class TestCustomField:
def test_can_use_custom_field_decorator(self, spec_fixture):
- @spec_fixture.marshmallow_plugin.map_to_openapi_type(DateTime)
class CustomNameA(Field):
pass
- @spec_fixture.marshmallow_plugin.map_to_openapi_type("integer", "int32")
+ spec_fixture.marshmallow_plugin.map_to_openapi_type(CustomNameA, DateTime)
+
class CustomNameB(Field):
pass
- with pytest.raises(TypeError):
+ spec_fixture.marshmallow_plugin.map_to_openapi_type(
+ CustomNameB, "integer", "int32"
+ )
- @spec_fixture.marshmallow_plugin.map_to_openapi_type("integer")
- class BadCustomField(Field):
- pass
+ class BadCustomField(Field):
+ pass
+
+ with pytest.raises(TypeError):
+ spec_fixture.marshmallow_plugin.map_to_openapi_type(
+ BadCustomField, "integer"
+ )
class CustomPetASchema(PetSchema):
name = CustomNameA()
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index aab4304..dcba184 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -212,10 +212,11 @@ def test_field_with_range_string_type(spec_fixture, field):
@pytest.mark.parametrize("spec_fixture", ("3.1.0",), indirect=True)
def test_field_with_range_type_list_with_number(spec_fixture):
- @spec_fixture.openapi.map_to_openapi_type(["integer", "null"], None)
class NullableInteger(fields.Field):
"""Nullable integer"""
+ spec_fixture.openapi.map_to_openapi_type(NullableInteger, ["integer", "null"], None)
+
field = NullableInteger(validate=validate.Range(min=1, max=10))
res = spec_fixture.openapi.field2property(field)
assert res["minimum"] == 1
@@ -225,10 +226,11 @@ def test_field_with_range_type_list_with_number(spec_fixture):
@pytest.mark.parametrize("spec_fixture", ("3.1.0",), indirect=True)
def test_field_with_range_type_list_without_number(spec_fixture):
- @spec_fixture.openapi.map_to_openapi_type(["string", "null"], None)
class NullableInteger(fields.Field):
"""Nullable integer"""
+ spec_fixture.openapi.map_to_openapi_type(NullableInteger, ["string", "null"], None)
+
field = NullableInteger(validate=validate.Range(min=1, max=10))
res = spec_fixture.openapi.field2property(field)
assert res["x-minimum"] == 1
|
Allow map_to_openapi_type to be called like a function
Hi,
so I have a schema which uses a custom field. Currently you expect that we do the following:
```
ma = MarshmallowPlugin()
@ma.map_to_openapi_type(fields.Dict)
class Custom(field.Field): pass
```
However, it's not very nice if the fields are in separate files since you always need the `MarshmallowPlugin` instance. As a workaround, I figured out, that the decorator doesn't really change something in the class, therefore I can also write:
`ma.map_to_openapi_type(fields.Dict)(Custom)`. However, still not very nice syntax.
Therefore I would like to propose a new function which just takes the two args: `ma.map_to_openapi_type2(Custom, fileds,Dict)` (name can be improved 😄 ). This can then be called whereever the `MarshmallowPlugin` is created.
What do you think?
|
0.0
|
c084e1c4078231ac9423d30553350426a6b7b862
|
[
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[2.0]",
"tests/test_ext_marshmallow.py::TestCustomField::test_can_use_custom_field_decorator[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]"
] |
[
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_can_use_schema_as_definition[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_helper_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[AnalysisWithListSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_in_list[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_schema_dict_auto_reference_return_none[schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-AnalysisSchema]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_warning_when_schema_added_twice[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_instances_with_different_modifiers_added[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[2.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_schema_with_clashing_names[3.0.0]",
"tests/test_ext_marshmallow.py::TestDefinitionHelper::test_resolve_nested_schema_many_true_resolver_return_none",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter_with_content[PetSchema-3.0.0]",
"tests/test_ext_marshmallow.py::TestComponentParameterHelper::test_can_use_schema_in_parameter_with_content[schema1-3.0.0]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[2.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_can_use_schema_in_response_header[3.0.0-schema1]",
"tests/test_ext_marshmallow.py::TestComponentResponseHelper::test_content_without_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestComponentHeaderHelper::test_can_use_schema_in_header[PetSchema-3.0.0]",
"tests/test_ext_marshmallow.py::TestComponentHeaderHelper::test_can_use_schema_in_header[schema1-3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v2[2.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-pet_schema2]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_v3[3.0.0-tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_expand_parameters_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v2",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_allof_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_oneof_anyof_allof_v3[oneOf-3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_oneof_anyof_allof_v3[anyOf-3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_oneof_anyof_allof_v3[allOf-3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_not_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_resolver_not_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v2[tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[pet_schema1]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_name_resolver_returns_none_v3[tests.schemas.PetSchema]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_if_available_name_resolver_returns_none_v3",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_uses_ref_in_parameters_and_request_body_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_array_uses_ref_if_available_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v2[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_callback_schema_partially_v3[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_parameter_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_response_reference[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2json[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_schema_global_state_untouched_2parameters[3.0.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_resolve_schema_dict_ref_as_string[2.0]",
"tests/test_ext_marshmallow.py::TestOperationHelper::test_resolve_schema_dict_ref_as_string[3.0.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[2.0]",
"tests/test_ext_marshmallow.py::TestCircularReference::test_circular_referencing_schemas[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_single[3.0.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[2.0]",
"tests/test_ext_marshmallow.py::TestSelfReference::test_self_referencing_field_many[3.0.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[2.0]",
"tests/test_ext_marshmallow.py::TestOrderedSchema::test_ordered_schema[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props[3.0.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[2.0]",
"tests/test_ext_marshmallow.py::TestFieldWithCustomProps::test_field_with_custom_props_passed_as_snake_case[3.0.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[2.0]",
"tests/test_ext_marshmallow.py::TestSchemaWithDefaultValues::test_schema_with_default_values[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_values_resolve_to_additional_properties[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_empty_values_field[3.0.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestDictValues::test_dict_with_nested[3.0.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[2.0]",
"tests/test_ext_marshmallow.py::TestList::test_list_with_nested[3.0.0]",
"tests/test_ext_marshmallow.py::TestTimeDelta::test_timedelta_x_unit[2.0]",
"tests/test_ext_marshmallow.py::TestTimeDelta::test_timedelta_x_unit[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default_and_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default_and_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_enum_symbol_field[2.0]",
"tests/test_ext_marshmallow_field.py::test_enum_symbol_field[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[2.0-True]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[3.0.0-True]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-11 22:12:36+00:00
|
mit
| 3,748 |
|
marshmallow-code__apispec-807
|
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index 5c9abc5..20bc56f 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -509,7 +509,11 @@ class FieldConverterMixin:
ret = {}
if isinstance(field, marshmallow.fields.Enum):
ret = self.field2property(field.field)
- ret["enum"] = field.choices_text
+ if field.by_value is False:
+ choices = (m for m in field.enum.__members__)
+ else:
+ choices = (m.value for m in field.enum)
+ ret["enum"] = [field.field._serialize(v, None, None) for v in choices]
return ret
|
marshmallow-code/apispec
|
7abbf7dfea6b77d50504ad33262f6a8ed643781e
|
diff --git a/tests/test_ext_marshmallow_field.py b/tests/test_ext_marshmallow_field.py
index dcba184..41143dd 100644
--- a/tests/test_ext_marshmallow_field.py
+++ b/tests/test_ext_marshmallow_field.py
@@ -274,7 +274,7 @@ def test_enum_symbol_field(spec_fixture):
field = fields.Enum(MyEnum)
ret = spec_fixture.openapi.field2property(field)
assert ret["type"] == "string"
- assert ret["enum"] == "one, two"
+ assert ret["enum"] == ["one", "two"]
@pytest.mark.parametrize("by_value", [fields.Integer, True])
@@ -289,7 +289,7 @@ def test_enum_value_field(spec_fixture, by_value):
assert "type" not in ret
else:
assert ret["type"] == "integer"
- assert ret["enum"] == "1, 2"
+ assert ret["enum"] == [1, 2]
def test_field2property_nested_spec_metadatas(spec_fixture):
|
exported marshmallow Enum fields should be arrays, not CSV strings
Hi,
I really love new support for marshmalow Enum fields but... these are not correctly exported into OAS3 :disappointed: .
We get strings:
```json
"status": {
"type": "string",
"enum": "INACTIVE, ACTIVE"
}
```
but we need lists:
```json
"status": {
"type": "string",
"enum": [
"INACTIVE", "ACTIVE"
]
}
```
This breaks ReDoc completelly (fails to load spec and UI), and SwaggerUI partially (loads UI, but errors into console when trying to display some object schema).
Relevant docs:
- [OpenAPI guide - enums](https://swagger.io/docs/specification/data-models/enums/)
- [OpenAPI specification Schema Object - properties](https://swagger.io/specification/#schema-object)
- [JSON Schema Validation](https://datatracker.ietf.org/doc/html/draft-wright-json-schema-validation-00#section-5.20)
Minimal example:
```py
import enum
import json
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow import Schema, fields
spec = APISpec(
title="Example",
version="1.0.0",
openapi_version="3.0.2",
plugins=[MarshmallowPlugin()],
)
class Statuses(enum.Enum):
INACTIVE = 0
ACTIVE = 1
class ItemSchema(Schema):
id = fields.Int()
status = fields.Enum(Statuses, allow_none=False)
spec.components.schema("Item", schema=ItemSchema)
print(json.dumps(spec.to_dict(), indent=2))
```
gives us this:
```jsoh
{
"paths": {},
"info": {
"title": "Example",
"version": "1.0.0"
},
"openapi": "3.0.2",
"components": {
"schemas": {
"Item": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"status": {
"type": "string",
"enum": "INACTIVE, ACTIVE"
}
}
}
}
}
}
```
|
0.0
|
7abbf7dfea6b77d50504ad33262f6a8ed643781e
|
[
"tests/test_ext_marshmallow_field.py::test_enum_symbol_field[2.0]",
"tests/test_ext_marshmallow_field.py::test_enum_symbol_field[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[2.0-True]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_enum_value_field[3.0.0-True]"
] |
[
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2choices_preserving_order[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[2.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Integer-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Number-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Float-number]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-String-string1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean0]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Boolean-boolean1]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-UUID-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-DateTime-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Date-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Time-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-TimeDelta-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Email-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-Url-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomStringField-string]",
"tests/test_ext_marshmallow_field.py::test_field2property_type[3.0.0-CustomIntegerField-integer]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[2.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Field]",
"tests/test_ext_marshmallow_field.py::test_field2property_no_type_[3.0.0-Raw]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[2.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-List]",
"tests/test_ext_marshmallow_field.py::test_formatted_field_translates_to_array[3.0.0-CustomList]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[2.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-UUID-uuid]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-DateTime-date-time]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Date-date]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Email-email]",
"tests/test_ext_marshmallow_field.py::test_field2property_formats[3.0.0-Url-url]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_description[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_boolean_field_with_false_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_datetime_field_with_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default_callable[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_default_callable[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default_and_load_default[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_default_and_load_default[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_equal[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_only_allows_valid_properties_in_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_choices_multiple[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_additional_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_allow_none[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_load_only[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_no_type[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[2.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Number]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_string_type[3.0.0-Integer]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_with_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_range_type_list_without_number[3.1.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_str_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_pattern_obj_regex[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_no_pattern[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[2.0]",
"tests/test_ext_marshmallow_field.py::test_field_with_multiple_patterns[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec_metadatas[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_ref[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_nested_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::test_nested_field_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_spec[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_metadata[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many[3.0.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[2.0]",
"tests/test_ext_marshmallow_field.py::TestField2PropertyPluck::test_many_with_property[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_field.py::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[2.0]",
"tests/test_ext_marshmallow_field.py::test_field2property_with_non_string_metadata_keys[3.0.0]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-05 21:16:51+00:00
|
mit
| 3,749 |
|
marshmallow-code__apispec-811
|
diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py
index 011af55..6d6fcb5 100644
--- a/src/apispec/ext/marshmallow/openapi.py
+++ b/src/apispec/ext/marshmallow/openapi.py
@@ -40,7 +40,7 @@ __location_map__ = {
class OpenAPIConverter(FieldConverterMixin):
"""Adds methods for generating OpenAPI specification from marshmallow schemas and fields.
- :param Version openapi_version: The OpenAPI version to use.
+ :param Version|str openapi_version: The OpenAPI version to use.
Should be in the form '2.x' or '3.x.x' to comply with the OpenAPI standard.
:param callable schema_name_resolver: Callable to generate the schema definition name.
Receives the `Schema` class and returns the name to be used in refs within
@@ -52,11 +52,15 @@ class OpenAPIConverter(FieldConverterMixin):
def __init__(
self,
- openapi_version: Version,
+ openapi_version: Version | str,
schema_name_resolver,
spec: APISpec,
) -> None:
- self.openapi_version = openapi_version
+ self.openapi_version = (
+ Version(openapi_version)
+ if isinstance(openapi_version, str)
+ else openapi_version
+ )
self.schema_name_resolver = schema_name_resolver
self.spec = spec
self.init_attribute_functions()
|
marshmallow-code/apispec
|
986b46428ef4af293f9541121f1e80cc99f4dfb1
|
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 46824f3..fc27626 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -4,8 +4,9 @@ import pytest
from marshmallow import EXCLUDE, fields, INCLUDE, RAISE, Schema, validate
-from apispec.ext.marshmallow import MarshmallowPlugin
+from apispec.ext.marshmallow import MarshmallowPlugin, OpenAPIConverter
from apispec import exceptions, APISpec
+from packaging.version import Version
from .schemas import CustomList, CustomStringField
from .utils import get_schemas, build_ref, validate_spec
@@ -608,6 +609,15 @@ def test_openapi_tools_validate_v3():
pytest.fail(str(error))
+def test_openapi_converter_openapi_version_types():
+ converter_with_version = OpenAPIConverter(Version("3.1"), None, None)
+ converter_with_str_version = OpenAPIConverter("3.1", None, None)
+ assert (
+ converter_with_version.openapi_version
+ == converter_with_str_version.openapi_version
+ )
+
+
class TestFieldValidation:
class ValidationSchema(Schema):
id = fields.Int(dump_only=True)
|
Marshmallow OpenApiConverter does not support str openapi_version
The [mashmallow ext documentation](https://apispec.readthedocs.io/en/latest/api_ext.html#apispec.ext.marshmallow.openapi.OpenAPIConverter) says
```
openapi_version (Version) – The OpenAPI version to use. Should be in the form ‘2.x’ or ‘3.x.x’ to comply with the OpenAPI standard.
```
but in [APISpec](https://apispec.readthedocs.io/en/latest/api_core.html#module-apispec.core) str is supported which leads to confusion:
```
openapi_version (str) – OpenAPI Specification version. Should be in the form ‘2.x’ or ‘3.x.x’ to comply with the OpenAPI standard.
```
This commit has removed the conversion from str to version instance in marshmallow ext:
https://github.com/marshmallow-code/apispec/commit/d9e7ef9e1225a4d9f1169caba6c7c1235afe8ecd#diff-d2965e63925ff25611aef4a29719e18095c4a035c9a855e65d4d8ea7908298b8L54-L60
which when using str version leads to errors like `AttributeError: 'str' object has no attribute 'major'` here https://github.com/marshmallow-code/apispec/blob/dev/src/apispec/ext/marshmallow/openapi.py#L191 in version 6.0.1
Is it the desired behavior?
Thanks
|
0.0
|
986b46428ef4af293f9541121f1e80cc99f4dfb1
|
[
"tests/test_ext_marshmallow_openapi.py::test_openapi_converter_openapi_version_types"
] |
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-10 16:06:48+00:00
|
mit
| 3,750 |
|
marshmallow-code__apispec-851
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index d6975b1..4376766 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,21 +1,21 @@
repos:
- repo: https://github.com/asottile/pyupgrade
- rev: v3.8.0
+ rev: v3.10.1
hooks:
- id: pyupgrade
args: [--py37-plus]
- repo: https://github.com/psf/black
- rev: 23.3.0
+ rev: 23.7.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
- rev: 6.0.0
+ rev: 6.1.0
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear==22.12.6]
- repo: https://github.com/asottile/blacken-docs
- rev: 1.14.0
+ rev: 1.15.0
hooks:
- id: blacken-docs
additional_dependencies: [black==22.3.0]
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 02662ce..17bea2b 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -77,3 +77,4 @@ Contributors (chronological)
- Edwin Erdmanis `@vorticity <https://github.com/vorticity>`_
- Mounier Florian `@paradoxxxzero <https://github.com/paradoxxxzero>`_
- Renato Damas `@codectl <https://github.com/codectl>`_
+- Tayler Sokalski `@tsokalski <https://github.com/tsokalski>`_
diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py
index d075aca..2bf8a9d 100644
--- a/src/apispec/ext/marshmallow/field_converter.py
+++ b/src/apispec/ext/marshmallow/field_converter.py
@@ -6,6 +6,7 @@
This module is treated as private API.
Users should not need to use this module directly.
"""
+from __future__ import annotations
import re
import functools
import operator
@@ -18,7 +19,7 @@ from marshmallow.orderedset import OrderedSet
# marshmallow field => (JSON Schema type, format)
-DEFAULT_FIELD_MAPPING = {
+DEFAULT_FIELD_MAPPING: dict[type, tuple[str | None, str | None]] = {
marshmallow.fields.Integer: ("integer", None),
marshmallow.fields.Number: ("number", None),
marshmallow.fields.Float: ("number", None),
@@ -86,7 +87,7 @@ _VALID_PREFIX = "x-"
class FieldConverterMixin:
"""Adds methods for converting marshmallow fields to an OpenAPI properties."""
- field_mapping = DEFAULT_FIELD_MAPPING
+ field_mapping: dict[type, tuple[str | None, str | None]] = DEFAULT_FIELD_MAPPING
openapi_version: Version
def init_attribute_functions(self):
diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py
index a27bc4f..22ff6ef 100644
--- a/src/apispec/ext/marshmallow/openapi.py
+++ b/src/apispec/ext/marshmallow/openapi.py
@@ -197,6 +197,8 @@ class OpenAPIConverter(FieldConverterMixin):
else:
if "description" in prop:
ret["description"] = prop.pop("description")
+ if "deprecated" in prop:
+ ret["deprecated"] = prop.pop("deprecated")
ret["schema"] = prop
for param_attr_func in self.parameter_attribute_functions:
|
marshmallow-code/apispec
|
95d73b45c472d312dea28cf6c89581bfe5fdc969
|
diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py
index 2617329..ed7fb0e 100644
--- a/tests/test_ext_marshmallow_openapi.py
+++ b/tests/test_ext_marshmallow_openapi.py
@@ -245,6 +245,11 @@ class TestMarshmallowSchemaToParameters:
res = openapi._field2parameter(field, name="field", location="query")
assert res["required"] is True
+ def test_field_deprecated(self, openapi):
+ field = fields.Str(metadata={"deprecated": True})
+ res = openapi._field2parameter(field, name="field", location="query")
+ assert res["deprecated"] is True
+
def test_schema_partial(self, openapi):
class UserSchema(Schema):
field = fields.Str(required=True)
|
Deprecated flag is not configured correctly on query parameter objects
When using the `metadata` parameter on a Marshmallow field, the `deprecated` field is not properly configured on parameter objects with a location of `"query"` in the generated spec (the `description` field is set as expected, but not `deprecated`):
```python
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow import Schema, fields
expected_result = """paths:
/endpoint:
get:
parameters:
- in: query
name: bar
description: A field called bar
deprecated: true
schema:
type: string
required: true
info:
title: My API Spec
version: 1.0.0
openapi: 3.1.0
"""
actual_result = """paths:
/endpoint:
get:
parameters:
- in: query
name: bar
description: A field called bar
schema:
type: string
deprecated: true
required: true
info:
title: My API Spec
version: 1.0.0
openapi: 3.1.0
"""
class TestSchema(Schema):
bar = fields.Str(
required=True,
metadata={"description": "A field called bar", "deprecated": True},
)
spec = APISpec(
title="My API Spec",
version="1.0.0",
openapi_version="3.1.0",
plugins=[MarshmallowPlugin()],
)
spec.path(
"/endpoint",
operations={"get": {"parameters": [{"in": "query", "schema": TestSchema}]}},
)
assert spec.to_yaml() == actual_result # passes when it should fail
assert spec.to_yaml() == expected_result # fails when it should pass
```
The `deprecated` field works correctly for request and response bodies, but not for query parameters. It seems to me that setting `deprecated = True` in the metadata on a field instance should mark it as deprecated on the parameter object itself and not the nested schema object, since the schema itself is not what is deprecated.
It looks like the `OpenAPIConverter._field2parameter` method might need updating to promote the `deprecated` flag from the nested `schema` object into the parent object, similar to how `description` is handled.
|
0.0
|
95d73b45c472d312dea28cf6c89581bfe5fdc969
|
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_deprecated[3.0.0]"
] |
[
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_load_default_load[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_default_location_mapping_if_schema_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowFieldToOpenAPI::test_fields_with_dump_only[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_with_explicit_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema2jsonschema_override_name[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_no_required_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_title_and_description_may_be_added[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_disallow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_allow[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_unknown_values_ignore[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_only_explicitly_declared_fields_are_translated[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_observed_field_name_for_required_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[2.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-True]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_schema_instance_inspection[3.0.0-False]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToModelDefinition::test_raises_error_if_no_declared_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_custom_properties_for_custom_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_required[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_deprecated[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_partial_list[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[2.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-List]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_field_list[3.0.0-CustomList]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_with_dump_only[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_body_many[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_schema_query_instance_many_should_raise_exception[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_fields_query[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestMarshmallowSchemaToParameters::test_raises_error_if_not_a_schema[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[2.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-only]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_only_exclude[3.0.0-exclude]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_field[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_plucked_fields_with_adhoc_changes[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[2.0]",
"tests/test_ext_marshmallow_openapi.py::TestNesting::test_schema2jsonschema_with_nested_excluded_fields[3.0.0]",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v2",
"tests/test_ext_marshmallow_openapi.py::test_openapi_tools_validate_v3",
"tests/test_ext_marshmallow_openapi.py::test_openapi_converter_openapi_version_types",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[2.0-date_range-properties9]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range-properties0]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-range_no_upper-properties1]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_ranges-properties2]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-list_length-properties3]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_list_length-properties4]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-string_length-properties5]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-custom_field_length-properties6]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-multiple_lengths-properties7]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-equal_length-properties8]",
"tests/test_ext_marshmallow_openapi.py::TestFieldValidation::test_properties[3.0.0-date_range-properties9]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-17 15:58:38+00:00
|
mit
| 3,751 |
|
marshmallow-code__apispec-webframeworks-64
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index b42ae4a..86f2842 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,12 @@
Changelog
---------
+0.5.2 (unreleased)
+++++++++++++++++++
+
+* BottlePlugin: Fix support for typed path arguments (:issue:`16`).
+ Thanks :user:`genbits` for reporting and thanks :user:`elfjes` for the fix.
+
0.5.1 (2019-11-18)
++++++++++++++++++
diff --git a/src/apispec_webframeworks/bottle.py b/src/apispec_webframeworks/bottle.py
index 4ed5327..b1bbbcf 100644
--- a/src/apispec_webframeworks/bottle.py
+++ b/src/apispec_webframeworks/bottle.py
@@ -27,8 +27,8 @@ from bottle import default_app
from apispec import BasePlugin, yaml_utils
from apispec.exceptions import APISpecError
+RE_URL = re.compile(r"<([^<>:]+):?[^>]*>")
-RE_URL = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
_default_app = default_app()
|
marshmallow-code/apispec-webframeworks
|
fa71207b856ce549886020f3ea9d7371d02eb2dc
|
diff --git a/src/apispec_webframeworks/tests/test_ext_bottle.py b/src/apispec_webframeworks/tests/test_ext_bottle.py
index bbaf116..47c168a 100644
--- a/src/apispec_webframeworks/tests/test_ext_bottle.py
+++ b/src/apispec_webframeworks/tests/test_ext_bottle.py
@@ -99,10 +99,13 @@ class TestPathHelpers:
spec.path(view=get_pet)
assert "/pet/{pet_id}" in get_paths(spec)
- def test_path_with_params(self, spec):
- @route("/pet/<pet_id>/<shop_id>", methods=["POST"])
- def set_pet():
- return "new pet!"
+ @pytest.mark.parametrize(
+ "path", ["/pet/<pet_id:int>/<shop_id:re:[a-z]+>", "/pet/<pet_id>/<shop_id>"],
+ )
+ def test_path_with_params(self, spec, path):
+ @route(path, methods=["GET"])
+ def handler():
+ pass
- spec.path(view=set_pet)
+ spec.path(view=handler)
assert "/pet/{pet_id}/{shop_id}" in get_paths(spec)
|
Bottle plugin path regex bug when using argument type in the url
<a href="https://github.com/genbits"><img src="https://avatars0.githubusercontent.com/u/3424362?v=4" align="left" width="96" height="96" hspace="10"></img></a> **Issue by [genbits](https://github.com/genbits)**
_Monday May 21, 2018 at 10:56 GMT_
_Originally opened as https://github.com/marshmallow-code/apispec/issues/215_
----
When parsing the path of a bottle app in the form: `/path/to/<resourceId:int>`, the generated API path becomes `/path/to/{int}`.
reproduce:
import re
RE_URL = re.compile(r'<(?:[^:<>]+:)?([^<>]+)>')
path = '/path/to/<resourceId:int>'
RE_URL.sub(r'{\1}', path) # --> '/path/to/{int}'
This can be fixed easily by replacing RE_URL with: `re.compile(r'<([^:]+)(?::.+)?>')`
|
0.0
|
fa71207b856ce549886020f3ea9d7371d02eb2dc
|
[
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_params[2.0-/pet/<pet_id:int>/<shop_id:re:[a-z]+>]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_params[3.0.0-/pet/<pet_id:int>/<shop_id:re:[a-z]+>]"
] |
[
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_from_view[2.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_from_view[3.0.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_multiple_methods[2.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_multiple_methods[3.0.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_integration_with_docstring_introspection[2.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_integration_with_docstring_introspection[3.0.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_is_translated_to_openapi_template[2.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_is_translated_to_openapi_template[3.0.0]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_params[2.0-/pet/<pet_id>/<shop_id>]",
"src/apispec_webframeworks/tests/test_ext_bottle.py::TestPathHelpers::test_path_with_params[3.0.0-/pet/<pet_id>/<shop_id>]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-21 09:04:10+00:00
|
mit
| 3,752 |
|
marshmallow-code__flask-marshmallow-249
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 95aebfa..103c30d 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -3,9 +3,9 @@ repos:
rev: v2.31.0
hooks:
- id: pyupgrade
- args: [--py36-plus]
+ args: [--py37-plus]
- repo: https://github.com/python/black
- rev: 22.1.0
+ rev: 22.3.0
hooks:
- id: black
language_version: python3
@@ -13,9 +13,9 @@ repos:
rev: 3.9.2
hooks:
- id: flake8
- additional_dependencies: [flake8-bugbear==22.1.11]
+ additional_dependencies: [flake8-bugbear==22.1.11, importlib-metadata==4.12.0]
- repo: https://github.com/asottile/blacken-docs
rev: v1.12.1
hooks:
- id: blacken-docs
- additional_dependencies: [black==22.1.0]
+ additional_dependencies: [black==22.3.0]
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 6412833..b766d1c 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -27,10 +27,10 @@ jobs:
toxenvs:
- lint
- - py36-marshmallow3
- py37-marshmallow3
- py38-marshmallow3
- py39-marshmallow3
+ - py310-marshmallow3
- py39-lowest
- py39-marshmallowdev
diff --git a/setup.py b/setup.py
index 49c56dc..fd39157 100644
--- a/setup.py
+++ b/setup.py
@@ -4,10 +4,10 @@ from setuptools import setup, find_packages
EXTRAS_REQUIRE = {
"sqlalchemy": [
- "flask-sqlalchemy",
+ "flask-sqlalchemy>=3.0.0",
"marshmallow-sqlalchemy>=0.24.0",
],
- "docs": ["marshmallow-sqlalchemy>=0.13.0", "Sphinx==3.5.4", "sphinx-issues==1.2.0"],
+ "docs": ["marshmallow-sqlalchemy>=0.13.0", "Sphinx==4.5.0", "sphinx-issues==3.0.1"],
"lint": [
"flake8==3.9.2",
"flake8-bugbear==20.11.1",
@@ -59,7 +59,7 @@ setup(
license="MIT",
zip_safe=False,
keywords="flask-marshmallow",
- python_requires=">=3.6",
+ python_requires=">=3.7",
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
diff --git a/src/flask_marshmallow/__init__.py b/src/flask_marshmallow/__init__.py
index a0f0f1c..a3afa4d 100755
--- a/src/flask_marshmallow/__init__.py
+++ b/src/flask_marshmallow/__init__.py
@@ -111,7 +111,7 @@ class Marshmallow:
# If using Flask-SQLAlchemy, attach db.session to SQLAlchemySchema
if has_sqla and "sqlalchemy" in app.extensions:
- db = app.extensions["sqlalchemy"].db
+ db = app.extensions["sqlalchemy"]
if self.SQLAlchemySchema:
self.SQLAlchemySchema.OPTIONS_CLASS.session = db.session
if self.SQLAlchemyAutoSchema:
diff --git a/tox.ini b/tox.ini
index 24608a1..d91a53f 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,7 +1,7 @@
[tox]
envlist=
lint
- py{36,37,38,39}-marshmallow3
+ py{37,38,39,310}-marshmallow3
py39-lowest
py39-marshmallowdev
docs
|
marshmallow-code/flask-marshmallow
|
13f673979937bc5b366863eeff4eefadfb8433d1
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 0dfebd9..f74d30e 100755
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,7 +1,7 @@
import json
from flask import Flask, url_for
-from werkzeug.wrappers import BaseResponse
+from werkzeug.wrappers import Response
from flask_marshmallow import Marshmallow
from tests.markers import flask_1_req
@@ -29,7 +29,7 @@ def test_schema(app, schemas, mockauthor):
def test_jsonify_instance(app, schemas, mockauthor):
s = schemas.AuthorSchema()
resp = s.jsonify(mockauthor)
- assert isinstance(resp, BaseResponse)
+ assert isinstance(resp, Response)
assert resp.content_type == "application/json"
obj = json.loads(resp.get_data(as_text=True))
assert isinstance(obj, dict)
@@ -39,7 +39,7 @@ def test_jsonify_instance(app, schemas, mockauthor):
def test_jsonify_collection(app, schemas, mockauthorlist):
s = schemas.AuthorSchema()
resp = s.jsonify(mockauthorlist, many=True)
- assert isinstance(resp, BaseResponse)
+ assert isinstance(resp, Response)
assert resp.content_type == "application/json"
obj = json.loads(resp.get_data(as_text=True))
assert isinstance(obj, list)
@@ -49,7 +49,7 @@ def test_jsonify_collection(app, schemas, mockauthorlist):
def test_jsonify_collection_via_schema_attr(app, schemas, mockauthorlist):
s = schemas.AuthorSchema(many=True)
resp = s.jsonify(mockauthorlist)
- assert isinstance(resp, BaseResponse)
+ assert isinstance(resp, Response)
assert resp.content_type == "application/json"
obj = json.loads(resp.get_data(as_text=True))
assert isinstance(obj, list)
diff --git a/tests/test_sqla.py b/tests/test_sqla.py
index 2bf138f..5f11e4e 100644
--- a/tests/test_sqla.py
+++ b/tests/test_sqla.py
@@ -1,7 +1,7 @@
import pytest
from flask import Flask, url_for
from flask_sqlalchemy import SQLAlchemy
-from werkzeug.wrappers import BaseResponse
+from werkzeug.wrappers import Response
from flask_marshmallow import Marshmallow
from flask_marshmallow.sqla import HyperlinkRelated
@@ -130,7 +130,7 @@ class TestSQLAlchemy:
assert book_result["author_id"] == book.author_id
resp = author_schema.jsonify(author)
- assert isinstance(resp, BaseResponse)
+ assert isinstance(resp, Response)
@requires_sqlalchemyschema
def test_can_declare_sqla_auto_schemas(self, extma, models, db):
@@ -168,7 +168,7 @@ class TestSQLAlchemy:
assert book_result["author_id"] == book.author_id
resp = author_schema.jsonify(author)
- assert isinstance(resp, BaseResponse)
+ assert isinstance(resp, Response)
@requires_sqlalchemyschema
def test_hyperlink_related_field(self, extma, models, db, extapp):
|
DeprecationWarning from Flask-SQLAlchemy for app.extensions["sqlalchemy"]
Flask-SQLAlchemy has rewritten the way to load the extension. No longer `app.extensions["sqlalchemy"].db` but simply `app.extensions["sqlalchemy"]` see https://github.com/pallets-eco/flask-sqlalchemy/issues/698.
This is used here: https://github.com/marshmallow-code/flask-marshmallow/blob/13f673979937bc5b366863eeff4eefadfb8433d1/src/flask_marshmallow/__init__.py#L114
This is a breaking change and would require to also pin Flask-SQLAlchemy to `>3.0` in https://github.com/marshmallow-code/flask-marshmallow/blob/13f673979937bc5b366863eeff4eefadfb8433d1/setup.py#L7
|
0.0
|
13f673979937bc5b366863eeff4eefadfb8433d1
|
[
"tests/test_sqla.py::TestSQLAlchemy::test_can_initialize_extensions"
] |
[
"tests/test_core.py::test_deferred_initialization",
"tests/test_core.py::test_schema",
"tests/test_core.py::test_jsonify_instance",
"tests/test_core.py::test_jsonify_collection",
"tests/test_core.py::test_jsonify_collection_via_schema_attr",
"tests/test_core.py::test_links_within_nested_object"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-04 19:14:57+00:00
|
mit
| 3,753 |
|
marshmallow-code__flask-smorest-409
|
diff --git a/flask_smorest/spec/__init__.py b/flask_smorest/spec/__init__.py
index cb43dbf..76e8351 100644
--- a/flask_smorest/spec/__init__.py
+++ b/flask_smorest/spec/__init__.py
@@ -7,6 +7,7 @@ from flask import current_app
import click
import apispec
from apispec.ext.marshmallow import MarshmallowPlugin
+from webargs.fields import DelimitedList
try: # pragma: no cover
import yaml
@@ -28,6 +29,18 @@ def _add_leading_slash(string):
return string if string.startswith("/") else "/" + string
+def delimited_list2param(self, field, **kwargs):
+ """apispec parameter attribute function documenting DelimitedList field"""
+ ret = {}
+ if isinstance(field, DelimitedList):
+ if self.openapi_version.major < 3:
+ ret["collectionFormat"] = "csv"
+ else:
+ ret["explode"] = False
+ ret["style"] = "form"
+ return ret
+
+
class DocBlueprintMixin:
"""Extend Api to serve the spec in a dedicated blueprint."""
@@ -217,6 +230,8 @@ class APISpecMixin(DocBlueprintMixin):
self._register_converter(*args)
# Register Upload field properties function
self.ma_plugin.converter.add_attribute_function(uploadfield2properties)
+ # Register DelimitedList field parameter attribute function
+ self.ma_plugin.converter.add_parameter_attribute_function(delimited_list2param)
# Lazy register default responses
self._register_responses()
|
marshmallow-code/flask-smorest
|
710e1f5bfa9dacdba3e0f561f9ec64edb71bfe78
|
diff --git a/tests/test_spec.py b/tests/test_spec.py
index 0f0a8cc..03ea05c 100644
--- a/tests/test_spec.py
+++ b/tests/test_spec.py
@@ -5,6 +5,8 @@ from unittest import mock
import pytest
import yaml
+from webargs.fields import DelimitedList
+import marshmallow as ma
from flask_smorest import Api, Blueprint
from flask_smorest import etag as fs_etag
@@ -34,7 +36,7 @@ class TestAPISpec:
assert "consumes" not in spec
@pytest.mark.parametrize("openapi_version", ["2.0", "3.0.2"])
- def test_api_lazy_registers_error_responses(self, app, openapi_version):
+ def test_apispec_lazy_registers_error_responses(self, app, openapi_version):
"""Test error responses are registered"""
app.config["OPENAPI_VERSION"] = openapi_version
api = Api(app)
@@ -81,7 +83,7 @@ class TestAPISpec:
}
@pytest.mark.parametrize("openapi_version", ["2.0", "3.0.2"])
- def test_api_lazy_registers_etag_headers(self, app, openapi_version):
+ def test_apispec_lazy_registers_etag_headers(self, app, openapi_version):
"""Test etag headers are registered"""
app.config["OPENAPI_VERSION"] = openapi_version
api = Api(app)
@@ -126,7 +128,7 @@ class TestAPISpec:
assert parameters["IF_NONE_MATCH"] == fs_etag.IF_NONE_MATCH_HEADER
assert parameters["IF_MATCH"] == fs_etag.IF_MATCH_HEADER
- def test_api_lazy_registers_pagination_header(self, app):
+ def test_apispec_lazy_registers_pagination_header(self, app):
"""Test pagination header is registered"""
api = Api(app)
@@ -155,6 +157,39 @@ class TestAPISpec:
"schema": {"$ref": "#/components/schemas/PaginationMetadata"},
}
+ @pytest.mark.parametrize("openapi_version", ("2.0", "3.0.2"))
+ def test_apispec_delimited_list_documentation(self, app, openapi_version):
+ """Test DelimitedList if correctly documented"""
+ app.config["OPENAPI_VERSION"] = openapi_version
+ api = Api(app)
+
+ blp = Blueprint("test", "test", url_prefix="/test")
+
+ class ListInputsSchema(ma.Schema):
+ inputs = DelimitedList(ma.fields.Integer)
+
+ @blp.route("/")
+ @blp.arguments(ListInputsSchema, location="query")
+ def test(args):
+ # Also test DelimitedList behaves as expected
+ assert args == {"inputs": [1, 2, 3]}
+
+ api.register_blueprint(blp)
+ spec = api.spec.to_dict()
+ parameters = spec["paths"]["/test/"]["get"]["parameters"]
+ param = next(p for p in parameters if p["name"] == "inputs")
+ if openapi_version == "2.0":
+ assert param["type"] == "array"
+ assert param["items"] == {"type": "integer"}
+ assert param["collectionFormat"] == "csv"
+ else:
+ assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
+ assert param["explode"] is False
+ assert param["style"] == "form"
+
+ client = app.test_client()
+ client.get("/test/", query_string={"inputs": "1,2,3"})
+
class TestAPISpecServeDocs:
"""Test APISpec class doc-serving features"""
|
Unexpected behaviour for webargs.fields.DelimitedList
Taking the following schema:
```python
from marshmallow import Schema
from webargs import fields
class MyScghema(Schema):
a = fields.String()
b = fields.String()
sort_by = fields.DelimitedList(fields.String())
```
According to [Webargs](https://webargs.readthedocs.io/en/latest/quickstart.html#parsing-lists-in-query-strings) and [webargs/issues/406](https://github.com/marshmallow-code/webargs/issues/406), I would expect the OpenAPI specification to design something like this:
```bash
curl 'http://localhost:5000/benchmarks?sort_by=a,b'
```
However, when I use the swagger interface, it produces something like this:
```bash
curl 'http://localhost:5000/benchmarks?sort_by=a&sort_by=b'
```
To use a correct OpenAPI serialization I would recommend:
[Swagger, serialization](https://swagger.io/docs/specification/serialization/) -> Query Parameters (style='form' + explode=false)
|
0.0
|
710e1f5bfa9dacdba3e0f561f9ec64edb71bfe78
|
[
"tests/test_spec.py::TestAPISpec::test_apispec_delimited_list_documentation[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_delimited_list_documentation[AppConfig-3.0.2]"
] |
[
"tests/test_spec.py::TestAPISpec::test_apispec_sets_produces_consumes[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_sets_produces_consumes[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_error_responses[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_error_responses[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_etag_headers[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_etag_headers[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_pagination_header[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-/docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-docs_url_prefix/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-/docs_url_prefix/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-spec.json-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-spec.json-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-redoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-redoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-redoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-redoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-swagger-ui-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-swagger-ui-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-swagger-ui-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-swagger-ui-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui_config[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-rapidoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-rapidoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-rapidoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-rapidoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc_config[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_preserve_order[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_print[AppConfig-'openapi",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_print_output_yaml_no_yaml_module[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_write[AppConfig-'openapi",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_write_output_yaml_no_yaml_module[AppConfig]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-16 17:53:00+00:00
|
mit
| 3,754 |
|
marshmallow-code__flask-smorest-542
|
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 5eb59fa..6af896f 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -26,3 +26,4 @@ Contributors (chronological)
- Dmitry Erlikh `@derlikh-smart <https://github.com/derlikh-smart>`_
- 0x78f1935 `@0x78f1935 <https://github.com/0x78f1935>`_
- One Codex, Inc. `@onecodex <https://github.com/onecodex>`_
+- Dorian Hoxha `@ddorian <https://github.com/ddorian>`_
diff --git a/flask_smorest/spec/plugins.py b/flask_smorest/spec/plugins.py
index e235992..cbafe16 100644
--- a/flask_smorest/spec/plugins.py
+++ b/flask_smorest/spec/plugins.py
@@ -110,7 +110,11 @@ class FlaskPlugin(BasePlugin):
def rule_to_params(self, rule):
"""Get parameters from flask Rule"""
params = []
- for argument in [a for a in rule.arguments if a not in rule.defaults]:
+ for argument in [
+ a
+ for is_dynamic, a in rule._trace
+ if is_dynamic is True and a not in rule.defaults
+ ]:
param = {
"in": "path",
"name": argument,
|
marshmallow-code/flask-smorest
|
ea52d1d35c8f081ca6903b083e307eef6c8ebece
|
diff --git a/tests/test_spec.py b/tests/test_spec.py
index 33eace7..ea0ceb4 100644
--- a/tests/test_spec.py
+++ b/tests/test_spec.py
@@ -35,6 +35,27 @@ class TestAPISpec:
assert "produces" not in spec
assert "consumes" not in spec
+ @pytest.mark.parametrize("openapi_version", ["2.0", "3.0.2"])
+ def test_apispec_correct_path_parameters_ordering(self, app, openapi_version):
+ """Test path parameters are sorted from left to right.
+
+ If this test is flaky it's considered a failure.
+ """
+ app.config["OPENAPI_VERSION"] = openapi_version
+ api = Api(app)
+
+ blp = Blueprint("pets", "pets", url_prefix="/pets")
+
+ @blp.route("/project/<project_id>/upload/<part_id>/complete")
+ def do_nothing():
+ return
+
+ api.register_blueprint(blp)
+
+ sorted_params = list(api.spec.to_dict()["paths"].values())[0]["parameters"]
+ assert sorted_params[0]["name"] == "project_id"
+ assert sorted_params[1]["name"] == "part_id"
+
@pytest.mark.parametrize("openapi_version", ["2.0", "3.0.2"])
def test_apispec_lazy_registers_error_responses(self, app, openapi_version):
"""Test error responses are registered"""
|
Inconsistent order of parameters when using rule.arguments from werkzeug inside FlaskPlugin
I'm using this with flask-smorest. In https://flask-smorest.readthedocs.io/en/latest/openapi.html#enforce-order-in-openapi-specification-file, you say to use "ordered = True" so they're ordered and I can do snapshot-testing on the openapi json output.
~~But in this line:https://github.com/marshmallow-code/apispec/blob/dev/src/apispec/ext/marshmallow/common.py#L54, `schema._declared_fields` is not an ordered dict, but a simple dict. The `schema.fields` is ordered though.~~
~~Do you have any idea how to fix this even with classes instead of just objects?~~
See https://github.com/marshmallow-code/flask-smorest/issues/541 for correct issue
Regards,
Dorian
|
0.0
|
ea52d1d35c8f081ca6903b083e307eef6c8ebece
|
[
"tests/test_spec.py::TestAPISpec::test_apispec_correct_path_parameters_ordering[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_correct_path_parameters_ordering[AppConfig-3.0.2]"
] |
[
"tests/test_spec.py::TestAPISpec::test_apispec_sets_produces_consumes[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_sets_produces_consumes[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_error_responses[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_error_responses[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_etag_headers[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_etag_headers[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpec::test_apispec_lazy_registers_pagination_header[AppConfig]",
"tests/test_spec.py::TestAPISpec::test_apispec_delimited_list_documentation[AppConfig-2.0]",
"tests/test_spec.py::TestAPISpec::test_apispec_delimited_list_documentation[AppConfig-3.0.2]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-/docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-docs_url_prefix/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_prefix[AppConfig-/docs_url_prefix/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-spec.json-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_json_path[AppConfig-spec.json-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-redoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-None-redoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-redoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_redoc[AppConfig-https://my-redoc/-redoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-swagger-ui-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-None-swagger-ui-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-swagger-ui-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui[AppConfig-https://my-swagger/-swagger-ui-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_swagger_ui_config[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-rapidoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-None-rapidoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-None-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-None-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-rapidoc-None]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc[AppConfig-https://my-rapidoc/-rapidoc-docs_url_prefix]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_rapidoc_config[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-json-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-redoc-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-swagger-ui-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc--]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc--/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc-/-]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_empty_path[AppConfig-rapidoc-/-/]",
"tests/test_spec.py::TestAPISpecServeDocs::test_apispec_serve_spec_preserve_order[AppConfig]",
"tests/test_spec.py::TestAPISpecServeDocs::test_multiple_apis_serve_separate_specs[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_print[AppConfig-'openapi",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_print_output_yaml_no_yaml_module[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_write[AppConfig-'openapi",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_write_output_yaml_no_yaml_module[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_print_with_multiple_apis[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_write_with_multiple_apis[AppConfig]",
"tests/test_spec.py::TestAPISpecCLICommands::test_apispec_command_list_config_prefixes[AppConfig]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-17 13:52:02+00:00
|
mit
| 3,755 |
|
marshmallow-code__flask-smorest-561
|
diff --git a/flask_smorest/etag.py b/flask_smorest/etag.py
index 0a3bc0e..5fcef90 100644
--- a/flask_smorest/etag.py
+++ b/flask_smorest/etag.py
@@ -2,13 +2,12 @@
from functools import wraps
from copy import deepcopy
-import json
import http
import warnings
import hashlib
-from flask import request
+from flask import request, json
from .exceptions import PreconditionRequired, PreconditionFailed, NotModified
from .utils import deepupdate, resolve_schema_instance, get_appcontext
@@ -98,11 +97,13 @@ class EtagMixin:
def _generate_etag(etag_data, extra_data=None):
"""Generate an ETag from data
- etag_data: Data to use to compute ETag (must be json serializable)
+ etag_data: Data to use to compute ETag
extra_data: Extra data to add before hashing
Typically, extra_data is used to add pagination metadata to the hash.
It is not dumped through the Schema.
+
+ Data is JSON serialized before hashing using the Flask app JSON serializer.
"""
if extra_data:
etag_data = (etag_data, extra_data)
diff --git a/flask_smorest/spec/__init__.py b/flask_smorest/spec/__init__.py
index 4cf624a..c38460a 100644
--- a/flask_smorest/spec/__init__.py
+++ b/flask_smorest/spec/__init__.py
@@ -1,6 +1,5 @@
"""API specification using OpenAPI"""
-import json
import http
import flask
@@ -126,10 +125,9 @@ class DocBlueprintMixin:
def _openapi_json(self):
"""Serve JSON spec file"""
- # We don't use Flask.jsonify here as it would sort the keys
- # alphabetically while we want to preserve the order.
return current_app.response_class(
- json.dumps(self.spec.to_dict(), indent=2), mimetype="application/json"
+ flask.json.dumps(self.spec.to_dict(), indent=2, sort_keys=False),
+ mimetype="application/json",
)
def _openapi_redoc(self):
@@ -396,7 +394,9 @@ def print_openapi_doc(format, config_prefix):
"""Print OpenAPI JSON document."""
config_prefix = normalize_config_prefix(config_prefix)
if format == "json":
- click.echo(json.dumps(_get_spec_dict(config_prefix), indent=2))
+ click.echo(
+ flask.json.dumps(_get_spec_dict(config_prefix), indent=2, sort_keys=False)
+ )
else: # format == "yaml"
if HAS_PYYAML:
click.echo(yaml.dump(_get_spec_dict(config_prefix)))
@@ -415,7 +415,7 @@ def write_openapi_doc(format, output_file, config_prefix):
config_prefix = normalize_config_prefix(config_prefix)
if format == "json":
click.echo(
- json.dumps(_get_spec_dict(config_prefix), indent=2),
+ flask.json.dumps(_get_spec_dict(config_prefix), indent=2, sort_keys=False),
file=output_file,
)
else: # format == "yaml"
|
marshmallow-code/flask-smorest
|
50216078382efe9fca01b55ca7df157301b27215
|
diff --git a/tests/test_api.py b/tests/test_api.py
index 2760bef..1f28575 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,8 +1,11 @@
"""Test Api class"""
+import json
+
import pytest
from flask import jsonify
from flask.views import MethodView
+from flask.json.provider import DefaultJSONProvider
from werkzeug.routing import BaseConverter
import marshmallow as ma
import apispec
@@ -522,3 +525,45 @@ class TestApi:
"API_V2_OPENAPI_VERSION",
}
assert len(api_v2.config) == 3
+
+ @pytest.mark.parametrize("openapi_version", ["2.0", "3.0.2"])
+ def test_api_serializes_doc_with_flask_json(self, app, openapi_version):
+ """Check that app.json, not standard json, is used to serialize API doc"""
+
+ class CustomType:
+ """Custom type"""
+
+ class CustomJSONEncoder(json.JSONEncoder):
+ def default(self, object):
+ if isinstance(object, CustomType):
+ return 42
+ return super().default(object)
+
+ class CustomJsonProvider(DefaultJSONProvider):
+ def dumps(self, obj, **kwargs):
+ return json.dumps(obj, **kwargs, cls=CustomJSONEncoder)
+
+ class CustomSchema(ma.Schema):
+ custom_field = ma.fields.Field(load_default=CustomType())
+
+ app.config["OPENAPI_VERSION"] = openapi_version
+ app.json = CustomJsonProvider(app)
+ api = Api(app)
+ blp = Blueprint("test", "test", url_prefix="/test")
+
+ @blp.route("/")
+ @blp.arguments(CustomSchema)
+ def test(args):
+ pass
+
+ api.register_blueprint(blp)
+
+ with app.app_context():
+ spec_dict = api._openapi_json().json
+
+ if openapi_version == "2.0":
+ schema = spec_dict["definitions"]["Custom"]
+ else:
+ schema = spec_dict["components"]["schemas"]["Custom"]
+
+ assert schema["properties"]["custom_field"]["default"] == 42
|
Apispec 6.1.0: Accessing API docs throws TypeError: Object of type Decimal is not JSON serializable
The update to 6.1.0 causes an 500 internal server error for me when trying to view my API docs in a browser. Using flask-smorest. No such error in 6.0.2.
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 2213, in __call__
return self.wsgi_app(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 2193, in wsgi_app
response = self.handle_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 2190, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 1486, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 1484, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask/app.py", line 1469, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/flask_smorest/spec/__init__.py", line 131, in _openapi_json
json.dumps(self.spec.to_dict(), indent=2), mimetype="application/json"
File "/usr/local/lib/python3.11/json/__init__.py", line 238, in dumps
**kw).encode(obj)
^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/encoder.py", line 202, in encode
chunks = list(chunks)
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/encoder.py", line 432, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/usr/local/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
yield from chunks
File "/usr/local/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
yield from chunks
File "/usr/local/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
yield from chunks
[Previous line repeated 3 more times]
File "/usr/local/lib/python3.11/json/encoder.py", line 439, in _iterencode
o = _default(o)
^^^^^^^^^^^
File "/usr/local/lib/python3.11/json/encoder.py", line 180, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
Package Version Editable project location
---------------------- ---------- -------------------------
apispec 6.1.0
Flask 2.3.2
flask-smorest 0.42.0
|
0.0
|
50216078382efe9fca01b55ca7df157301b27215
|
[
"tests/test_api.py::TestApi::test_api_serializes_doc_with_flask_json[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_serializes_doc_with_flask_json[AppConfig-3.0.2]"
] |
[
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params0-2.0]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params0-3.0.2]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params1-2.0]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params1-3.0.2]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params2-2.0]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params2-3.0.2]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params3-2.0]",
"tests/test_api.py::TestApi::test_api_unicode_converter[AppConfig-params3-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params0-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params0-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params1-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params1-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params2-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params2-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params3-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-int-params3-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params0-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params0-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params1-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params1-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params2-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params2-3.0.2]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params3-2.0]",
"tests/test_api.py::TestApi::test_api_int_float_converter[AppConfig-float-params3-3.0.2]",
"tests/test_api.py::TestApi::test_api_uuid_converter[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_uuid_converter[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_any_converter[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_any_converter[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-function-True-2.0]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-function-True-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-function-False-2.0]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-function-False-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-method-True-2.0]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-method-True-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-method-False-2.0]",
"tests/test_api.py::TestApi::test_api_register_converter[AppConfig-method-False-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_converter_before_or_after_init[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_register_converter_before_or_after_init[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_field_parameters[AppConfig-mapping0]",
"tests/test_api.py::TestApi::test_api_register_field_parameters[AppConfig-mapping1]",
"tests/test_api.py::TestApi::test_api_register_field_parameters[AppConfig-mapping2]",
"tests/test_api.py::TestApi::test_api_register_field_before_and_after_init[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_register_field_before_and_after_init[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_extra_spec_kwargs[AppConfig-at_once]",
"tests/test_api.py::TestApi::test_api_extra_spec_kwargs[AppConfig-init]",
"tests/test_api.py::TestApi::test_api_extra_spec_kwargs[AppConfig-init_app]",
"tests/test_api.py::TestApi::test_api_extra_spec_kwargs_init_app_update_init[AppConfig]",
"tests/test_api.py::TestApi::test_api_extra_spec_plugins[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_extra_spec_plugins[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_register_blueprint_options[AppConfig]",
"tests/test_api.py::TestApi::test_api_api_parameters[AppConfig-parameter0]",
"tests/test_api.py::TestApi::test_api_api_parameters[AppConfig-parameter1]",
"tests/test_api.py::TestApi::test_api_openapi_version_parameter[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_openapi_version_parameter[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_api_lazy_registers_default_error_response[AppConfig-2.0]",
"tests/test_api.py::TestApi::test_api_lazy_registers_default_error_response[AppConfig-3.0.2]",
"tests/test_api.py::TestApi::test_multiple_apis_using_config_prefix_attribute[AppConfig]",
"tests/test_api.py::TestApi::test_prefixed_api_to_raise_correctly_formatted_error[AppConfig]",
"tests/test_api.py::TestApi::test_current_api[AppConfig]",
"tests/test_api.py::TestApi::test_api_config_proxying_flask_config[AppConfig]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-02 07:27:02+00:00
|
mit
| 3,756 |
|
marshmallow-code__marshmallow-jsonapi-289
|
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 05a075a..5813f7c 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -31,3 +31,4 @@ Contributors (chronological)
- `@aberres <https://github.com/aberres>`_
- George Alton `@georgealton <https://github.com/georgealton>`_
- Areeb Jamal `@iamareebjamal <https://github.com/iamareebjamal>`_
+- Suren Khorenyan `@mahenzon <https://github.com/mahenzon>`_
diff --git a/docs/requirements.txt b/docs/requirements.txt
index 544309a..50ad354 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -1,5 +1,5 @@
marshmallow>=2.0.0rc1
Flask==1.1.1
-sphinx==2.4.2
+sphinx==2.4.4
sphinx-rtd-theme==0.4.3
sphinx-issues>=0.2.0
diff --git a/marshmallow_jsonapi/schema.py b/marshmallow_jsonapi/schema.py
index b8de86a..2224516 100644
--- a/marshmallow_jsonapi/schema.py
+++ b/marshmallow_jsonapi/schema.py
@@ -1,3 +1,5 @@
+import itertools
+
import marshmallow as ma
from marshmallow.exceptions import ValidationError
from marshmallow.utils import is_collection
@@ -286,21 +288,34 @@ class Schema(ma.Schema):
formatted_errors = []
if many:
- for index, errors in errors.items():
- for field_name, field_errors in errors.items():
- formatted_errors.extend(
- [
- self.format_error(field_name, message, index=index)
- for message in field_errors
- ]
- )
+ for index, i_errors in errors.items():
+ formatted_errors.extend(self._get_formatted_errors(i_errors, index))
else:
- for field_name, field_errors in errors.items():
- formatted_errors.extend(
- [self.format_error(field_name, message) for message in field_errors]
- )
+ formatted_errors.extend(self._get_formatted_errors(errors))
+
return {"errors": formatted_errors}
+ def _get_formatted_errors(self, errors, index=None):
+ return itertools.chain(
+ *(
+ [
+ self.format_error(field_name, message, index=index)
+ for message in field_errors
+ ]
+ for field_name, field_errors in itertools.chain(
+ *(self._process_nested_errors(k, v) for k, v in errors.items())
+ )
+ )
+ )
+
+ def _process_nested_errors(self, name, data):
+ if not isinstance(data, dict):
+ return [(name, data)]
+
+ return itertools.chain(
+ *(self._process_nested_errors(f"{name}/{k}", v) for k, v in data.items())
+ )
+
def format_error(self, field_name, message, index=None):
"""Override-able hook to format a single error message as an Error object.
|
marshmallow-code/marshmallow-jsonapi
|
f0f3ed18180c40420ea484b931d6f9545857a80a
|
diff --git a/tests/test_schema.py b/tests/test_schema.py
index 4ca16ea..bd6ad4b 100755
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -1,4 +1,5 @@
import pytest
+import marshmallow as ma
from marshmallow import ValidationError
from marshmallow_jsonapi import Schema, fields
@@ -608,6 +609,56 @@ class TestErrorFormatting:
assert id_err["source"]["pointer"] == "/data/1/id"
assert id_err["detail"] == "Not a valid string."
+ def test_nested_fields_error(self):
+ min_size = 10
+
+ class ThirdLevel(ma.Schema):
+ number = fields.Int(required=True, validate=ma.validate.Range(min=min_size))
+
+ class SecondLevel(ma.Schema):
+ foo = fields.Str(required=True)
+ third = fields.Nested(ThirdLevel)
+
+ class FirstLevel(Schema):
+ class Meta:
+ type_ = "first"
+
+ id = fields.Int()
+ second = fields.Nested(SecondLevel)
+
+ schema = FirstLevel()
+ result = schema.validate(
+ {
+ "data": {
+ "type": "first",
+ "attributes": {"second": {"third": {"number": 5}}},
+ }
+ }
+ )
+
+ def sort_func(d):
+ return d["source"]["pointer"]
+
+ expected_errors = sorted(
+ [
+ {
+ "source": {"pointer": "/data/attributes/second/third/number"},
+ "detail": f"Must be greater than or equal to {min_size}."
+ if _MARSHMALLOW_VERSION_INFO[0] >= 3
+ else f"Must be at least {min_size}.",
+ },
+ {
+ "source": {"pointer": "/data/attributes/second/foo"},
+ "detail": ma.fields.Field.default_error_messages["required"],
+ },
+ ],
+ key=sort_func,
+ )
+
+ errors = sorted(result["errors"], key=sort_func)
+
+ assert errors == expected_errors
+
class TestMeta:
shape = {
|
Validation errors for nested fields are not formatted properly
```
from marshmallow import validate, Schema as BasicSchema
from marshmallow_jsonapi import Schema, fields
class SecondNestedSchema(BasicSchema):
second = fields.String(validate=validate.OneOf(['test']))
class FirstNestedSchema(BasicSchema):
first = fields.String(validate=validate.OneOf(['test']))
second_nest = fields.Nested(SecondNestedSchema, many=True)
class SimpleSchema(Schema):
id = fields.UUID(dump_only=True)
simple = fields.String(validate=validate.OneOf(['test']))
first_nest = fields.Nested(FirstNestedSchema, many=True)
class Meta:
type_ = 'simples'
###########################################################
schema = SimpleSchema()
data = {
'data': {
'type': 'simples',
'attributes': {
'simple': 'tes',
'first_nest': [
{
'first': 'tes',
'second_nest': [
{
'second': 'tes'
}
]
}
]
}
}
}
try:
data = schema.load(data)
print(data)
except ValidationError as err:
print(err.messages)
```
This will be printed:
```
{
'errors': [
{
'detail': 0,
'source': {
'pointer': '/data/attributes/first_nest'
}
},
{
'detail': 'Not a valid choice.',
'source': {
'pointer': '/data/attributes/simple'
}
}
]
}
```
This is what I wished for:
```
{
'errors': [
{
'detail': 'Not a valid choice.',
'source': {
'pointer': '/data/attributes/first_nest/first'
}
},
{
'detail': 'Not a valid choice.',
'source': {
'pointer': '/data/attributes/first_nest/second_nest/second'
}
},
{
'detail': 'Not a valid choice.',
'source': {
'pointer': '/data/attributes/simple'
}
}
]
}
```
Is there a possibility for the desired output to happen?
|
0.0
|
f0f3ed18180c40420ea484b931d6f9545857a80a
|
[
"tests/test_schema.py::TestErrorFormatting::test_nested_fields_error"
] |
[
"tests/test_schema.py::test_type_is_required",
"tests/test_schema.py::test_id_field_is_required",
"tests/test_schema.py::TestResponseFormatting::test_dump_single",
"tests/test_schema.py::TestResponseFormatting::test_dump_many",
"tests/test_schema.py::TestResponseFormatting::test_self_link_single",
"tests/test_schema.py::TestResponseFormatting::test_self_link_many",
"tests/test_schema.py::TestResponseFormatting::test_dump_to",
"tests/test_schema.py::TestResponseFormatting::test_dump_none",
"tests/test_schema.py::TestResponseFormatting::test_dump_empty_list",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_many",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_single",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_all_relations",
"tests/test_schema.py::TestCompoundDocuments::test_include_no_data",
"tests/test_schema.py::TestCompoundDocuments::test_include_self_referential_relationship",
"tests/test_schema.py::TestCompoundDocuments::test_include_self_referential_relationship_many",
"tests/test_schema.py::TestCompoundDocuments::test_include_self_referential_relationship_many_deep",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_many_and_schema_as_class",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_nested_only_arg",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_nested_exclude_arg",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_load",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_load_null",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_load_without_schema_loads_only_ids",
"tests/test_schema.py::TestCompoundDocuments::test_include_data_with_schema_context",
"tests/test_schema.py::TestErrorFormatting::test_validate",
"tests/test_schema.py::TestErrorFormatting::test_errors_in_strict_mode",
"tests/test_schema.py::TestErrorFormatting::test_no_type_raises_error",
"tests/test_schema.py::TestErrorFormatting::test_validate_no_data_raises_error",
"tests/test_schema.py::TestErrorFormatting::test_validate_type",
"tests/test_schema.py::TestErrorFormatting::test_validate_id",
"tests/test_schema.py::TestErrorFormatting::test_load",
"tests/test_schema.py::TestErrorFormatting::test_errors_is_empty_if_valid",
"tests/test_schema.py::TestErrorFormatting::test_errors_many",
"tests/test_schema.py::TestErrorFormatting::test_errors_many_not_list",
"tests/test_schema.py::TestErrorFormatting::test_many_id_errors",
"tests/test_schema.py::TestMeta::test_dump_single",
"tests/test_schema.py::TestMeta::test_dump_many",
"tests/test_schema.py::TestMeta::test_load_single",
"tests/test_schema.py::TestMeta::test_load_many",
"tests/test_schema.py::TestRelationshipLoading::test_deserializing_relationship_fields",
"tests/test_schema.py::TestRelationshipLoading::test_deserializing_nested_relationship_fields",
"tests/test_schema.py::TestRelationshipLoading::test_deserializing_relationship_errors",
"tests/test_schema.py::TestRelationshipLoading::test_deserializing_missing_required_relationship",
"tests/test_schema.py::TestRelationshipLoading::test_deserializing_relationship_with_missing_param"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-12 16:52:20+00:00
|
mit
| 3,757 |
|
marshmallow-code__marshmallow-sqlalchemy-239
|
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 6119d05..fc44907 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -30,3 +30,4 @@ Contributors
- jean-philippe serafin `@jeanphix <https://github.com/jeanphix>`_
- Jack Smith `@jacksmith15 <https://github.com/jacksmith15>`_
- Kazantcev Andrey `@heckad <https://github.com/heckad>`_
+- Samuel Searles-Bryant `@samueljsb <https://github.com/samueljsb>`_
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index c1163bf..71ecaaa 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,52 @@
Changelog
---------
+0.17.1 (unreleased)
++++++++++++++++++++
+
+Bug fixes:
+
+* Add ``marshmallow_sqlalchemy.fields.Nested`` field that inherits its session from its schema. This fixes a bug where an exception was raised when using ``Nested`` within a ``ModelSchema`` (:issue:`67`).
+ Thanks :user:`nickw444` for reporting and thanks :user:`samueljsb` for the PR.
+
+User code should be updated to use marshmallow-sqlalchemy's ``Nested`` instead of ``marshmallow.fields.Nested``.
+
+.. code-block:: python
+
+ # Before
+ from marshmallow import fields
+ from marshmallow_sqlalchemy import ModelSchema
+
+
+ class ArtistSchema(ModelSchema):
+ class Meta:
+ model = models.Artist
+
+
+ class AlbumSchema(ModelSchema):
+ class Meta:
+ model = models.Album
+
+ artist = fields.Nested(ArtistSchema)
+
+
+ # After
+ from marshmallow import fields
+ from marshmallow_sqlalchemy import ModelSchema
+ from marshmallow_sqlalchemy.fields import Nested
+
+
+ class ArtistSchema(ModelSchema):
+ class Meta:
+ model = models.Artist
+
+
+ class AlbumSchema(ModelSchema):
+ class Meta:
+ model = models.Album
+
+ artist = Nested(ArtistSchema)
+
0.17.0 (2019-06-22)
+++++++++++++++++++
diff --git a/docs/recipes.rst b/docs/recipes.rst
index e717941..61e5b08 100644
--- a/docs/recipes.rst
+++ b/docs/recipes.rst
@@ -124,11 +124,12 @@ Any field generated by a `ModelSchema <marshmallow_sqlalchemy.ModelSchema>` can
from marshmallow import fields
from marshmallow_sqlalchemy import ModelSchema
+ from marshmallow_sqlalchemy.fields import Nested
class AuthorSchema(ModelSchema):
# Override books field to use a nested representation rather than pks
- books = fields.Nested(BookSchema, many=True, exclude=("author",))
+ books = Nested(BookSchema, many=True, exclude=("author",))
class Meta:
model = Author
@@ -162,7 +163,7 @@ You can customize the keyword arguments passed to a column property's correspond
Automatically Generating Schemas For SQLAlchemy Models
======================================================
-It can be tedious to implement a large number of schemas if not overriding any of the generated fields as detailed above. SQLAlchemy has a hook that can be used to trigger the creation of the schemas, assigning them to the SQLAlchemy model property `<Model.__marshmallow__>`.
+It can be tedious to implement a large number of schemas if not overriding any of the generated fields as detailed above. SQLAlchemy has a hook that can be used to trigger the creation of the schemas, assigning them to the SQLAlchemy model property ``Model.__marshmallow__``.
.. code-block:: python
@@ -243,7 +244,10 @@ To serialize nested attributes to primary keys unless they are already loaded, y
.. code-block:: python
- class SmartNested(fields.Nested):
+ from marshmallow_sqlalchemy.fields import Nested
+
+
+ class SmartNested(Nested):
def serialize(self, attr, obj, accessor=None):
if attr not in obj.__dict__:
return {"id": int(getattr(obj, attr + "_id"))}
diff --git a/src/marshmallow_sqlalchemy/fields.py b/src/marshmallow_sqlalchemy/fields.py
index 8289d08..64d19ac 100644
--- a/src/marshmallow_sqlalchemy/fields.py
+++ b/src/marshmallow_sqlalchemy/fields.py
@@ -131,3 +131,16 @@ class Related(fields.Field):
if result is None:
raise NoResultFound
return result
+
+
+class Nested(fields.Nested):
+ """Nested field that inherits the session from its parent."""
+
+ def _deserialize(self, *args, **kwargs):
+ if hasattr(self.schema, "session"):
+ try:
+ self.schema.session = self.root.session
+ except AttributeError:
+ # Marshmallow 2.0.0 has no root property.
+ self.schema.session = self.parent.session
+ return super(Nested, self)._deserialize(*args, **kwargs)
|
marshmallow-code/marshmallow-sqlalchemy
|
be6df3e87c61d699b321e2a1257e5999e46f6ef8
|
diff --git a/tests/test_marshmallow_sqlalchemy.py b/tests/test_marshmallow_sqlalchemy.py
index da5b9d0..cc77550 100644
--- a/tests/test_marshmallow_sqlalchemy.py
+++ b/tests/test_marshmallow_sqlalchemy.py
@@ -25,7 +25,7 @@ from marshmallow_sqlalchemy import (
field_for,
ModelConversionError,
)
-from marshmallow_sqlalchemy.fields import Related, RelatedList
+from marshmallow_sqlalchemy.fields import Related, RelatedList, Nested
MARSHMALLOW_VERSION_INFO = tuple(
[int(part) for part in marshmallow.__version__.split(".") if part.isdigit()]
@@ -1318,6 +1318,77 @@ class TestMarshmallowContext:
assert dump_result == data
+class TestNestedFieldSession:
+ """Test the session can be passed to nested fields."""
+
+ @pytest.fixture
+ def association_table(self, Base):
+ return sa.Table(
+ "association",
+ Base.metadata,
+ sa.Column("left_id", sa.Integer, sa.ForeignKey("left.id")),
+ sa.Column("right_id", sa.Integer, sa.ForeignKey("right.id")),
+ )
+
+ @pytest.fixture
+ def parent_model(self, Base, association_table):
+ class Parent(Base):
+ __tablename__ = "left"
+ id = sa.Column(sa.Integer, primary_key=True)
+ name = sa.Column(sa.Text)
+ children = relationship(
+ "Child", secondary=association_table, back_populates="parents"
+ )
+
+ return Parent
+
+ @pytest.fixture
+ def child_model(self, Base, parent_model, association_table):
+ class Child(Base):
+ __tablename__ = "right"
+ id = sa.Column(sa.Integer, primary_key=True)
+ name = sa.Column(sa.Text)
+ parents = relationship(
+ "Parent", secondary=association_table, back_populates="children"
+ )
+
+ return Child
+
+ @pytest.fixture
+ def child_schema(self, child_model):
+ class ChildSchema(ModelSchema):
+ class Meta:
+ model = child_model
+
+ return ChildSchema
+
+ def test_session_is_passed_to_nested_field(
+ self, child_schema, parent_model, session
+ ):
+ class ParentSchema(ModelSchema):
+ children = Nested(child_schema, many=True)
+
+ class Meta:
+ model = parent_model
+
+ data = {"name": "Parent1", "children": [{"name": "Child1"}]}
+ ParentSchema().load(data, session=session)
+
+ def test_session_is_passed_to_nested_field_in_list_field(
+ self, parent_model, child_model, child_schema, session
+ ):
+ """The session is passed to a nested field in a List field."""
+
+ class ParentSchema(ModelSchema):
+ children = fields.List(Nested(child_schema))
+
+ class Meta:
+ model = parent_model
+
+ data = {"name": "Jorge", "children": [{"name": "Jose"}]}
+ ParentSchema().load(data, session=session)
+
+
def _repr_validator_list(validators):
return sorted([repr(validator) for validator in validators])
|
Schema deserialisation with defined session and nested field throws an exception
Not sure if this is intended functionality, however the code below throws `ValueError: Deserialization requires a session` when trying to load data into a nested object.
I would expect passing a session would propagate to nested fields, however this doesn't seem to be the case. Is this by design?
If i remove `followup` (the nested field) from the `only=` property, the data loads fine from the non-nested field.
``` python
class FollowUp(ModelSchema):
reasonCode =fields.String(attribute='reason_code')
comment = fields.String()
class Occurence(ModelSchema):
#... other fields before ...
followup = fields.Nested(FollowUp())
status = fields.String()
# Inside my request handler:
obj = DBOccurence.query.get_or_404(occ_id)
res = Occurence(only=['status', 'followup']).load(
request.json,
instance=obj,
session=current_app.db.session
)
```
|
0.0
|
be6df3e87c61d699b321e2a1257e5999e46f6ef8
|
[
"tests/test_marshmallow_sqlalchemy.py::TestModelFieldConversion::test_fields_for_model_handles_custom_types",
"tests/test_marshmallow_sqlalchemy.py::TestModelFieldConversion::test_sets_enum_choices",
"tests/test_marshmallow_sqlalchemy.py::TestModelFieldConversion::test_overridden_with_fk",
"tests/test_marshmallow_sqlalchemy.py::TestModelFieldConversion::test_info_overrides",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_custom_type_mapping_on_schema",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_String",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Unicode",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_LargeBinary",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Text",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Date",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_DateTime",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Boolean",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Numeric",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_Float",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_SmallInteger",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_UUID",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_MACADDR",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_INET",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_ARRAY_String",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_ARRAY_Integer",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_TSVECTOR",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_default",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_server_default",
"tests/test_marshmallow_sqlalchemy.py::TestPropertyFieldConversion::test_convert_autoincrement",
"tests/test_marshmallow_sqlalchemy.py::TestPropToFieldClass::test_property2field",
"tests/test_marshmallow_sqlalchemy.py::TestPropToFieldClass::test_can_pass_extra_kwargs",
"tests/test_marshmallow_sqlalchemy.py::TestColumnToFieldClass::test_column2field",
"tests/test_marshmallow_sqlalchemy.py::TestColumnToFieldClass::test_can_pass_extra_kwargs",
"tests/test_marshmallow_sqlalchemy.py::TestColumnToFieldClass::test_uuid_column2field",
"tests/test_marshmallow_sqlalchemy.py::TestFieldFor::test_field_for_can_override_validators",
"tests/test_marshmallow_sqlalchemy.py::TestTableSchema::test_dump_row",
"tests/test_marshmallow_sqlalchemy.py::TestTableSchema::test_exclude",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_model_schema_class_meta_inheritance",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_model_schema_ordered",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_fields_option",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_exclude_option",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_additional_option",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_field_override",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_dump_only_relationship",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_schema",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_load",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_load_with_unknown_include",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_schema_with_relationship",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_schema_with_association",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_transient_schema_with_implicit_association",
"tests/test_marshmallow_sqlalchemy.py::TestModelSchema::test_exclude",
"tests/test_marshmallow_sqlalchemy.py::TestMarshmallowContext::test_getting_session_from_marshmallow_context",
"tests/test_marshmallow_sqlalchemy.py::test_merge_validators[defaults0-new0-expected0]",
"tests/test_marshmallow_sqlalchemy.py::test_merge_validators[defaults1-new1-expected1]",
"tests/test_marshmallow_sqlalchemy.py::test_merge_validators[defaults2-new2-expected2]",
"tests/test_marshmallow_sqlalchemy.py::test_merge_validators[defaults3-new3-expected3]"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-08-23 15:46:48+00:00
|
mit
| 3,758 |
|
marshmallow-code__webargs-428
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 1b98a37..3eb6b9c 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -15,7 +15,7 @@ repos:
- id: blacken-docs
additional_dependencies: [black==19.3b0]
- repo: https://github.com/pre-commit/mirrors-mypy
- rev: v0.720
+ rev: v0.730
hooks:
- id: mypy
language_version: python3
diff --git a/AUTHORS.rst b/AUTHORS.rst
index 363afc7..b1c8efd 100644
--- a/AUTHORS.rst
+++ b/AUTHORS.rst
@@ -40,3 +40,4 @@ Contributors (chronological)
* Xiaoyu Lee <https://github.com/lee3164>
* Jonathan Angelo <https://github.com/jangelo>
* @zhenhua32 <https://github.com/zhenhua32>
+* Martin Roy <https://github.com/lindycoder>
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index d038031..224bb84 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,14 @@
Changelog
---------
+5.5.2 (unreleased)
+******************
+
+Bug fixes:
+
+* Handle ``UnicodeDecodeError`` when parsing JSON payloads (:issue:`427`).
+ Thanks :user:`lindycoder` for the catch and patch.
+
5.5.1 (2019-09-15)
******************
diff --git a/src/webargs/aiohttpparser.py b/src/webargs/aiohttpparser.py
index b36428c..9e76e05 100644
--- a/src/webargs/aiohttpparser.py
+++ b/src/webargs/aiohttpparser.py
@@ -102,6 +102,9 @@ class AIOHTTPParser(AsyncParser):
return core.missing
else:
return self.handle_invalid_json_error(e, req)
+ except UnicodeDecodeError as e:
+ return self.handle_invalid_json_error(e, req)
+
self._cache["json"] = json_data
return core.get_value(json_data, name, field, allow_many_nested=True)
@@ -164,7 +167,11 @@ class AIOHTTPParser(AsyncParser):
)
def handle_invalid_json_error(
- self, error: json.JSONDecodeError, req: Request, *args, **kwargs
+ self,
+ error: typing.Union[json.JSONDecodeError, UnicodeDecodeError],
+ req: Request,
+ *args,
+ **kwargs
) -> "typing.NoReturn":
error_class = exception_map[400]
messages = {"json": ["Invalid JSON body."]}
diff --git a/src/webargs/bottleparser.py b/src/webargs/bottleparser.py
index a03fb11..568dc65 100644
--- a/src/webargs/bottleparser.py
+++ b/src/webargs/bottleparser.py
@@ -47,6 +47,9 @@ class BottleParser(core.Parser):
return core.missing
else:
return self.handle_invalid_json_error(e, req)
+ except UnicodeDecodeError as e:
+ return self.handle_invalid_json_error(e, req)
+
if json_data is None:
return core.missing
return core.get_value(json_data, name, field, allow_many_nested=True)
diff --git a/src/webargs/core.py b/src/webargs/core.py
index b3eec6b..fe2f39b 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -112,7 +112,14 @@ def get_value(data, name, field, allow_many_nested=False):
def parse_json(s, encoding="utf-8"):
if isinstance(s, bytes):
- s = s.decode(encoding)
+ try:
+ s = s.decode(encoding)
+ except UnicodeDecodeError as e:
+ raise json.JSONDecodeError(
+ "Bytes decoding error : {}".format(e.reason),
+ doc=str(e.object),
+ pos=e.start,
+ )
return json.loads(s)
|
marshmallow-code/webargs
|
f2db6bcb2b2f963b819d409da4788411fea3170d
|
diff --git a/src/webargs/testing.py b/src/webargs/testing.py
index 2d07684..922bc47 100644
--- a/src/webargs/testing.py
+++ b/src/webargs/testing.py
@@ -117,6 +117,18 @@ class CommonTestCase(object):
text = u"øˆƒ£ºº∆ƒˆ∆"
assert testapp.post_json("/echo", {"name": text}).json == {"name": text}
+ # https://github.com/marshmallow-code/webargs/issues/427
+ def test_parse_json_with_nonutf8_chars(self, testapp):
+ res = testapp.post(
+ "/echo",
+ b"\xfe",
+ headers={"Accept": "application/json", "Content-Type": "application/json"},
+ expect_errors=True,
+ )
+
+ assert res.status_code == 400
+ assert res.json == {"json": ["Invalid JSON body."]}
+
def test_validation_error_returns_422_response(self, testapp):
res = testapp.post("/echo", {"name": "b"}, expect_errors=True)
assert res.status_code == 422
diff --git a/tests/test_falconparser.py b/tests/test_falconparser.py
index 7162a0d..d6092c7 100644
--- a/tests/test_falconparser.py
+++ b/tests/test_falconparser.py
@@ -16,6 +16,18 @@ class TestFalconParser(CommonTestCase):
def test_use_args_hook(self, testapp):
assert testapp.get("/echo_use_args_hook?name=Fred").json == {"name": "Fred"}
+ # https://github.com/marshmallow-code/webargs/issues/427
+ def test_parse_json_with_nonutf8_chars(self, testapp):
+ res = testapp.post(
+ "/echo",
+ b"\xfe",
+ headers={"Accept": "application/json", "Content-Type": "application/json"},
+ expect_errors=True,
+ )
+
+ assert res.status_code == 400
+ assert res.json["errors"] == {"json": ["Invalid JSON body."]}
+
# https://github.com/sloria/webargs/issues/329
def test_invalid_json(self, testapp):
res = testapp.post(
|
Non UTF-8 json payload produce a 500 and a stack trace
Hi,
First of all thanks for thie library, while doing some testing with random payload we stumbled upon a corner case:
## Actual Behavior:
If non utf-8 data is sent with header Application/Json the `core`'s `parse_json` will raise a UnicodeDecodeError, which generates a 500.
## Expected Behavior
A `400 BAD REQUEST`
## Notes
- `Python 3.6`
- `webargs==5.5.1`
I would handle the problem my self but as you can see in the stack trace, my code is never reached so i would need a wrapper above `@use_args`
## Reproduce
CODE (From README example with `methods=` added):
```
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
@use_args({"name": fields.Str(required=True)})
def index(args):
return "Hello " + args["name"]
if __name__ == "__main__":
app.run()
```
Curl invocation
```
$ curl http://localhost:5000/ -H 'Content-Type: Application/Json' -d $(python -c "import os; import sys; os.write(sys.stdout.fileno(), b'\xfe')")
```
Output
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
```
Full Stack trace
```
.../.tox/py36/bin/python3.6 .../tests/webargs_poc.py
* Serving Flask app "webargs_poc" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2019-09-23 09:07:54,383] ERROR in app: Exception on / [POST]
Traceback (most recent call last):
File ".../.tox/py36/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File ".../.tox/py36/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File ".../.tox/py36/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File ".../.tox/py36/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File ".../.tox/py36/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File ".../.tox/py36/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 444, in wrapper
error_headers=error_headers,
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 347, in parse
schema=schema, req=req, locations=locations or self.locations
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 263, in _parse_request
parsed_value = self.parse_arg(argname, field_obj, req, locations)
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 226, in parse_arg
value = self._get_value(name, field, req=req, location=location)
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 202, in _get_value
return function(req, name, argobj)
File ".../.tox/py36/lib/python3.6/site-packages/webargs/flaskparser.py", line 69, in parse_json
self._cache["json"] = json_data = core.parse_json(data)
File ".../.tox/py36/lib/python3.6/site-packages/webargs/core.py", line 115, in parse_json
s = s.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte
127.0.0.1 - - [23/Sep/2019 09:07:54] "POST / HTTP/1.1" 500 -
```
|
0.0
|
f2db6bcb2b2f963b819d409da4788411fea3170d
|
[
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_nonutf8_chars"
] |
[
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_args",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_with_query_location_specified",
"tests/test_falconparser.py::TestFalconParser::test_parse_form",
"tests/test_falconparser.py::TestFalconParser::test_parse_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_default",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_default",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_charset",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_vendor_media_type",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_ignores_extra_data",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_blank",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_ignore_unexpected_int",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_ignore_unexpected_list",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema_invalid_input",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema_ignore_malformed_data",
"tests/test_falconparser.py::TestFalconParser::test_parsing_form_default",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_multiple",
"tests/test_falconparser.py::TestFalconParser::test_parse_form_multiple",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_list",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_nonascii_chars",
"tests/test_falconparser.py::TestFalconParser::test_validation_error_returns_422_response",
"tests/test_falconparser.py::TestFalconParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_falconparser.py::TestFalconParser::test_use_args_decorator",
"tests/test_falconparser.py::TestFalconParser::test_use_args_with_path_param",
"tests/test_falconparser.py::TestFalconParser::test_use_args_with_validation",
"tests/test_falconparser.py::TestFalconParser::test_use_kwargs_decorator",
"tests/test_falconparser.py::TestFalconParser::test_use_kwargs_with_path_param",
"tests/test_falconparser.py::TestFalconParser::test_parsing_headers",
"tests/test_falconparser.py::TestFalconParser::test_parsing_cookies",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_many_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_many_missing",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_if_no_json",
"tests/test_falconparser.py::TestFalconParser::test_empty_json",
"tests/test_falconparser.py::TestFalconParser::test_use_args_hook",
"tests/test_falconparser.py::TestFalconParser::test_invalid_json"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-09-23 14:16:33+00:00
|
mit
| 3,759 |
|
marshmallow-code__webargs-462
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index ceb534d..71e4ce4 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,14 @@
Changelog
---------
+6.0.0b6 (Unreleased)
+********************
+
+Refactoring:
+
+* Remove the cache attached to webargs parsers. Due to changes between webargs
+ v5 and v6, the cache is no longer considered useful.
+
6.0.0b5 (2020-01-30)
********************
diff --git a/src/webargs/aiohttpparser.py b/src/webargs/aiohttpparser.py
index 47ac1bc..c41cbe4 100644
--- a/src/webargs/aiohttpparser.py
+++ b/src/webargs/aiohttpparser.py
@@ -84,10 +84,8 @@ class AIOHTTPParser(AsyncParser):
async def load_form(self, req: Request, schema: Schema) -> MultiDictProxy:
"""Return form values from the request as a MultiDictProxy."""
- post_data = self._cache.get("post")
- if post_data is None:
- self._cache["post"] = await req.post()
- return MultiDictProxy(self._cache["post"], schema)
+ post_data = await req.post()
+ return MultiDictProxy(post_data, schema)
async def load_json_or_form(
self, req: Request, schema: Schema
@@ -99,22 +97,17 @@ class AIOHTTPParser(AsyncParser):
async def load_json(self, req: Request, schema: Schema) -> typing.Dict:
"""Return a parsed json payload from the request."""
- json_data = self._cache.get("json")
- if json_data is None:
- if not (req.body_exists and is_json_request(req)):
+ if not (req.body_exists and is_json_request(req)):
+ return core.missing
+ try:
+ return await req.json(loads=json.loads)
+ except json.JSONDecodeError as e:
+ if e.doc == "":
return core.missing
- try:
- json_data = await req.json(loads=json.loads)
- except json.JSONDecodeError as e:
- if e.doc == "":
- return core.missing
- else:
- return self._handle_invalid_json_error(e, req)
- except UnicodeDecodeError as e:
+ else:
return self._handle_invalid_json_error(e, req)
-
- self._cache["json"] = json_data
- return json_data
+ except UnicodeDecodeError as e:
+ return self._handle_invalid_json_error(e, req)
def load_headers(self, req: Request, schema: Schema) -> MultiDictProxy:
"""Return headers from the request as a MultiDictProxy."""
diff --git a/src/webargs/asyncparser.py b/src/webargs/asyncparser.py
index f67dc57..0eb6037 100644
--- a/src/webargs/asyncparser.py
+++ b/src/webargs/asyncparser.py
@@ -35,7 +35,6 @@ class AsyncParser(core.Parser):
Receives the same arguments as `webargs.core.Parser.parse`.
"""
- self.clear_cache() # in case someone used `location_load_*()`
req = req if req is not None else self.get_default_request()
if req is None:
raise ValueError("Must pass req object")
diff --git a/src/webargs/core.py b/src/webargs/core.py
index fbe1983..b5fe2f9 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -2,7 +2,6 @@ import functools
import inspect
import logging
import warnings
-from copy import copy
from collections.abc import Mapping
import json
@@ -130,8 +129,6 @@ class Parser:
self.location = location or self.DEFAULT_LOCATION
self.error_callback = _callable_or_raise(error_handler)
self.schema_class = schema_class or self.DEFAULT_SCHEMA_CLASS
- #: A short-lived cache to store results from processing request bodies.
- self._cache = {}
def _get_loader(self, location):
"""Get the loader function for the given location.
@@ -207,15 +204,6 @@ class Parser:
)
return schema
- def _clone(self):
- """Clone the current parser in order to ensure that it has a fresh and
- independent cache. This is used whenever `Parser.parse` is called, so
- that these methods always have separate caches.
- """
- clone = copy(self)
- clone.clear_cache()
- return clone
-
def parse(
self,
argmap,
@@ -250,32 +238,20 @@ class Parser:
raise ValueError("Must pass req object")
data = None
validators = _ensure_list_of_callables(validate)
- parser = self._clone()
schema = self._get_schema(argmap, req)
try:
- location_data = parser._load_location_data(
+ location_data = self._load_location_data(
schema=schema, req=req, location=location or self.location
)
result = schema.load(location_data)
data = result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else result
- parser._validate_arguments(data, validators)
+ self._validate_arguments(data, validators)
except ma.exceptions.ValidationError as error:
- parser._on_validation_error(
+ self._on_validation_error(
error, req, schema, error_status_code, error_headers
)
return data
- def clear_cache(self):
- """Invalidate the parser's cache.
-
- This is usually a no-op now since the Parser clone used for parsing a
- request is discarded afterwards. It can still be used when manually
- calling ``parse_*`` methods which would populate the cache on the main
- Parser instance.
- """
- self._cache = {}
- return None
-
def get_default_request(self):
"""Optional override. Provides a hook for frameworks that use thread-local
request objects.
@@ -458,19 +434,14 @@ class Parser:
# `_handle_invalid_json_error` and `_raw_load_json`
# these methods are not part of the public API and are used to simplify
# code sharing amongst the built-in webargs parsers
- if "json" not in self._cache:
- try:
- json_data = self._raw_load_json(req)
- except json.JSONDecodeError as e:
- if e.doc == "":
- json_data = missing
- else:
- return self._handle_invalid_json_error(e, req)
- except UnicodeDecodeError as e:
- return self._handle_invalid_json_error(e, req)
- self._cache["json"] = json_data
-
- return self._cache["json"]
+ try:
+ return self._raw_load_json(req)
+ except json.JSONDecodeError as e:
+ if e.doc == "":
+ return missing
+ return self._handle_invalid_json_error(e, req)
+ except UnicodeDecodeError as e:
+ return self._handle_invalid_json_error(e, req)
def load_json_or_form(self, req, schema):
"""Load data from a request, accepting either JSON or form-encoded
diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py
index b64a4a3..6b68afb 100644
--- a/src/webargs/falconparser.py
+++ b/src/webargs/falconparser.py
@@ -91,9 +91,7 @@ class FalconParser(core.Parser):
The request stream will be read and left at EOF.
"""
- form = self._cache.get("form")
- if form is None:
- self._cache["form"] = form = parse_form_body(req)
+ form = parse_form_body(req)
if form is core.missing:
return form
return MultiDictProxy(form, schema)
|
marshmallow-code/webargs
|
1b34470908cb54862b7aeb578f794ac3285cdf38
|
diff --git a/tests/test_flaskparser.py b/tests/test_flaskparser.py
index c00ae11..f5f70e8 100644
--- a/tests/test_flaskparser.py
+++ b/tests/test_flaskparser.py
@@ -1,5 +1,3 @@
-import threading
-
from werkzeug.exceptions import HTTPException
import pytest
@@ -126,37 +124,3 @@ def test_abort_has_serializable_data():
error = json.loads(serialized_error)
assert isinstance(error, dict)
assert error["message"] == "custom error message"
-
-
-def test_json_cache_race_condition():
- app = Flask("testapp")
- lock = threading.Lock()
- lock.acquire()
-
- class MyField(fields.Field):
- def _deserialize(self, value, attr, data, **kwargs):
- with lock:
- return value
-
- argmap = {"value": MyField()}
- results = {}
-
- def thread_fn(value):
- with app.test_request_context(
- "/foo",
- method="post",
- data=json.dumps({"value": value}),
- content_type="application/json",
- ):
- results[value] = parser.parse(argmap)["value"]
-
- t1 = threading.Thread(target=thread_fn, args=(42,))
- t2 = threading.Thread(target=thread_fn, args=(23,))
- t1.start()
- t2.start()
- lock.release()
- t1.join()
- t2.join()
- # ensure we didn't get contaminated by a parallel request
- assert results[42] == 42
- assert results[23] == 23
diff --git a/tests/test_tornadoparser.py b/tests/test_tornadoparser.py
index 542365e..50e281b 100644
--- a/tests/test_tornadoparser.py
+++ b/tests/test_tornadoparser.py
@@ -51,9 +51,6 @@ def test_tornado_multidictproxy():
class TestQueryArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Aeschylus")]
request = make_get_request(query)
@@ -75,9 +72,6 @@ class TestQueryArgs:
class TestFormArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Aristophanes")]
request = make_form_request(query)
@@ -99,9 +93,6 @@ class TestFormArgs:
class TestJSONArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = {"name": "Euripides"}
request = make_json_request(query)
@@ -162,14 +153,10 @@ class TestJSONArgs:
def test_it_should_handle_value_error_on_parse_json(self):
request = make_request("this is json not")
result = parser.load_json(request, author_schema)
- assert parser._cache.get("json") == missing
assert result is missing
class TestHeadersArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = {"name": "Euphorion"}
request = make_request(headers=query)
@@ -190,9 +177,6 @@ class TestHeadersArgs:
class TestFilesArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Sappho")]
request = make_files_request(query)
@@ -221,9 +205,6 @@ class TestErrorHandler:
class TestParse:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_parse_query_arguments(self):
attrs = {"string": fields.Field(), "integer": fields.List(fields.Int())}
@@ -322,9 +303,6 @@ class TestParse:
class TestUseArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_pass_parsed_as_first_argument(self):
class Handler:
request = make_json_request({"key": "value"})
|
Re-factor cache invalidation
https://github.com/marshmallow-code/webargs/issues/371#issuecomment-471578852
|
0.0
|
1b34470908cb54862b7aeb578f794ac3285cdf38
|
[
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_multiple_nested_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_not_include_fieldnames_if_not_present",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_handle_type_error_on_load_json",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_handle_value_error_on_parse_json"
] |
[
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_or_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_charset",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_vendor_media_type",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_ignore_extra_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_empty",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_int",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_invalid_input",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_form_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple_single_value",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonascii_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonutf8_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_validation_error_returns_422_response",
"tests/test_flaskparser.py::TestFlaskParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_validation",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_cookies",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_files",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json_with_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_invalid_json",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_json-{\"name\":",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_form-payload1-application/json]",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_view_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_invalid_view_arg",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_view_args_parsing",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_missing_data",
"tests/test_flaskparser.py::TestFlaskParser::test_nested_many_with_data_key",
"tests/test_flaskparser.py::test_abort_called_on_validation_error",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[None]",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[application/json]",
"tests/test_flaskparser.py::test_abort_with_message",
"tests/test_flaskparser.py::test_abort_has_serializable_data",
"tests/test_tornadoparser.py::test_tornado_multidictproxy",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_parsing_request_with_vendor_content_type",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestErrorHandler::test_it_should_raise_httperror_on_failed_validation",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_query_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_form_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_json_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_raise_when_json_is_invalid",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_header_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_cookies_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_files_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_required_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_multiple_arg_required",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_pass_parsed_as_first_argument",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_pass_parsed_as_kwargs_arguments",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_be_validate_arguments_when_validator_is_passed",
"tests/test_tornadoparser.py::TestApp::test_get_path_param",
"tests/test_tornadoparser.py::TestApp::test_get_with_no_json_body",
"tests/test_tornadoparser.py::TestApp::test_post",
"tests/test_tornadoparser.py::TestValidateApp::test_missing_required_field_throws_422",
"tests/test_tornadoparser.py::TestValidateApp::test_required_field_provided",
"tests/test_tornadoparser.py::TestValidateApp::test_use_kwargs_with_error",
"tests/test_tornadoparser.py::TestValidateApp::test_user_validator_returns_422_by_default"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-24 22:48:59+00:00
|
mit
| 3,760 |
|
marshmallow-code__webargs-463
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index c11fe33..6991c91 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,16 @@
Changelog
---------
+6.0.0b7 (Unreleased)
+********************
+
+Features:
+
+* *Backwards-incompatible*: webargs will rewrite the error messages in
+ ValidationErrors to be namespaced under the location which raised the error.
+ The `messages` field on errors will therefore be one layer deeper with a
+ single top-level key.
+
6.0.0b6 (2020-01-31)
********************
diff --git a/src/webargs/asyncparser.py b/src/webargs/asyncparser.py
index 0eb6037..ec9773b 100644
--- a/src/webargs/asyncparser.py
+++ b/src/webargs/asyncparser.py
@@ -36,6 +36,7 @@ class AsyncParser(core.Parser):
Receives the same arguments as `webargs.core.Parser.parse`.
"""
req = req if req is not None else self.get_default_request()
+ location = location or self.location
if req is None:
raise ValueError("Must pass req object")
data = None
@@ -43,14 +44,14 @@ class AsyncParser(core.Parser):
schema = self._get_schema(argmap, req)
try:
location_data = await self._load_location_data(
- schema=schema, req=req, location=location or self.location
+ schema=schema, req=req, location=location
)
result = schema.load(location_data)
data = result.data if core.MARSHMALLOW_VERSION_INFO[0] < 3 else result
self._validate_arguments(data, validators)
except ma.exceptions.ValidationError as error:
await self._on_validation_error(
- error, req, schema, error_status_code, error_headers
+ error, req, schema, location, error_status_code, error_headers
)
return data
@@ -78,9 +79,16 @@ class AsyncParser(core.Parser):
error: ValidationError,
req: Request,
schema: Schema,
+ location: str,
error_status_code: typing.Union[int, None],
error_headers: typing.Union[typing.Mapping[str, str], None] = None,
) -> None:
+ # rewrite messages to be namespaced under the location which created
+ # them
+ # e.g. {"json":{"foo":["Not a valid integer."]}}
+ # instead of
+ # {"foo":["Not a valid integer."]}
+ error.messages = {location: error.messages}
error_handler = self.error_callback or self.handle_error
await error_handler(error, req, schema, error_status_code, error_headers)
diff --git a/src/webargs/core.py b/src/webargs/core.py
index b5fe2f9..8160b7c 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -168,8 +168,14 @@ class Parser:
return data
def _on_validation_error(
- self, error, req, schema, error_status_code, error_headers
+ self, error, req, schema, location, error_status_code, error_headers
):
+ # rewrite messages to be namespaced under the location which created
+ # them
+ # e.g. {"json":{"foo":["Not a valid integer."]}}
+ # instead of
+ # {"foo":["Not a valid integer."]}
+ error.messages = {location: error.messages}
error_handler = self.error_callback or self.handle_error
error_handler(error, req, schema, error_status_code, error_headers)
@@ -234,6 +240,7 @@ class Parser:
:return: A dictionary of parsed arguments
"""
req = req if req is not None else self.get_default_request()
+ location = location or self.location
if req is None:
raise ValueError("Must pass req object")
data = None
@@ -241,14 +248,14 @@ class Parser:
schema = self._get_schema(argmap, req)
try:
location_data = self._load_location_data(
- schema=schema, req=req, location=location or self.location
+ schema=schema, req=req, location=location
)
result = schema.load(location_data)
data = result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else result
self._validate_arguments(data, validators)
except ma.exceptions.ValidationError as error:
self._on_validation_error(
- error, req, schema, error_status_code, error_headers
+ error, req, schema, location, error_status_code, error_headers
)
return data
|
marshmallow-code/webargs
|
20b55591888b3cfaae061d858a6f21cb17edee44
|
diff --git a/tests/apps/flask_app.py b/tests/apps/flask_app.py
index 17030f0..cfa6d12 100644
--- a/tests/apps/flask_app.py
+++ b/tests/apps/flask_app.py
@@ -212,4 +212,16 @@ def echo_use_kwargs_missing(username, **kwargs):
def handle_error(err):
if err.code == 422:
assert isinstance(err.data["schema"], ma.Schema)
- return J(err.data["messages"]), err.code
+
+ if MARSHMALLOW_VERSION_INFO[0] >= 3:
+ return J(err.data["messages"]), err.code
+
+ # on marshmallow2, validation errors for nested schemas can fail to encode:
+ # https://github.com/marshmallow-code/marshmallow/issues/493
+ # to workaround this, convert integer keys to strings
+ def tweak_data(value):
+ if not isinstance(value, dict):
+ return value
+ return {str(k): v for k, v in value.items()}
+
+ return J({k: tweak_data(v) for k, v in err.data["messages"].items()}), err.code
diff --git a/tests/test_core.py b/tests/test_core.py
index feef0c1..43df976 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -165,7 +165,9 @@ def test_parse_required_list(parser, web_request):
args = {"foo": fields.List(fields.Field(), required=True)}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request)
- assert excinfo.value.messages["foo"][0] == "Missing data for required field."
+ assert (
+ excinfo.value.messages["json"]["foo"][0] == "Missing data for required field."
+ )
# Regression test for https://github.com/marshmallow-code/webargs/issues/107
@@ -180,7 +182,7 @@ def test_parse_list_dont_allow_none(parser, web_request):
args = {"foo": fields.List(fields.Field(), allow_none=False)}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request)
- assert excinfo.value.messages["foo"][0] == "Field may not be null."
+ assert excinfo.value.messages["json"]["foo"][0] == "Field may not be null."
def test_parse_empty_list(parser, web_request):
@@ -369,7 +371,7 @@ def test_required_with_custom_error(parser, web_request):
# Test that `validate` receives dictionary of args
parser.parse(args, web_request)
- assert "We need foo" in excinfo.value.messages["foo"]
+ assert "We need foo" in excinfo.value.messages["json"]["foo"]
if MARSHMALLOW_VERSION_INFO[0] < 3:
assert "foo" in excinfo.value.field_names
@@ -402,7 +404,7 @@ def test_full_input_validator_receives_nonascii_input(web_request):
args = {"text": fields.Str()}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request, validate=validate)
- assert excinfo.value.messages == ["Invalid value."]
+ assert excinfo.value.messages == {"json": ["Invalid value."]}
def test_invalid_argument_for_validate(web_request, parser):
@@ -482,8 +484,9 @@ def test_parse_with_data_key_retains_field_name_in_error(web_request):
args = {"content_type": fields.Str(**data_key_kwargs)}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request)
- assert "Content-Type" in excinfo.value.messages
- assert excinfo.value.messages["Content-Type"] == ["Not a valid string."]
+ assert "json" in excinfo.value.messages
+ assert "Content-Type" in excinfo.value.messages["json"]
+ assert excinfo.value.messages["json"]["Content-Type"] == ["Not a valid string."]
def test_parse_nested_with_data_key(web_request):
@@ -607,7 +610,9 @@ def test_multiple_arg_required_with_int_conversion(web_request, parser):
web_request.json = {}
with pytest.raises(ValidationError) as excinfo:
parser.parse(args, web_request)
- assert excinfo.value.messages == {"ids": ["Missing data for required field."]}
+ assert excinfo.value.messages == {
+ "json": {"ids": ["Missing data for required field."]}
+ }
def test_parse_with_callable(web_request, parser):
@@ -888,7 +893,7 @@ def test_delimited_list_passed_invalid_type(web_request, parser):
with pytest.raises(ValidationError) as excinfo:
parser.parse(schema, web_request)
- assert excinfo.value.messages == {"ids": ["Not a valid delimited list."]}
+ assert excinfo.value.messages == {"json": {"ids": ["Not a valid delimited list."]}}
def test_missing_list_argument_not_in_parsed_result(web_request, parser):
diff --git a/tests/test_flaskparser.py b/tests/test_flaskparser.py
index f5f70e8..f8ccf36 100644
--- a/tests/test_flaskparser.py
+++ b/tests/test_flaskparser.py
@@ -28,7 +28,7 @@ class TestFlaskParser(CommonTestCase):
def test_parsing_invalid_view_arg(self, testapp):
res = testapp.get("/echo_view_arg/foo", expect_errors=True)
assert res.status_code == 422
- assert res.json == {"view_arg": ["Not a valid integer."]}
+ assert res.json == {"view_args": {"view_arg": ["Not a valid integer."]}}
def test_use_args_with_view_args_parsing(self, testapp):
res = testapp.get("/echo_view_arg_use_args/42")
@@ -87,7 +87,7 @@ def test_abort_called_on_validation_error(mock_abort):
abort_args, abort_kwargs = mock_abort.call_args
assert abort_args[0] == 422
expected_msg = "Invalid value."
- assert abort_kwargs["messages"]["value"] == [expected_msg]
+ assert abort_kwargs["messages"]["json"]["value"] == [expected_msg]
assert type(abort_kwargs["exc"]) == ValidationError
|
[RFC] Namespace error structures by location in response
I think there's a case we never really considered: two schemas in a different location with a common field name.
In webargs 5, this is not possible in a single `use_args` call. In a multi `use_args` call, it depends if the user specifies the locations. The response is ambiguous about which field is wrong.
In current implementation in webargs 6, the response is ambiguous. A way to fix this would be to namespace the error structures by location.
Just thinking out loud, writing this here before I forget.
|
0.0
|
20b55591888b3cfaae061d858a6f21cb17edee44
|
[
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_invalid_view_arg",
"tests/test_flaskparser.py::test_abort_called_on_validation_error"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_list_as_string_v2",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_dict2schema",
"tests/test_core.py::test_dict2schema_doesnt_add_to_class_registry",
"tests/test_core.py::test_dict2schema_with_nesting",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_or_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_charset",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_vendor_media_type",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_ignore_extra_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_empty",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_int",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_invalid_input",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_form_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple_single_value",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonascii_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonutf8_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_validation_error_returns_422_response",
"tests/test_flaskparser.py::TestFlaskParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_validation",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_cookies",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_files",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json_with_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_invalid_json",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_json-{\"name\":",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_form-payload1-application/json]",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_view_args",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_view_args_parsing",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_missing_data",
"tests/test_flaskparser.py::TestFlaskParser::test_nested_many_with_data_key",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[None]",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[application/json]",
"tests/test_flaskparser.py::test_abort_with_message",
"tests/test_flaskparser.py::test_abort_has_serializable_data"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-25 00:04:45+00:00
|
mit
| 3,761 |
|
marshmallow-code__webargs-464
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 8c56899..a88f6bc 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,16 @@
Changelog
---------
+6.0.0b5 (Unreleased)
+********************
+
+Refactoring:
+
+* *Backwards-incompatible*: `DelimitedList` now requires that its input be a
+ string and always serializes as a string. It can still serialize and deserialize
+ using another field, e.g. `DelimitedList(Int())` is still valid and requires
+ that the values in the list parse as ints.
+
6.0.0b4 (2020-01-28)
********************
diff --git a/src/webargs/fields.py b/src/webargs/fields.py
index 0d8d46b..fcdf05f 100644
--- a/src/webargs/fields.py
+++ b/src/webargs/fields.py
@@ -44,37 +44,35 @@ class Nested(ma.fields.Nested):
class DelimitedList(ma.fields.List):
- """Same as `marshmallow.fields.List`, except can load from either a list or
- a delimited string (e.g. "foo,bar,baz").
+ """A field which is similar to a List, but takes its input as a delimited
+ string (e.g. "foo,bar,baz").
+
+ Like List, it can be given a nested field type which it will use to
+ de/serialize each element of the list.
:param Field cls_or_instance: A field class or instance.
:param str delimiter: Delimiter between values.
- :param bool as_string: Dump values to string.
"""
+ default_error_messages = {"invalid": "Not a valid delimited list."}
delimiter = ","
- def __init__(self, cls_or_instance, delimiter=None, as_string=False, **kwargs):
+ def __init__(self, cls_or_instance, delimiter=None, **kwargs):
self.delimiter = delimiter or self.delimiter
- self.as_string = as_string
super().__init__(cls_or_instance, **kwargs)
def _serialize(self, value, attr, obj):
- ret = super()._serialize(value, attr, obj)
- if self.as_string:
- return self.delimiter.join(format(each) for each in ret)
- return ret
+ # serializing will start with List serialization, so that we correctly
+ # output lists of non-primitive types, e.g. DelimitedList(DateTime)
+ return self.delimiter.join(
+ format(each) for each in super()._serialize(value, attr, obj)
+ )
def _deserialize(self, value, attr, data, **kwargs):
- try:
- ret = (
- value
- if ma.utils.is_iterable_but_not_string(value)
- else value.split(self.delimiter)
- )
- except AttributeError:
+ # attempting to deserialize from a non-string source is an error
+ if not isinstance(value, (str, bytes)):
if MARSHMALLOW_VERSION_INFO[0] < 3:
self.fail("invalid")
else:
raise self.make_error("invalid")
- return super()._deserialize(ret, attr, data, **kwargs)
+ return super()._deserialize(value.split(self.delimiter), attr, data, **kwargs)
|
marshmallow-code/webargs
|
01ef08a35a1ec9249725e54dc215efc682debfcf
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 4ff341b..feef0c1 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -835,21 +835,6 @@ def test_delimited_list_default_delimiter(web_request, parser):
parsed = parser.parse(schema, web_request)
assert parsed["ids"] == [1, 2, 3]
- dumped = schema.dump(parsed)
- data = dumped.data if MARSHMALLOW_VERSION_INFO[0] < 3 else dumped
- assert data["ids"] == [1, 2, 3]
-
-
-def test_delimited_list_as_string(web_request, parser):
- web_request.json = {"ids": "1,2,3"}
- schema_cls = dict2schema(
- {"ids": fields.DelimitedList(fields.Int(), as_string=True)}
- )
- schema = schema_cls()
-
- parsed = parser.parse(schema, web_request)
- assert parsed["ids"] == [1, 2, 3]
-
dumped = schema.dump(parsed)
data = dumped.data if MARSHMALLOW_VERSION_INFO[0] < 3 else dumped
assert data["ids"] == "1,2,3"
@@ -858,11 +843,7 @@ def test_delimited_list_as_string(web_request, parser):
def test_delimited_list_as_string_v2(web_request, parser):
web_request.json = {"dates": "2018-11-01,2018-11-02"}
schema_cls = dict2schema(
- {
- "dates": fields.DelimitedList(
- fields.DateTime(format="%Y-%m-%d"), as_string=True
- )
- }
+ {"dates": fields.DelimitedList(fields.DateTime(format="%Y-%m-%d"))}
)
schema = schema_cls()
@@ -886,13 +867,17 @@ def test_delimited_list_custom_delimiter(web_request, parser):
assert parsed["ids"] == [1, 2, 3]
-def test_delimited_list_load_list(web_request, parser):
+def test_delimited_list_load_list_errors(web_request, parser):
web_request.json = {"ids": [1, 2, 3]}
schema_cls = dict2schema({"ids": fields.DelimitedList(fields.Int())})
schema = schema_cls()
- parsed = parser.parse(schema, web_request)
- assert parsed["ids"] == [1, 2, 3]
+ with pytest.raises(ValidationError) as excinfo:
+ parser.parse(schema, web_request)
+ exc = excinfo.value
+ assert isinstance(exc, ValidationError)
+ errors = exc.args[0]
+ assert errors["ids"] == ["Not a valid delimited list."]
# Regresion test for https://github.com/marshmallow-code/webargs/issues/149
@@ -903,7 +888,7 @@ def test_delimited_list_passed_invalid_type(web_request, parser):
with pytest.raises(ValidationError) as excinfo:
parser.parse(schema, web_request)
- assert excinfo.value.messages == {"ids": ["Not a valid list."]}
+ assert excinfo.value.messages == {"ids": ["Not a valid delimited list."]}
def test_missing_list_argument_not_in_parsed_result(web_request, parser):
|
RFC: Only accept delimited string in DelimitedList
`DelimitedList` accepts either a list or a delimited string (e.g. "foo,bar,baz").
I'd like to make it more strict by only accepting a delimited list. Rather than adding a `strict` parameter, I'm thinking of dropping the whole "also accept a list" feature.
Any reason to support both?
I understand it inherits from `List` because once the string is parsed, it can be deserialized as a normal list. But are there cases where you'd expect either a list or a delimited string?
|
0.0
|
01ef08a35a1ec9249725e54dc215efc682debfcf
|
[
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_list_as_string_v2",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_dict2schema",
"tests/test_core.py::test_dict2schema_doesnt_add_to_class_registry",
"tests/test_core.py::test_dict2schema_with_nesting",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-25 02:26:25+00:00
|
mit
| 3,762 |
|
marshmallow-code__webargs-471
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index ceb534d..71e4ce4 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,14 @@
Changelog
---------
+6.0.0b6 (Unreleased)
+********************
+
+Refactoring:
+
+* Remove the cache attached to webargs parsers. Due to changes between webargs
+ v5 and v6, the cache is no longer considered useful.
+
6.0.0b5 (2020-01-30)
********************
diff --git a/src/webargs/aiohttpparser.py b/src/webargs/aiohttpparser.py
index 47ac1bc..c41cbe4 100644
--- a/src/webargs/aiohttpparser.py
+++ b/src/webargs/aiohttpparser.py
@@ -84,10 +84,8 @@ class AIOHTTPParser(AsyncParser):
async def load_form(self, req: Request, schema: Schema) -> MultiDictProxy:
"""Return form values from the request as a MultiDictProxy."""
- post_data = self._cache.get("post")
- if post_data is None:
- self._cache["post"] = await req.post()
- return MultiDictProxy(self._cache["post"], schema)
+ post_data = await req.post()
+ return MultiDictProxy(post_data, schema)
async def load_json_or_form(
self, req: Request, schema: Schema
@@ -99,22 +97,17 @@ class AIOHTTPParser(AsyncParser):
async def load_json(self, req: Request, schema: Schema) -> typing.Dict:
"""Return a parsed json payload from the request."""
- json_data = self._cache.get("json")
- if json_data is None:
- if not (req.body_exists and is_json_request(req)):
+ if not (req.body_exists and is_json_request(req)):
+ return core.missing
+ try:
+ return await req.json(loads=json.loads)
+ except json.JSONDecodeError as e:
+ if e.doc == "":
return core.missing
- try:
- json_data = await req.json(loads=json.loads)
- except json.JSONDecodeError as e:
- if e.doc == "":
- return core.missing
- else:
- return self._handle_invalid_json_error(e, req)
- except UnicodeDecodeError as e:
+ else:
return self._handle_invalid_json_error(e, req)
-
- self._cache["json"] = json_data
- return json_data
+ except UnicodeDecodeError as e:
+ return self._handle_invalid_json_error(e, req)
def load_headers(self, req: Request, schema: Schema) -> MultiDictProxy:
"""Return headers from the request as a MultiDictProxy."""
diff --git a/src/webargs/asyncparser.py b/src/webargs/asyncparser.py
index f67dc57..0eb6037 100644
--- a/src/webargs/asyncparser.py
+++ b/src/webargs/asyncparser.py
@@ -35,7 +35,6 @@ class AsyncParser(core.Parser):
Receives the same arguments as `webargs.core.Parser.parse`.
"""
- self.clear_cache() # in case someone used `location_load_*()`
req = req if req is not None else self.get_default_request()
if req is None:
raise ValueError("Must pass req object")
diff --git a/src/webargs/core.py b/src/webargs/core.py
index fbe1983..b5fe2f9 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -2,7 +2,6 @@ import functools
import inspect
import logging
import warnings
-from copy import copy
from collections.abc import Mapping
import json
@@ -130,8 +129,6 @@ class Parser:
self.location = location or self.DEFAULT_LOCATION
self.error_callback = _callable_or_raise(error_handler)
self.schema_class = schema_class or self.DEFAULT_SCHEMA_CLASS
- #: A short-lived cache to store results from processing request bodies.
- self._cache = {}
def _get_loader(self, location):
"""Get the loader function for the given location.
@@ -207,15 +204,6 @@ class Parser:
)
return schema
- def _clone(self):
- """Clone the current parser in order to ensure that it has a fresh and
- independent cache. This is used whenever `Parser.parse` is called, so
- that these methods always have separate caches.
- """
- clone = copy(self)
- clone.clear_cache()
- return clone
-
def parse(
self,
argmap,
@@ -250,32 +238,20 @@ class Parser:
raise ValueError("Must pass req object")
data = None
validators = _ensure_list_of_callables(validate)
- parser = self._clone()
schema = self._get_schema(argmap, req)
try:
- location_data = parser._load_location_data(
+ location_data = self._load_location_data(
schema=schema, req=req, location=location or self.location
)
result = schema.load(location_data)
data = result.data if MARSHMALLOW_VERSION_INFO[0] < 3 else result
- parser._validate_arguments(data, validators)
+ self._validate_arguments(data, validators)
except ma.exceptions.ValidationError as error:
- parser._on_validation_error(
+ self._on_validation_error(
error, req, schema, error_status_code, error_headers
)
return data
- def clear_cache(self):
- """Invalidate the parser's cache.
-
- This is usually a no-op now since the Parser clone used for parsing a
- request is discarded afterwards. It can still be used when manually
- calling ``parse_*`` methods which would populate the cache on the main
- Parser instance.
- """
- self._cache = {}
- return None
-
def get_default_request(self):
"""Optional override. Provides a hook for frameworks that use thread-local
request objects.
@@ -458,19 +434,14 @@ class Parser:
# `_handle_invalid_json_error` and `_raw_load_json`
# these methods are not part of the public API and are used to simplify
# code sharing amongst the built-in webargs parsers
- if "json" not in self._cache:
- try:
- json_data = self._raw_load_json(req)
- except json.JSONDecodeError as e:
- if e.doc == "":
- json_data = missing
- else:
- return self._handle_invalid_json_error(e, req)
- except UnicodeDecodeError as e:
- return self._handle_invalid_json_error(e, req)
- self._cache["json"] = json_data
-
- return self._cache["json"]
+ try:
+ return self._raw_load_json(req)
+ except json.JSONDecodeError as e:
+ if e.doc == "":
+ return missing
+ return self._handle_invalid_json_error(e, req)
+ except UnicodeDecodeError as e:
+ return self._handle_invalid_json_error(e, req)
def load_json_or_form(self, req, schema):
"""Load data from a request, accepting either JSON or form-encoded
diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py
index b64a4a3..6b68afb 100644
--- a/src/webargs/falconparser.py
+++ b/src/webargs/falconparser.py
@@ -91,9 +91,7 @@ class FalconParser(core.Parser):
The request stream will be read and left at EOF.
"""
- form = self._cache.get("form")
- if form is None:
- self._cache["form"] = form = parse_form_body(req)
+ form = parse_form_body(req)
if form is core.missing:
return form
return MultiDictProxy(form, schema)
diff --git a/src/webargs/pyramidparser.py b/src/webargs/pyramidparser.py
index 55fa6e0..ba8ede8 100644
--- a/src/webargs/pyramidparser.py
+++ b/src/webargs/pyramidparser.py
@@ -138,7 +138,7 @@ class PyramidParser(core.Parser):
location = location or self.location
# Optimization: If argmap is passed as a dictionary, we only need
# to generate a Schema once
- if isinstance(argmap, collections.Mapping):
+ if isinstance(argmap, collections.abc.Mapping):
argmap = core.dict2schema(argmap, self.schema_class)()
def decorator(func):
|
marshmallow-code/webargs
|
1b34470908cb54862b7aeb578f794ac3285cdf38
|
diff --git a/tests/test_flaskparser.py b/tests/test_flaskparser.py
index c00ae11..f5f70e8 100644
--- a/tests/test_flaskparser.py
+++ b/tests/test_flaskparser.py
@@ -1,5 +1,3 @@
-import threading
-
from werkzeug.exceptions import HTTPException
import pytest
@@ -126,37 +124,3 @@ def test_abort_has_serializable_data():
error = json.loads(serialized_error)
assert isinstance(error, dict)
assert error["message"] == "custom error message"
-
-
-def test_json_cache_race_condition():
- app = Flask("testapp")
- lock = threading.Lock()
- lock.acquire()
-
- class MyField(fields.Field):
- def _deserialize(self, value, attr, data, **kwargs):
- with lock:
- return value
-
- argmap = {"value": MyField()}
- results = {}
-
- def thread_fn(value):
- with app.test_request_context(
- "/foo",
- method="post",
- data=json.dumps({"value": value}),
- content_type="application/json",
- ):
- results[value] = parser.parse(argmap)["value"]
-
- t1 = threading.Thread(target=thread_fn, args=(42,))
- t2 = threading.Thread(target=thread_fn, args=(23,))
- t1.start()
- t2.start()
- lock.release()
- t1.join()
- t2.join()
- # ensure we didn't get contaminated by a parallel request
- assert results[42] == 42
- assert results[23] == 23
diff --git a/tests/test_tornadoparser.py b/tests/test_tornadoparser.py
index 542365e..50e281b 100644
--- a/tests/test_tornadoparser.py
+++ b/tests/test_tornadoparser.py
@@ -51,9 +51,6 @@ def test_tornado_multidictproxy():
class TestQueryArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Aeschylus")]
request = make_get_request(query)
@@ -75,9 +72,6 @@ class TestQueryArgs:
class TestFormArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Aristophanes")]
request = make_form_request(query)
@@ -99,9 +93,6 @@ class TestFormArgs:
class TestJSONArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = {"name": "Euripides"}
request = make_json_request(query)
@@ -162,14 +153,10 @@ class TestJSONArgs:
def test_it_should_handle_value_error_on_parse_json(self):
request = make_request("this is json not")
result = parser.load_json(request, author_schema)
- assert parser._cache.get("json") == missing
assert result is missing
class TestHeadersArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = {"name": "Euphorion"}
request = make_request(headers=query)
@@ -190,9 +177,6 @@ class TestHeadersArgs:
class TestFilesArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_get_single_values(self):
query = [("name", "Sappho")]
request = make_files_request(query)
@@ -221,9 +205,6 @@ class TestErrorHandler:
class TestParse:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_parse_query_arguments(self):
attrs = {"string": fields.Field(), "integer": fields.List(fields.Int())}
@@ -322,9 +303,6 @@ class TestParse:
class TestUseArgs:
- def setup_method(self, method):
- parser.clear_cache()
-
def test_it_should_pass_parsed_as_first_argument(self):
class Handler:
request = make_json_request({"key": "value"})
|
Importing ABC directly from collections module was removed in Python 3.9
Since the project is Python 3 only importing from collections.abc will resolve the issue. I will raise a PR.
https://github.com/marshmallow-code/webargs/blob/1b34470908cb54862b7aeb578f794ac3285cdf38/src/webargs/pyramidparser.py#L141
|
0.0
|
1b34470908cb54862b7aeb578f794ac3285cdf38
|
[
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_multiple_nested_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_not_include_fieldnames_if_not_present",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_handle_type_error_on_load_json",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_handle_value_error_on_parse_json"
] |
[
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_or_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_charset",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_vendor_media_type",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_ignore_extra_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_empty",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_int",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_invalid_input",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_form_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple_single_value",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonascii_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonutf8_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_validation_error_returns_422_response",
"tests/test_flaskparser.py::TestFlaskParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_validation",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_cookies",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_files",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json_with_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_invalid_json",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_json-{\"name\":",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_form-payload1-application/json]",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_view_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_invalid_view_arg",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_view_args_parsing",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_missing_data",
"tests/test_flaskparser.py::TestFlaskParser::test_nested_many_with_data_key",
"tests/test_flaskparser.py::test_abort_called_on_validation_error",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[None]",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[application/json]",
"tests/test_flaskparser.py::test_abort_with_message",
"tests/test_flaskparser.py::test_abort_has_serializable_data",
"tests/test_tornadoparser.py::test_tornado_multidictproxy",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestQueryArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestFormArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestJSONArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestJSONArgs::test_parsing_request_with_vendor_content_type",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestHeadersArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_get_single_values",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_get_multiple_values",
"tests/test_tornadoparser.py::TestFilesArgs::test_it_should_return_missing_if_not_present",
"tests/test_tornadoparser.py::TestErrorHandler::test_it_should_raise_httperror_on_failed_validation",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_query_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_form_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_json_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_raise_when_json_is_invalid",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_header_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_cookies_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_files_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_required_arguments",
"tests/test_tornadoparser.py::TestParse::test_it_should_parse_multiple_arg_required",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_pass_parsed_as_first_argument",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_pass_parsed_as_kwargs_arguments",
"tests/test_tornadoparser.py::TestUseArgs::test_it_should_be_validate_arguments_when_validator_is_passed",
"tests/test_tornadoparser.py::TestApp::test_get_path_param",
"tests/test_tornadoparser.py::TestApp::test_get_with_no_json_body",
"tests/test_tornadoparser.py::TestApp::test_post",
"tests/test_tornadoparser.py::TestValidateApp::test_missing_required_field_throws_422",
"tests/test_tornadoparser.py::TestValidateApp::test_required_field_provided",
"tests/test_tornadoparser.py::TestValidateApp::test_use_kwargs_with_error",
"tests/test_tornadoparser.py::TestValidateApp::test_user_validator_returns_422_by_default"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-31 18:47:27+00:00
|
mit
| 3,763 |
|
marshmallow-code__webargs-541
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 0b1acda..aef96c7 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -45,6 +45,12 @@ Usages are varied, but include
parser = MyParser()
+Changes:
+
+* Registered `error_handler` callbacks are required to raise an exception.
+ If a handler is invoked and no exception is raised, `webargs` will raise
+ a `ValueError` (:issue:`527`)
+
6.1.1 (2020-09-08)
******************
diff --git a/src/webargs/core.py b/src/webargs/core.py
index 922bd95..bab7f8b 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -283,10 +283,9 @@ class Parser:
error_status_code=error_status_code,
error_headers=error_headers,
)
- warnings.warn(
- "_on_validation_error hook did not raise an exception and flow "
- "of control returned to parse(). You may get unexpected results"
- )
+ raise ValueError(
+ "_on_validation_error hook did not raise an exception"
+ ) from error
return data
def get_default_request(self):
|
marshmallow-code/webargs
|
e62f478ae39efa55f363b389f5c69b583bf420f8
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 1995636..293d108 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -289,14 +289,19 @@ def test_value_error_raised_if_parse_called_with_invalid_location(parser, web_re
@mock.patch("webargs.core.Parser.handle_error")
def test_handle_error_called_when_parsing_raises_error(handle_error, web_request):
+ # handle_error must raise an error to be valid
+ handle_error.side_effect = ValidationError("parsing failed")
+
def always_fail(*args, **kwargs):
raise ValidationError("error occurred")
p = Parser()
assert handle_error.call_count == 0
- p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
+ with pytest.raises(ValidationError):
+ p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
assert handle_error.call_count == 1
- p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
+ with pytest.raises(ValidationError):
+ p.parse({"foo": fields.Field()}, web_request, validate=always_fail)
assert handle_error.call_count == 2
@@ -360,6 +365,25 @@ def test_custom_error_handler_decorator(web_request):
parser.parse(mock_schema, web_request)
+def test_custom_error_handler_must_reraise(web_request):
+ class CustomError(Exception):
+ pass
+
+ mock_schema = mock.Mock(spec=Schema)
+ mock_schema.strict = True
+ mock_schema.load.side_effect = ValidationError("parsing json failed")
+ parser = Parser()
+
+ @parser.error_handler
+ def handle_error(error, req, schema, *, error_status_code, error_headers):
+ pass
+
+ # because the handler above does not raise a new error, the parser should
+ # raise a ValueError -- indicating a programming error
+ with pytest.raises(ValueError):
+ parser.parse(mock_schema, web_request)
+
+
def test_custom_location_loader(web_request):
web_request.data = {"foo": 42}
diff --git a/tests/test_flaskparser.py b/tests/test_flaskparser.py
index 3429992..e9f08a4 100644
--- a/tests/test_flaskparser.py
+++ b/tests/test_flaskparser.py
@@ -1,4 +1,4 @@
-from werkzeug.exceptions import HTTPException
+from werkzeug.exceptions import HTTPException, BadRequest
import pytest
from flask import Flask
@@ -85,6 +85,9 @@ class TestFlaskParser(CommonTestCase):
@mock.patch("webargs.flaskparser.abort")
def test_abort_called_on_validation_error(mock_abort):
+ # error handling must raise an error to be valid
+ mock_abort.side_effect = BadRequest("foo")
+
app = Flask("testapp")
def validate(x):
@@ -97,7 +100,8 @@ def test_abort_called_on_validation_error(mock_abort):
data=json.dumps({"value": 41}),
content_type="application/json",
):
- parser.parse(argmap)
+ with pytest.raises(HTTPException):
+ parser.parse(argmap)
mock_abort.assert_called()
abort_args, abort_kwargs = mock_abort.call_args
assert abort_args[0] == 422
|
Failing to (re)raise an error when handling validation errors should raise a new error
Per #525 , we're going to start warning if you setup an error handler which does not, itself, raise an error. The result of failing to raise in your handler is that parsing "falls through" and returns incorrect data (`None` today, but the behavior is not well-defined) to the caller.
In version 7.0 of webargs, we should change this to raise an error, because it's not correct usage of webargs.
I think the most developer-friendly thing for us to do in this case is to raise `ValueError` or something similar (i.e. not a `ValidationError`, which they might be catching and handling outside of the parsing context). That will make it immediately apparent to the developer that they've done something wrong.
We can't make any guesses about whether or not people are testing their error handlers well, so no matter what we do here, there's a risk that people's applications crashfail in these scenarios.
|
0.0
|
e62f478ae39efa55f363b389f5c69b583bf420f8
|
[
"tests/test_core.py::test_custom_error_handler_must_reraise"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_dict2schema",
"tests/test_core.py::test_dict2schema_doesnt_add_to_class_registry",
"tests/test_core.py::test_dict2schema_with_nesting",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_or_form",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_charset",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_vendor_media_type",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_ignore_extra_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_empty",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_int",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_error_unexpected_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_invalid_input",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_many_schema_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_form_default",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_querystring_multiple_single_value",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_form_multiple",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_list_error_malformed_data",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonascii_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_json_with_nonutf8_chars",
"tests/test_flaskparser.py::TestFlaskParser::test_validation_error_returns_422_response",
"tests/test_flaskparser.py::TestFlaskParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_validation",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_decorator",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_path_param",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_cookies",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_json",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_nested_many_missing",
"tests/test_flaskparser.py::TestFlaskParser::test_parse_files",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json",
"tests/test_flaskparser.py::TestFlaskParser::test_empty_json_with_headers",
"tests/test_flaskparser.py::TestFlaskParser::test_invalid_json",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_json-{\"name\":",
"tests/test_flaskparser.py::TestFlaskParser::test_content_type_mismatch[/echo_form-payload1-application/json]",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_view_args",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_invalid_view_arg",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_with_view_args_parsing",
"tests/test_flaskparser.py::TestFlaskParser::test_use_args_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_on_a_method_view",
"tests/test_flaskparser.py::TestFlaskParser::test_use_kwargs_with_missing_data",
"tests/test_flaskparser.py::TestFlaskParser::test_nested_many_with_data_key",
"tests/test_flaskparser.py::TestFlaskParser::test_parsing_unexpected_headers_when_raising",
"tests/test_flaskparser.py::test_abort_called_on_validation_error",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[None]",
"tests/test_flaskparser.py::test_load_json_returns_missing_if_no_data[application/json]",
"tests/test_flaskparser.py::test_abort_with_message",
"tests/test_flaskparser.py::test_abort_has_serializable_data"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-08 18:42:44+00:00
|
mit
| 3,764 |
|
marshmallow-code__webargs-555
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index d0778f5..310c851 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -3,7 +3,7 @@ repos:
rev: v2.7.3
hooks:
- id: pyupgrade
- args: ["--py36-plus", "--keep-mock"]
+ args: ["--py36-plus"]
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py
index 5b4a21f..d2eb448 100644
--- a/src/webargs/falconparser.py
+++ b/src/webargs/falconparser.py
@@ -3,6 +3,8 @@
import falcon
from falcon.util.uri import parse_query_string
+import marshmallow as ma
+
from webargs import core
from webargs.multidictproxy import MultiDictProxy
@@ -69,7 +71,21 @@ class HTTPError(falcon.HTTPError):
class FalconParser(core.Parser):
- """Falcon request argument parser."""
+ """Falcon request argument parser.
+
+ Defaults to using the `media` location. See :py:meth:`~FalconParser.load_media` for
+ details on the media location."""
+
+ # by default, Falcon will use the 'media' location to load data
+ #
+ # this effectively looks the same as loading JSON data by default, but if
+ # you add a handler for a different media type to Falcon, webargs will
+ # automatically pick up on that capability
+ DEFAULT_LOCATION = "media"
+ DEFAULT_UNKNOWN_BY_LOCATION = dict(
+ media=ma.RAISE, **core.Parser.DEFAULT_UNKNOWN_BY_LOCATION
+ )
+ __location_map__ = dict(media="load_media", **core.Parser.__location_map__)
# Note on the use of MultiDictProxy throughout:
# Falcon parses query strings and form values into ordinary dicts, but with
@@ -95,6 +111,25 @@ class FalconParser(core.Parser):
return form
return MultiDictProxy(form, schema)
+ def load_media(self, req, schema):
+ """Return data unpacked and parsed by one of Falcon's media handlers.
+ By default, Falcon only handles JSON payloads.
+
+ To configure additional media handlers, see the
+ `Falcon documentation on media types`__.
+
+ .. _FalconMedia: https://falcon.readthedocs.io/en/stable/api/media.html
+ __ FalconMedia_
+
+ .. note::
+
+ The request stream will be read and left at EOF.
+ """
+ # if there is no body, return missing instead of erroring
+ if req.content_length in (None, 0):
+ return core.missing
+ return req.media
+
def _raw_load_json(self, req):
"""Return a json payload from the request for the core parser's load_json
|
marshmallow-code/webargs
|
60a4a27143b4844294eb80fa3e8e29653d8f5a5f
|
diff --git a/src/webargs/testing.py b/src/webargs/testing.py
index ca04040..23bf918 100644
--- a/src/webargs/testing.py
+++ b/src/webargs/testing.py
@@ -62,9 +62,6 @@ class CommonTestCase:
def test_parse_querystring_default(self, testapp):
assert testapp.get("/echo").json == {"name": "World"}
- def test_parse_json_default(self, testapp):
- assert testapp.post_json("/echo_json", {}).json == {"name": "World"}
-
def test_parse_json_with_charset(self, testapp):
res = testapp.post(
"/echo_json",
diff --git a/tests/apps/falcon_app.py b/tests/apps/falcon_app.py
index 314a35a..cb22529 100644
--- a/tests/apps/falcon_app.py
+++ b/tests/apps/falcon_app.py
@@ -37,6 +37,12 @@ class EchoJSON:
resp.body = json.dumps(parsed)
+class EchoMedia:
+ def on_post(self, req, resp):
+ parsed = parser.parse(hello_args, req, location="media")
+ resp.body = json.dumps(parsed)
+
+
class EchoJSONOrForm:
def on_post(self, req, resp):
parsed = parser.parse(hello_args, req, location="json_or_form")
@@ -161,6 +167,7 @@ def create_app():
app.add_route("/echo", Echo())
app.add_route("/echo_form", EchoForm())
app.add_route("/echo_json", EchoJSON())
+ app.add_route("/echo_media", EchoMedia())
app.add_route("/echo_json_or_form", EchoJSONOrForm())
app.add_route("/echo_use_args", EchoUseArgs())
app.add_route("/echo_use_kwargs", EchoUseKwargs())
diff --git a/tests/test_falconparser.py b/tests/test_falconparser.py
index 860c132..4f65313 100644
--- a/tests/test_falconparser.py
+++ b/tests/test_falconparser.py
@@ -16,28 +16,47 @@ class TestFalconParser(CommonTestCase):
def test_use_args_hook(self, testapp):
assert testapp.get("/echo_use_args_hook?name=Fred").json == {"name": "Fred"}
+ def test_parse_media(self, testapp):
+ assert testapp.post_json("/echo_media", {"name": "Fred"}).json == {
+ "name": "Fred"
+ }
+
+ def test_parse_media_missing(self, testapp):
+ assert testapp.post("/echo_media", "").json == {"name": "World"}
+
+ def test_parse_media_empty(self, testapp):
+ assert testapp.post_json("/echo_media", {}).json == {"name": "World"}
+
+ def test_parse_media_error_unexpected_int(self, testapp):
+ res = testapp.post_json("/echo_media", 1, expect_errors=True)
+ assert res.status_code == 422
+
# https://github.com/marshmallow-code/webargs/issues/427
- def test_parse_json_with_nonutf8_chars(self, testapp):
+ @pytest.mark.parametrize("path", ["/echo_json", "/echo_media"])
+ def test_parse_json_with_nonutf8_chars(self, testapp, path):
res = testapp.post(
- "/echo_json",
+ path,
b"\xfe",
headers={"Accept": "application/json", "Content-Type": "application/json"},
expect_errors=True,
)
assert res.status_code == 400
- assert res.json["errors"] == {"json": ["Invalid JSON body."]}
+ if path.endswith("json"):
+ assert res.json["errors"] == {"json": ["Invalid JSON body."]}
# https://github.com/sloria/webargs/issues/329
- def test_invalid_json(self, testapp):
+ @pytest.mark.parametrize("path", ["/echo_json", "/echo_media"])
+ def test_invalid_json(self, testapp, path):
res = testapp.post(
- "/echo_json",
+ path,
'{"foo": "bar", }',
headers={"Accept": "application/json", "Content-Type": "application/json"},
expect_errors=True,
)
assert res.status_code == 400
- assert res.json["errors"] == {"json": ["Invalid JSON body."]}
+ if path.endswith("json"):
+ assert res.json["errors"] == {"json": ["Invalid JSON body."]}
# Falcon converts headers to all-caps
def test_parsing_headers(self, testapp):
|
FalconParser should ideally support falcon's native media decoding
Falcon has a native media handling mechanism which can decode an incoming request body based on the `Content-Type` header and adding the dictionary of resulting key-value pairs as a cached property `req.media`. I've written my own FalconParser subclass that (very naively) uses this, but it seems like something that might be worth supporting out of the box.
```python
def parse_json(self, req, name, field):
"""
Pull a JSON body value from the request.
uses falcon's native req.media
"""
json_data = self._cache.get("json_data")
if json_data is None:
self._cache["json_data"] = json_data = req.media
return core.get_value(json_data, name, field, allow_many_nested=True)
```
This could probably be improved upon; since the `media` property is already cached on the request object, we could just access `req.media` directly without caching on the parser. (Not sure if this impacts other things that might use that cache, though; I haven't dug deep enough to fully understand that implication.) Also, since `media` was added in 1.3, if webargs still wanted to support older versions of falcon we could add a check for it and fall back to the existing behavior.
Maybe something like:
```python
def parse_json(self, req, name, field):
"""Pull a JSON body value from the request.
.. note::
The request stream will be read and left at EOF.
"""
json_data = req.media if hasattr(req, 'media') else self._cache.get("json_data")
if json_data is None:
self._cache["json_data"] = json_data = parse_json_body(req)
return core.get_value(json_data, name, field, allow_many_nested=True)
```
|
0.0
|
60a4a27143b4844294eb80fa3e8e29653d8f5a5f
|
[
"tests/test_falconparser.py::TestFalconParser::test_parse_media",
"tests/test_falconparser.py::TestFalconParser::test_parse_media_missing",
"tests/test_falconparser.py::TestFalconParser::test_parse_media_empty",
"tests/test_falconparser.py::TestFalconParser::test_parse_media_error_unexpected_int",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_nonutf8_chars[/echo_media]",
"tests/test_falconparser.py::TestFalconParser::test_invalid_json[/echo_media]"
] |
[
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_args",
"tests/test_falconparser.py::TestFalconParser::test_parse_form",
"tests/test_falconparser.py::TestFalconParser::test_parse_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_missing",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_or_form",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_default",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_charset",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_vendor_media_type",
"tests/test_falconparser.py::TestFalconParser::test_parse_ignore_extra_data",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_empty",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_error_unexpected_int",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_error_unexpected_list",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema_invalid_input",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_many_schema_error_malformed_data",
"tests/test_falconparser.py::TestFalconParser::test_parsing_form_default",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_multiple",
"tests/test_falconparser.py::TestFalconParser::test_parse_querystring_multiple_single_value",
"tests/test_falconparser.py::TestFalconParser::test_parse_form_multiple",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_list",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_list_error_malformed_data",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_nonascii_chars",
"tests/test_falconparser.py::TestFalconParser::test_validation_error_returns_422_response",
"tests/test_falconparser.py::TestFalconParser::test_user_validation_error_returns_422_response_by_default",
"tests/test_falconparser.py::TestFalconParser::test_use_args_decorator",
"tests/test_falconparser.py::TestFalconParser::test_use_args_with_path_param",
"tests/test_falconparser.py::TestFalconParser::test_use_args_with_validation",
"tests/test_falconparser.py::TestFalconParser::test_use_kwargs_decorator",
"tests/test_falconparser.py::TestFalconParser::test_use_kwargs_with_path_param",
"tests/test_falconparser.py::TestFalconParser::test_parsing_cookies",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_many_json",
"tests/test_falconparser.py::TestFalconParser::test_parse_nested_many_missing",
"tests/test_falconparser.py::TestFalconParser::test_empty_json",
"tests/test_falconparser.py::TestFalconParser::test_empty_json_with_headers",
"tests/test_falconparser.py::TestFalconParser::test_content_type_mismatch[/echo_json-{\"name\":",
"tests/test_falconparser.py::TestFalconParser::test_content_type_mismatch[/echo_form-payload1-application/json]",
"tests/test_falconparser.py::TestFalconParser::test_use_args_hook",
"tests/test_falconparser.py::TestFalconParser::test_parse_json_with_nonutf8_chars[/echo_json]",
"tests/test_falconparser.py::TestFalconParser::test_invalid_json[/echo_json]",
"tests/test_falconparser.py::TestFalconParser::test_parsing_headers",
"tests/test_falconparser.py::TestFalconParser::test_body_parsing_works_with_simulate"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-05 20:57:01+00:00
|
mit
| 3,765 |
|
marshmallow-code__webargs-583
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 138d5f1..26589ca 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -6,6 +6,10 @@ Changelog
Features:
+* Add `Parser.pre_load` as a method for allowing users to modify data before
+ schema loading, but without redefining location loaders. See advanced docs on
+ `Parser pre_load` for usage information
+
* ``unknown`` defaults to `None` for body locations (`json`, `form` and
`json_or_form`) (:issue:`580`).
diff --git a/docs/advanced.rst b/docs/advanced.rst
index 50ad01d..853fd64 100644
--- a/docs/advanced.rst
+++ b/docs/advanced.rst
@@ -435,6 +435,50 @@ To add your own parser, extend :class:`Parser <webargs.core.Parser>` and impleme
structure_dict_pair(r, k, v)
return r
+Parser pre_load
+---------------
+
+Similar to ``@pre_load`` decorated hooks on marshmallow Schemas,
+:class:`Parser <webargs.core.Parser>` classes define a method,
+`pre_load <webargs.core.Parser.pre_load>` which can
+be overridden to provide per-parser transformations of data.
+The only way to make use of `pre_load <webargs.core.Parser.pre_load>` is to
+subclass a :class:`Parser <webargs.core.Parser>` and provide an
+implementation.
+
+`pre_load <webargs.core.Parser.pre_load>` is given the data fetched from a
+location, the schema which will be used, the request object, and the location
+name which was requested. For example, to define a ``FlaskParser`` which strips
+whitespace from ``form`` and ``query`` data, one could write the following:
+
+.. code-block:: python
+
+ from webargs.flaskparser import FlaskParser
+ import typing
+
+
+ def _strip_whitespace(value):
+ if isinstance(value, str):
+ value = value.strip()
+ elif isinstance(value, typing.Mapping):
+ return {k: _strip_whitespace(value[k]) for k in value}
+ elif isinstance(value, (list, tuple)):
+ return type(value)(map(_strip_whitespace, value))
+ return value
+
+
+ class WhitspaceStrippingFlaskParser(FlaskParser):
+ def pre_load(self, location_data, *, schema, req, location):
+ if location in ("query", "form"):
+ return _strip_whitespace(location_data)
+ return location_data
+
+Note that `Parser.pre_load <webargs.core.Parser.pre_load>` is run after location
+loading but before ``Schema.load`` is called. It can therefore be called on
+multiple types of mapping objects, including
+:class:`MultiDictProxy <webargs.MultiDictProxy>`, depending on what the
+location loader returns.
+
Returning HTTP 400 Responses
----------------------------
diff --git a/src/webargs/core.py b/src/webargs/core.py
index 3752479..e675d77 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -322,7 +322,10 @@ class Parser:
location_data = self._load_location_data(
schema=schema, req=req, location=location
)
- data = schema.load(location_data, **load_kwargs)
+ preprocessed_data = self.pre_load(
+ location_data, schema=schema, req=req, location=location
+ )
+ data = schema.load(preprocessed_data, **load_kwargs)
self._validate_arguments(data, validators)
except ma.exceptions.ValidationError as error:
self._on_validation_error(
@@ -523,6 +526,15 @@ class Parser:
self.error_callback = func
return func
+ def pre_load(
+ self, location_data: Mapping, *, schema: ma.Schema, req: Request, location: str
+ ) -> Mapping:
+ """A method of the parser which can transform data after location
+ loading is done. By default it does nothing, but users can subclass
+ parsers and override this method.
+ """
+ return location_data
+
def _handle_invalid_json_error(
self,
error: typing.Union[json.JSONDecodeError, UnicodeDecodeError],
|
marshmallow-code/webargs
|
f953dff5c77b5eeb96046aef4a29fd9d097085c3
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 1219659..48b8ca6 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,4 +1,5 @@
import datetime
+import typing
from unittest import mock
import pytest
@@ -37,6 +38,9 @@ class MockRequestParser(Parser):
def load_querystring(self, req, schema):
return self._makeproxy(req.query, schema)
+ def load_form(self, req, schema):
+ return MultiDictProxy(req.form, schema)
+
def load_json(self, req, schema):
return req.json
@@ -1224,3 +1228,84 @@ def test_custom_default_schema_class(load_json, web_request):
p = CustomParser()
ret = p.parse(argmap, web_request)
assert ret == {"value": "hello world"}
+
+
+def test_parser_pre_load(web_request):
+ class CustomParser(MockRequestParser):
+ # pre-load hook to strip whitespace from query params
+ def pre_load(self, data, *, schema, req, location):
+ if location == "query":
+ return {k: v.strip() for k, v in data.items()}
+ return data
+
+ parser = CustomParser()
+
+ # mock data for both query and json
+ web_request.query = web_request.json = {"value": " hello "}
+ argmap = {"value": fields.Str()}
+
+ # data gets through for 'json' just fine
+ ret = parser.parse(argmap, web_request)
+ assert ret == {"value": " hello "}
+
+ # but for 'query', the pre_load hook changes things
+ ret = parser.parse(argmap, web_request, location="query")
+ assert ret == {"value": "hello"}
+
+
+# this test is meant to be a run of the WhitspaceStrippingFlaskParser we give
+# in the docs/advanced.rst examples for how to use pre_load
+# this helps ensure that the example code is correct
+# rather than a FlaskParser, we're working with the mock parser, but it's
+# otherwise the same
+def test_whitespace_stripping_parser_example(web_request):
+ def _strip_whitespace(value):
+ if isinstance(value, str):
+ value = value.strip()
+ elif isinstance(value, typing.Mapping):
+ return {k: _strip_whitespace(value[k]) for k in value}
+ elif isinstance(value, (list, tuple)):
+ return type(value)(map(_strip_whitespace, value))
+ return value
+
+ class WhitspaceStrippingParser(MockRequestParser):
+ def pre_load(self, location_data, *, schema, req, location):
+ if location in ("query", "form"):
+ ret = _strip_whitespace(location_data)
+ return ret
+ return location_data
+
+ parser = WhitspaceStrippingParser()
+
+ # mock data for query, form, and json
+ web_request.form = web_request.query = web_request.json = {"value": " hello "}
+ argmap = {"value": fields.Str()}
+
+ # data gets through for 'json' just fine
+ ret = parser.parse(argmap, web_request)
+ assert ret == {"value": " hello "}
+
+ # but for 'query' and 'form', the pre_load hook changes things
+ for loc in ("query", "form"):
+ ret = parser.parse(argmap, web_request, location=loc)
+ assert ret == {"value": "hello"}
+
+ # check that it applies in the case where the field is a list type
+ # applied to an argument (logic for `tuple` is effectively the same)
+ web_request.form = web_request.query = web_request.json = {
+ "ids": [" 1", "3", " 4"],
+ "values": [" foo ", " bar"],
+ }
+ schema = Schema.from_dict(
+ {"ids": fields.List(fields.Int), "values": fields.List(fields.Str)}
+ )
+ for loc in ("query", "form"):
+ ret = parser.parse(schema, web_request, location=loc)
+ assert ret == {"ids": [1, 3, 4], "values": ["foo", "bar"]}
+
+ # json loading should also work even though the pre_load hook above
+ # doesn't strip whitespace from JSON data
+ # - values=[" foo ", ...] will have whitespace preserved
+ # - ids=[" 1", ...] will still parse okay because " 1" is valid for fields.Int
+ ret = parser.parse(schema, web_request, location="json")
+ assert ret == {"ids": [1, 3, 4], "values": [" foo ", " bar"]}
|
Automatically trim leading/trailing whitespace from argument values
Does webargs provide any clean way to do this? I guess leading/trailing whitespace are almost never something you want (especially when having required fields that must not be empty)...
|
0.0
|
f953dff5c77b5eeb96046aef4a29fd9d097085c3
|
[
"tests/test_core.py::test_parser_pre_load",
"tests/test_core.py::test_whitespace_stripping_parser_example"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[custom_class]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[instance_setting]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[both]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_error_handler_must_reraise",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict2]",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_nested_field_from_dict",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-01 23:11:50+00:00
|
mit
| 3,766 |
|
marshmallow-code__webargs-584
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 310c851..392e538 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -25,3 +25,4 @@ repos:
- id: mypy
language_version: python3
files: ^src/webargs/
+ additional_dependencies: ["marshmallow>=3,<4"]
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 4549beb..732f7c0 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,19 @@
Changelog
---------
+7.1.0 (Unreleased)
+******************
+
+Features:
+
+* Detection of fields as "multi-value" for unpacking lists from multi-dict
+ types is now extensible with the `is_multiple` attribute. If a field sets
+ `is_multiple = True` it will be detected as a multi-value field.
+ (:issue:`563`)
+
+* If `is_multiple` is not set or is set to `None`, webargs will check if the
+ field is an instance of `List`.
+
7.0.1 (2020-12-14)
******************
diff --git a/docs/advanced.rst b/docs/advanced.rst
index 53cbde8..edac845 100644
--- a/docs/advanced.rst
+++ b/docs/advanced.rst
@@ -110,7 +110,7 @@ When you need more flexibility in defining input schemas, you can pass a marshma
@use_args(UserSchema())
def profile_view(args):
- username = args["userame"]
+ username = args["username"]
# ...
diff --git a/setup.py b/setup.py
index f68b745..91c44ff 100644
--- a/setup.py
+++ b/setup.py
@@ -20,12 +20,12 @@ EXTRAS_REQUIRE = {
]
+ FRAMEWORKS,
"lint": [
- "mypy==0.800",
+ "mypy==0.812",
"flake8==3.8.4",
- "flake8-bugbear==20.11.1",
+ "flake8-bugbear==21.3.1",
"pre-commit~=2.4",
],
- "docs": ["Sphinx==3.4.3", "sphinx-issues==1.2.0", "sphinx-typlog-theme==0.8.0"]
+ "docs": ["Sphinx==3.5.2", "sphinx-issues==1.2.0", "sphinx-typlog-theme==0.8.0"]
+ FRAMEWORKS,
}
EXTRAS_REQUIRE["dev"] = EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["lint"] + ["tox"]
diff --git a/src/webargs/core.py b/src/webargs/core.py
index 25080ee..d161030 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -8,8 +8,6 @@ import marshmallow as ma
from marshmallow import ValidationError
from marshmallow.utils import missing
-from webargs.fields import DelimitedList
-
logger = logging.getLogger(__name__)
@@ -34,6 +32,12 @@ ErrorHandler = typing.Callable[..., typing.NoReturn]
# generic type var with no particular meaning
T = typing.TypeVar("T")
+# a set of fields which are known to satisfy the `is_multiple` criteria, but
+# which come from marshmallow and therefore don't know about webargs (and
+# do not set `is_multiple=True`)
+# TODO: `ma.fields.Tuple` should be added here in v8.0
+KNOWN_MULTI_FIELDS: typing.List[typing.Type] = [ma.fields.List]
+
# a value used as the default for arguments, so that when `None` is passed, it
# can be distinguished from the default value
@@ -59,7 +63,12 @@ def _callable_or_raise(obj: typing.Optional[T]) -> typing.Optional[T]:
def is_multiple(field: ma.fields.Field) -> bool:
"""Return whether or not `field` handles repeated/multi-value arguments."""
- return isinstance(field, ma.fields.List) and not isinstance(field, DelimitedList)
+ # fields which set `is_multiple = True/False` will have the value selected,
+ # otherwise, we check for explicit criteria
+ is_multiple_attr = getattr(field, "is_multiple", None)
+ if is_multiple_attr is not None:
+ return is_multiple_attr
+ return isinstance(field, tuple(KNOWN_MULTI_FIELDS))
def get_mimetype(content_type: str) -> str:
diff --git a/src/webargs/fields.py b/src/webargs/fields.py
index 806cc5d..f8991d1 100644
--- a/src/webargs/fields.py
+++ b/src/webargs/fields.py
@@ -55,6 +55,8 @@ class DelimitedFieldMixin:
"""
delimiter: str = ","
+ # delimited fields set is_multiple=False for webargs.core.is_multiple
+ is_multiple: bool = False
def _serialize(self, value, attr, obj, **kwargs):
# serializing will start with parent-class serialization, so that we correctly
diff --git a/tox.ini b/tox.ini
index f3915a2..f18520b 100644
--- a/tox.ini
+++ b/tox.ini
@@ -30,6 +30,7 @@ commands = pre-commit run --all-files
# issues in which `mypy` running on every file standalone won't catch things
[testenv:mypy]
deps = mypy
+extras = frameworks
commands = mypy src/
[testenv:docs]
|
marshmallow-code/webargs
|
d4fbbb7e70648af961ba0c5214812bc8cf3426f1
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 829a3fe..b78f9ef 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1032,6 +1032,72 @@ def test_type_conversion_with_multiple_required(web_request, parser):
parser.parse(args, web_request)
[email protected]("input_dict", multidicts)
[email protected](
+ "setting",
+ ["is_multiple_true", "is_multiple_false", "is_multiple_notset", "list_field"],
+)
+def test_is_multiple_detection(web_request, parser, input_dict, setting):
+ # define a custom List-like type which deserializes string lists
+ str_instance = fields.String()
+
+ # this custom class "multiplexes" in that it can be given a single value or
+ # list of values -- a single value is treated as a string, and a list of
+ # values is treated as a list of strings
+ class CustomMultiplexingField(fields.Field):
+ def _deserialize(self, value, attr, data, **kwargs):
+ if isinstance(value, str):
+ return str_instance.deserialize(value, **kwargs)
+ return [str_instance.deserialize(v, **kwargs) for v in value]
+
+ def _serialize(self, value, attr, data, **kwargs):
+ if isinstance(value, str):
+ return str_instance._serialize(value, **kwargs)
+ return [str_instance._serialize(v, **kwargs) for v in value]
+
+ class CustomMultipleField(CustomMultiplexingField):
+ is_multiple = True
+
+ class CustomNonMultipleField(CustomMultiplexingField):
+ is_multiple = False
+
+ # the request's query params are the input multidict
+ web_request.query = input_dict
+
+ # case 1: is_multiple=True
+ if setting == "is_multiple_true":
+ # the multidict should unpack to a list of strings
+ #
+ # order is not necessarily guaranteed by the multidict implementations, but
+ # both values must be present
+ args = {"foos": CustomMultipleField()}
+ result = parser.parse(args, web_request, location="query")
+ assert result["foos"] in (["a", "b"], ["b", "a"])
+ # case 2: is_multiple=False
+ elif setting == "is_multiple_false":
+ # the multidict should unpack to a string
+ #
+ # either value may be returned, depending on the multidict implementation,
+ # but not both
+ args = {"foos": CustomNonMultipleField()}
+ result = parser.parse(args, web_request, location="query")
+ assert result["foos"] in ("a", "b")
+ # case 3: is_multiple is not set
+ elif setting == "is_multiple_notset":
+ # this should be the same as is_multiple=False
+ args = {"foos": CustomMultiplexingField()}
+ result = parser.parse(args, web_request, location="query")
+ assert result["foos"] in ("a", "b")
+ # case 4: the field is a List (special case)
+ elif setting == "list_field":
+ # this should behave like the is_multiple=True case
+ args = {"foos": fields.List(fields.Str())}
+ result = parser.parse(args, web_request, location="query")
+ assert result["foos"] in (["a", "b"], ["b", "a"])
+ else:
+ raise NotImplementedError
+
+
def test_validation_errors_in_validator_are_passed_to_handle_error(parser, web_request):
def validate(value):
raise ValidationError("Something went wrong.")
|
`is_multiple` vs custom fields
Right now I don't get multiple values in a custom field that does not inherit from the `List` field because `is_multiple` only checks for this.
And for some cases rewriting the field to be nested in an actual List field is not feasible, for example a `SQLAlchemyModelList`-like field where sending individual queries would be inefficient compared to one query with an SQL `IN` filter.
I propose adding a `MultiValueField` which would simply inherit from Field and do nothing itself, and instead of checking for isinstance List check for that one in `is_multiple`. `List` would then of course inherit from that instead of `Field`.
Alternatively, check for something like `isinstance(field, List) or getattr(field, 'is_multiple', False)`.
I can send a PR if there's interest in this.
|
0.0
|
d4fbbb7e70648af961ba0c5214812bc8cf3426f1
|
[
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict2]"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[custom_class]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[instance_setting]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[both]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_error_handler_must_reraise",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict2]",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_nested_field_from_dict",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-02 04:12:35+00:00
|
mit
| 3,767 |
|
marshmallow-code__webargs-594
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 703bfe6..138d5f1 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,20 +1,23 @@
Changelog
---------
-7.1.0 (Unreleased)
+8.0.0 (Unreleased)
******************
Features:
+* ``unknown`` defaults to `None` for body locations (`json`, `form` and
+ `json_or_form`) (:issue:`580`).
+
* Detection of fields as "multi-value" for unpacking lists from multi-dict
- types is now extensible with the `is_multiple` attribute. If a field sets
- `is_multiple = True` it will be detected as a multi-value field.
+ types is now extensible with the ``is_multiple`` attribute. If a field sets
+ ``is_multiple = True`` it will be detected as a multi-value field.
(:issue:`563`)
-* If `is_multiple` is not set or is set to `None`, webargs will check if the
- field is an instance of `List`.
+* If ``is_multiple`` is not set or is set to ``None``, webargs will check if the
+ field is an instance of ``List`` or ``Tuple``.
-* A new attribute on `Parser` objects, ``Parser.KNOWN_MULTI_FIELDS`` can be
+* A new attribute on ``Parser`` objects, ``Parser.KNOWN_MULTI_FIELDS`` can be
used to set fields which should be detected as ``is_multiple=True`` even when
the attribute is not set.
diff --git a/setup.py b/setup.py
index 15c033b..b201de5 100644
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,7 @@ EXTRAS_REQUIRE = {
+ FRAMEWORKS,
"lint": [
"mypy==0.812",
- "flake8==3.8.4",
+ "flake8==3.9.0",
"flake8-bugbear==21.3.2",
"pre-commit~=2.4",
],
diff --git a/src/webargs/aiohttpparser.py b/src/webargs/aiohttpparser.py
index 334e601..b85ff51 100644
--- a/src/webargs/aiohttpparser.py
+++ b/src/webargs/aiohttpparser.py
@@ -71,7 +71,7 @@ del _find_exceptions
class AIOHTTPParser(AsyncParser):
"""aiohttp request argument parser."""
- DEFAULT_UNKNOWN_BY_LOCATION = {
+ DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, typing.Optional[str]] = {
"match_info": RAISE,
"path": RAISE,
**core.Parser.DEFAULT_UNKNOWN_BY_LOCATION,
diff --git a/src/webargs/core.py b/src/webargs/core.py
index de8953d..3752479 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -126,10 +126,10 @@ class Parser:
DEFAULT_LOCATION: str = "json"
#: Default value to use for 'unknown' on schema load
# on a per-location basis
- DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, str] = {
- "json": ma.RAISE,
- "form": ma.RAISE,
- "json_or_form": ma.RAISE,
+ DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, typing.Optional[str]] = {
+ "json": None,
+ "form": None,
+ "json_or_form": None,
"querystring": ma.EXCLUDE,
"query": ma.EXCLUDE,
"headers": ma.EXCLUDE,
@@ -142,9 +142,8 @@ class Parser:
DEFAULT_VALIDATION_STATUS: int = DEFAULT_VALIDATION_STATUS
#: Default error message for validation errors
DEFAULT_VALIDATION_MESSAGE: str = "Invalid value."
- # TODO: add ma.fields.Tuple in v8.0
#: field types which should always be treated as if they set `is_multiple=True`
- KNOWN_MULTI_FIELDS: typing.List[typing.Type] = [ma.fields.List]
+ KNOWN_MULTI_FIELDS: typing.List[typing.Type] = [ma.fields.List, ma.fields.Tuple]
#: Maps location => method name
__location_map__: typing.Dict[str, typing.Union[str, typing.Callable]] = {
diff --git a/src/webargs/flaskparser.py b/src/webargs/flaskparser.py
index 29bc93d..053988d 100644
--- a/src/webargs/flaskparser.py
+++ b/src/webargs/flaskparser.py
@@ -20,6 +20,8 @@ Example: ::
uid=uid, per_page=args["per_page"]
)
"""
+import typing
+
import flask
from werkzeug.exceptions import HTTPException
@@ -49,7 +51,7 @@ def is_json_request(req):
class FlaskParser(core.Parser):
"""Flask request argument parser."""
- DEFAULT_UNKNOWN_BY_LOCATION = {
+ DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, typing.Optional[str]] = {
"view_args": ma.RAISE,
"path": ma.RAISE,
**core.Parser.DEFAULT_UNKNOWN_BY_LOCATION,
diff --git a/src/webargs/multidictproxy.py b/src/webargs/multidictproxy.py
index 7017d96..a277178 100644
--- a/src/webargs/multidictproxy.py
+++ b/src/webargs/multidictproxy.py
@@ -18,7 +18,10 @@ class MultiDictProxy(Mapping):
self,
multidict,
schema: ma.Schema,
- known_multi_fields: typing.Tuple[typing.Type, ...] = (ma.fields.List,),
+ known_multi_fields: typing.Tuple[typing.Type, ...] = (
+ ma.fields.List,
+ ma.fields.Tuple,
+ ),
):
self.data = multidict
self.known_multi_fields = known_multi_fields
diff --git a/src/webargs/pyramidparser.py b/src/webargs/pyramidparser.py
index 46bb377..4be2884 100644
--- a/src/webargs/pyramidparser.py
+++ b/src/webargs/pyramidparser.py
@@ -25,6 +25,7 @@ Example usage: ::
server.serve_forever()
"""
import functools
+import typing
from collections.abc import Mapping
from webob.multidict import MultiDict
@@ -43,7 +44,7 @@ def is_json_request(req):
class PyramidParser(core.Parser):
"""Pyramid request argument parser."""
- DEFAULT_UNKNOWN_BY_LOCATION = {
+ DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, typing.Optional[str]] = {
"matchdict": ma.RAISE,
"path": ma.RAISE,
**core.Parser.DEFAULT_UNKNOWN_BY_LOCATION,
|
marshmallow-code/webargs
|
2f05e314163825b57018ac9682d7e6463dbfcd35
|
diff --git a/tests/test_core.py b/tests/test_core.py
index d7b35fb..1219659 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -35,7 +35,7 @@ class MockRequestParser(Parser):
"""A minimal parser implementation that parses mock requests."""
def load_querystring(self, req, schema):
- return MultiDictProxy(req.query, schema)
+ return self._makeproxy(req.query, schema)
def load_json(self, req, schema):
return req.json
@@ -1040,6 +1040,7 @@ def test_type_conversion_with_multiple_required(web_request, parser):
"is_multiple_false",
"is_multiple_notset",
"list_field",
+ "tuple_field",
"added_to_known",
],
)
@@ -1103,13 +1104,20 @@ def test_is_multiple_detection(web_request, parser, input_dict, setting):
args = {"foos": fields.List(fields.Str())}
result = parser.parse(args, web_request, location="query")
assert result["foos"] in (["a", "b"], ["b", "a"])
+ # case 5: the field is a Tuple (special case)
+ elif setting == "tuple_field":
+ # this should behave like the is_multiple=True case and produce a tuple
+ args = {"foos": fields.Tuple((fields.Str, fields.Str))}
+ result = parser.parse(args, web_request, location="query")
+ assert result["foos"] in (("a", "b"), ("b", "a"))
+ # case 6: the field is custom, but added to the known fields of the parser
elif setting == "added_to_known":
# if it's included in the known multifields and is_multiple is not set, behave
# like is_multiple=True
parser.KNOWN_MULTI_FIELDS.append(CustomMultiplexingField)
args = {"foos": CustomMultiplexingField()}
result = parser.parse(args, web_request, location="query")
- assert result["foos"] in ("a", "b")
+ assert result["foos"] in (["a", "b"], ["b", "a"])
else:
raise NotImplementedError
|
Add marshmallow.fields.Tuple to detected `is_multiple` fields
I noticed this while working on #584 . Currently, `is_multiple(ma.fields.List(...)) == True`, but `is_multiple(ma.fields.Tuple(...)) == False`.
We should add `Tuple` so that `is_multiple` returns true.
It is possible that users have subclassed `fields.Tuple` or done something else which could make that a breaking change. I don't think that's very likely, but we are already queuing things up for 8.0 . I'm going to put this in the 8.0 milestone. We could probably do it sooner if there's a reason to do so.
I don't think using `Tuple` for a query param is a good idea. Supporting `...?foo=1&foo=2` but *not* `...?foo=1` or `...?foo=1&foo=2&foo=3` is unusual and therefore likely to be confusing. I'd advise webargs users not to do that. However! It's surprising that `Tuple` is not treated as `is_multiple=True`, and I'm just aiming for the least surprising behavior for webargs here.
|
0.0
|
2f05e314163825b57018ac9682d7e6463dbfcd35
|
[
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict2]"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[custom_class]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[instance_setting]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[both]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_error_handler_must_reraise",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict2]",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_nested_field_from_dict",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-12 22:30:26+00:00
|
mit
| 3,768 |
|
marshmallow-code__webargs-682
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 2af8116..e540cf3 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -20,9 +20,9 @@ repos:
additional_dependencies: [black==21.12b0]
args: ["--target-version", "py37"]
- repo: https://github.com/pre-commit/mirrors-mypy
- rev: v0.910-1
+ rev: v0.930
hooks:
- id: mypy
language_version: python3
files: ^src/webargs/
- additional_dependencies: ["marshmallow>=3,<4"]
+ additional_dependencies: ["marshmallow>=3,<4", "packaging"]
diff --git a/setup.py b/setup.py
index a87ab5d..da04cfd 100644
--- a/setup.py
+++ b/setup.py
@@ -20,7 +20,7 @@ EXTRAS_REQUIRE = {
]
+ FRAMEWORKS,
"lint": [
- "mypy==0.910",
+ "mypy==0.930",
"flake8==4.0.1",
"flake8-bugbear==21.11.29",
"pre-commit~=2.4",
diff --git a/src/webargs/__init__.py b/src/webargs/__init__.py
index e19b678..e7de3d8 100755
--- a/src/webargs/__init__.py
+++ b/src/webargs/__init__.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from packaging.version import Version
from marshmallow.utils import missing
@@ -9,7 +11,9 @@ from webargs import fields
__version__ = "8.0.1"
__parsed_version__ = Version(__version__)
-__version_info__ = __parsed_version__.release
+__version_info__: tuple[int, int, int] | tuple[
+ int, int, int, str, int
+] = __parsed_version__.release # type: ignore[assignment]
if __parsed_version__.pre:
- __version_info__ += __parsed_version__.pre
+ __version_info__ += __parsed_version__.pre # type: ignore[assignment]
__all__ = ("ValidationError", "fields", "missing", "validate")
diff --git a/src/webargs/asyncparser.py b/src/webargs/asyncparser.py
index b0b1024..2335097 100644
--- a/src/webargs/asyncparser.py
+++ b/src/webargs/asyncparser.py
@@ -5,7 +5,6 @@ import asyncio
import functools
import inspect
import typing
-from collections.abc import Mapping
from marshmallow import Schema, ValidationError
import marshmallow as ma
@@ -150,8 +149,8 @@ class AsyncParser(core.Parser):
request_obj = req
# Optimization: If argmap is passed as a dictionary, we only need
# to generate a Schema once
- if isinstance(argmap, Mapping):
- argmap = self.schema_class.from_dict(dict(argmap))()
+ if isinstance(argmap, dict):
+ argmap = self.schema_class.from_dict(argmap)()
def decorator(func: typing.Callable) -> typing.Callable:
req_ = request_obj
diff --git a/src/webargs/core.py b/src/webargs/core.py
index b098cba..618a334 100644
--- a/src/webargs/core.py
+++ b/src/webargs/core.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import functools
import typing
import logging
-from collections.abc import Mapping
import json
import marshmallow as ma
@@ -26,7 +25,7 @@ __all__ = [
Request = typing.TypeVar("Request")
ArgMap = typing.Union[
ma.Schema,
- typing.Mapping[str, ma.fields.Field],
+ typing.Dict[str, typing.Union[ma.fields.Field, typing.Type[ma.fields.Field]]],
typing.Callable[[Request], ma.Schema],
]
ValidateArg = typing.Union[None, typing.Callable, typing.Iterable[typing.Callable]]
@@ -34,6 +33,11 @@ CallableList = typing.List[typing.Callable]
ErrorHandler = typing.Callable[..., typing.NoReturn]
# generic type var with no particular meaning
T = typing.TypeVar("T")
+# type var for callables, to make type-preserving decorators
+C = typing.TypeVar("C", bound=typing.Callable)
+# type var for a callable which is an error handler
+# used to ensure that the error_handler decorator is type preserving
+ErrorHandlerT = typing.TypeVar("ErrorHandlerT", bound=ErrorHandler)
# a value used as the default for arguments, so that when `None` is passed, it
@@ -257,8 +261,10 @@ class Parser:
schema = argmap()
elif callable(argmap):
schema = argmap(req)
+ elif isinstance(argmap, dict):
+ schema = self.schema_class.from_dict(argmap)()
else:
- schema = self.schema_class.from_dict(dict(argmap))()
+ raise TypeError(f"argmap was of unexpected type {type(argmap)}")
return schema
def parse(
@@ -417,8 +423,8 @@ class Parser:
request_obj = req
# Optimization: If argmap is passed as a dictionary, we only need
# to generate a Schema once
- if isinstance(argmap, Mapping):
- argmap = self.schema_class.from_dict(dict(argmap))()
+ if isinstance(argmap, dict):
+ argmap = self.schema_class.from_dict(argmap)()
def decorator(func):
req_ = request_obj
@@ -468,7 +474,7 @@ class Parser:
kwargs["as_kwargs"] = True
return self.use_args(*args, **kwargs)
- def location_loader(self, name: str):
+ def location_loader(self, name: str) -> typing.Callable[[C], C]:
"""Decorator that registers a function for loading a request location.
The wrapped function receives a schema and a request.
@@ -489,13 +495,13 @@ class Parser:
:param str name: The name of the location to register.
"""
- def decorator(func):
+ def decorator(func: C) -> C:
self.__location_map__[name] = func
return func
return decorator
- def error_handler(self, func: ErrorHandler) -> ErrorHandler:
+ def error_handler(self, func: ErrorHandlerT) -> ErrorHandlerT:
"""Decorator that registers a custom error handling function. The
function should receive the raised error, request object,
`marshmallow.Schema` instance used to parse the request, error status code,
@@ -523,8 +529,13 @@ class Parser:
return func
def pre_load(
- self, location_data: Mapping, *, schema: ma.Schema, req: Request, location: str
- ) -> Mapping:
+ self,
+ location_data: typing.Mapping,
+ *,
+ schema: ma.Schema,
+ req: Request,
+ location: str,
+ ) -> typing.Mapping:
"""A method of the parser which can transform data after location
loading is done. By default it does nothing, but users can subclass
parsers and override this method.
diff --git a/tox.ini b/tox.ini
index e021c50..81e3a8f 100644
--- a/tox.ini
+++ b/tox.ini
@@ -29,7 +29,7 @@ commands = pre-commit run --all-files
# `webargs` and `marshmallow` both installed is a valuable safeguard against
# issues in which `mypy` running on every file standalone won't catch things
[testenv:mypy]
-deps = mypy==0.910
+deps = mypy==0.930
extras = frameworks
commands = mypy src/
|
marshmallow-code/webargs
|
ef8a34ae75ef200d7006ada35770aa170dae5902
|
diff --git a/tests/test_core.py b/tests/test_core.py
index 441f22d..bc8e97b 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,3 +1,4 @@
+import collections
import datetime
import typing
from unittest import mock
@@ -1321,3 +1322,15 @@ def test_whitespace_stripping_parser_example(web_request):
# - ids=[" 1", ...] will still parse okay because " 1" is valid for fields.Int
ret = parser.parse(schema, web_request, location="json")
assert ret == {"ids": [1, 3, 4], "values": [" foo ", " bar"]}
+
+
+def test_parse_rejects_non_dict_argmap_mapping(parser, web_request):
+ web_request.json = {"username": 42, "password": 42}
+ argmap = collections.UserDict(
+ {"username": fields.Field(), "password": fields.Field()}
+ )
+
+ # UserDict is dict-like in all meaningful ways, but not a subclass of `dict`
+ # it will therefore be rejected with a TypeError when used
+ with pytest.raises(TypeError):
+ parser.parse(argmap, web_request)
|
The type of "argmap" allows for `Mapping[str, Field]`, but `Schema.from_dict` only supports `Dict[str, Field]`
I ran into this while looking at getting #663 merged.
We have arguments annotated as allowing a `Mapping`. The most likely usage for users is just a dict, and that is all that our examples show.
`Schema.from_dict` uses `dict.copy`. That's not part of the `Mapping` protocol in `collections.abc`.
I almost suggested that `Schema.from_dict` be modified to allow for a `Mapping` object. It's not particularly hard (switch `input_object.copy()` to `dict(input_object)`), but it seems wrong. There's no particular reason to support non-dict mappings for either `marshmallow` or `webargs`. I think our annotations in `webargs` are just inaccurate.
I think we should consider updating annotations in `webargs` from `Mapping` to `Dict`.
@lafrech, for now, I'm going to make an update to the #663 branch and add `dict(argmap)` calls to make the types align.
|
0.0
|
ef8a34ae75ef200d7006ada35770aa170dae5902
|
[
"tests/test_core.py::test_parse_rejects_non_dict_argmap_mapping"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[custom_class]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[instance_setting]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[both]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_error_handler_must_reraise",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_empty_string",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict2]",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_nested_field_from_dict",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class",
"tests/test_core.py::test_parser_pre_load",
"tests/test_core.py::test_whitespace_stripping_parser_example"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-05 17:32:36+00:00
|
mit
| 3,769 |
|
marshmallow-code__webargs-832
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index d02eb12..3ba8020 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,9 +1,34 @@
Changelog
---------
-8.3.1 (Unreleased)
+8.4.0 (Unreleased)
******************
+Features:
+
+* Add a new class attribute, ``empty_value`` to ``DelimitedList`` and
+ ``DelimitedTuple``, with a default of ``""``.
+ This controls the value deserialized when an empty string is seen.
+
+``empty_value`` can be used to handle types other than strings more gracefully, e.g.
+
+.. code-block:: python
+
+ from webargs import fields
+
+
+ class IntList(fields.DelimitedList):
+ empty_value = 0
+
+
+ myfield = IntList(fields.Int())
+
+.. note::
+
+ ``empty_value`` will be changing in webargs v9.0 to be ``missing`` by
+ default. This will allow use of fields with ``load_default`` to specify
+ handling of the empty value.
+
Changes:
* Type annotations for ``FlaskParser`` have been improved
diff --git a/src/webargs/fields.py b/src/webargs/fields.py
index 5598b54..96590a3 100644
--- a/src/webargs/fields.py
+++ b/src/webargs/fields.py
@@ -15,6 +15,8 @@ tells webargs where to parse the request argument from.
"""
from __future__ import annotations
+import typing
+
import marshmallow as ma
# Expose all fields from marshmallow.fields.
@@ -64,6 +66,8 @@ class DelimitedFieldMixin:
delimiter: str = ","
# delimited fields set is_multiple=False for webargs.core.is_multiple
is_multiple: bool = False
+ # NOTE: in 8.x this defaults to "" but in 9.x it will be 'missing'
+ empty_value: typing.Any = ""
def _serialize(self, value, attr, obj, **kwargs):
# serializing will start with parent-class serialization, so that we correctly
@@ -77,6 +81,8 @@ class DelimitedFieldMixin:
if not isinstance(value, (str, bytes)):
raise self.make_error("invalid")
values = value.split(self.delimiter) if value else []
+ # convert empty strings to the empty value; typically "" and therefore a no-op
+ values = [v or self.empty_value for v in values]
return super()._deserialize(values, attr, data, **kwargs)
@@ -117,6 +123,12 @@ class DelimitedTuple(DelimitedFieldMixin, ma.fields.Tuple):
default_error_messages = {"invalid": "Not a valid delimited tuple."}
- def __init__(self, tuple_fields, *, delimiter: str | None = None, **kwargs):
+ def __init__(
+ self,
+ tuple_fields,
+ *,
+ delimiter: str | None = None,
+ **kwargs,
+ ):
self.delimiter = delimiter or self.delimiter
super().__init__(tuple_fields, **kwargs)
|
marshmallow-code/webargs
|
44e2037a5607f3655f47d475272eab01d49aaaa0
|
diff --git a/tests/test_core.py b/tests/test_core.py
index c24ac1b..39b8284 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -11,6 +11,7 @@ from marshmallow import (
INCLUDE,
RAISE,
Schema,
+ missing,
post_load,
pre_load,
validates_schema,
@@ -1106,6 +1107,47 @@ def test_delimited_tuple_passed_invalid_type(web_request, parser):
assert excinfo.value.messages == {"json": {"ids": ["Not a valid delimited tuple."]}}
+def test_delimited_list_custom_empty_value(web_request, parser):
+ class ZeroList(fields.DelimitedList):
+ empty_value = 0
+
+ web_request.json = {"ids": "1,,3"}
+ schema_cls = Schema.from_dict({"ids": ZeroList(fields.Int())})
+ schema = schema_cls()
+
+ parsed = parser.parse(schema, web_request)
+ assert parsed["ids"] == [1, 0, 3]
+
+
+def test_delimited_tuple_custom_empty_value(web_request, parser):
+ class ZeroTuple(fields.DelimitedTuple):
+ empty_value = 0
+
+ web_request.json = {"ids": "1,,3"}
+ schema_cls = Schema.from_dict(
+ {"ids": ZeroTuple((fields.Int, fields.Int, fields.Int))}
+ )
+ schema = schema_cls()
+
+ parsed = parser.parse(schema, web_request)
+ assert parsed["ids"] == (1, 0, 3)
+
+
+def test_delimited_list_using_missing_for_empty(web_request, parser):
+ # this is "future" because we plan to make this the default for webargs v9.0
+ class FutureList(fields.DelimitedList):
+ empty_value = missing
+
+ web_request.json = {"ids": "foo,,bar"}
+ schema_cls = Schema.from_dict(
+ {"ids": FutureList(fields.String(load_default="nil"))}
+ )
+ schema = schema_cls()
+
+ parsed = parser.parse(schema, web_request)
+ assert parsed["ids"] == ["foo", "nil", "bar"]
+
+
def test_missing_list_argument_not_in_parsed_result(web_request, parser):
# arg missing in request
web_request.json = {}
|
Dealing with empty values in `DelimitedFieldMixin`
`DelimitedList(String())` deserializes "a,,c" as `["a", "", "c"]`.
I guess this meets user expectations.
My expectation with integers would be that
`DelimitedList(Integer(allow_none=True))` deserializes `"1,,3"` as `[1,None,3]`
but it errors.
The reason for this is that when the string is split, it is turned into `["1", "", "3"]`. This is why it works in the string case.
I'm not sure this was really intended. It may be a side effect of the `split` function that happens to do well with strings.
We could change that to replace empty values with `None`. But it would break the string use case, unless the user overloads `String` field to deserialize `None` as `""`.
Likewise, users may already overload `Integer` to deserialize `""` as `None` and no modification is required to `DelimitedFieldMixin`.
Just been caught by this and wondering out loud. Advice welcome.
In any case, there is an intrinsic limitation in the delimited string format: one can't distinguish empty string from missing value (as opposed to a JSON payload). It is not clear to me how OpenAPI (for instance) deals with the case of an empty element in an array (in a query argument).
|
0.0
|
44e2037a5607f3655f47d475272eab01d49aaaa0
|
[
"tests/test_core.py::test_delimited_list_custom_empty_value",
"tests/test_core.py::test_delimited_tuple_custom_empty_value",
"tests/test_core.py::test_delimited_list_using_missing_for_empty"
] |
[
"tests/test_core.py::test_load_json_called_by_parse_default",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[querystring]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[form]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[headers]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[cookies]",
"tests/test_core.py::test_load_nondefault_called_by_parse_with_location[files]",
"tests/test_core.py::test_parse[parse]",
"tests/test_core.py::test_parse[async_parse]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[schema_instance]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parse_call]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_default]",
"tests/test_core.py::test_parse_with_unknown_behavior_specified[parser_class_default]",
"tests/test_core.py::test_parse_with_explicit_unknown_overrides_schema",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[custom_class]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[instance_setting]",
"tests/test_core.py::test_parse_with_default_unknown_cleared_uses_schema_value[both]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error[parse]",
"tests/test_core.py::test_parse_required_arg_raises_validation_error[async_parse]",
"tests/test_core.py::test_arg_not_required_excluded_in_parsed_output",
"tests/test_core.py::test_arg_allow_none",
"tests/test_core.py::test_parse_required_arg",
"tests/test_core.py::test_parse_required_list",
"tests/test_core.py::test_parse_list_allow_none",
"tests/test_core.py::test_parse_list_dont_allow_none",
"tests/test_core.py::test_parse_empty_list",
"tests/test_core.py::test_parse_missing_list",
"tests/test_core.py::test_default_location",
"tests/test_core.py::test_missing_with_default",
"tests/test_core.py::test_default_can_be_none",
"tests/test_core.py::test_arg_with_default_and_location",
"tests/test_core.py::test_value_error_raised_if_parse_called_with_invalid_location",
"tests/test_core.py::test_handle_error_called_when_parsing_raises_error",
"tests/test_core.py::test_handle_error_called_when_async_parsing_raises_error",
"tests/test_core.py::test_handle_error_reraises_errors",
"tests/test_core.py::test_location_as_init_argument",
"tests/test_core.py::test_custom_error_handler",
"tests/test_core.py::test_custom_error_handler_decorator",
"tests/test_core.py::test_custom_error_handler_decorator_in_async_parse[True]",
"tests/test_core.py::test_custom_error_handler_decorator_in_async_parse[False]",
"tests/test_core.py::test_custom_error_handler_must_reraise",
"tests/test_core.py::test_custom_location_loader",
"tests/test_core.py::test_custom_location_loader_with_data_key",
"tests/test_core.py::test_full_input_validation",
"tests/test_core.py::test_full_input_validation_with_multiple_validators",
"tests/test_core.py::test_required_with_custom_error",
"tests/test_core.py::test_required_with_custom_error_and_validation_error",
"tests/test_core.py::test_full_input_validator_receives_nonascii_input",
"tests/test_core.py::test_invalid_argument_for_validate",
"tests/test_core.py::test_multidict_proxy[input_dict0]",
"tests/test_core.py::test_multidict_proxy[input_dict1]",
"tests/test_core.py::test_multidict_proxy[input_dict2]",
"tests/test_core.py::test_parse_with_data_key",
"tests/test_core.py::test_parse_with_data_key_retains_field_name_in_error",
"tests/test_core.py::test_parse_nested_with_data_key",
"tests/test_core.py::test_parse_nested_with_missing_key_and_data_key",
"tests/test_core.py::test_parse_nested_with_default",
"tests/test_core.py::test_nested_many",
"tests/test_core.py::test_use_args",
"tests/test_core.py::test_use_args_stacked",
"tests/test_core.py::test_use_args_forbids_invalid_usages",
"tests/test_core.py::test_use_kwargs_stacked",
"tests/test_core.py::test_decorators_dont_change_docstring[use_args]",
"tests/test_core.py::test_decorators_dont_change_docstring[use_kwargs]",
"tests/test_core.py::test_list_allowed_missing",
"tests/test_core.py::test_int_list_allowed_missing",
"tests/test_core.py::test_multiple_arg_required_with_int_conversion",
"tests/test_core.py::test_parse_with_callable",
"tests/test_core.py::test_use_args_callable",
"tests/test_core.py::TestPassingSchema::test_passing_schema_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_passing_schema_factory_to_parse",
"tests/test_core.py::TestPassingSchema::test_use_args_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_can_be_passed_a_schema_factory",
"tests/test_core.py::TestPassingSchema::test_use_kwargs_stacked",
"tests/test_core.py::TestPassingSchema::test_parse_does_not_add_missing_values_to_schema_validator",
"tests/test_core.py::test_use_args_with_custom_location_in_parser",
"tests/test_core.py::test_use_kwargs",
"tests/test_core.py::test_use_kwargs_with_arg_missing",
"tests/test_core.py::test_delimited_list_empty_string",
"tests/test_core.py::test_delimited_list_default_delimiter",
"tests/test_core.py::test_delimited_tuple_default_delimiter",
"tests/test_core.py::test_delimited_tuple_incorrect_arity",
"tests/test_core.py::test_delimited_list_with_datetime",
"tests/test_core.py::test_delimited_list_custom_delimiter",
"tests/test_core.py::test_delimited_tuple_custom_delimiter",
"tests/test_core.py::test_delimited_list_load_list_errors",
"tests/test_core.py::test_delimited_tuple_load_list_errors",
"tests/test_core.py::test_delimited_list_passed_invalid_type",
"tests/test_core.py::test_delimited_tuple_passed_invalid_type",
"tests/test_core.py::test_missing_list_argument_not_in_parsed_result",
"tests/test_core.py::test_type_conversion_with_multiple_required",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_true-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_false-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[is_multiple_notset-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[list_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[tuple_field-input_dict2]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict0]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict1]",
"tests/test_core.py::test_is_multiple_detection[added_to_known-input_dict2]",
"tests/test_core.py::test_validation_errors_in_validator_are_passed_to_handle_error",
"tests/test_core.py::test_parse_basic",
"tests/test_core.py::test_parse_raises_validation_error_if_data_invalid",
"tests/test_core.py::test_nested_field_from_dict",
"tests/test_core.py::test_is_json",
"tests/test_core.py::test_get_mimetype",
"tests/test_core.py::test_parse_with_error_status_code_and_headers",
"tests/test_core.py::test_custom_schema_class",
"tests/test_core.py::test_custom_default_schema_class",
"tests/test_core.py::test_parser_pre_load",
"tests/test_core.py::test_whitespace_stripping_parser_example",
"tests/test_core.py::test_parse_allows_non_dict_argmap_mapping",
"tests/test_core.py::test_use_args_allows_non_dict_argmap_mapping",
"tests/test_core.py::test_parse_rejects_unknown_argmap_type",
"tests/test_core.py::test_parser_opt_out_positional_args",
"tests/test_core.py::test_use_args_implicit_arg_names",
"tests/test_core.py::test_use_args_explicit_arg_names[True]",
"tests/test_core.py::test_use_args_explicit_arg_names[False]",
"tests/test_core.py::test_use_args_errors_on_explicit_arg_name_conflict",
"tests/test_core.py::test_use_args_errors_on_implicit_arg_name_conflict",
"tests/test_core.py::test_use_args_with_arg_name_supports_multi_stacked_decorators"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-26 19:58:02+00:00
|
mit
| 3,770 |
|
martinrusev__imbox-95
|
diff --git a/imbox/parser.py b/imbox/parser.py
index 374ffdf..4b1b6f2 100644
--- a/imbox/parser.py
+++ b/imbox/parser.py
@@ -69,7 +69,7 @@ def decode_param(param):
if type_ == 'Q':
value = quopri.decodestring(code)
elif type_ == 'B':
- value = base64.decodestring(code)
+ value = base64.decodebytes(code.encode())
value = str_encode(value, encoding)
value_results.append(value)
if value_results:
|
martinrusev/imbox
|
61a6c87fe65a3dbbd0124307d3232c72015425a8
|
diff --git a/tests/parser_tests.py b/tests/parser_tests.py
index fae3543..11961b0 100644
--- a/tests/parser_tests.py
+++ b/tests/parser_tests.py
@@ -80,6 +80,46 @@ Content-Transfer-Encoding: quoted-printable
"""
+raw_email_encoded_bad_multipart = b"""Delivered-To: [email protected]
+Return-Path: <[email protected]>
+From: [email protected]
+To: "Receiver" <[email protected]>, "Second\r\n Receiver" <[email protected]>
+Subject: Re: Looking to connect with you...
+Date: Thu, 20 Apr 2017 15:32:52 +0000
+Message-ID: <BN6PR16MB179579288933D60C4016D078C31B0@BN6PR16MB1795.namprd16.prod.outlook.com>
+Content-Type: multipart/related;
+ boundary="_004_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_";
+ type="multipart/alternative"
+MIME-Version: 1.0
+--_004_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_
+Content-Type: multipart/alternative;
+ boundary="_000_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_"
+--_000_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_
+Content-Type: text/plain; charset="utf-8"
+Content-Transfer-Encoding: base64
+SGkgRGFuaWVsbGUsDQoNCg0KSSBhY3R1YWxseSBhbSBoYXBweSBpbiBteSBjdXJyZW50IHJvbGUs
+Y3J1aXRlciB8IENoYXJsb3R0ZSwgTkMNClNlbnQgdmlhIEhhcHBpZQ0KDQoNCg==
+--_000_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_
+Content-Type: text/html; charset="utf-8"
+Content-Transfer-Encoding: base64
+PGh0bWw+DQo8aGVhZD4NCjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIgY29udGVudD0i
+CjwvZGl2Pg0KPC9kaXY+DQo8L2JvZHk+DQo8L2h0bWw+DQo=
+--_000_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_--
+--_004_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_
+Content-Type: image/png; name="=?utf-8?B?T3V0bG9va0Vtb2ppLfCfmIoucG5n?="
+Content-Description: =?utf-8?B?T3V0bG9va0Vtb2ppLfCfmIoucG5n?=
+Content-Disposition: inline;
+ filename="=?utf-8?B?T3V0bG9va0Vtb2ppLfCfmIoucG5n?="; size=488;
+ creation-date="Thu, 20 Apr 2017 15:32:52 GMT";
+ modification-date="Thu, 20 Apr 2017 15:32:52 GMT"
+Content-ID: <254962e2-f05c-40d1-aa11-0d34671b056c>
+Content-Transfer-Encoding: base64
+iVBORw0KGgoAAAANSUhEUgAAABMAAAATCAYAAAByUDbMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
+cvED9AIR3TCAAAMAqh+p+YMVeBQAAAAASUVORK5CYII=
+--_004_BN6PR16MB179579288933D60C4016D078C31B0BN6PR16MB1795namp_--
+"""
+
+
class TestParser(unittest.TestCase):
def test_parse_email(self):
@@ -96,6 +136,10 @@ class TestParser(unittest.TestCase):
self.assertEqual('Выписка по карте', parsed_email.subject)
self.assertEqual('Выписка по карте 1234', parsed_email.body['html'][0])
+ def test_parse_email_bad_multipart(self):
+ parsed_email = parse_email(raw_email_encoded_bad_multipart)
+ self.assertEqual("Re: Looking to connect with you...", parsed_email.subject)
+
def test_parse_email_ignores_header_casing(self):
self.assertEqual('one', parse_email('Message-ID: one').message_id)
self.assertEqual('one', parse_email('Message-Id: one').message_id)
|
error when parsing attachment
I am running the example provided by README, My python version is 3.5, on windows platform, here is the error message, please take a look.
```
Traceback (most recent call last):
File "C:\Users\**\Miniconda3\lib\base64.py", line 518, in _input_type_check
m = memoryview(s)
TypeError: memoryview: a bytes-like object is required, not 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:/Project/account-adapter/imbox_downloader.py", line 61, in <module>
for uid, message in all_messages:
File "C:\Users\**\Miniconda3\lib\site-packages\imbox\__init__.py", line 50, in fetch_list
yield (uid, self.fetch_by_uid(uid))
File "C:\Users\**\Miniconda3\lib\site-packages\imbox\__init__.py", line 41, in fetch_by_uid
email_object = parse_email(raw_email)
File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 160, in parse_email
attachment = parse_attachment(part)
File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 102, in parse_attachment
name, value = decode_param(param)
File "C:\Users\**\Miniconda3\lib\site-packages\imbox\parser.py", line 74, in decode_param
value = base64.decodestring(code)
File "C:\Users\**\Miniconda3\lib\base64.py", line 560, in decodestring
return decodebytes(s)
File "C:\Users\**\Miniconda3\lib\base64.py", line 552, in decodebytes
_input_type_check(s)
File "C:\Users\**\Miniconda3\lib\base64.py", line 521, in _input_type_check
raise TypeError(msg) from err
TypeError: expected bytes-like object, not str
```
|
0.0
|
61a6c87fe65a3dbbd0124307d3232c72015425a8
|
[
"tests/parser_tests.py::TestParser::test_parse_email_bad_multipart"
] |
[
"tests/parser_tests.py::TestParser::test_decode_mail_header",
"tests/parser_tests.py::TestParser::test_get_mail_addresses",
"tests/parser_tests.py::TestParser::test_parse_attachment",
"tests/parser_tests.py::TestParser::test_parse_email",
"tests/parser_tests.py::TestParser::test_parse_email_encoded",
"tests/parser_tests.py::TestParser::test_parse_email_ignores_header_casing",
"tests/parser_tests.py::TestParser::test_parse_email_with_policy"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-09-25 11:06:04+00:00
|
mit
| 3,771 |
|
matchms__matchms-187
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07a6a014..bd59a321 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Very minor bugs in `add_parent_mass` [#188](https://github.com/matchms/matchms/pull/188)
+
## [0.8.1] - 2021-02-19
### Fixed
diff --git a/matchms/filtering/add_parent_mass.py b/matchms/filtering/add_parent_mass.py
index d7b48dfa..e69a6d09 100644
--- a/matchms/filtering/add_parent_mass.py
+++ b/matchms/filtering/add_parent_mass.py
@@ -36,11 +36,11 @@ def add_parent_mass(spectrum_in: SpectrumType, estimate_from_adduct: bool = True
try:
precursor_mz = spectrum.get("precursor_mz", None)
if precursor_mz is None:
- precursor_mz = spectrum.get("pepmass")[0]
- except KeyError:
+ precursor_mz = spectrum.get("pepmass", None)[0]
+ except TypeError:
print("Not sufficient spectrum metadata to derive parent mass.")
+ return spectrum
- spectrum = spectrum_in.clone()
if estimate_from_adduct and adduct in adducts_dict:
multiplier = adducts_dict[adduct]["mass_multiplier"]
correction_mass = adducts_dict[adduct]["correction_mass"]
@@ -51,9 +51,9 @@ def add_parent_mass(spectrum_in: SpectrumType, estimate_from_adduct: bool = True
protons_mass = PROTON_MASS * charge
precursor_mass = precursor_mz * abs(charge)
parent_mass = precursor_mass - protons_mass
- else:
- print("Not sufficient spectrum metadata to derive parent mass.")
- if parent_mass is not None:
- spectrum.set("parent_mass", parent_mass)
+ if parent_mass is None:
+ print("Not sufficient spectrum metadata to derive parent mass.")
+ else:
+ spectrum.set("parent_mass", float(parent_mass))
return spectrum
|
matchms/matchms
|
a1896f8ffc26d2a4c8e2975c05081c8f808aae92
|
diff --git a/tests/test_add_parent_mass.py b/tests/test_add_parent_mass.py
index 46d2b1cf..3ebccd5e 100644
--- a/tests/test_add_parent_mass.py
+++ b/tests/test_add_parent_mass.py
@@ -4,7 +4,7 @@ from matchms import Spectrum
from matchms.filtering import add_parent_mass
-def test_add_parent_mass():
+def test_add_parent_mass(capsys):
"""Test if parent mass is correctly derived."""
mz = numpy.array([], dtype='float')
intensities = numpy.array([], dtype='float')
@@ -17,9 +17,26 @@ def test_add_parent_mass():
spectrum = add_parent_mass(spectrum_in)
assert numpy.abs(spectrum.get("parent_mass") - 445.0) < .01, "Expected parent mass of about 445.0."
+ assert isinstance(spectrum.get("parent_mass"), float), "Expected parent mass to be float."
+ assert "Not sufficient spectrum metadata to derive parent mass." not in capsys.readouterr().out
-def test_add_parent_mass_no_pepmass():
+def test_add_parent_mass_no_pepmass(capsys):
+ """Test if correct expection is returned."""
+ mz = numpy.array([], dtype='float')
+ intensities = numpy.array([], dtype='float')
+ metadata = {"charge": -1}
+ spectrum_in = Spectrum(mz=mz,
+ intensities=intensities,
+ metadata=metadata)
+
+ spectrum = add_parent_mass(spectrum_in)
+
+ assert spectrum.get("parent_mass") is None, "Expected no parent mass"
+ assert "Not sufficient spectrum metadata to derive parent mass." in capsys.readouterr().out
+
+
+def test_add_parent_mass_no_pepmass_but_precursormz(capsys):
"""Test if parent mass is correctly derived if "pepmass" is not present."""
mz = numpy.array([], dtype='float')
intensities = numpy.array([], dtype='float')
@@ -32,6 +49,8 @@ def test_add_parent_mass_no_pepmass():
spectrum = add_parent_mass(spectrum_in)
assert numpy.abs(spectrum.get("parent_mass") - 445.0) < .01, "Expected parent mass of about 445.0."
+ assert isinstance(spectrum.get("parent_mass"), float), "Expected parent mass to be float."
+ assert "Not sufficient spectrum metadata to derive parent mass." not in capsys.readouterr().out
@pytest.mark.parametrize("adduct, expected", [("[M+2Na-H]+", 399.02884),
@@ -51,6 +70,22 @@ def test_add_parent_mass_using_adduct(adduct, expected):
spectrum = add_parent_mass(spectrum_in)
assert numpy.allclose(spectrum.get("parent_mass"), expected, atol=1e-4), f"Expected parent mass of about {expected}."
+ assert isinstance(spectrum.get("parent_mass"), float), "Expected parent mass to be float."
+
+
+def test_add_parent_mass_not_sufficient_data(capsys):
+ """Test when there is not enough information to derive parent_mass."""
+ mz = numpy.array([], dtype='float')
+ intensities = numpy.array([], dtype='float')
+ metadata = {"precursor_mz": 444.0}
+ spectrum_in = Spectrum(mz=mz,
+ intensities=intensities,
+ metadata=metadata)
+
+ spectrum = add_parent_mass(spectrum_in)
+
+ assert spectrum.get("parent_mass") is None, "Expected no parent mass"
+ assert "Not sufficient spectrum metadata to derive parent mass." in capsys.readouterr().out
def test_empty_spectrum():
diff --git a/tests/test_modified_cosine.py b/tests/test_modified_cosine.py
index 5656e600..e5b0adcd 100644
--- a/tests/test_modified_cosine.py
+++ b/tests/test_modified_cosine.py
@@ -62,6 +62,28 @@ def test_modified_cosine_with_mass_shift_5_tolerance_2():
assert score["matches"] == 6, "Expected 6 matching peaks."
+def test_modified_cosine_with_mass_shifted_and_unshifted_matches():
+ """Test modified cosine on two spectra with mass set shift.
+ In this example 5 peak pairs are possible, but only 3 should be selected (every peak
+ can only be counted once!)"""
+ spectrum_1 = Spectrum(mz=numpy.array([100, 110, 200, 300, 400, 500, 600], dtype="float"),
+ intensities=numpy.array([100, 50, 1, 80, 1, 1, 50], dtype="float"),
+ metadata={"precursor_mz": 1000.0})
+
+ spectrum_2 = Spectrum(mz=numpy.array([110, 200, 300, 310, 700, 800], dtype="float"),
+ intensities=numpy.array([100, 1, 90, 90, 1, 100], dtype="float"),
+ metadata={"precursor_mz": 1010.0})
+
+ modified_cosine = ModifiedCosine()
+ score = modified_cosine.pair(spectrum_1, spectrum_2)
+ spec1 = spectrum_1.peaks.intensities
+ spec2 = spectrum_2.peaks.intensities
+ peak_pairs_multiplied = spec1[0] * spec2[0] + spec1[3] * spec2[3] + spec1[2] * spec2[1]
+ expected_score = peak_pairs_multiplied / numpy.sqrt(numpy.sum(spec1 ** 2) * numpy.sum(spec2 ** 2))
+ assert score["score"] == pytest.approx(expected_score, 0.00001), "Expected different cosine score."
+ assert score["matches"] == 3, "Expected 3 matching peaks."
+
+
def test_modified_cosine_order_of_input_spectrums():
"""Test modified cosine on two spectra in changing order."""
spectrum_1 = Spectrum(mz=numpy.array([100, 150, 200, 300, 500, 510, 1100], dtype="float"),
|
Latest release did not end up on zenodo or RSD
The latest release found on zenodo is 0.4.0 (0.5.0 hence wasn't added).
In the RSD I also only found an older version (0.3.1).
I guess that usually should be done automatically when a release is done, so not sure what went wrong here.
|
0.0
|
a1896f8ffc26d2a4c8e2975c05081c8f808aae92
|
[
"tests/test_add_parent_mass.py::test_add_parent_mass_no_pepmass"
] |
[
"tests/test_add_parent_mass.py::test_add_parent_mass",
"tests/test_add_parent_mass.py::test_add_parent_mass_no_pepmass_but_precursormz",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[M+2Na-H]+-399.02884]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[M+H+NH4]2+-212.47945]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[2M+FA-H]--843.001799]",
"tests/test_add_parent_mass.py::test_add_parent_mass_not_sufficient_data",
"tests/test_add_parent_mass.py::test_empty_spectrum",
"tests/test_modified_cosine.py::test_modified_cosine_without_precursor_mz",
"tests/test_modified_cosine.py::test_modified_cosine_with_mass_shift_5",
"tests/test_modified_cosine.py::test_modified_cosine_with_mass_shift_5_tolerance_2",
"tests/test_modified_cosine.py::test_modified_cosine_with_mass_shifted_and_unshifted_matches",
"tests/test_modified_cosine.py::test_modified_cosine_order_of_input_spectrums",
"tests/test_modified_cosine.py::test_modified_cosine_with_mass_shift_5_no_matches_expected"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-01 14:16:43+00:00
|
apache-2.0
| 3,772 |
|
matchms__matchms-212
|
diff --git a/matchms/similarity/spectrum_similarity_functions.py b/matchms/similarity/spectrum_similarity_functions.py
index 2cb4657b..381a424f 100644
--- a/matchms/similarity/spectrum_similarity_functions.py
+++ b/matchms/similarity/spectrum_similarity_functions.py
@@ -33,7 +33,7 @@ def collect_peak_pairs(spec1: numpy.ndarray, spec2: numpy.ndarray,
matching_pairs : numpy array
Array of found matching peaks.
"""
- matches = find_matches(spec1, spec2, tolerance, shift)
+ matches = find_matches(spec1[:, 0], spec2[:, 0], tolerance, shift)
idx1 = [x[0] for x in matches]
idx2 = [x[1] for x in matches]
if len(idx1) == 0:
@@ -47,7 +47,7 @@ def collect_peak_pairs(spec1: numpy.ndarray, spec2: numpy.ndarray,
@numba.njit
-def find_matches(spec1: numpy.ndarray, spec2: numpy.ndarray,
+def find_matches(spec1_mz: numpy.ndarray, spec2_mz: numpy.ndarray,
tolerance: float, shift: float = 0) -> List[Tuple[int, int]]:
"""Faster search for matching peaks.
Makes use of the fact that spec1 and spec2 contain ordered peak m/z (from
@@ -55,10 +55,10 @@ def find_matches(spec1: numpy.ndarray, spec2: numpy.ndarray,
Parameters
----------
- spec1:
- Spectrum peaks and intensities as numpy array. Peak mz values must be ordered.
- spec2:
- Spectrum peaks and intensities as numpy array. Peak mz values must be ordered.
+ spec1_mz:
+ Spectrum peak m/z values as numpy array. Peak mz values must be ordered.
+ spec2_mz:
+ Spectrum peak m/z values as numpy array. Peak mz values must be ordered.
tolerance
Peaks will be considered a match when <= tolerance appart.
shift
@@ -72,12 +72,12 @@ def find_matches(spec1: numpy.ndarray, spec2: numpy.ndarray,
"""
lowest_idx = 0
matches = []
- for peak1_idx in range(spec1.shape[0]):
- mz = spec1[peak1_idx, 0]
+ for peak1_idx in range(spec1_mz.shape[0]):
+ mz = spec1_mz[peak1_idx]
low_bound = mz - tolerance
high_bound = mz + tolerance
- for peak2_idx in range(lowest_idx, spec2.shape[0]):
- mz2 = spec2[peak2_idx, 0] + shift
+ for peak2_idx in range(lowest_idx, spec2_mz.shape[0]):
+ mz2 = spec2_mz[peak2_idx] + shift
if mz2 > high_bound:
break
if mz2 < low_bound:
|
matchms/matchms
|
5cf15bcc89128f1bffacd62a8688062edfd8d06e
|
diff --git a/tests/test_spectrum_similarity_functions.py b/tests/test_spectrum_similarity_functions.py
index be6372e8..cf479ec0 100644
--- a/tests/test_spectrum_similarity_functions.py
+++ b/tests/test_spectrum_similarity_functions.py
@@ -59,17 +59,15 @@ def test_collect_peak_pairs_no_matches(numba_compiled):
def test_find_matches_shifted(numba_compiled):
"""Test finding matches with shifted peaks."""
shift = -5.0
- spec1 = numpy.array([[100, 200, 300, 500],
- [0.1, 0.1, 1.0, 1.0]], dtype="float").T
+ spec1_mz = numpy.array([100, 200, 300, 500], dtype="float")
- spec2 = numpy.array([[105, 205.1, 300, 304.99, 500.1],
- [0.1, 0.1, 1.0, 0.8, 1.0]], dtype="float").T
+ spec2_mz = numpy.array([105, 205.1, 300, 304.99, 500.1], dtype="float")
expected_matches = [(0, 0), (1, 1), (2, 3)]
if numba_compiled:
- matches = find_matches(spec1, spec2, tolerance=0.2, shift=shift)
+ matches = find_matches(spec1_mz, spec2_mz, tolerance=0.2, shift=shift)
else:
- matches = find_matches.py_func(spec1, spec2, tolerance=0.2, shift=shift)
+ matches = find_matches.py_func(spec1_mz, spec2_mz, tolerance=0.2, shift=shift)
assert expected_matches == matches, "Expected different matches."
@@ -77,15 +75,13 @@ def test_find_matches_shifted(numba_compiled):
def test_find_matches_no_matches(numba_compiled):
"""Test function for no matching peaks."""
shift = -20.0
- spec1 = numpy.array([[100, 200, 300, 500],
- [0.1, 0.1, 1.0, 1.0]], dtype="float").T
+ spec1_mz = numpy.array([100, 200, 300, 500], dtype="float")
- spec2 = numpy.array([[105, 205.1, 300, 500.1],
- [0.1, 0.1, 1.0, 1.0]], dtype="float").T
+ spec2_mz = numpy.array([105, 205.1, 300, 500.1], dtype="float")
if numba_compiled:
- matches = find_matches(spec1, spec2, tolerance=0.2, shift=shift)
+ matches = find_matches(spec1_mz, spec2_mz, tolerance=0.2, shift=shift)
else:
- matches = find_matches.py_func(spec1, spec2, tolerance=0.2, shift=shift)
+ matches = find_matches.py_func(spec1_mz, spec2_mz, tolerance=0.2, shift=shift)
assert matches == [], "Expected empty list of matches."
|
find_matches function expects 2d array with m/z and intensity, but uses only m/z
**Describe the bug**
The function is being given/passed information which is not necessary and used.
See https://github.com/matchms/matchms/blob/5cf15bcc89128f1bffacd62a8688062edfd8d06e/matchms/similarity/spectrum_similarity_functions.py#L50-87
**Expected behavior**
The function should take only the m/z values of the peaks, or the spectrum objects.
It could also become a class function of the spectrum, which would then ensure the assumption that the arrays are sorted.
**Additional context**
This would make the code more easy to read and concise, given that the Spectrum class already has a sorted list of only m/z values.
|
0.0
|
5cf15bcc89128f1bffacd62a8688062edfd8d06e
|
[
"tests/test_spectrum_similarity_functions.py::test_find_matches_shifted[True]",
"tests/test_spectrum_similarity_functions.py::test_find_matches_shifted[False]",
"tests/test_spectrum_similarity_functions.py::test_find_matches_no_matches[True]",
"tests/test_spectrum_similarity_functions.py::test_find_matches_no_matches[False]"
] |
[
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs_compiled[0.0-expected_pairs0-expected_matches0]",
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs_compiled[-5.0-expected_pairs1-expected_matches1]",
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs[0.0-expected_pairs0-expected_matches0]",
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs[-5.0-expected_pairs1-expected_matches1]",
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs_no_matches[True]",
"tests/test_spectrum_similarity_functions.py::test_collect_peak_pairs_no_matches[False]",
"tests/test_spectrum_similarity_functions.py::test_score_best_matches_compiled[matching_pairs0-expected_score0]",
"tests/test_spectrum_similarity_functions.py::test_score_best_matches_compiled[matching_pairs1-expected_score1]",
"tests/test_spectrum_similarity_functions.py::test_score_best_matches[matching_pairs0-expected_score0]",
"tests/test_spectrum_similarity_functions.py::test_score_best_matches[matching_pairs1-expected_score1]"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-22 16:12:58+00:00
|
apache-2.0
| 3,773 |
|
matchms__matchms-215
|
diff --git a/.github/workflows/CI_build.yml b/.github/workflows/CI_build.yml
index 560f56f3..5da54c30 100644
--- a/.github/workflows/CI_build.yml
+++ b/.github/workflows/CI_build.yml
@@ -257,16 +257,11 @@ jobs:
run: |
export BUILDDIR=$RUNNER_TEMP/matchms/_build/noarch/
[ "$RUNNING_OS" = "Windows" ] && export BUILDDIR=$RUNNER_TEMP\\matchms\\_build\\noarch\\
- conda install \
- --channel bioconda \
- --channel conda-forge \
- --channel nlesc \
- matchms
# Install matchms without nlesc channel to prevent package to be installed from nlesc channel instead of wanted $BUILDDIR channel
conda install \
- --channel bioconda \
+ --channel $BUILDDIR \
--channel conda-forge \
- --channel $BUILDDIR -v \
+ --channel bioconda -v \
matchms
- name: List conda packages
shell: bash -l {0}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d42aaf67..59a1d1ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- `save_as_msp()` function to export spectrums to .msp file [#215](https://github.com/matchms/matchms/pull/215)
+
## [0.8.2] - 2021-03-08
### Added
diff --git a/conda/environment-dev.yml b/conda/environment-dev.yml
index 4f1fa6f0..69db070c 100644
--- a/conda/environment-dev.yml
+++ b/conda/environment-dev.yml
@@ -14,4 +14,14 @@ dependencies:
- rdkit >=2020.03.1
- scipy >=1.4.0
- pip:
- - -e ..[dev]
+ - bump2version
+ - deprecated
+ - lxml
+ - isort>=4.2.5,<5
+ - prospector[with_pyroma]
+ - pytest
+ - pytest-cov
+ - sphinx>=3.0.0,!=3.2.0,!=3.5.0,<4.0.0
+ - sphinx_rtd_theme
+ - sphinxcontrib-apidoc
+ - yapf
diff --git a/matchms/exporting/__init__.py b/matchms/exporting/__init__.py
index cd91b5dc..4de3e38f 100644
--- a/matchms/exporting/__init__.py
+++ b/matchms/exporting/__init__.py
@@ -3,13 +3,15 @@ Functions for exporting mass spectral data
##########################################
Individual :meth:`~matchms.Spectrum`, or lists of :meth:`~matchms.Spectrum`
-can be exported to json or mgf files.
+can be exported to json, mgf, or msp files.
"""
from .save_as_json import save_as_json
from .save_as_mgf import save_as_mgf
+from .save_as_msp import save_as_msp
__all__ = [
"save_as_json",
"save_as_mgf",
+ "save_as_msp",
]
diff --git a/matchms/exporting/save_as_msp.py b/matchms/exporting/save_as_msp.py
new file mode 100644
index 00000000..a440705e
--- /dev/null
+++ b/matchms/exporting/save_as_msp.py
@@ -0,0 +1,68 @@
+import os
+from typing import IO
+from typing import List
+from ..Spectrum import Spectrum
+from ..Spikes import Spikes
+
+
+def save_as_msp(spectra: List[Spectrum], filename: str):
+ """Save spectrum(s) as msp file.
+
+ :py:attr:`~matchms.Spectrum.losses` of spectrum will not be saved.
+
+ Example:
+
+ .. code-block:: python
+
+ import numpy
+ from matchms import Spectrum
+ from matchms.exporting import save_as_msp
+
+ # Create dummy spectrum
+ spectrum = Spectrum(mz=numpy.array([100, 200, 300], dtype="float"),
+ intensities=numpy.array([10, 10, 500], dtype="float"),
+ metadata={"charge": -1,
+ "inchi": '"InChI=1S/C6H12"',
+ "precursor_mz": 222.2})
+
+ # Write spectrum to test file
+ save_as_msp(spectrum, "test.msp")
+
+ Parameters
+ ----------
+ spectra:
+ Expected input are match.Spectrum.Spectrum() objects.
+ filename:
+ Provide filename to save spectrum(s).
+ """
+
+ assert filename.endswith('.msp'), "File extension must be 'msp'."
+
+ spectra = ensure_list(spectra)
+
+ with open(filename, 'w') as outfile:
+ for spectrum in spectra:
+ write_spectrum(spectrum, outfile)
+
+
+def write_spectrum(spectrum: Spectrum, outfile: IO):
+ write_metadata(spectrum.metadata, outfile)
+ write_peaks(spectrum.peaks, outfile)
+ outfile.write(os.linesep)
+
+
+def write_peaks(peaks: Spikes, outfile: IO):
+ for mz, intensity in zip(peaks.mz, peaks.intensities):
+ outfile.write('%s\t%s\n' % (str(mz), str(intensity)))
+
+
+def write_metadata(metadata: dict, outfile: IO):
+ for key, value in metadata.items():
+ outfile.write('%s: %s\n' % (key.upper(), str(value)))
+
+
+def ensure_list(spectra) -> List[Spectrum]:
+ if not isinstance(spectra, list):
+ # Assume that input was single Spectrum
+ spectra = [spectra]
+ return spectra
|
matchms/matchms
|
5497b7363af1d555b8d1ab0162e01458ac7fbf53
|
diff --git a/tests/test_save_as_msp.py b/tests/test_save_as_msp.py
new file mode 100644
index 00000000..129b6c40
--- /dev/null
+++ b/tests/test_save_as_msp.py
@@ -0,0 +1,108 @@
+import os
+import tempfile
+from typing import List
+import numpy
+import pytest
+from matchms import Spectrum
+from matchms.exporting import save_as_msp
+from matchms.importing import load_from_msp
+
+
[email protected]
+def none_spectrum():
+ return None
+
+
[email protected]
+def spectrum():
+ return Spectrum(mz=numpy.array([100, 200, 290, 490, 510], dtype="float"),
+ intensities=numpy.array([0.1, 0.2, 1.0, 0.3, 0.4], dtype="float"))
+
+
[email protected](params=["rcx_gc-ei_ms_20201028_perylene.msp", "MoNA-export-GC-MS-first10.msp"])
+def data(request):
+ module_root = os.path.join(os.path.dirname(__file__), "..")
+ spectrums_file = os.path.join(module_root, "tests", request.param)
+ spectra = load_from_msp(spectrums_file)
+ return list(spectra)
+
+
[email protected]_fixture
+def filename():
+ with tempfile.TemporaryDirectory() as temp_dir:
+ filename = os.path.join(temp_dir, "test.msp")
+ yield filename
+
+
+def test_spectrum_none_exception(none_spectrum, filename):
+ """ Test for exception being thrown if the spectrum to be saved. """
+ with pytest.raises(AttributeError) as exception:
+ save_as_msp(none_spectrum, filename)
+
+ message = exception.value.args[0]
+ assert message == "'NoneType' object has no attribute 'metadata'"
+
+
+def test_wrong_filename_exception():
+ """ Test for exception being thrown if output file doesn't end with .msp. """
+ with tempfile.TemporaryDirectory() as temp_dir:
+ filename = os.path.join(temp_dir, "test.mzml")
+
+ with pytest.raises(AssertionError) as exception:
+ save_as_msp(None, filename)
+
+ message = exception.value.args[0]
+ assert message == "File extension must be 'msp'."
+
+
+# Using tmp_path fixture from pytest: https://docs.pytest.org/en/stable/tmpdir.html#the-tmp-path-fixture
+def test_file_exists_single_spectrum(spectrum, filename):
+ """ Test checking if the file is created. """
+ save_as_msp(spectrum, filename)
+
+ assert os.path.isfile(filename)
+
+
+def test_stores_all_spectra(filename, data):
+ """ Test checking if all spectra contained in the original file are stored
+ and loaded back in properly. """
+ spectra = save_and_reload_spectra(filename, data)
+
+ assert len(spectra) == len(data)
+
+
+def test_have_metadata(filename, data):
+ """ Test checking of all metadate is stored correctly. """
+ spectra = save_and_reload_spectra(filename, data)
+
+ assert len(spectra) == len(data)
+
+ for actual, expected in zip(spectra, data):
+ assert actual.metadata == expected.metadata
+
+
+def test_have_peaks(filename, data):
+ """ Test checking if all peaks are stored correctly. """
+ spectra = save_and_reload_spectra(filename, data)
+
+ assert len(spectra) == len(data)
+
+ for actual, expected in zip(spectra, data):
+ assert actual.peaks == expected.peaks
+
+
+def save_and_reload_spectra(filename, spectra: List[Spectrum]):
+ """ Utility function to save spectra to msp and load them again.
+
+ Params:
+ -------
+ spectra: Spectra objects to store
+
+ Returns:
+ --------
+ reloaded_spectra: Spectra loaded from saved msp file.
+ """
+
+ save_as_msp(spectra, filename)
+ reloaded_spectra = list(load_from_msp(filename))
+ return reloaded_spectra
|
Would be nice to have a save_as_msp module
Hi All, Hi @florian-huber
matchms is a really nice tools for the community, Thanks.
I would like to know if you plan to create a save_as_msp module?
I'm asking because I'm using NIST database a lot and it would be nice to be able to create MSP database from GNPS/MSHUB MGF outputs.
Best
Yann
|
0.0
|
5497b7363af1d555b8d1ab0162e01458ac7fbf53
|
[
"tests/test_save_as_msp.py::test_spectrum_none_exception",
"tests/test_save_as_msp.py::test_wrong_filename_exception",
"tests/test_save_as_msp.py::test_file_exists_single_spectrum",
"tests/test_save_as_msp.py::test_stores_all_spectra[rcx_gc-ei_ms_20201028_perylene.msp]",
"tests/test_save_as_msp.py::test_stores_all_spectra[MoNA-export-GC-MS-first10.msp]",
"tests/test_save_as_msp.py::test_have_metadata[rcx_gc-ei_ms_20201028_perylene.msp]",
"tests/test_save_as_msp.py::test_have_metadata[MoNA-export-GC-MS-first10.msp]",
"tests/test_save_as_msp.py::test_have_peaks[rcx_gc-ei_ms_20201028_perylene.msp]",
"tests/test_save_as_msp.py::test_have_peaks[MoNA-export-GC-MS-first10.msp]"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-30 12:42:41+00:00
|
apache-2.0
| 3,774 |
|
matchms__matchms-223
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 69fc630d..76c8e954 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- `add_precursor_mz()` filter now also checks for metadata in keys `precursormz` and `precursor_mass` [#223](https://github.com/matchms/matchms/pull/223)
- `load_from_msp()` now handles .msp files containing multiple peaks per line separated by `;` [#221](https://github.com/matchms/matchms/pull/221)
## [0.8.2] - 2021-03-08
diff --git a/matchms/filtering/add_precursor_mz.py b/matchms/filtering/add_precursor_mz.py
index 9e402764..2022653f 100644
--- a/matchms/filtering/add_precursor_mz.py
+++ b/matchms/filtering/add_precursor_mz.py
@@ -1,6 +1,21 @@
+from typing import Iterable
+from typing import TypeVar
from ..typing import SpectrumType
+_T = TypeVar('_T')
+_accepted_keys = ["precursor_mz", "precursormz", "precursor_mass"]
+_accepted_types = (float, str, int)
+_convertible_types = (str, int)
+
+
+def get_first_common_element(first: Iterable[_T], second: Iterable[_T]) -> _T:
+ """ Get first common element from two lists.
+ Returns 'None' if there are no common elements.
+ """
+ return next((item for item in first if item in second), None)
+
+
def add_precursor_mz(spectrum_in: SpectrumType) -> SpectrumType:
"""Add precursor_mz to correct field and make it a float.
@@ -12,10 +27,19 @@ def add_precursor_mz(spectrum_in: SpectrumType) -> SpectrumType:
spectrum = spectrum_in.clone()
- if isinstance(spectrum.get("precursor_mz", None), str):
- spectrum.set("precursor_mz", float(spectrum.get("precursor_mz").strip()))
- elif spectrum.get("precursor_mz", None) is None:
- pepmass = spectrum.get("pepmass", None)
+ precursor_mz_key = get_first_common_element(spectrum.metadata.keys(), _accepted_keys)
+ precursor_mz = spectrum.get(precursor_mz_key)
+
+ if isinstance(precursor_mz, _accepted_types):
+ if isinstance(precursor_mz, str):
+ try:
+ precursor_mz = float(precursor_mz.strip())
+ except ValueError:
+ print("%s can't be converted to float.", precursor_mz)
+ return spectrum
+ spectrum.set("precursor_mz", float(precursor_mz))
+ elif precursor_mz is None:
+ pepmass = spectrum.get("pepmass")
if pepmass is not None and isinstance(pepmass[0], float):
spectrum.set("precursor_mz", pepmass[0])
else:
|
matchms/matchms
|
7d9a1620e78457e5a916d42abef7fc650b3e3109
|
diff --git a/tests/test_add_precursor_mz.py b/tests/test_add_precursor_mz.py
index 920bd282..e644159b 100644
--- a/tests/test_add_precursor_mz.py
+++ b/tests/test_add_precursor_mz.py
@@ -1,4 +1,5 @@
import numpy
+import pytest
from matchms import Spectrum
from matchms.filtering import add_precursor_mz
@@ -45,18 +46,28 @@ def test_add_precursor_mz_only_pepmass_present():
assert spectrum.get("precursor_mz") == 444.0, "Expected different precursor_mz."
-def test_add_precursor_mz_no_precursor_mz():
[email protected]("key, value, expected", [
+ ["precursor_mz", "444.0", 444.0],
+ ["precursormz", "15.6", 15.6],
+ ["precursormz", 15.0, 15.0],
+ ["precursor_mass", "17.887654", 17.887654],
+ ["precursor_mass", "N/A", None],
+ ["precursor_mass", "test", None],
+ ["pepmass", (33.89, 50), 33.89],
+ ["pepmass", "None", None],
+ ["pepmass", None, None]])
+def test_add_precursor_mz_no_precursor_mz(key, value, expected):
"""Test if precursor_mz is correctly derived if "precursor_mz" is str."""
mz = numpy.array([], dtype='float')
intensities = numpy.array([], dtype='float')
- metadata = {"precursor_mz": "444.0"}
+ metadata = {key: value}
spectrum_in = Spectrum(mz=mz,
intensities=intensities,
metadata=metadata)
spectrum = add_precursor_mz(spectrum_in)
- assert spectrum.get("precursor_mz") == 444.0, "Expected different precursor_mz."
+ assert spectrum.get("precursor_mz") == expected, "Expected different precursor_mz."
def test_empty_spectrum():
|
Add more possible field names to add precursor mz values from metadata
**Problem**
The code below currently only allows precursor m/z related data in `pepmass` or `precursor_mz` while fields such as `percursormz` etc. are ignored.
**Solution**
Expand the dictionary of allowed keys that can be used to store the precursor m/z values in the file's metadata.
https://github.com/matchms/matchms/blob/04af51cec2eedf6ca2c398b44b614e387e309f16/matchms/filtering/add_precursor_mz.py#L4-L24
|
0.0
|
7d9a1620e78457e5a916d42abef7fc650b3e3109
|
[
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursormz-15.6-15.6]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursormz-15.0-15.0]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursor_mass-17.887654-17.887654]"
] |
[
"tests/test_add_precursor_mz.py::test_add_precursor_mz",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_masses",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_only_pepmass_present",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursor_mz-444.0-444.0]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursor_mass-N/A-None]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[precursor_mass-test-None]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[pepmass-value6-33.89]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[pepmass-None-None0]",
"tests/test_add_precursor_mz.py::test_add_precursor_mz_no_precursor_mz[pepmass-None-None1]",
"tests/test_add_precursor_mz.py::test_empty_spectrum"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-13 14:22:14+00:00
|
apache-2.0
| 3,775 |
|
matchms__matchms-265
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95f5f529..8d688ee0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,11 +11,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Spectrum()` objects now also allows generating hashes, e.g. `hash(spectrum)` [#259](https://github.com/matchms/matchms/pull/259)
- `Spectrum()` objects can generate `.spectrum_hash()` and `.metadata_hash()` to track changes to peaks or metadata [#259](https://github.com/matchms/matchms/pull/259)
-- 'load_from_mf()` now accepts both a path to a mgf file or a file-like object from a preloaded MGF file [#258](https://github.com/matchms/matchms/pull/258)
-
+- `load_from_mgf()` now accepts both a path to a mgf file or a file-like object from a preloaded MGF file [#258](https://github.com/matchms/matchms/pull/258)
+- Added `add_retention` filters with function `add_retention_time()` and `add_retention_index()` [#265](https://github.com/matchms/matchms/pull/265)
### Changed
- Code linting triggered by pylint update [#257](https://github.com/matchms/matchms/pull/257)
+- Refactored `add_parent_mass()` filter can now also handle missing charge entries (if ionmode is known) [#252](https://github.com/matchms/matchms/pull/252)
## [0.9.2] - 2021-07-20
diff --git a/matchms/filtering/__init__.py b/matchms/filtering/__init__.py
index 249386d1..93ccdaa9 100644
--- a/matchms/filtering/__init__.py
+++ b/matchms/filtering/__init__.py
@@ -41,6 +41,8 @@ from .add_fingerprint import add_fingerprint
from .add_losses import add_losses
from .add_parent_mass import add_parent_mass
from .add_precursor_mz import add_precursor_mz
+from .add_retention import add_retention_index
+from .add_retention import add_retention_time
from .clean_compound_name import clean_compound_name
from .correct_charge import correct_charge
from .default_filters import default_filters
@@ -77,6 +79,8 @@ __all__ = [
"add_losses",
"add_parent_mass",
"add_precursor_mz",
+ "add_retention_index",
+ "add_retention_time",
"clean_compound_name",
"correct_charge",
"default_filters",
diff --git a/matchms/filtering/add_parent_mass.py b/matchms/filtering/add_parent_mass.py
index 0f02745c..e7b3bd81 100644
--- a/matchms/filtering/add_parent_mass.py
+++ b/matchms/filtering/add_parent_mass.py
@@ -32,28 +32,56 @@ def add_parent_mass(spectrum_in: SpectrumType, estimate_from_adduct: bool = True
spectrum = spectrum_in.clone()
adducts_dict = load_adducts_dict()
- if spectrum.get("parent_mass", None) is None or overwrite_existing_entry:
- parent_mass = None
- charge = spectrum.get("charge")
- adduct = clean_adduct(spectrum.get("adduct"))
- precursor_mz = spectrum.get("precursor_mz", None)
- if precursor_mz is None:
- print("Missing precursor m/z to derive parent mass.")
- return spectrum
-
- if estimate_from_adduct and adduct in adducts_dict:
- multiplier = adducts_dict[adduct]["mass_multiplier"]
- correction_mass = adducts_dict[adduct]["correction_mass"]
- parent_mass = precursor_mz * multiplier - correction_mass
-
- if parent_mass is None and charge is not None and charge != 0:
- # Otherwise assume adduct of shape [M+xH] or [M-xH]
- protons_mass = PROTON_MASS * charge
- precursor_mass = precursor_mz * abs(charge)
- parent_mass = precursor_mass - protons_mass
-
- if parent_mass is None:
- print("Not sufficient spectrum metadata to derive parent mass.")
- else:
- spectrum.set("parent_mass", float(parent_mass))
+ if spectrum.get("parent_mass", None) and not overwrite_existing_entry:
+ return spectrum
+
+ parent_mass = None
+ charge = _get_charge(spectrum)
+ adduct = clean_adduct(spectrum.get("adduct"))
+ precursor_mz = spectrum.get("precursor_mz", None)
+ if precursor_mz is None:
+ print("Missing precursor m/z to derive parent mass.")
+ return spectrum
+
+ if estimate_from_adduct and (adduct in adducts_dict):
+ multiplier = adducts_dict[adduct]["mass_multiplier"]
+ correction_mass = adducts_dict[adduct]["correction_mass"]
+ parent_mass = precursor_mz * multiplier - correction_mass
+
+ if (parent_mass is None) and _is_valid_charge(charge):
+ # Assume adduct of shape [M+xH] or [M-xH]
+ protons_mass = PROTON_MASS * charge
+ precursor_mass = precursor_mz * abs(charge)
+ parent_mass = precursor_mass - protons_mass
+
+ if parent_mass is None:
+ print("Not sufficient spectrum metadata to derive parent mass.")
+ else:
+ spectrum.set("parent_mass", float(parent_mass))
return spectrum
+
+
+def _is_valid_charge(charge):
+ return (charge is not None) and (charge != 0)
+
+
+def _get_charge(spectrum):
+ """Get charge from `Spectrum()` object.
+ In case no valid charge is found, guess +1 or -1 based on ionmode.
+ Else return 0.
+ """
+ charge = spectrum.get("charge")
+ if _is_valid_charge(charge):
+ return charge
+ if spectrum.get('ionmode') == "positive":
+ print("Missing charge entry, but positive ionmode detected. "
+ "Consider prior run of `correct_charge()` filter.")
+ return 1
+ if spectrum.get('ionmode') == "negative":
+ print("Missing charge entry, but negative ionmode detected. "
+ "Consider prior run of `correct_charge()` filter.")
+ return -1
+
+ print("Missing charge and ionmode entries. "
+ "Consider prior run of `derive_ionmode()` and `correct_charge()` filters.")
+ return 0
diff --git a/matchms/filtering/add_precursor_mz.py b/matchms/filtering/add_precursor_mz.py
index 2022653f..6aeb8479 100644
--- a/matchms/filtering/add_precursor_mz.py
+++ b/matchms/filtering/add_precursor_mz.py
@@ -1,19 +1,9 @@
-from typing import Iterable
-from typing import TypeVar
+from matchms.utils import get_first_common_element
from ..typing import SpectrumType
-_T = TypeVar('_T')
_accepted_keys = ["precursor_mz", "precursormz", "precursor_mass"]
_accepted_types = (float, str, int)
-_convertible_types = (str, int)
-
-
-def get_first_common_element(first: Iterable[_T], second: Iterable[_T]) -> _T:
- """ Get first common element from two lists.
- Returns 'None' if there are no common elements.
- """
- return next((item for item in first if item in second), None)
def add_precursor_mz(spectrum_in: SpectrumType) -> SpectrumType:
diff --git a/matchms/filtering/add_retention.py b/matchms/filtering/add_retention.py
new file mode 100644
index 00000000..f5b38c5e
--- /dev/null
+++ b/matchms/filtering/add_retention.py
@@ -0,0 +1,108 @@
+from typing import Any
+from typing import List
+from typing import Optional
+from matchms.utils import filter_none
+from matchms.utils import get_common_keys
+from ..typing import SpectrumType
+
+
+_retention_time_keys = ["retention_time", "retentiontime", "rt", "scan_start_time", "RT_Query"]
+_retention_index_keys = ["retention_index", "retentionindex", "ri"]
+
+
+def safe_store_value(spectrum: SpectrumType, value: Any, target_key: str) -> SpectrumType:
+ """Helper function to safely store a value in the target key without throwing an exception, but storing 'None' instead.
+
+ Args:
+ spectrum (SpectrumType): Spectrum to which to add 'value' in 'target_key'.
+ value (Any): Value to parse into 'target_key'.
+ target_key (str): Name of the key in which to store the value.
+
+ Returns:
+ SpectrumType: Spectrum with added key.
+ """
+ if value is not None: # one of accepted keys is present
+ value = safe_convert_to_float(value)
+ spectrum.set(target_key, value)
+ return spectrum
+
+
+def safe_convert_to_float(value: Any) -> Optional[float]:
+ """Safely convert value to float. Return 'None' on failure.
+
+ Args:
+ value (Any): Object to convert to float.
+
+ Returns:
+ Optional[float]: Converted float value or 'None' if conversion is not possible.
+ """
+ if isinstance(value, list) and len(value) == 1:
+ value = value[0]
+ try:
+ value = float(value)
+ rt = value if value >= 0 else None # discard negative RT values
+ except ValueError:
+ print(f"{value} can't be converted to float.")
+ rt = None
+ return rt
+
+
+def _add_retention(spectrum: SpectrumType, target_key: str, accepted_keys: List[str]) -> SpectrumType:
+ """Add value from one of accepted keys to target key.
+
+ Args:
+ spectrum (SpectrumType): Spectrum from which to read the values.
+ target_key (str): Key under which to store the value.
+ accepted_keys (List[str]): List of accepted keys from which a value will be read (in order).
+
+ Returns:
+ SpectrumType: Spectrum with value from first accepted key stored under target_key.
+ """
+ common_keys = get_common_keys(spectrum.metadata.keys(), accepted_keys)
+ values_for_keys = filter_none([spectrum.get(key) for key in common_keys])
+ values = list(map(safe_convert_to_float, values_for_keys))
+ value = next(filter_none(values), None)
+
+ spectrum = safe_store_value(spectrum, value, target_key)
+ return spectrum
+
+
+def add_retention_time(spectrum_in: SpectrumType) -> SpectrumType:
+ """Add retention time information to the 'retention_time' key as float.
+ Negative values and those not convertible to a float result in 'retention_time'
+ being 'None'.
+
+ Args:
+ spectrum_in (SpectrumType): Spectrum with retention time information.
+
+ Returns:
+ SpectrumType: Spectrum with harmonized retention time information.
+ """
+ if spectrum_in is None:
+ return None
+
+ spectrum = spectrum_in.clone()
+
+ target_key = "retention_time"
+ spectrum = _add_retention(spectrum, target_key, _retention_time_keys)
+ return spectrum
+
+
+def add_retention_index(spectrum_in: SpectrumType) -> SpectrumType:
+ """Add retention index into 'retention_index' key if present.
+
+
+ Args:
+ spectrum_in (SpectrumType): Spectrum with RI information.
+
+ Returns:
+ SpectrumType: Spectrum with RI info stored under 'retention_index'.
+ """
+ if spectrum_in is None:
+ return None
+
+ spectrum = spectrum_in.clone()
+
+ target_key = "retention_index"
+ spectrum = _add_retention(spectrum, target_key, _retention_index_keys)
+ return spectrum
diff --git a/matchms/utils.py b/matchms/utils.py
index c12897a5..6bc394c4 100644
--- a/matchms/utils.py
+++ b/matchms/utils.py
@@ -1,4 +1,6 @@
import re
+from typing import Iterable
+from typing import List
from typing import Optional
import numpy
from .importing import load_adducts_dict
@@ -303,3 +305,35 @@ def clean_adduct(adduct: str) -> str:
adduct_cleaned = adduct_core[:-len(adduct_charge)] + "]" + adduct_charge
return adduct_conversion(adduct_cleaned)
+
+
+def get_first_common_element(first: Iterable[str], second: Iterable[str]) -> str:
+ """ Get first common element from two lists.
+ Returns 'None' if there are no common elements.
+ """
+ return next((item for item in first if item in second), None)
+
+
+def get_common_keys(first: List[str], second: List[str]) -> List[str]:
+ """Get common elements of two sets of strings in a case insensitive way.
+
+ Args:
+ first (List[str]): First list of strings.
+ second (List[str]): List of strings to search for matches.
+
+ Returns:
+ List[str]: List of common elements without regarding case of first list.
+ """
+ return [value for value in first if value in second or value.lower() in second]
+
+
+def filter_none(iterable: Iterable) -> Iterable:
+ """Filter iterable to remove 'None' elements.
+
+ Args:
+ iterable (Iterable): Iterable to filter.
+
+ Returns:
+ Iterable: Filtered iterable.
+ """
+ return filter(lambda x: x is not None, iterable)
|
matchms/matchms
|
374df6359b0d3c1456540c1cb42e91d3e13aba46
|
diff --git a/tests/test_add_parent_mass.py b/tests/test_add_parent_mass.py
index ca411603..3fb5d5f7 100644
--- a/tests/test_add_parent_mass.py
+++ b/tests/test_add_parent_mass.py
@@ -1,6 +1,7 @@
import numpy
import pytest
from matchms import Spectrum
+from matchms.constants import PROTON_MASS
from matchms.filtering import add_parent_mass
@@ -90,7 +91,9 @@ def test_add_parent_mass_using_adduct(adduct, expected):
assert isinstance(spectrum.get("parent_mass"), float), "Expected parent mass to be float."
-def test_add_parent_mass_overwrite():
[email protected]("overwrite, expected", [(True, 442.992724),
+ (False, 443.0)])
+def test_add_parent_mass_overwrite(overwrite, expected):
"""Test if parent mass is replaced by newly calculated value."""
mz = numpy.array([], dtype='float')
intensities = numpy.array([], dtype='float')
@@ -102,9 +105,9 @@ def test_add_parent_mass_overwrite():
intensities=intensities,
metadata=metadata)
- spectrum = add_parent_mass(spectrum_in, overwrite_existing_entry=True)
+ spectrum = add_parent_mass(spectrum_in, overwrite_existing_entry=overwrite)
- assert numpy.allclose(spectrum.get("parent_mass"), 442.992724, atol=1e-4), \
+ assert numpy.allclose(spectrum.get("parent_mass"), expected, atol=1e-4), \
"Expected parent mass to be replaced by new value."
@@ -128,3 +131,21 @@ def test_empty_spectrum():
spectrum = add_parent_mass(spectrum_in)
assert spectrum is None, "Expected different handling of None spectrum."
+
+
[email protected]("ionmode, expected", [("positive", 444.0 - PROTON_MASS),
+ ("negative", 444.0 + PROTON_MASS)])
+def test_use_of_ionmode(ionmode, expected):
+ """Test when there is no charge given, than the ionmode
+ is used to derive parent mass."""
+ mz = numpy.array([], dtype='float')
+ intensities = numpy.array([], dtype='float')
+ metadata = {"precursor_mz": 444.0, "ionmode": ionmode}
+ spectrum_in = Spectrum(mz=mz,
+ intensities=intensities,
+ metadata=metadata)
+
+ spectrum = add_parent_mass(spectrum_in)
+
+ assert spectrum.get("parent_mass") == expected, \
+ "Expected a different parent_mass"
diff --git a/tests/test_add_retention.py b/tests/test_add_retention.py
new file mode 100644
index 00000000..452f91f8
--- /dev/null
+++ b/tests/test_add_retention.py
@@ -0,0 +1,66 @@
+import numpy
+import pytest
+from matchms import Spectrum
+from matchms.filtering import add_retention_index
+from matchms.filtering import add_retention_time
+
+
[email protected]("metadata, expected", [
+ [{"retention_time": 100.0}, 100.0],
+ [{"retention_time": "NA"}, None],
+ [{"retention_time": "100.0"}, 100.0],
+ [{"retentiontime": 200}, 200.0],
+ [{"retentiontime": -1}, None],
+ [{"retentiontime": "-1"}, None],
+ [{"rt": 200}, 200.0],
+ [{"RT": 200}, 200.0],
+ [{"RT_Query": 200}, 200.0],
+ [{"nothing": "200"}, None],
+ [{'scan_start_time': 0.629566}, 0.629566],
+ [{'scan_start_time': [0.629566]}, 0.629566],
+ [{"rt": "None", "retentiontime": 12.17}, 12.17]
+])
+def test_add_retention_time(metadata, expected):
+ spectrum_in = Spectrum(mz=numpy.array(
+ [], "float"), intensities=numpy.array([], "float"), metadata=metadata)
+
+ spectrum = add_retention_time(spectrum_in)
+ actual = spectrum.get("retention_time")
+
+ if expected is None:
+ assert actual is None
+ else:
+ assert actual == expected and isinstance(actual, float)
+
+
[email protected]("metadata, expected", [
+ [{"retention_index": 100.0}, 100.0],
+ [{"retention_index": "NA"}, None],
+ [{"retention_index": "100.0"}, 100.0],
+ [{"retentionindex": 200}, 200.0],
+ [{"retentionindex": -1}, None],
+ [{"retentionindex": "-1"}, None],
+ [{"ri": 200}, 200.0],
+ [{"RI": 200}, 200.0],
+ [{"nothing": "200"}, None]
+])
+def test_add_retention_index(metadata, expected):
+ spectrum_in = Spectrum(mz=numpy.array(
+ [], "float"), intensities=numpy.array([], "float"), metadata=metadata)
+
+ spectrum = add_retention_index(spectrum_in)
+ actual = spectrum.get("retention_index")
+
+ if expected is None:
+ assert actual is None
+ else:
+ assert actual == expected and isinstance(actual, float)
+
+
+def test_empty_spectrum():
+ spectrum_in = None
+ spectrum = add_retention_time(spectrum_in)
+ assert spectrum is None, "Expected different handling of None spectrum."
+
+ spectrum = add_retention_index(spectrum_in)
+ assert spectrum is None, "Expected different handling of None spectrum."
|
Add retention data filters
As discussed in #251 , adding RI and RT filters to clean the metadata in the spectrum object would be good.
One additional idea would be for the retention time filter to allow passing a conversion factor which converts the RT to seconds and use this as a canonical unit for RT?
|
0.0
|
374df6359b0d3c1456540c1cb42e91d3e13aba46
|
[
"tests/test_add_parent_mass.py::test_add_parent_mass_pepmass_no_precursormz",
"tests/test_add_parent_mass.py::test_add_parent_mass_no_precursormz",
"tests/test_add_parent_mass.py::test_add_parent_mass_precursormz_zero_charge",
"tests/test_add_parent_mass.py::test_add_parent_mass_precursormz",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[M+2Na-H]+-399.02884]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[M+H+NH4]2+-212.47945]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[[2M+FA-H]--843.001799]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[M+H-442.992724]",
"tests/test_add_parent_mass.py::test_add_parent_mass_using_adduct[M+H-H2O-461.003289]",
"tests/test_add_parent_mass.py::test_add_parent_mass_overwrite[True-442.992724]",
"tests/test_add_parent_mass.py::test_add_parent_mass_overwrite[False-443.0]",
"tests/test_add_parent_mass.py::test_add_parent_mass_not_sufficient_data",
"tests/test_add_parent_mass.py::test_empty_spectrum",
"tests/test_add_parent_mass.py::test_use_of_ionmode[positive-442.9927235480092]",
"tests/test_add_parent_mass.py::test_use_of_ionmode[negative-445.0072764519908]",
"tests/test_add_retention.py::test_add_retention_time[metadata0-100.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata1-None]",
"tests/test_add_retention.py::test_add_retention_time[metadata2-100.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata3-200.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata4-None]",
"tests/test_add_retention.py::test_add_retention_time[metadata5-None]",
"tests/test_add_retention.py::test_add_retention_time[metadata6-200.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata7-200.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata8-200.0]",
"tests/test_add_retention.py::test_add_retention_time[metadata9-None]",
"tests/test_add_retention.py::test_add_retention_time[metadata10-0.629566]",
"tests/test_add_retention.py::test_add_retention_time[metadata11-0.629566]",
"tests/test_add_retention.py::test_add_retention_time[metadata12-12.17]",
"tests/test_add_retention.py::test_add_retention_index[metadata0-100.0]",
"tests/test_add_retention.py::test_add_retention_index[metadata1-None]",
"tests/test_add_retention.py::test_add_retention_index[metadata2-100.0]",
"tests/test_add_retention.py::test_add_retention_index[metadata3-200.0]",
"tests/test_add_retention.py::test_add_retention_index[metadata4-None]",
"tests/test_add_retention.py::test_add_retention_index[metadata5-None]",
"tests/test_add_retention.py::test_add_retention_index[metadata6-200.0]",
"tests/test_add_retention.py::test_add_retention_index[metadata7-200.0]",
"tests/test_add_retention.py::test_add_retention_index[metadata8-None]",
"tests/test_add_retention.py::test_empty_spectrum"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-16 10:46:07+00:00
|
apache-2.0
| 3,776 |
|
matchms__matchms-349
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d41be843..d43aec48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `Spectrum` objects now also have `.mz` and `.intensities` properties [#339](https://github.com/matchms/matchms/pull/339)
+- `SimilarityNetwork`: similarity-network graphs can now be exported to [cyjs](http://manual.cytoscape.org/en/stable/index.html),
+[gexf](http://gexf.net/schema.html), [gml](https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1),
+and node-link JSON formats [#349](https://github.com/matchms/matchms/pull/349)
### Changed
- metadata filtering: made prefilter check for SMILES and InChI more lenient, eventually resulting in longer runtimes but more accurate checks [#337](https://github.com/matchms/matchms/pull/337)
diff --git a/matchms/networking/SimilarityNetwork.py b/matchms/networking/SimilarityNetwork.py
index 4be05392..72ead9da 100644
--- a/matchms/networking/SimilarityNetwork.py
+++ b/matchms/networking/SimilarityNetwork.py
@@ -1,3 +1,4 @@
+import json
from typing import Optional
import networkx as nx
import numpy
@@ -6,7 +7,7 @@ from .networking_functions import get_top_hits
class SimilarityNetwork:
- """Create a spectal network from spectrum similarities.
+ """Create a spectral network from spectrum similarities.
For example
@@ -54,7 +55,7 @@ class SimilarityNetwork:
Parameters
----------
identifier_key
- Metadata key for unique intentifier for each spectrum in scores.
+ Metadata key for unique identifier for each spectrum in scores.
Will also be used for the naming the network nodes. Default is 'spectrum_id'.
top_n
Consider edge between spectrumA and spectrumB if score falls into
@@ -68,7 +69,7 @@ class SimilarityNetwork:
Important side note: The max_links restriction is strict which means that
if scores around max_links are equal still only max_links will be added
which can results in some random variations (sorting spectra with equal
- scores restuls in a random order of such elements).
+ scores results in a random order of such elements).
score_cutoff
Threshold for given similarities. Edges/Links will only be made for
similarities > score_cutoff. Default = 0.7.
@@ -152,6 +153,35 @@ class SimilarityNetwork:
msnet.remove_nodes_from(list(nx.isolates(msnet)))
self.graph = msnet
+ def export_to_file(self, filename: str, graph_format: str = "graphml"):
+ """
+ Save the network to a file with chosen format.
+
+ Parameters
+ ----------
+ filename
+ Path to file to write to.
+ graph_format
+ Format, in which to store the network graph. Supported formats are: "cyjs", "gexf", "gml", "graphml", "json".
+ Default is "graphml".
+ """
+ if not self.graph:
+ raise ValueError("No network found. Make sure to first run .create_network() step")
+
+ writer = self._generate_writer(graph_format)
+ writer(filename)
+
+ def _generate_writer(self, graph_format: str):
+ writer = {"cyjs": self._export_to_cyjs,
+ "gexf": self._export_to_gexf,
+ "gml": self._export_to_gml,
+ "graphml": self.export_to_graphml,
+ "json": self._export_to_node_link_json}
+
+ assert graph_format in writer, "Format not supported.\n" \
+ "Please use one of supported formats: 'cyjs', 'gexf', 'gml', 'graphml', 'json'"
+ return writer[graph_format]
+
def export_to_graphml(self, filename: str):
"""Save the network as .graphml file.
@@ -161,6 +191,37 @@ class SimilarityNetwork:
Specify filename for exporting the graph.
"""
- if not self.graph:
- raise ValueError("No network found. Make sure to first run .create_network() step")
nx.write_graphml_lxml(self.graph, filename)
+
+ def _export_to_cyjs(self, filename: str):
+ """Save the network in cyjs format."""
+ graph = nx.cytoscape_data(self.graph)
+ return self._write_to_json(graph, filename)
+
+ def _export_to_node_link_json(self, filename: str):
+ """Save the network in node-link format."""
+ graph = nx.node_link_data(self.graph)
+ return self._write_to_json(graph, filename)
+
+ @staticmethod
+ def _write_to_json(graph: dict, filename: str):
+ """Save the network as JSON file.
+
+ Parameters
+ ----------
+ graph
+ JSON-dictionary type graph to save.
+ filename
+ Specify filename for exporting the graph.
+
+ """
+ with open(filename, "w", encoding="utf-8") as file:
+ json.dump(graph, file)
+
+ def _export_to_gexf(self, filename: str):
+ """Save the network as .gexf file."""
+ nx.write_gexf(self.graph, filename)
+
+ def _export_to_gml(self, filename: str):
+ """Save the network as .gml file."""
+ nx.write_gml(self.graph, filename)
|
matchms/matchms
|
e780a91f9dfb7ba975f0e8e2732f800ee122163f
|
diff --git a/tests/test_SimilarityNetwork.py b/tests/test_SimilarityNetwork.py
index 9e5787a6..bf86a88e 100644
--- a/tests/test_SimilarityNetwork.py
+++ b/tests/test_SimilarityNetwork.py
@@ -7,11 +7,17 @@ from matchms.networking import SimilarityNetwork
from matchms.similarity import FingerprintSimilarity, ModifiedCosine
[email protected]
-def filename():
[email protected](params=["cyjs", "gexf", "gml", "graphml", "json"])
+def graph_format(request):
+ yield request.param
+
+
[email protected]()
+def filename(graph_format):
+ filename = f"test.{graph_format}"
with tempfile.TemporaryDirectory() as temp_dir:
- filename = os.path.join(temp_dir, "test.graphml")
- yield filename
+ filepath = os.path.join(temp_dir, filename)
+ yield filepath
def create_dummy_spectrums():
@@ -127,15 +133,15 @@ def test_create_network_symmetric_modified_cosine():
assert len(edges_list) == 28, "Expected different number of edges"
-def test_create_network_export_to_graphml(filename):
- """Test creating a graph from a symmetric Scores object using ModifiedCosine"""
+def test_create_network_export_to_file(filename, graph_format):
+ """Test creating a graph file from a symmetric Scores object using ModifiedCosine"""
cutoff = 0.7
scores = create_dummy_scores_symmetric_modified_cosine()
msnet = SimilarityNetwork(score_cutoff=cutoff)
msnet.create_network(scores)
- msnet.export_to_graphml(filename)
+ msnet.export_to_file(filename, graph_format)
- assert os.path.isfile(filename), "graphml file not found"
+ assert os.path.isfile(filename), "network file not found"
def test_create_network_symmetric_higher_cutoff():
|
Add `.cyjs` export to networking module
**Is your feature request related to a problem? Please describe.**
Currently only `.graphml` output is supported, which is not supported by the cytoscape Galaxy plugin.
**Describe the solution you'd like**
Add the option to export to `.cyjs` using the networkx package to the Networking module.
**Any good starting points?**
[Do you know of any alternative solutions or do you have some helping code/links at hand?
](https://networkx.org/documentation/stable/reference/readwrite/json_graph.html)
|
0.0
|
e780a91f9dfb7ba975f0e8e2732f800ee122163f
|
[
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[cyjs]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[gexf]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[gml]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[graphml]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[json]"
] |
[
"tests/test_SimilarityNetwork.py::test_create_network_symmetric",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_remove_unconnected_nodes",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_modified_cosine",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_higher_cutoff",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_mutual_method",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_max_links_1"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-07 16:17:43+00:00
|
apache-2.0
| 3,777 |
|
matchms__matchms-350
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d41be843..d43aec48 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `Spectrum` objects now also have `.mz` and `.intensities` properties [#339](https://github.com/matchms/matchms/pull/339)
+- `SimilarityNetwork`: similarity-network graphs can now be exported to [cyjs](http://manual.cytoscape.org/en/stable/index.html),
+[gexf](http://gexf.net/schema.html), [gml](https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1),
+and node-link JSON formats [#349](https://github.com/matchms/matchms/pull/349)
### Changed
- metadata filtering: made prefilter check for SMILES and InChI more lenient, eventually resulting in longer runtimes but more accurate checks [#337](https://github.com/matchms/matchms/pull/337)
diff --git a/matchms/networking/SimilarityNetwork.py b/matchms/networking/SimilarityNetwork.py
index 4be05392..72ead9da 100644
--- a/matchms/networking/SimilarityNetwork.py
+++ b/matchms/networking/SimilarityNetwork.py
@@ -1,3 +1,4 @@
+import json
from typing import Optional
import networkx as nx
import numpy
@@ -6,7 +7,7 @@ from .networking_functions import get_top_hits
class SimilarityNetwork:
- """Create a spectal network from spectrum similarities.
+ """Create a spectral network from spectrum similarities.
For example
@@ -54,7 +55,7 @@ class SimilarityNetwork:
Parameters
----------
identifier_key
- Metadata key for unique intentifier for each spectrum in scores.
+ Metadata key for unique identifier for each spectrum in scores.
Will also be used for the naming the network nodes. Default is 'spectrum_id'.
top_n
Consider edge between spectrumA and spectrumB if score falls into
@@ -68,7 +69,7 @@ class SimilarityNetwork:
Important side note: The max_links restriction is strict which means that
if scores around max_links are equal still only max_links will be added
which can results in some random variations (sorting spectra with equal
- scores restuls in a random order of such elements).
+ scores results in a random order of such elements).
score_cutoff
Threshold for given similarities. Edges/Links will only be made for
similarities > score_cutoff. Default = 0.7.
@@ -152,6 +153,35 @@ class SimilarityNetwork:
msnet.remove_nodes_from(list(nx.isolates(msnet)))
self.graph = msnet
+ def export_to_file(self, filename: str, graph_format: str = "graphml"):
+ """
+ Save the network to a file with chosen format.
+
+ Parameters
+ ----------
+ filename
+ Path to file to write to.
+ graph_format
+ Format, in which to store the network graph. Supported formats are: "cyjs", "gexf", "gml", "graphml", "json".
+ Default is "graphml".
+ """
+ if not self.graph:
+ raise ValueError("No network found. Make sure to first run .create_network() step")
+
+ writer = self._generate_writer(graph_format)
+ writer(filename)
+
+ def _generate_writer(self, graph_format: str):
+ writer = {"cyjs": self._export_to_cyjs,
+ "gexf": self._export_to_gexf,
+ "gml": self._export_to_gml,
+ "graphml": self.export_to_graphml,
+ "json": self._export_to_node_link_json}
+
+ assert graph_format in writer, "Format not supported.\n" \
+ "Please use one of supported formats: 'cyjs', 'gexf', 'gml', 'graphml', 'json'"
+ return writer[graph_format]
+
def export_to_graphml(self, filename: str):
"""Save the network as .graphml file.
@@ -161,6 +191,37 @@ class SimilarityNetwork:
Specify filename for exporting the graph.
"""
- if not self.graph:
- raise ValueError("No network found. Make sure to first run .create_network() step")
nx.write_graphml_lxml(self.graph, filename)
+
+ def _export_to_cyjs(self, filename: str):
+ """Save the network in cyjs format."""
+ graph = nx.cytoscape_data(self.graph)
+ return self._write_to_json(graph, filename)
+
+ def _export_to_node_link_json(self, filename: str):
+ """Save the network in node-link format."""
+ graph = nx.node_link_data(self.graph)
+ return self._write_to_json(graph, filename)
+
+ @staticmethod
+ def _write_to_json(graph: dict, filename: str):
+ """Save the network as JSON file.
+
+ Parameters
+ ----------
+ graph
+ JSON-dictionary type graph to save.
+ filename
+ Specify filename for exporting the graph.
+
+ """
+ with open(filename, "w", encoding="utf-8") as file:
+ json.dump(graph, file)
+
+ def _export_to_gexf(self, filename: str):
+ """Save the network as .gexf file."""
+ nx.write_gexf(self.graph, filename)
+
+ def _export_to_gml(self, filename: str):
+ """Save the network as .gml file."""
+ nx.write_gml(self.graph, filename)
|
matchms/matchms
|
e780a91f9dfb7ba975f0e8e2732f800ee122163f
|
diff --git a/tests/test_SimilarityNetwork.py b/tests/test_SimilarityNetwork.py
index 9e5787a6..bf86a88e 100644
--- a/tests/test_SimilarityNetwork.py
+++ b/tests/test_SimilarityNetwork.py
@@ -7,11 +7,17 @@ from matchms.networking import SimilarityNetwork
from matchms.similarity import FingerprintSimilarity, ModifiedCosine
[email protected]
-def filename():
[email protected](params=["cyjs", "gexf", "gml", "graphml", "json"])
+def graph_format(request):
+ yield request.param
+
+
[email protected]()
+def filename(graph_format):
+ filename = f"test.{graph_format}"
with tempfile.TemporaryDirectory() as temp_dir:
- filename = os.path.join(temp_dir, "test.graphml")
- yield filename
+ filepath = os.path.join(temp_dir, filename)
+ yield filepath
def create_dummy_spectrums():
@@ -127,15 +133,15 @@ def test_create_network_symmetric_modified_cosine():
assert len(edges_list) == 28, "Expected different number of edges"
-def test_create_network_export_to_graphml(filename):
- """Test creating a graph from a symmetric Scores object using ModifiedCosine"""
+def test_create_network_export_to_file(filename, graph_format):
+ """Test creating a graph file from a symmetric Scores object using ModifiedCosine"""
cutoff = 0.7
scores = create_dummy_scores_symmetric_modified_cosine()
msnet = SimilarityNetwork(score_cutoff=cutoff)
msnet.create_network(scores)
- msnet.export_to_graphml(filename)
+ msnet.export_to_file(filename, graph_format)
- assert os.path.isfile(filename), "graphml file not found"
+ assert os.path.isfile(filename), "network file not found"
def test_create_network_symmetric_higher_cutoff():
|
Add `.cyjs` export to networking module
**Is your feature request related to a problem? Please describe.**
Currently only `.graphml` output is supported, which is not supported by the cytoscape Galaxy plugin.
**Describe the solution you'd like**
Add the option to export to `.cyjs` using the networkx package to the Networking module.
**Any good starting points?**
[Do you know of any alternative solutions or do you have some helping code/links at hand?
](https://networkx.org/documentation/stable/reference/readwrite/json_graph.html)
|
0.0
|
e780a91f9dfb7ba975f0e8e2732f800ee122163f
|
[
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[cyjs]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[gexf]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[gml]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[graphml]",
"tests/test_SimilarityNetwork.py::test_create_network_export_to_file[json]"
] |
[
"tests/test_SimilarityNetwork.py::test_create_network_symmetric",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_remove_unconnected_nodes",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_modified_cosine",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_higher_cutoff",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_mutual_method",
"tests/test_SimilarityNetwork.py::test_create_network_symmetric_max_links_1"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-09 07:25:45+00:00
|
apache-2.0
| 3,778 |
|
matchms__matchms-399
|
diff --git a/matchms/similarity/FingerprintSimilarity.py b/matchms/similarity/FingerprintSimilarity.py
index a9af3628..09873c18 100644
--- a/matchms/similarity/FingerprintSimilarity.py
+++ b/matchms/similarity/FingerprintSimilarity.py
@@ -1,5 +1,6 @@
from typing import List, Union
import numpy as np
+from sparsestack import StackedSparseArray
from matchms.typing import SpectrumType
from .BaseSimilarity import BaseSimilarity
from .vector_similarity_functions import (cosine_similarity,
@@ -141,8 +142,6 @@ class FingerprintSimilarity(BaseSimilarity):
similarity_matrix[:] = self.set_empty_scores
return similarity_matrix
- if array_type != "numpy":
- raise NotImplementedError("Output array type other than numpy is not yet implemented.")
fingerprints1, idx_fingerprints1 = collect_fingerprints(references)
fingerprints2, idx_fingerprints2 = collect_fingerprints(queries)
assert idx_fingerprints1.size > 0 and idx_fingerprints2.size > 0, ("Not enouth molecular fingerprints.",
@@ -162,4 +161,10 @@ class FingerprintSimilarity(BaseSimilarity):
similarity_matrix[np.ix_(idx_fingerprints1,
idx_fingerprints2)] = cosine_similarity_matrix(fingerprints1,
fingerprints2)
- return similarity_matrix.astype(self.score_datatype)
+ if array_type == "sparse":
+ scores_array = StackedSparseArray(len(references), len(queries))
+ scores_array.add_dense_matrix(similarity_matrix.astype(self.score_datatype), "")
+ return scores_array
+ if array_type == "numpy":
+ return similarity_matrix.astype(self.score_datatype)
+ raise NotImplementedError("Output array type is not yet implemented.")
|
matchms/matchms
|
580869e3f17efaa64cf1dca1db6075f562eb0c0a
|
diff --git a/tests/test_fingerprint_similarity.py b/tests/test_fingerprint_similarity.py
index 37f895a8..97c8b9dc 100644
--- a/tests/test_fingerprint_similarity.py
+++ b/tests/test_fingerprint_similarity.py
@@ -1,4 +1,5 @@
import numpy as np
+from sparsestack import StackedSparseArray
import pytest
from matchms import Spectrum, calculate_scores
from matchms.similarity import FingerprintSimilarity
@@ -42,10 +43,10 @@ def test_fingerprint_similarity_parallel_empty_fingerprint(test_method):
[0, 1.]]), 0.001), "Expected different values."
[email protected]("test_method, expected_score", [("cosine", 0.84515425),
- ("jaccard", 0.71428571),
- ("dice", 0.83333333)])
-def test_fingerprint_similarity_parallel(test_method, expected_score):
[email protected]("test_method, expected_score, array_type, set_empty", [("cosine", 0.84515425, "numpy", np.nan),
+ ("jaccard", 0.71428571, "sparse", np.nan),
+ ("dice", 0.83333333, "numpy", 0)])
+def test_fingerprint_similarity_parallel(test_method, expected_score, array_type, set_empty):
"""Test score matrix with known values for the provided methods."""
spectrum0 = Spectrum(mz=np.array([], dtype="float"),
intensities=np.array([], dtype="float"),
@@ -61,38 +62,15 @@ def test_fingerprint_similarity_parallel(test_method, expected_score):
intensities=np.array([], dtype="float"),
metadata={"fingerprint": fingerprint2})
- similarity_measure = FingerprintSimilarity(similarity_measure=test_method)
- score_matrix = similarity_measure.matrix([spectrum0, spectrum1, spectrum2],
- [spectrum0, spectrum1, spectrum2])
- expected_matrix = np.array([[1., expected_score],
- [expected_score, 1.]])
- assert score_matrix[1:, 1:] == pytest.approx(expected_matrix, 0.001), "Expected different values."
- assert np.all(np.isnan(score_matrix[:, 0])), "Expected 'nan' entries."
- assert np.all(np.isnan(score_matrix[0, :])), "Expected 'nan' entries."
-
-
-def test_fingerprint_similarity_parallel_cosine_set_empty_to_0():
- """Test cosine score matrix with known values. Set non-exising values to 0."""
- spectrum0 = Spectrum(mz=np.array([], dtype="float"),
- intensities=np.array([], dtype="float"),
- metadata={})
-
- fingerprint1 = np.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0])
- spectrum1 = Spectrum(mz=np.array([], dtype="float"),
- intensities=np.array([], dtype="float"),
- metadata={"fingerprint": fingerprint1})
-
- fingerprint2 = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1])
- spectrum2 = Spectrum(mz=np.array([], dtype="float"),
- intensities=np.array([], dtype="float"),
- metadata={"fingerprint": fingerprint2})
-
- similarity_measure = FingerprintSimilarity(set_empty_scores=0, similarity_measure="cosine")
+ similarity_measure = FingerprintSimilarity(set_empty_scores=set_empty, similarity_measure=test_method)
score_matrix = similarity_measure.matrix([spectrum0, spectrum1, spectrum2],
- [spectrum0, spectrum1, spectrum2])
- assert score_matrix == pytest.approx(np.array([[0, 0, 0],
- [0, 1., 0.84515425],
- [0, 0.84515425, 1.]]), 0.001), "Expected different values."
+ [spectrum0, spectrum1, spectrum2], array_type=array_type)
+ expected_matrix = np.array([[set_empty, set_empty, set_empty],
+ [set_empty, 1, expected_score],
+ [set_empty, expected_score, 1]])
+ if isinstance(score_matrix, (StackedSparseArray)):
+ score_matrix = score_matrix.to_array()
+ assert np.allclose(score_matrix , expected_matrix, equal_nan=True) , "Expected different values."
def test_fingerprint_similarity_with_scores_sorting():
|
Implement `sparse` array_type computation for fingerprint similarity
A naive implementation computing the dense matrix and then just returning it as sparse could be sufficient - or compute dense and then filter out 0 values.
|
0.0
|
580869e3f17efaa64cf1dca1db6075f562eb0c0a
|
[
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel[jaccard-0.71428571-sparse-nan]"
] |
[
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_pair_calculations[cosine-0.6761234]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_pair_calculations[jaccard-0.5]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_pair_calculations[dice-0.6666666666666666]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel_empty_fingerprint[cosine]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel_empty_fingerprint[jaccard]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel_empty_fingerprint[dice]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel[cosine-0.84515425-numpy-nan]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_parallel[dice-0.83333333-numpy-0]",
"tests/test_fingerprint_similarity.py::test_fingerprint_similarity_with_scores_sorting"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-17 14:26:52+00:00
|
apache-2.0
| 3,779 |
|
matchms__matchms-493
|
diff --git a/matchms/Pipeline.py b/matchms/Pipeline.py
index baf579bb..32214b4e 100644
--- a/matchms/Pipeline.py
+++ b/matchms/Pipeline.py
@@ -214,24 +214,25 @@ class Pipeline:
self.__workflow = workflow
self.check_workflow()
- self.write_to_logfile("--- Processing pipeline: ---")
self._initialize_spectrum_processor_queries()
if self.is_symmetric is False:
self._initialize_spectrum_processor_references()
def _initialize_spectrum_processor_queries(self):
"""Initialize spectrum processing workflow for the query spectra."""
+ self.write_to_logfile("--- Processing pipeline query spectra: ---")
self.processing_queries = initialize_spectrum_processor(
None,
self.__workflow["query_filters"]
)
-
self.write_to_logfile(str(self.processing_queries))
if self.processing_queries.processing_steps != self.__workflow["query_filters"]:
logger.warning("The order of the filters has been changed compared to the Yaml file.")
def _initialize_spectrum_processor_references(self):
"""Initialize spectrum processing workflow for the reference spectra."""
+ self.write_to_logfile("--- Processing pipeline reference spectra: ---")
+
self.processing_references = initialize_spectrum_processor(
None,
self.__workflow["reference_filters"]
diff --git a/matchms/SpectrumProcessor.py b/matchms/SpectrumProcessor.py
index 51964296..5a5f8c31 100644
--- a/matchms/SpectrumProcessor.py
+++ b/matchms/SpectrumProcessor.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from functools import partial
-from typing import Optional, Tuple, Union
+from typing import Dict, Optional, Tuple, Union
import numpy as np
import pandas as pd
from tqdm import tqdm
@@ -30,8 +30,8 @@ class SpectrumProcessor:
raise ValueError("Predefined pipeline parameter should be a string")
if predefined_pipeline not in PREDEFINED_PIPELINES:
raise ValueError(f"Unknown processing pipeline '{predefined_pipeline}'. Available pipelines: {list(PREDEFINED_PIPELINES.keys())}")
- for fname in PREDEFINED_PIPELINES[predefined_pipeline]:
- self.add_matchms_filter(fname)
+ for filter_name in PREDEFINED_PIPELINES[predefined_pipeline]:
+ self.add_matchms_filter(filter_name)
def add_filter(self, filter_function: Union[Tuple[str], str]):
"""Add a filter to the processing pipeline. Takes both matchms filter names (and parameters)
@@ -44,7 +44,7 @@ class SpectrumProcessor:
else:
self.add_custom_filter(filter_function[0], filter_function[1])
- def add_matchms_filter(self, filter_spec: Union[Tuple[str], str]):
+ def add_matchms_filter(self, filter_spec: Union[Tuple[str, Dict[str, any]], str]):
"""
Add a filter to the processing pipeline.
@@ -171,11 +171,27 @@ class SpectrumProcessor:
@property
def processing_steps(self):
- return [x.__name__ for x in self.filters]
+ filter_list = []
+ for filter_step in self.filters:
+ if isinstance(filter_step, partial):
+ filter_params = filter_step.keywords
+ filter_list.append((filter_step.__name__, filter_params))
+ else:
+ filter_list.append(filter_step.__name__)
+ return filter_list
def __str__(self):
- summary_string = "SpectrumProcessor\nProcessing steps:\n - "
- return summary_string + "\n - ".join(self.processing_steps)
+ summary_string = "SpectrumProcessor\nProcessing steps:"
+ for processing_step in self.processing_steps:
+ if isinstance(processing_step, str):
+ summary_string += "\n- " + processing_step
+ elif isinstance(processing_step, tuple):
+ filter_name = processing_step[0]
+ summary_string += "\n- - " + filter_name
+ filter_params = processing_step[1]
+ for filter_param in filter_params:
+ summary_string += "\n - " + str(filter_param)
+ return summary_string
# List all filters in a functionally working order
@@ -246,7 +262,6 @@ DEFAULT_FILTERS = BASIC_FILTERS \
"harmonize_undefined_inchi",
"harmonize_undefined_smiles",
"repair_inchi_inchikey_smiles",
- "repair_parent_mass_match_smiles_wrapper",
"normalize_intensities",
]
FULLY_ANNOTATED_PROCESSING = DEFAULT_FILTERS \
|
matchms/matchms
|
6aa1fac88debee22495c8c02c64a3130b8b757f5
|
diff --git a/tests/filtering/test_spectrum_processor.py b/tests/filtering/test_spectrum_processor.py
index 0cad682c..44330aaf 100644
--- a/tests/filtering/test_spectrum_processor.py
+++ b/tests/filtering/test_spectrum_processor.py
@@ -40,7 +40,6 @@ def test_filter_sorting_and_output():
'harmonize_undefined_inchi',
'harmonize_undefined_smiles',
'repair_inchi_inchikey_smiles',
- 'repair_parent_mass_match_smiles_wrapper',
'normalize_intensities'
]
actual_filters = [x.__name__ for x in processing.filters]
@@ -51,8 +50,8 @@ def test_filter_sorting_and_output():
def test_string_output():
processing = SpectrumProcessor("minimal")
- expected_str = "SpectrumProcessor\nProcessing steps:\n - make_charge_int\n - interpret_pepmass"\
- "\n - derive_ionmode\n - correct_charge"
+ expected_str = "SpectrumProcessor\nProcessing steps:\n- make_charge_int\n- interpret_pepmass"\
+ "\n- derive_ionmode\n- correct_charge"
assert str(processing) == expected_str
|
Filter parameters in default pipelines are not used
When adding filter parameters in the default filters they are not used by SpectrumProcessor.
For instance in the code below "ion_mode_to_keep" is not set to "both"
```python
FULLY_ANNOTATED_PROCESSING = DEFAULT_FILTERS \
+ ["clean_adduct",
"derive_inchi_from_smiles",
"derive_smiles_from_inchi",
("require_correct_ionmode", {"ion_mode_to_keep": "both"}),
("require_parent_mass_match_smiles", {'mass_tolerance': 0.1}),
"require_valid_annotation",
]
```
|
0.0
|
6aa1fac88debee22495c8c02c64a3130b8b757f5
|
[
"tests/filtering/test_spectrum_processor.py::test_filter_sorting_and_output",
"tests/filtering/test_spectrum_processor.py::test_string_output"
] |
[
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata0-None]",
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata1-expected1]",
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata2-expected2]",
"tests/filtering/test_spectrum_processor.py::test_no_filters",
"tests/filtering/test_spectrum_processor.py::test_unknown_keyword",
"tests/filtering/test_spectrum_processor.py::test_filter_spectrums",
"tests/filtering/test_spectrum_processor.py::test_filter_spectrums_report",
"tests/filtering/test_spectrum_processor.py::test_processing_report_class",
"tests/filtering/test_spectrum_processor.py::test_adding_custom_filter",
"tests/filtering/test_spectrum_processor.py::test_adding_custom_filter_with_parameters",
"tests/filtering/test_spectrum_processor.py::test_add_filter_with_custom",
"tests/filtering/test_spectrum_processor.py::test_add_filter_with_matchms_filter",
"tests/filtering/test_spectrum_processor.py::test_all_filters_is_complete",
"tests/filtering/test_spectrum_processor.py::test_all_filters_no_duplicates"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-21 09:28:12+00:00
|
apache-2.0
| 3,780 |
|
matchms__matchms-496
|
diff --git a/matchms/Pipeline.py b/matchms/Pipeline.py
index baf579bb..32214b4e 100644
--- a/matchms/Pipeline.py
+++ b/matchms/Pipeline.py
@@ -214,24 +214,25 @@ class Pipeline:
self.__workflow = workflow
self.check_workflow()
- self.write_to_logfile("--- Processing pipeline: ---")
self._initialize_spectrum_processor_queries()
if self.is_symmetric is False:
self._initialize_spectrum_processor_references()
def _initialize_spectrum_processor_queries(self):
"""Initialize spectrum processing workflow for the query spectra."""
+ self.write_to_logfile("--- Processing pipeline query spectra: ---")
self.processing_queries = initialize_spectrum_processor(
None,
self.__workflow["query_filters"]
)
-
self.write_to_logfile(str(self.processing_queries))
if self.processing_queries.processing_steps != self.__workflow["query_filters"]:
logger.warning("The order of the filters has been changed compared to the Yaml file.")
def _initialize_spectrum_processor_references(self):
"""Initialize spectrum processing workflow for the reference spectra."""
+ self.write_to_logfile("--- Processing pipeline reference spectra: ---")
+
self.processing_references = initialize_spectrum_processor(
None,
self.__workflow["reference_filters"]
diff --git a/matchms/Scores.py b/matchms/Scores.py
index c35bafb8..274983f9 100644
--- a/matchms/Scores.py
+++ b/matchms/Scores.py
@@ -111,6 +111,9 @@ class Scores:
self._index = 0
raise StopIteration
+ def __repr__(self):
+ return self._scores.__repr__()
+
def __str__(self):
return self._scores.__str__()
diff --git a/matchms/Spectrum.py b/matchms/Spectrum.py
index cdbb3230..a125d4c7 100644
--- a/matchms/Spectrum.py
+++ b/matchms/Spectrum.py
@@ -27,9 +27,11 @@ class Spectrum:
spectrum = Spectrum(mz=np.array([100, 150, 200.]),
intensities=np.array([0.7, 0.2, 0.1]),
- metadata={'id': 'spectrum1',
+ metadata={"id": 'spectrum1',
+ "precursor_mz": 222.333,
"peak_comments": {200.: "the peak at 200 m/z"}})
+ print(spectrum)
print(spectrum.peaks.mz[0])
print(spectrum.peaks.intensities[0])
print(spectrum.get('id'))
@@ -39,6 +41,7 @@ class Spectrum:
.. testoutput::
+ Spectrum(precursor m/z=222.33, 3 fragments between 100.0 and 200.0)
100.0
0.7
spectrum1
@@ -101,6 +104,16 @@ class Spectrum:
combined_hash = self.metadata_hash() + self.spectrum_hash()
return int.from_bytes(bytearray(combined_hash, 'utf-8'), 'big')
+ def __repr__(self):
+ num_peaks = len(self.peaks)
+ min_mz = min(self.peaks.mz)
+ max_mz = max(self.peaks.mz)
+ precursor_mz = self.get("precursor_mz")
+ return f"Spectrum(precursor m/z={precursor_mz:.2f}, {num_peaks} fragments between {min_mz:.1f} and {max_mz:.1f})"
+
+ def __str__(self):
+ return self.__repr__()
+
def spectrum_hash(self):
"""Return a (truncated) sha256-based hash which is generated
based on the spectrum peaks (mz:intensity pairs).
diff --git a/matchms/SpectrumProcessor.py b/matchms/SpectrumProcessor.py
index 51964296..090c3f4b 100644
--- a/matchms/SpectrumProcessor.py
+++ b/matchms/SpectrumProcessor.py
@@ -1,6 +1,7 @@
+import inspect
from collections import defaultdict
from functools import partial
-from typing import Optional, Tuple, Union
+from typing import Dict, Optional, Tuple, Union
import numpy as np
import pandas as pd
from tqdm import tqdm
@@ -30,10 +31,10 @@ class SpectrumProcessor:
raise ValueError("Predefined pipeline parameter should be a string")
if predefined_pipeline not in PREDEFINED_PIPELINES:
raise ValueError(f"Unknown processing pipeline '{predefined_pipeline}'. Available pipelines: {list(PREDEFINED_PIPELINES.keys())}")
- for fname in PREDEFINED_PIPELINES[predefined_pipeline]:
- self.add_matchms_filter(fname)
+ for filter_name in PREDEFINED_PIPELINES[predefined_pipeline]:
+ self.add_matchms_filter(filter_name)
- def add_filter(self, filter_function: Union[Tuple[str], str]):
+ def add_filter(self, filter_function: Union[Tuple[str, Dict[str, any]], str]):
"""Add a filter to the processing pipeline. Takes both matchms filter names (and parameters)
as well as custom-made functions.
"""
@@ -44,7 +45,7 @@ class SpectrumProcessor:
else:
self.add_custom_filter(filter_function[0], filter_function[1])
- def add_matchms_filter(self, filter_spec: Union[Tuple[str], str]):
+ def add_matchms_filter(self, filter_spec: Union[Tuple[str, Dict[str, any]], str]):
"""
Add a filter to the processing pipeline.
@@ -66,7 +67,7 @@ class SpectrumProcessor:
filter_func.__name__ = FILTER_FUNCTIONS[filter_name].__name__
else:
raise TypeError("filter_spec should be a string or a tuple or list")
-
+ check_all_parameters_given(filter_func)
self.filters.append(filter_func)
# Sort filters according to their order in self.filter_order
self.filters.sort(key=lambda f: self.filter_order.index(f.__name__))
@@ -93,12 +94,12 @@ class SpectrumProcessor:
if filter_func.__name__ in self.filter_order:
filter_position = self.filter_order.index(filter_func.__name__)
self.filter_order.insert(filter_position + 1, filter_function.__name__)
- if filter_params is None:
- self.filters.append(filter_function)
- else:
- filter_func = partial(filter_function, **filter_params)
- filter_func.__name__ = filter_function.__name__
- self.filters.append(filter_func)
+ if filter_params is not None:
+ partial_filter_func = partial(filter_function, **filter_params)
+ partial_filter_func.__name__ = filter_function.__name__
+ filter_function = partial_filter_func
+ check_all_parameters_given(filter_function)
+ self.filters.append(filter_function)
def process_spectrum(self, spectrum,
processing_report: Optional["ProcessingReport"] = None):
@@ -171,11 +172,54 @@ class SpectrumProcessor:
@property
def processing_steps(self):
- return [x.__name__ for x in self.filters]
+ filter_list = []
+ for filter_step in self.filters:
+ parameter_settings = get_parameter_settings(filter_step)
+ if parameter_settings is not None:
+ filter_list.append((filter_step.__name__, parameter_settings))
+ else:
+ filter_list.append(filter_step.__name__)
+ return filter_list
def __str__(self):
- summary_string = "SpectrumProcessor\nProcessing steps:\n - "
- return summary_string + "\n - ".join(self.processing_steps)
+ summary_string = "SpectrumProcessor\nProcessing steps:"
+ for processing_step in self.processing_steps:
+ if isinstance(processing_step, str):
+ summary_string += "\n- " + processing_step
+ elif isinstance(processing_step, tuple):
+ filter_name = processing_step[0]
+ summary_string += "\n- - " + filter_name
+ filter_params = processing_step[1]
+ for filter_param in filter_params:
+ summary_string += "\n - " + str(filter_param)
+ return summary_string
+
+
+def check_all_parameters_given(func):
+ """Asserts that all added parameters for a function are given (except spectrum_in)"""
+ signature = inspect.signature(func)
+ parameters_without_value = []
+ for parameter, value in signature.parameters.items():
+ if value.default is inspect.Parameter.empty:
+ parameters_without_value.append(parameter)
+ assert len(parameters_without_value) == 1, \
+ f"More than one parameter of the function {func.__name__} is not specified, " \
+ f"the parameters not specified are {parameters_without_value}"
+
+
+def get_parameter_settings(func):
+ """Returns all parameters and parameter values for a function
+
+ This includes default parameter settings and, but also the settings stored in partial"""
+ signature = inspect.signature(func)
+ parameter_settings = {
+ parameter: value.default
+ for parameter, value in signature.parameters.items()
+ if value.default is not inspect.Parameter.empty
+ }
+ if parameter_settings == {}:
+ return None
+ return parameter_settings
# List all filters in a functionally working order
@@ -246,7 +290,6 @@ DEFAULT_FILTERS = BASIC_FILTERS \
"harmonize_undefined_inchi",
"harmonize_undefined_smiles",
"repair_inchi_inchikey_smiles",
- "repair_parent_mass_match_smiles_wrapper",
"normalize_intensities",
]
FULLY_ANNOTATED_PROCESSING = DEFAULT_FILTERS \
diff --git a/pyproject.toml b/pyproject.toml
index 07a8d7fc..3c9469de 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -42,7 +42,6 @@ rdkit = "^2023.3.2"
pyyaml = "^6.0.1"
deprecated = "^1.2.14"
-
[tool.poetry.group.dev.dependencies]
decorator = "^5.1.1"
isort = "^5.12.0"
@@ -59,7 +58,7 @@ poetry-bumpversion = "^0.3.1"
[tool.poetry.group.docs.dependencies]
sphinxcontrib-apidoc = "^0.3.0"
sphinx-rtd-theme = "^1.2.2"
-sphinx = "<7"
+sphinx = "^7"
[build-system]
diff --git a/readthedocs/conf.py b/readthedocs/conf.py
index fcf34b61..46c6e91d 100644
--- a/readthedocs/conf.py
+++ b/readthedocs/conf.py
@@ -23,8 +23,8 @@ import matchms
# -- Project information -----------------------------------------------------
project = "matchms"
-copyright = "2020, Netherlands eScience Center"
-author = "Netherlands eScience Center"
+copyright = "2023, Düsseldorf University of Applied Sciences & Netherlands eScience Center"
+author = "matchms development team"
# -- General configuration ---------------------------------------------------
|
matchms/matchms
|
6aa1fac88debee22495c8c02c64a3130b8b757f5
|
diff --git a/tests/filtering/test_spectrum_processor.py b/tests/filtering/test_spectrum_processor.py
index 0cad682c..a34253e4 100644
--- a/tests/filtering/test_spectrum_processor.py
+++ b/tests/filtering/test_spectrum_processor.py
@@ -24,35 +24,53 @@ def spectrums():
def test_filter_sorting_and_output():
processing = SpectrumProcessor("default")
- expected_filters = [
- 'make_charge_int',
- 'add_compound_name',
- 'derive_adduct_from_name',
- 'derive_formula_from_name',
- 'clean_compound_name',
- 'interpret_pepmass',
- 'add_precursor_mz',
- 'derive_ionmode',
- 'correct_charge',
- 'require_precursor_mz',
- 'add_parent_mass',
- 'harmonize_undefined_inchikey',
- 'harmonize_undefined_inchi',
- 'harmonize_undefined_smiles',
- 'repair_inchi_inchikey_smiles',
- 'repair_parent_mass_match_smiles_wrapper',
- 'normalize_intensities'
- ]
- actual_filters = [x.__name__ for x in processing.filters]
- assert actual_filters == expected_filters
- # 2nd way to access the filter names via processing_steps attribute:
+ expected_filters = ['make_charge_int',
+ 'add_compound_name',
+ ('derive_adduct_from_name', {'remove_adduct_from_name': True}),
+ ('derive_formula_from_name', {'remove_formula_from_name': True}),
+ 'clean_compound_name',
+ 'interpret_pepmass',
+ 'add_precursor_mz',
+ 'derive_ionmode',
+ 'correct_charge',
+ ('require_precursor_mz', {'minimum_accepted_mz': 10.0}),
+ ('add_parent_mass',
+ {'estimate_from_adduct': True, 'overwrite_existing_entry': False}),
+ ('harmonize_undefined_inchikey', {'aliases': None, 'undefined': ''}),
+ ('harmonize_undefined_inchi', {'aliases': None, 'undefined': ''}),
+ ('harmonize_undefined_smiles', {'aliases': None, 'undefined': ''}),
+ 'repair_inchi_inchikey_smiles',
+ 'normalize_intensities']
assert processing.processing_steps == expected_filters
[email protected]("filter_step, expected", [
+ [("add_parent_mass", {'estimate_from_adduct': False}),
+ ('add_parent_mass', {'estimate_from_adduct': False, 'overwrite_existing_entry': False})],
+ ["derive_adduct_from_name",
+ ('derive_adduct_from_name', {'remove_adduct_from_name': True})],
+ [("require_correct_ionmode", {"ion_mode_to_keep": "both"}),
+ ("require_correct_ionmode", {"ion_mode_to_keep": "both"})],
+])
+def test_overwrite_default_settings(filter_step, expected):
+ """Test if both default settings and set settings are returned in processing steps"""
+ processor = SpectrumProcessor(None)
+ processor.add_filter(filter_step)
+ expected_filters = [expected]
+ assert processor.processing_steps == expected_filters
+
+
+def test_incomplete_parameters():
+ """Test if an error is raised when running an incomplete command"""
+ with pytest.raises(AssertionError):
+ processor = SpectrumProcessor(None)
+ processor.add_filter("require_correct_ionmode")
+
+
def test_string_output():
processing = SpectrumProcessor("minimal")
- expected_str = "SpectrumProcessor\nProcessing steps:\n - make_charge_int\n - interpret_pepmass"\
- "\n - derive_ionmode\n - correct_charge"
+ expected_str = "SpectrumProcessor\nProcessing steps:\n- make_charge_int\n- interpret_pepmass" \
+ "\n- derive_ionmode\n- correct_charge"
assert str(processing) == expected_str
@@ -65,7 +83,7 @@ def test_add_matchms_filter(metadata, expected):
spectrum_in = SpectrumBuilder().with_metadata(metadata).build()
processor = SpectrumProcessor("minimal")
processor.add_matchms_filter(("require_correct_ionmode",
- {"ion_mode_to_keep": "both"}))
+ {"ion_mode_to_keep": "both"}))
spectrum = processor.process_spectrum(spectrum_in)
if expected is None:
assert spectrum is None
@@ -175,7 +193,7 @@ def test_add_filter_with_custom(spectrums):
def test_add_filter_with_matchms_filter(spectrums):
processor = SpectrumProcessor("minimal")
processor.add_filter(("require_correct_ionmode",
- {"ion_mode_to_keep": "both"}))
+ {"ion_mode_to_keep": "both"}))
filters = processor.filters
assert filters[-1].__name__ == "require_correct_ionmode"
spectrums, _ = processor.process_spectrums(spectrums, create_report=True)
@@ -187,6 +205,7 @@ def test_all_filters_is_complete():
This is important, since performing tests in the wrong order can make some filters useless.
"""
+
def get_functions_from_file(file_path):
"""Gets all python functions in a file"""
with open(file_path, 'r', encoding="utf-8") as file:
|
Add default filters to yaml file
Any default settings of functions are not shown in the yaml file. This is bad for reproducibility, since changing any default settings in a filter function will currently result in a different pipeline running.
Suggested change:
Automatically get the default filter settings from each filter and returning them in properties. (this will be used to create yaml files and printing the log file)
|
0.0
|
6aa1fac88debee22495c8c02c64a3130b8b757f5
|
[
"tests/filtering/test_spectrum_processor.py::test_filter_sorting_and_output",
"tests/filtering/test_spectrum_processor.py::test_overwrite_default_settings[filter_step0-expected0]",
"tests/filtering/test_spectrum_processor.py::test_overwrite_default_settings[derive_adduct_from_name-expected1]",
"tests/filtering/test_spectrum_processor.py::test_overwrite_default_settings[filter_step2-expected2]",
"tests/filtering/test_spectrum_processor.py::test_incomplete_parameters",
"tests/filtering/test_spectrum_processor.py::test_string_output"
] |
[
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata0-None]",
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata1-expected1]",
"tests/filtering/test_spectrum_processor.py::test_add_matchms_filter[metadata2-expected2]",
"tests/filtering/test_spectrum_processor.py::test_no_filters",
"tests/filtering/test_spectrum_processor.py::test_unknown_keyword",
"tests/filtering/test_spectrum_processor.py::test_filter_spectrums",
"tests/filtering/test_spectrum_processor.py::test_filter_spectrums_report",
"tests/filtering/test_spectrum_processor.py::test_processing_report_class",
"tests/filtering/test_spectrum_processor.py::test_adding_custom_filter",
"tests/filtering/test_spectrum_processor.py::test_adding_custom_filter_with_parameters",
"tests/filtering/test_spectrum_processor.py::test_add_filter_with_custom",
"tests/filtering/test_spectrum_processor.py::test_add_filter_with_matchms_filter",
"tests/filtering/test_spectrum_processor.py::test_all_filters_is_complete",
"tests/filtering/test_spectrum_processor.py::test_all_filters_no_duplicates"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-21 10:13:37+00:00
|
apache-2.0
| 3,781 |
|
matchms__matchms-539
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8abb2a16..e51ca0b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The file structure of metadata_utils was refactored [#503](https://github.com/matchms/matchms/pull/503)
- interpret_pepmass now removes the pepmass field after entering precursor_mz [#533](https://github.com/matchms/matchms/pull/533)
- Filters that did not have any effect are also mentioned in processing report [#530](https://github.com/matchms/matchms/pull/530)
+- Added regex to pepmass reading to properly interpret string representations [#539](https://github.com/matchms/matchms/pull/539)
### Fixed
diff --git a/matchms/filtering/metadata_processing/interpret_pepmass.py b/matchms/filtering/metadata_processing/interpret_pepmass.py
index 0e5ef752..7eec4284 100644
--- a/matchms/filtering/metadata_processing/interpret_pepmass.py
+++ b/matchms/filtering/metadata_processing/interpret_pepmass.py
@@ -1,4 +1,5 @@
import logging
+import re
import numpy as np
from .make_charge_int import _convert_charge_to_int
@@ -65,6 +66,11 @@ def _interpret_pepmass_metadata(metadata):
def _get_mz_intensity_charge(pepmass):
try:
+ if isinstance(pepmass, str):
+ matches = re.findall(r'\(([^)]+)\)', pepmass)
+ if len(matches) > 1:
+ raise ValueError("Found more than one tuple in pepmass field.")
+ pepmass = matches[0].split(",")
length = len(pepmass)
values = [None, None, None]
for i in range(length):
|
matchms/matchms
|
4a75f129c1fa0a6ca1f7a72f5c9d39b92c3baf00
|
diff --git a/tests/filtering/test_interpret_pepmass.py b/tests/filtering/test_interpret_pepmass.py
index c02f3786..388d534a 100644
--- a/tests/filtering/test_interpret_pepmass.py
+++ b/tests/filtering/test_interpret_pepmass.py
@@ -84,3 +84,15 @@ def test_empty_spectrum():
spectrum = interpret_pepmass(spectrum_in)
assert spectrum is None, "Expected different handling of None spectrum."
+
+
[email protected]("input_pepmass, expected_results", [
+ ["(981.54, None)", (981.54, None, None)],
+ ["(981.54, 44, -2)", (981.54, 44, -2)],
+])
+def test_interpret_pepmass_error_v0_22_0(input_pepmass, expected_results):
+ spectrum = SpectrumBuilder().with_metadata({"PEPMASS": input_pepmass}, metadata_harmonization=True).build()
+
+ assert spectrum.get("precursor_mz") == expected_results[0], "Expected different precursor_mz."
+ assert spectrum.get("precursor_intensity") == expected_results[1], "Expected different precursor_intensity."
+ assert spectrum.get("charge") == expected_results[2], "Expected different charge."
|
Interpret pepmass doesn't handle strings
**Describe the bug**
Reading a spectrum with pepmass information fails upon metadata harmonization.
**To Reproduce**
Read the following spectrum:
```
PEPMASS: (981.54, None)
CHARGE: 1
MSLEVEL: 2
SOURCE_INSTRUMENT: LC-ESI-qTof
FILENAME: 130618_Ger_Jenia_WT-3-Des-MCLR_MH981.4-qb.1.1..mgf
SEQ: *..*
IONMODE: positive
ORGANISM: GNPS-LIBRARY
NAME: 3-Des-Microcystein_LR M+H
PI: Gerwick
DATACOLLECTOR: Jenia
SMILES: CC(C)CC1NC(=O)C(C)NC(=O)C(=C)N(C)C(=O)CCC(NC(=O)C(C)C(NC(=O)C(CCCNC(N)=N)NC(=O)C(C)C(NC1=O)C(O)=O)\C=C\C(\C)=C\C(C)C(O)Cc1ccccc1)C(O)=O
INCHI: InChI=1S/C48H72N10O12/c1-25(2)22-36-45(66)57-39(47(69)70)29(6)41(62)54-34(16-13-21-51-48(49)50)44(65)53-33(18-17-26(3)23-27(4)37(59)24-32-14-11-10-12-15-32)28(5)40(61)55-35(46(67)68)19-20-38(60)58(9)31(8)43(64)52-30(7)42(63)56-36/h10-12,14-15,17-18,23,25,27-30,33-37,39,59H,8,13,16,19-22,24H2,1-7,9H3,(H,52,64)(H,53,65)(H,54,62)(H,55,61)(H,56,63)(H,57,66)(H,67,68)(H,69,70)(H4,49,50,51)/b18-17+,26-23+
INCHIAUX: N/A
PUBMED: N/A
SUBMITUSER: mwang87
LIBRARYQUALITY: 1
SPECTRUMID: CCMSLIB00000001547
SCANS: 1
COMPOUND_NAME: 3-Des-Microcystein LR
ADDUCT: [M+H]+
PRECURSOR_MZ: 981.54
PARENT_MASS: [980.532724]
INCHIKEY: IYDKWWDUBYWQGF-NNAZGLEUSA-N
NUM PEAKS: 218
289.286377 8068.0
295.545288 22507.0
298.489624 3925.0
317.324951 18742.0
319.655945 8604.0
324.482422 8041.0
325.316284 9738.0
339.789429 16145.0
343.947021 18094.0
347.020508 13981.0
347.913391 6765.0
361.147705 11763.0
361.84436 24296.0
364.232727 2346.0
364.858154 10782.0
365.845886 10242.0
368.22168 12761.0
368.965698 19147.0
375.069519 15644.0
375.751953 25393.0
382.750549 12765.0
384.197083 17912.0
390.574219 7993.0
394.049194 16135.0
397.106262 13986.0
404.420715 12326.0
411.092712 2348.0
413.784546 8715.0
427.667358 68137.0
436.192749 14879.0
443.266113 44427.0
446.267273 23472.0
447.747498 29292.0
455.25 70939.0
456.107544 105392.0
456.822144 3.0
457.543213 12862.0
464.285461 8617.0
469.872314 87594.0
471.062195 31482.0
475.257324 15449.0
476.143616 23143.0
476.975159 28430.0
478.891113 27890.0
479.975952 33235.0
483.242432 13564.0
487.210388 32885.0
488.160156 20786.0
491.191956 55073.0
494.279602 7435.0
495.653992 32208.0
498.412964 11684.0
503.028198 30643.0
503.699951 2.0
504.344543 36421.0
505.154541 9667.0
510.176514 38891.0
512.168701 10175.0
513.265381 16524.0
514.957397 11384.0
515.922852 78764.0
520.973389 28857.0
521.82373 5810.0
523.168945 58926.0
529.036865 20722.0
530.991211 31845.0
532.376709 3005.0
534.575195 12906.0
538.003174 220949.0
539.217773 272296.0
540.672852 43876.0
548.061401 13655.0
554.117432 76225.0
556.030396 214421.0
557.288818 52970.0
557.996094 6202.0
559.942261 18112.0
561.328735 14656.0
564.123047 25971.0
564.94873 34630.0
566.439941 35564.0
571.33374 61305.0
572.047363 17235.0
575.219238 42127.0
575.888916 6.0
577.102905 29550.0
579.645874 7151.0
580.942627 17609.0
582.110107 102075.0
583.458984 10113.0
585.237061 36774.0
598.172485 26085.0
599.352783 764523.0
600.382812 114267.0
601.06665 4.0
602.267578 27144.0
609.302002 10247.0
613.415771 8621.0
622.208984 23787.0
623.023193 63940.0
623.991455 19154.0
625.216187 23050.0
638.299561 12481.0
640.265625 17392.0
641.235107 65873.0
646.095947 8409.0
649.2771 5446.0
651.526611 17521.0
657.128906 12911.0
658.094971 14824.0
659.420898 41969.0
663.387695 18284.0
668.33252 65700.0
669.357178 5671.0
680.219727 44374.0
681.987793 24446.0
685.957764 19166.0
691.648682 29177.0
693.22583 33545.0
694.307861 22539.0
696.332397 121211.0
697.127808 9503.0
709.464478 20171.0
710.79541 22346.0
711.744873 32675.0
714.071777 50487.0
715.578979 54567.0
716.216553 8.0
723.267822 14415.0
724.081909 88510.0
725.488892 8470.0
728.352051 21518.0
735.806396 52022.0
738.34668 2697.0
744.365234 16205.0
747.456055 19268.0
753.27124 14114.0
761.609131 12373.0
764.462158 19876.0
765.280029 18361.0
769.275635 41999.0
770.328613 16548.0
771.386353 13776.0
787.432617 33003.0
796.139526 9637.0
797.232788 11322.0
806.556885 18639.0
808.442383 6355.0
811.637329 14687.0
812.300049 9904.0
813.149292 15959.0
817.219238 7640.0
820.274048 6246.0
821.288208 15591.0
823.361328 13693.0
824.618286 6895.0
828.517456 32132.0
830.409302 102583.0
831.306763 65294.0
832.105469 9727.0
833.18457 4115.0
835.212891 7606.0
836.078247 8740.0
838.518677 26160.0
839.455811 72006.0
845.612915 21577.0
847.433594 196462.0
848.125854 39637.0
851.380859 246170.0
852.370605 276882.0
853.270508 44216.0
865.5979 44697.0
866.295654 111012.0
867.19043 4120.0
868.372192 78023.0
869.331177 8584.0
871.557007 5374.0
877.137451 30131.0
880.216553 5692.0
883.442261 49241.0
884.216553 8.0
888.167114 41037.0
889.282959 24795.0
892.127808 14925.0
893.467896 23506.0
895.607422 13123.0
899.010132 28633.0
901.351196 13472.0
902.325562 3774.0
909.424438 244136.0
910.515381 43770.0
911.526367 15208.0
914.30896 6532.0
915.217773 28455.0
918.666138 5610.0
919.39624 85829.0
920.06665 3.0
921.123901 16163.0
922.205688 37863.0
925.063721 43395.0
931.132812 61732.0
932.351929 136657.0
933.524048 25202.0
935.493286 33896.0
936.552002 103130.0
937.588623 67605.0
938.471069 35379.0
939.61792 77289.0
946.257812 38584.0
949.370239 85420.0
950.284546 5976.0
951.551758 29995.0
953.396606 545281.0
954.491577 123937.0
963.686768 261578.0
964.524658 318164.0
965.192139 124405.0
982.221924 27147.0
```
**Expected behavior**
The spectrum should be read normally
**Additional context**
Observed first in version 0.22.0
|
0.0
|
4a75f129c1fa0a6ca1f7a72f5c9d39b92c3baf00
|
[
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass_error_v0_22_0[(981.54,"
] |
[
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[None-expected_results0]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[896.05-expected_results1]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[input_pepmass2-expected_results2]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[input_pepmass3-expected_results3]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[input_pepmass4-expected_results4]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass[input_pepmass5-expected_results5]",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass_charge_present",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass_mz_present",
"tests/filtering/test_interpret_pepmass.py::test_interpret_pepmass_intensity_present",
"tests/filtering/test_interpret_pepmass.py::test_empty_spectrum"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-17 13:03:41+00:00
|
apache-2.0
| 3,782 |
|
matchms__matchms-547
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 804ca02d..d4218b17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [unreleased]
+### Added
+- added option to set custom key replacements [#547](https://github.com/matchms/matchms/pull/547)
### Fixed
- handle missing `precursor_mz` in representation and [#452](https://github.com/matchms/matchms/issues/452) introduced by [#514](https://github.com/matchms/matchms/pull/514/files)[#540](https://github.com/matchms/matchms/pull/540)
diff --git a/matchms/Metadata.py b/matchms/Metadata.py
index 3ddb0845..190d90e6 100644
--- a/matchms/Metadata.py
+++ b/matchms/Metadata.py
@@ -11,11 +11,6 @@ from .filtering.metadata_processing.make_charge_int import \
from .utils import load_export_key_conversions, load_known_key_conversions
-_key_regex_replacements = {r"\s": "_",
- r"[!?.,;:]": ""}
-_key_replacements = load_known_key_conversions()
-
-
class Metadata:
"""Class to handle spectrum metadata in matchms.
@@ -46,6 +41,11 @@ class Metadata:
print(metadata["compound_name"]) # => None (now you need to use "compound name")
"""
+
+ _key_regex_replacements = {r"\s": "_",
+ r"[!?.,;:]": ""}
+ _key_replacements = load_known_key_conversions()
+
def __init__(self, metadata: dict = None,
matchms_key_style: bool = True):
"""
@@ -90,8 +90,8 @@ class Metadata:
replacements (such as precursor_mass --> precursor_mz).
"""
- self._data.key_regex_replacements = _key_regex_replacements
- self._data.key_replacements = _key_replacements
+ self._data.key_regex_replacements = Metadata._key_regex_replacements
+ self._data.key_replacements = Metadata._key_replacements
def harmonize_values(self):
"""Runs default harmonization of metadata.
@@ -195,3 +195,14 @@ class Metadata:
self.harmonize_keys()
else:
raise TypeError("Expected input of type dict or PickyDict.")
+
+ @staticmethod
+ def set_key_replacements(keys: dict):
+ """Set key replacements for metadata harmonization.
+
+ Parameters
+ ----------
+ keys:
+ Dictionary with key replacements.
+ """
+ Metadata._key_replacements = keys
\ No newline at end of file
|
matchms/matchms
|
765e45df4f1009241a9eef684aa653ead5982e53
|
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
index 99430668..ff540edd 100644
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -3,6 +3,7 @@ import numpy as np
import pytest
from pickydict import PickyDict
from matchms import Metadata
+from matchms.utils import load_known_key_conversions
@pytest.mark.parametrize("input_dict, harmonize, expected", [
@@ -106,3 +107,20 @@ def test_remove_invalid_metadata(input_dict, expected):
metadata.harmonize_values()
assert metadata == expected, "Expected metadata to be equal."
+
+
[email protected]("mapping, metadata", [
+ [{"name": "compound_name"}, {"name": "test"}],
+ [{}, {"name": "test"}],
+])
+def test_metadata_key_mapping(mapping: dict, metadata: dict):
+ Metadata.set_key_replacements(mapping)
+
+ sut = Metadata(metadata)
+ if len(mapping) > 0:
+ assert sut[next(iter(mapping.values()))] == next(iter(metadata.values()))
+ assert sut[next(iter(mapping))] is None
+ else:
+ assert sut[next(iter(metadata))] == next(iter(metadata.values()))
+
+ Metadata.set_key_replacements(load_known_key_conversions())
\ No newline at end of file
|
Enable setting key conversion with static method
Currently it is impossible to avoid the key conversion. It should be possible to set them to a user defined value with a static method.
|
0.0
|
765e45df4f1009241a9eef684aa653ead5982e53
|
[
"tests/test_metadata.py::test_metadata_key_mapping[mapping0-metadata0]",
"tests/test_metadata.py::test_metadata_key_mapping[mapping1-metadata1]"
] |
[
"tests/test_metadata.py::test_metadata_init[None-True-expected0]",
"tests/test_metadata.py::test_metadata_init[input_dict1-True-expected1]",
"tests/test_metadata.py::test_metadata_init[input_dict2-True-expected2]",
"tests/test_metadata.py::test_metadata_init[input_dict3-False-expected3]",
"tests/test_metadata.py::test_metadata_init[input_dict4-True-expected4]",
"tests/test_metadata.py::test_metadata_init[input_dict5-True-expected5]",
"tests/test_metadata.py::test_metadata_init[input_dict6-True-expected6]",
"tests/test_metadata.py::test_metadata_setter[True-precursor_mz-101.01-expected0]",
"tests/test_metadata.py::test_metadata_setter[True-precursormz-101.01-expected1]",
"tests/test_metadata.py::test_metadata_setter[False-precursormz-101.01-expected2]",
"tests/test_metadata.py::test_metadata_setter[True-ionmode-NEGATIVE-expected3]",
"tests/test_metadata.py::test_metadata_setter_getter[True-precursor_mz-101.01-precursor_mz-101.01]",
"tests/test_metadata.py::test_metadata_setter_getter[True-precursormz-101.01-precursor_mz-101.01]",
"tests/test_metadata.py::test_metadata_setter_getter[False-precursormz-101.01-precursormz-101.01]",
"tests/test_metadata.py::test_metadata_setter_getter[True-ionmode-NEGATIVE-ionmode-NEGATIVE]",
"tests/test_metadata.py::test_metadata_setitem_getitem[True-precursor_mz-101.01-precursor_mz-101.01]",
"tests/test_metadata.py::test_metadata_setitem_getitem[True-precursormz-101.01-precursor_mz-101.01]",
"tests/test_metadata.py::test_metadata_setitem_getitem[False-precursormz-101.01-precursormz-101.01]",
"tests/test_metadata.py::test_metadata_setitem_getitem[True-ionmode-NEGATIVE-ionmode-NEGATIVE]",
"tests/test_metadata.py::test_metadata_to_dict[None-matchms-expected0]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict1-matchms-expected1]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict2-massbank-expected2]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict3-massbank-expected3]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict4-nist-expected4]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict5-riken-expected5]",
"tests/test_metadata.py::test_metadata_to_dict[input_dict6-gnps-expected6]",
"tests/test_metadata.py::test_metadata_equal[dict10-dict20-True]",
"tests/test_metadata.py::test_metadata_equal[dict11-dict21-False]",
"tests/test_metadata.py::test_metadata_equal[dict12-dict22-True]",
"tests/test_metadata.py::test_metadata_equal[dict13-dict23-False]",
"tests/test_metadata.py::test_metadata_equal[dict14-dict24-True]",
"tests/test_metadata.py::test_metadata_equal[dict15-dict25-False]",
"tests/test_metadata.py::test_metadata_full_setter",
"tests/test_metadata.py::test_remove_invalid_metadata[input_dict0-expected0]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-25 12:23:12+00:00
|
apache-2.0
| 3,783 |
|
matchms__matchms-598
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98091849..b8ac3693 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
### Fixed
+- Fix to handle spectra with empty peak arrays. [#598](https://github.com/matchms/matchms/issues/598)
- Fix instability introduced in CosineGreedy by `np.argsort`. [#595](https://github.com/matchms/matchms/issues/595)
### Changed
diff --git a/matchms/Spectrum.py b/matchms/Spectrum.py
index 7d2bba6e..08855d9b 100644
--- a/matchms/Spectrum.py
+++ b/matchms/Spectrum.py
@@ -105,10 +105,12 @@ class Spectrum:
return int.from_bytes(bytearray(combined_hash, 'utf-8'), 'big')
def __repr__(self):
+ precursor_mz_str = f"{self.get('precursor_mz', 0.0):.2f}"
num_peaks = len(self.peaks)
+ if num_peaks == 0:
+ return f"Spectrum(precursor m/z={precursor_mz_str}, no fragments)"
min_mz = min(self.peaks.mz)
max_mz = max(self.peaks.mz)
- precursor_mz_str = f"{self.get('precursor_mz', 0.0):.2f}"
return f"Spectrum(precursor m/z={precursor_mz_str}, {num_peaks} fragments between {min_mz:.1f} and {max_mz:.1f})"
def __str__(self):
|
matchms/matchms
|
5a425e6b3f32f84b6303ae168632144f85739dc3
|
diff --git a/tests/test_spectrum.py b/tests/test_spectrum.py
index b6874122..d6428758 100644
--- a/tests/test_spectrum.py
+++ b/tests/test_spectrum.py
@@ -141,6 +141,16 @@ def test_spectrum_to_dict_matchms_style(spectrum: Spectrum):
assert spectrum_dict == expected_dict
+def test_spectrum_repr_and_str_method():
+ # Test the __repr__ and __str__ methods.
+ spectrum = Spectrum(mz=np.array([1., 2., 3.]), intensities=np.array([0, 0.5, 1.]))
+ assert repr(spectrum) == str(spectrum) == "Spectrum(precursor m/z=0.00, 3 fragments between 1.0 and 3.0)"
+
+ # Test if spectra with empty peak arrays are handled correctly:
+ spectrum = Spectrum(mz=np.array([]), intensities=np.array([]))
+ assert repr(spectrum) == str(spectrum) == "Spectrum(precursor m/z=0.00, no fragments)"
+
+
def test_spectrum_hash(spectrum: Spectrum):
assert hash(spectrum) == 382278160858921722, "Expected different hash."
assert spectrum.metadata_hash() == "78c223faa157cc130390", \
|
Fix generating empty spectrums
**Describe the bug**
The following code generate an empty spectrum
```
s = Spectrum(np.array([1.]), np.array([1.]))
processing = SpectrumProcessor(
[
lambda spec: select_by_mz(spec, 20, 30)
]
)
processing.process_spectrums([s])
```
It raises an error when trying to print the spectra, but I assume this can casue other problems. (I found one while trying to compute scores using this spectra.
```
ValueError: min() arg is an empty sequence
```
**To Reproduce**
Code above.
**Expected behavior**
It should not break, I guess empty spectrum is find in some cases, when processing data.
**Desktop (please complete the following information):**
- OS: Windows
- Version python3.11.2 , matchms:0.24.0
|
0.0
|
5a425e6b3f32f84b6303ae168632144f85739dc3
|
[
"tests/test_spectrum.py::test_spectrum_repr_and_str_method"
] |
[
"tests/test_spectrum.py::test_spectrum_getters_return_copies",
"tests/test_spectrum.py::test_spectrum_getters",
"tests/test_spectrum.py::test_spectrum_metadata_harmonization[input_dict0-expected_dict0]",
"tests/test_spectrum.py::test_spectrum_metadata_harmonization[input_dict1-expected_dict1]",
"tests/test_spectrum.py::test_spectrum_metadata_harmonization[input_dict2-expected_dict2]",
"tests/test_spectrum.py::test_comparing_spectra_with_metadata",
"tests/test_spectrum.py::test_comparing_spectra_with_arrays",
"tests/test_spectrum.py::test_spectrum_to_dict",
"tests/test_spectrum.py::test_spectrum_to_dict_matchms_style",
"tests/test_spectrum.py::test_spectrum_hash",
"tests/test_spectrum.py::test_spectrum_hash_mz_sensitivity",
"tests/test_spectrum.py::test_spectrum_hash_intensity_sensitivity",
"tests/test_spectrum.py::test_spectrum_hash_metadata_sensitivity",
"tests/test_spectrum.py::test_spectrum_clone[True]",
"tests/test_spectrum.py::test_spectrum_clone[False]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict0-True-expected0]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict1-True-expected1]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict2-True-expected2]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict3-False-expected3]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict4-True-expected4]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict5-True-expected5]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict6-True-expected6]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict7-True-expected7]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict8-True-expected8]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict9-True-expected9]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict10-True-expected10]",
"tests/test_spectrum.py::test_metadata_default_filtering[input_dict11-True-expected11]",
"tests/test_spectrum.py::test_spectrum_plot_same_peak_height",
"tests/test_spectrum.py::test_spectrum_plot",
"tests/test_spectrum.py::test_spectrum_mirror_plot"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-01-16 11:10:27+00:00
|
apache-2.0
| 3,784 |
|
materialsvirtuallab__monty-635
|
diff --git a/monty/io.py b/monty/io.py
index df7f1ff..98f3857 100644
--- a/monty/io.py
+++ b/monty/io.py
@@ -17,7 +17,7 @@ from typing import IO, Generator, Union
def zopen(filename: Union[str, Path], *args, **kwargs) -> IO:
- r"""
+ """
This function wraps around the bz2, gzip, lzma, xz and standard python's open
function to deal intelligently with bzipped, gzipped or standard text
files.
diff --git a/monty/shutil.py b/monty/shutil.py
index 1e19db3..2373984 100644
--- a/monty/shutil.py
+++ b/monty/shutil.py
@@ -7,7 +7,7 @@ import shutil
import warnings
from gzip import GzipFile
from pathlib import Path
-from typing import Literal
+from typing import Literal, Optional
from .io import zopen
@@ -65,7 +65,9 @@ def gzip_dir(path: str | Path, compresslevel: int = 6) -> None:
def compress_file(
- filepath: str | Path, compression: Literal["gz", "bz2"] = "gz"
+ filepath: str | Path,
+ compression: Literal["gz", "bz2"] = "gz",
+ target_dir: Optional[str | Path] = None,
) -> None:
"""
Compresses a file with the correct extension. Functions like standard
@@ -76,15 +78,26 @@ def compress_file(
filepath (str | Path): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
+ target_dir (str | Path): An optional target dir where the result compressed
+ file would be stored. Defaults to None for in-place compression.
"""
filepath = Path(filepath)
- if compression not in ["gz", "bz2"]:
+ target_dir = Path(target_dir) if target_dir is not None else None
+
+ if compression not in {"gz", "bz2"}:
raise ValueError("Supported compression formats are 'gz' and 'bz2'.")
+
if filepath.suffix.lower() != f".{compression}" and not filepath.is_symlink():
- with open(filepath, "rb") as f_in, zopen(
- f"{filepath}.{compression}", "wb"
- ) as f_out:
+ if target_dir is not None:
+ os.makedirs(target_dir, exist_ok=True)
+ compressed_file: str | Path = target_dir / f"{filepath.name}.{compression}"
+
+ else:
+ compressed_file = f"{str(filepath)}.{compression}"
+
+ with open(filepath, "rb") as f_in, zopen(compressed_file, "wb") as f_out:
f_out.writelines(f_in)
+
os.remove(filepath)
@@ -107,23 +120,37 @@ def compress_dir(path: str | Path, compression: Literal["gz", "bz2"] = "gz") ->
return None
-def decompress_file(filepath: str | Path) -> str | None:
+def decompress_file(
+ filepath: str | Path, target_dir: Optional[str | Path] = None
+) -> str | None:
"""
Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Args:
- filepath (str): Path to file.
+ filepath (str | Path): Path to file.
+ target_dir (str | Path): An optional target dir where the result decompressed
+ file would be stored. Defaults to None for in-place decompression.
Returns:
- str: The decompressed file path.
+ str | None: The decompressed file path, None if no operation.
"""
filepath = Path(filepath)
+ target_dir = Path(target_dir) if target_dir is not None else None
file_ext = filepath.suffix
- if file_ext.lower() in [".bz2", ".gz", ".z"] and filepath.is_file():
- decompressed_file = Path(str(filepath).removesuffix(file_ext))
+
+ if file_ext.lower() in {".bz2", ".gz", ".z"} and filepath.is_file():
+ if target_dir is not None:
+ os.makedirs(target_dir, exist_ok=True)
+ decompressed_file: str | Path = target_dir / filepath.name.removesuffix(
+ file_ext
+ )
+ else:
+ decompressed_file = str(filepath).removesuffix(file_ext)
+
with zopen(filepath, "rb") as f_in, open(decompressed_file, "wb") as f_out:
f_out.writelines(f_in)
+
os.remove(filepath)
return str(decompressed_file)
|
materialsvirtuallab/monty
|
2fab913f9e0c1fc8e1e14a6c39aae4b601e1459b
|
diff --git a/tests/test_shutil.py b/tests/test_shutil.py
index 70f76d0..d5e9cab 100644
--- a/tests/test_shutil.py
+++ b/tests/test_shutil.py
@@ -69,16 +69,19 @@ class TestCompressFileDir:
def test_compress_and_decompress_file(self):
fname = os.path.join(test_dir, "tempfile")
+
for fmt in ["gz", "bz2"]:
compress_file(fname, fmt)
assert os.path.exists(fname + "." + fmt)
assert not os.path.exists(fname)
+
decompress_file(fname + "." + fmt)
assert os.path.exists(fname)
assert not os.path.exists(fname + "." + fmt)
- with open(fname) as f:
- txt = f.read()
- assert txt == "hello world"
+
+ with open(fname) as f:
+ assert f.read() == "hello world"
+
with pytest.raises(ValueError):
compress_file("whatever", "badformat")
@@ -87,6 +90,30 @@ class TestCompressFileDir:
assert decompress_file("non-existent.gz") is None
assert decompress_file("non-existent.bz2") is None
+ def test_compress_and_decompress_with_target_dir(self):
+ fname = os.path.join(test_dir, "tempfile")
+ target_dir = os.path.join(test_dir, "temp_target_dir")
+
+ for fmt in ["gz", "bz2"]:
+ compress_file(fname, fmt, target_dir)
+ compressed_file_path = os.path.join(
+ target_dir, f"{os.path.basename(fname)}.{fmt}"
+ )
+ assert os.path.exists(compressed_file_path)
+ assert not os.path.exists(fname)
+
+ decompress_file(compressed_file_path, target_dir)
+ decompressed_file_path = os.path.join(target_dir, os.path.basename(fname))
+ assert os.path.exists(decompressed_file_path)
+ assert not os.path.exists(compressed_file_path)
+
+ # Reset temp file position
+ shutil.move(decompressed_file_path, fname)
+ shutil.rmtree(target_dir)
+
+ with open(fname) as f:
+ assert f.read() == "hello world"
+
def teardown_method(self):
os.remove(os.path.join(test_dir, "tempfile"))
|
[Feature Request]: `compress_file` and `decompress_file` allow specify target path
### Problem
Would it be a good idea to allow user to optionally specific the output file path for `compress_file` and `decompress_file`? I could help implement this if so.
Or is there any reason not to do so?
Thanks
### Proposed Solution
Append a prefix to `filepath` (if not None) should suffice:
https://github.com/materialsvirtuallab/monty/blob/4d60fd4745f840354e7b3f48346eaf3cd68f2b35/monty/shutil.py#L79-L87
### Code of Conduct
- [X] I agree to follow this project's Code of Conduct
|
0.0
|
2fab913f9e0c1fc8e1e14a6c39aae4b601e1459b
|
[
"tests/test_shutil.py::TestCompressFileDir::test_compress_and_decompress_with_target_dir"
] |
[
"tests/test_shutil.py::TestCopyR::test_recursive_copy_and_compress",
"tests/test_shutil.py::TestCopyR::test_pathlib",
"tests/test_shutil.py::TestCompressFileDir::test_compress_and_decompress_file",
"tests/test_shutil.py::TestGzipDir::test_gzip",
"tests/test_shutil.py::TestGzipDir::test_handle_sub_dirs",
"tests/test_shutil.py::TestRemove::test_remove_file",
"tests/test_shutil.py::TestRemove::test_remove_folder",
"tests/test_shutil.py::TestRemove::test_remove_symlink",
"tests/test_shutil.py::TestRemove::test_remove_symlink_follow"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-03-01 02:49:41+00:00
|
mit
| 3,785 |
|
mathLab__EZyRB-213
|
diff --git a/ezyrb/reducedordermodel.py b/ezyrb/reducedordermodel.py
index 8f654ab..cdcb228 100644
--- a/ezyrb/reducedordermodel.py
+++ b/ezyrb/reducedordermodel.py
@@ -217,15 +217,16 @@ class ReducedOrderModel():
db_range = list(range(len(self.database)))
for j in db_range:
- remaining_index = db_range[:]
- remaining_index.remove(j)
- new_db = self.database[remaining_index]
+ indeces = np.array([True] * len(self.database))
+ indeces[j] = False
+
+ new_db = self.database[indeces]
+ test_db = self.database[~indeces]
rom = type(self)(new_db, copy.deepcopy(self.reduction),
copy.deepcopy(self.approximation)).fit(
*args, **kwargs)
- error[j] = norm(self.database.snapshots[j] -
- rom.predict(self.database.parameters[j]))
+ error[j] = rom.test_error(test_db)
return error
|
mathLab/EZyRB
|
767a924ac5006e42f216ed25038178ba8c2e1911
|
diff --git a/tests/test_reducedordermodel.py b/tests/test_reducedordermodel.py
index 788bae6..7a94432 100644
--- a/tests/test_reducedordermodel.py
+++ b/tests/test_reducedordermodel.py
@@ -177,7 +177,7 @@ class TestReducedOrderModel(TestCase):
err = rom.loo_error()
np.testing.assert_allclose(
err,
- np.array([421.299091, 344.571787, 48.711501, 300.490491]),
+ np.array([0.540029, 1.211744, 0.271776, 0.919509]),
rtol=1e-4)
def test_loo_error_02(self):
@@ -188,7 +188,7 @@ class TestReducedOrderModel(TestCase):
err = rom.loo_error(normalizer=False)
np.testing.assert_allclose(
err[0],
- np.array(498.703803),
+ np.array(0.639247),
rtol=1e-3)
def test_loo_error_singular_values(self):
@@ -206,5 +206,5 @@ class TestReducedOrderModel(TestCase):
db = Database(param, snapshots.T)
rom = ROM(db, pod, rbf).fit()
opt_mu = rom.optimal_mu()
- np.testing.assert_allclose(opt_mu, [[-0.17687147, -0.21820951]],
+ np.testing.assert_allclose(opt_mu, [[-0.046381, -0.15578 ]],
rtol=1e-4)
|
LOO error is an absolute error
loo_error in reducedordermodel.py is an absolute error.
|
0.0
|
767a924ac5006e42f216ed25038178ba8c2e1911
|
[
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_loo_error_01",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_loo_error_02",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_optimal_mu"
] |
[
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_constructor",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_kfold_cv_error_01",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_load",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_load2",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_loo_error_singular_values",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_01",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_02",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_03",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_04",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_scaler_01",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_scaler_02",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_predict_scaling_coeffs",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_save",
"tests/test_reducedordermodel.py::TestReducedOrderModel::test_test_error"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-05-27 13:07:06+00:00
|
mit
| 3,786 |
|
mathandy__svgpathtools-136
|
diff --git a/svgpathtools/path.py b/svgpathtools/path.py
index 54ddac4..9f6ea3f 100644
--- a/svgpathtools/path.py
+++ b/svgpathtools/path.py
@@ -18,7 +18,7 @@ from itertools import tee
# in order to encourage code that generalizes to vector inputs
from numpy import sqrt, cos, sin, tan, arccos as acos, arcsin as asin, \
degrees, radians, log, pi, ceil
-from numpy import exp, sqrt as csqrt, angle as phase
+from numpy import exp, sqrt as csqrt, angle as phase, isnan
try:
from scipy.integrate import quad
@@ -898,31 +898,30 @@ class QuadraticBezier(object):
if abs(a) < 1e-12:
s = abs(b)*(t1 - t0)
- elif abs(a_dot_b + abs(a)*abs(b)) < 1e-12:
- tstar = abs(b)/(2*abs(a))
- if t1 < tstar:
- return abs(a)*(t0**2 - t1**2) - abs(b)*(t0 - t1)
- elif tstar < t0:
- return abs(a)*(t1**2 - t0**2) - abs(b)*(t1 - t0)
- else:
- return abs(a)*(t1**2 + t0**2) - abs(b)*(t1 + t0) + \
- abs(b)**2/(2*abs(a))
else:
- c2 = 4*(a.real**2 + a.imag**2)
- c1 = 4*a_dot_b
- c0 = b.real**2 + b.imag**2
-
- beta = c1/(2*c2)
- gamma = c0/c2 - beta**2
-
- dq1_mag = sqrt(c2*t1**2 + c1*t1 + c0)
- dq0_mag = sqrt(c2*t0**2 + c1*t0 + c0)
- logarand = (sqrt(c2)*(t1 + beta) + dq1_mag) / \
- (sqrt(c2)*(t0 + beta) + dq0_mag)
-
- s = (t1 + beta)*dq1_mag - (t0 + beta)*dq0_mag + \
- gamma*sqrt(c2)*log(logarand)
+ c2 = 4 * (a.real ** 2 + a.imag ** 2)
+ c1 = 4 * a_dot_b
+ c0 = b.real ** 2 + b.imag ** 2
+
+ beta = c1 / (2 * c2)
+ gamma = c0 / c2 - beta ** 2
+
+ dq1_mag = sqrt(c2 * t1 ** 2 + c1 * t1 + c0)
+ dq0_mag = sqrt(c2 * t0 ** 2 + c1 * t0 + c0)
+ logarand = (sqrt(c2) * (t1 + beta) + dq1_mag) / \
+ (sqrt(c2) * (t0 + beta) + dq0_mag)
+ s = (t1 + beta) * dq1_mag - (t0 + beta) * dq0_mag + \
+ gamma * sqrt(c2) * log(logarand)
s /= 2
+ if isnan(s):
+ tstar = abs(b) / (2 * abs(a))
+ if t1 < tstar:
+ return abs(a) * (t0 ** 2 - t1 ** 2) - abs(b) * (t0 - t1)
+ elif tstar < t0:
+ return abs(a) * (t1 ** 2 - t0 ** 2) - abs(b) * (t1 - t0)
+ else:
+ return abs(a) * (t1 ** 2 + t0 ** 2) - abs(b) * (t1 + t0) + \
+ abs(b) ** 2 / (2 * abs(a))
if t0 == 1 and t1 == 0:
self._length_info['length'] = s
@@ -2445,7 +2444,10 @@ class Path(MutableSequence):
lengths = [each.length(error=error, min_depth=min_depth) for each in
self._segments]
self._length = sum(lengths)
- self._lengths = [each/self._length for each in lengths]
+ if self._length == 0:
+ self._lengths = lengths # all lengths are 0.
+ else:
+ self._lengths = [each / self._length for each in lengths]
def point(self, pos):
@@ -2522,7 +2524,10 @@ class Path(MutableSequence):
return self.start == self.end
def _is_closable(self):
- end = self[-1].end
+ try:
+ end = self[-1].end
+ except IndexError:
+ return True
for segment in self:
if segment.start == end:
return True
@@ -2574,7 +2579,8 @@ class Path(MutableSequence):
"""Returns a path d-string for the path object.
For an explanation of useSandT and use_closed_attrib, see the
compatibility notes in the README."""
-
+ if len(self) == 0:
+ return ''
if use_closed_attrib:
self_closed = self.iscontinuous() and self.isclosed()
if self_closed:
@@ -2866,8 +2872,7 @@ class Path(MutableSequence):
# redundant intersection. This code block checks for and removes said
# redundancies.
if intersection_list:
- pts = [seg1.point(_t1)
- for _T1, _seg1, _t1 in list(zip(*intersection_list))[0]]
+ pts = [_seg1.point(_t1) for _T1, _seg1, _t1 in list(zip(*intersection_list))[0]]
indices2remove = []
for ind1 in range(len(pts)):
for ind2 in range(ind1 + 1, len(pts)):
|
mathandy/svgpathtools
|
091394b5e3267e5d5b45f6d71a23d12a1ff446b9
|
diff --git a/test/test_path.py b/test/test_path.py
index 3769bd0..5b7d448 100644
--- a/test/test_path.py
+++ b/test/test_path.py
@@ -687,7 +687,6 @@ class ArcTest(unittest.TestCase):
self.assertAlmostEqual(d,0.0, delta=2)
-
class TestPath(unittest.TestCase):
def test_circle(self):
@@ -1660,7 +1659,6 @@ class Test_intersect(unittest.TestCase):
assert_intersections(a0, a1, intersections, 0)
-
class TestPathTools(unittest.TestCase):
# moved from test_pathtools.py
@@ -1950,5 +1948,50 @@ class TestPathTools(unittest.TestCase):
self.assertTrue(enclosing_shape.is_contained_by(larger_shape))
+class TestPathBugs(unittest.TestCase):
+
+ def test_issue_113(self):
+ """
+ Tests against issue regebro/svg.path#61 mathandy/svgpathtools#113
+ """
+ p = Path('M 206.5,525 Q 162.5,583 162.5,583')
+ self.assertAlmostEqual(p.length(), 72.80109889280519)
+ p = Path('M 425.781 446.289 Q 410.40000000000003 373.047 410.4 373.047')
+ self.assertAlmostEqual(p.length(), 74.83959997888816)
+ p = Path('M 639.648 568.115 Q 606.6890000000001 507.568 606.689 507.568')
+ self.assertAlmostEqual(p.length(), 68.93645544992873)
+ p = Path('M 288.818 616.699 Q 301.025 547.3629999999999 301.025 547.363')
+ self.assertAlmostEqual(p.length(), 70.40235610403947)
+ p = Path('M 339.927 706.25 Q 243.92700000000002 806.25 243.927 806.25')
+ self.assertAlmostEqual(p.length(), 138.6217876093077)
+ p = Path('M 539.795 702.637 Q 548.0959999999999 803.4669999999999 548.096 803.467')
+ self.assertAlmostEqual(p.length(), 101.17111989594662)
+ p = Path('M 537.815 555.042 Q 570.1680000000001 499.1600000000001 570.168 499.16')
+ self.assertAlmostEqual(p.length(), 64.57177814649368)
+ p = Path('M 615.297 470.503 Q 538.797 694.5029999999999 538.797 694.503')
+ self.assertAlmostEqual(p.length(), 236.70287281737836)
+
+ def test_issue_71(self):
+ p = Path("M327 468z")
+ m = p.closed
+ q = p.d() # Failing to Crash is good.
+
+ def test_issue_95(self):
+ """
+ Corrects:
+ https://github.com/mathandy/svgpathtools/issues/95
+ """
+ p = Path('M261 166 L261 166')
+ self.assertEqual(p.length(), 0)
+
+ def test_issue_94(self):
+ # clipping rectangle
+ p1 = Path('M0.0 0.0 L27.84765625 0.0 L27.84765625 242.6669922 L0.0 242.6669922 z')
+ # clipping rectangle
+ p2 = Path('M166.8359375,235.5478516c0,3.7773438-3.0859375,6.8691406-6.8701172,6.8691406H7.1108398c-3.7749023,0-6.8608398-3.0917969-6.8608398-6.8691406V7.1201172C0.25,3.3427734,3.3359375,0.25,7.1108398,0.25h152.8549805c3.7841797,0,6.8701172,3.0927734,6.8701172,6.8701172v228.4277344z')
+ self.assertEqual(len(p1.intersect(p2)), len(p2.intersect(p1)))
+
+
+
if __name__ == '__main__':
unittest.main()
|
length() fails on certain quadratic curves (svg.path#61)
This code fails to the same bug in regebro/svg.path#61
You cannot calculate the length of the following paths without throwing an error:
- M 425.781 446.289 Q 410.40000000000003 373.047 410.4 373.047
- M 639.648 568.115 Q 606.6890000000001 507.568 606.689 507.568
- M 288.818 616.699 Q 301.025 547.3629999999999 301.025 547.363
- M 339.927 706.25 Q 243.92700000000002 806.25 243.927 806.25
- M 539.795 702.637 Q 548.0959999999999 803.4669999999999 548.096 803.467
- M 537.815 555.042 Q 570.1680000000001 499.1600000000001 570.168 499.16
- M 615.297 470.503 Q 538.797 694.5029999999999 538.797 694.503
Because the code in the quad arc performs a check for the quasi-linear against 1e-12 and these are not linear enough to fall into those prechecks, but are too linear to allow the function to work and they end up dividing by zero anyway.
QuadraticBezierCurve.length() https://github.com/mathandy/svgpathtools/blob/master/svgpathtools/path.py#L812
```python
if abs(a) < 1e-12:
s = abs(b)*(t1 - t0)
elif abs(a_dot_b + abs(a)*abs(b)) < 1e-12:
...
```
You need to try the main block of code, and perform these functions on fail rather than beforehand, if it throws a divide by zero or valueerror (domain) accordingly.
|
0.0
|
091394b5e3267e5d5b45f6d71a23d12a1ff446b9
|
[
"test/test_path.py::TestPathBugs::test_issue_113",
"test/test_path.py::TestPathBugs::test_issue_71",
"test/test_path.py::TestPathBugs::test_issue_94",
"test/test_path.py::TestPathBugs::test_issue_95"
] |
[
"test/test_path.py::LineTest::test_equality",
"test/test_path.py::LineTest::test_lines",
"test/test_path.py::LineTest::test_point_to_t",
"test/test_path.py::LineTest::test_radialrange",
"test/test_path.py::CubicBezierTest::test_approx_circle",
"test/test_path.py::CubicBezierTest::test_equality",
"test/test_path.py::CubicBezierTest::test_length",
"test/test_path.py::CubicBezierTest::test_svg_examples",
"test/test_path.py::QuadraticBezierTest::test_equality",
"test/test_path.py::QuadraticBezierTest::test_length",
"test/test_path.py::QuadraticBezierTest::test_svg_examples",
"test/test_path.py::ArcTest::test_approx_cubic",
"test/test_path.py::ArcTest::test_approx_quad",
"test/test_path.py::ArcTest::test_equality",
"test/test_path.py::ArcTest::test_length",
"test/test_path.py::ArcTest::test_point_to_t",
"test/test_path.py::ArcTest::test_points",
"test/test_path.py::ArcTest::test_trusting_acos",
"test/test_path.py::TestPath::test_circle",
"test/test_path.py::TestPath::test_continuous_subpaths",
"test/test_path.py::TestPath::test_cropped",
"test/test_path.py::TestPath::test_d",
"test/test_path.py::TestPath::test_equality",
"test/test_path.py::TestPath::test_repr",
"test/test_path.py::TestPath::test_svg_specs",
"test/test_path.py::TestPath::test_transform_scale",
"test/test_path.py::Test_ilength::test_ilength_arcs",
"test/test_path.py::Test_ilength::test_ilength_cubics",
"test/test_path.py::Test_ilength::test_ilength_exceptions",
"test/test_path.py::Test_ilength::test_ilength_lines",
"test/test_path.py::Test_ilength::test_ilength_paths",
"test/test_path.py::Test_ilength::test_ilength_quadratics",
"test/test_path.py::Test_intersect::test_arc_arc_0",
"test/test_path.py::Test_intersect::test_arc_arc_1",
"test/test_path.py::Test_intersect::test_arc_arc_2",
"test/test_path.py::Test_intersect::test_arc_arc_same_circle",
"test/test_path.py::Test_intersect::test_arc_arc_tangent_circles_inside",
"test/test_path.py::Test_intersect::test_arc_arc_tangent_circles_outside",
"test/test_path.py::Test_intersect::test_arc_line",
"test/test_path.py::Test_intersect::test_intersect",
"test/test_path.py::Test_intersect::test_intersect_arc_line_1",
"test/test_path.py::Test_intersect::test_intersect_arc_line_2",
"test/test_path.py::Test_intersect::test_intersect_arc_line_3",
"test/test_path.py::Test_intersect::test_intersect_arc_line_disjoint_bboxes",
"test/test_path.py::Test_intersect::test_line_line_0",
"test/test_path.py::Test_intersect::test_line_line_1",
"test/test_path.py::TestPathTools::test_bpoints2bezier",
"test/test_path.py::TestPathTools::test_closest_point_in_path",
"test/test_path.py::TestPathTools::test_farthest_point_in_path",
"test/test_path.py::TestPathTools::test_is_bezier_path",
"test/test_path.py::TestPathTools::test_is_bezier_segment",
"test/test_path.py::TestPathTools::test_is_contained_by",
"test/test_path.py::TestPathTools::test_path_area",
"test/test_path.py::TestPathTools::test_path_encloses_pt",
"test/test_path.py::TestPathTools::test_polynomial2bezier"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-20 17:06:11+00:00
|
mit
| 3,787 |
|
mathandy__svgpathtools-170
|
diff --git a/svgpathtools/document.py b/svgpathtools/document.py
index f88f5ba..1dd9077 100644
--- a/svgpathtools/document.py
+++ b/svgpathtools/document.py
@@ -289,7 +289,7 @@ class Document:
# If given a list of strings (one or more), assume it represents
# a sequence of nested group names
- elif all(isinstance(elem, str) for elem in group):
+ elif len(group) > 0 and all(isinstance(elem, str) for elem in group):
group = self.get_or_add_group(group)
elif not isinstance(group, Element):
|
mathandy/svgpathtools
|
c84c897bf2121ed86ceed45b4e027785351c2fd5
|
diff --git a/test/test_groups.py b/test/test_groups.py
index 44b6cb9..aeb3393 100644
--- a/test/test_groups.py
+++ b/test/test_groups.py
@@ -235,4 +235,11 @@ class TestGroups(unittest.TestCase):
path = parse_path(path_d)
svg_path = doc.add_path(path, group=new_leaf)
- self.assertEqual(path_d, svg_path.get('d'))
\ No newline at end of file
+ self.assertEqual(path_d, svg_path.get('d'))
+
+ # Test that paths are added to the correct group
+ new_sibling = doc.get_or_add_group(
+ ['base_group', 'new_parent', 'new_sibling'])
+ doc.add_path(path, group=new_sibling)
+ self.assertEqual(len(new_sibling), 1)
+ self.assertEqual(path_d, new_sibling[0].get('d'))
|
Document does not add path to empty group
When the passed group element has no children, `Document.add_path` incorrectly adds the path to the root element.
Example:
```python
doc = Document()
empty = doc.add_group(group_attribs={"id": "empty"})
doc.add_path("M 0,0 L 1,1", group=empty)
print(doc)
```
Output:
```svg
<svg xmlns:svg="http://www.w3.org/2000/svg"><svg:g id="empty" /><path d="M 0,0 L 1,1" /></svg>
```
Expected Output:
```svg
<svg xmlns:svg="http://www.w3.org/2000/svg"><svg:g id="empty"><path d="M 0,0 L 1,1" /></svg:g></svg>
```
|
0.0
|
c84c897bf2121ed86ceed45b4e027785351c2fd5
|
[
"test/test_groups.py::TestGroups::test_add_group"
] |
[
"test/test_groups.py::TestGroups::test_group_flatten",
"test/test_groups.py::TestGroups::test_nested_group"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-27 23:49:11+00:00
|
mit
| 3,788 |
|
mathause__mplotutils-61
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 023cb81..3afab67 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@
### Bug fixes
+- Fixed a bug in `set_map_layout`: the data ratio of a cartopy `GeoAxesSubplot` requires
+ a `draw` to be correct ([#61](https://github.com/mathause/mplotutils/pull/61)).
- Fix a regression introduced in [#33](https://github.com/mathause/mplotutils/pull/33):
`cyclic_dataarray` now correctly extrapolates the coordinates
([#58](https://github.com/mathause/mplotutils/pull/58)).
diff --git a/mplotutils/map_layout.py b/mplotutils/map_layout.py
index 33ce41b..ab620a0 100644
--- a/mplotutils/map_layout.py
+++ b/mplotutils/map_layout.py
@@ -40,6 +40,9 @@ def set_map_layout(axes, width=17.0, *, nrow=None, ncol=None):
# read figure data
f = ax.get_figure()
+ # getting the correct data ratio of geoaxes requires draw
+ f.canvas.draw()
+
bottom = f.subplotpars.bottom
top = f.subplotpars.top
left = f.subplotpars.left
|
mathause/mplotutils
|
a12b0242b93773de282b30adf2e050a8a6be7be2
|
diff --git a/mplotutils/tests/test_set_map_layout.py b/mplotutils/tests/test_set_map_layout.py
index 83aba3c..0ff4e10 100644
--- a/mplotutils/tests/test_set_map_layout.py
+++ b/mplotutils/tests/test_set_map_layout.py
@@ -195,3 +195,20 @@ def test_set_map_layout_nrow_ncol_only_one_raises():
with pytest.raises(ValueError, match="Must set none or both of 'nrow' and 'ncol'"):
set_map_layout(None, width=17.0, nrow=None, ncol=1)
+
+
+def test_set_map_layout_cartopy_2_2():
+
+ import cartopy.crs as ccrs
+
+ subplot_kw = {"projection": ccrs.PlateCarree()}
+ with subplots_context(2, 2, subplot_kw=subplot_kw) as (f, axs):
+
+ f.subplots_adjust(hspace=0, wspace=0, top=1, bottom=0, left=0, right=1)
+
+ set_map_layout(axs, width=17) # width is in cm
+
+ result = f.get_size_inches() * 2.54
+ expected = (17, 8.5)
+
+ np.testing.assert_allclose(result, expected)
|
aspect ratio requires draw for cartopy maps
The following leads to a wrong figure size:
```
f, axs = plt.subplots(2, 1, subplot_kw=dict(projection=ccrs.Robinson()))
f.subplots_adjust(hspace=0, wspace=0, top=1, bottom=0, left=0, right=1)
mpu.set_map_layout(axs, width=17) # width is in cm
print("Size (w x h): ", np.round(f.get_size_inches() * 2.54, 2))
```
cartopy maps seem to require a `f.canvas.draw()` command
|
0.0
|
a12b0242b93773de282b30adf2e050a8a6be7be2
|
[
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_cartopy_2_2"
] |
[
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_default_width",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_no_borders[nrow_ncol0]",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_no_borders[nrow_ncol1]",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_ax_arr[<lambda>0]",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_ax_arr[<lambda>1]",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_vert_borders",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_horz_borders",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_two_axes_vert",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_two_axes_horz",
"mplotutils/tests/test_set_map_layout.py::test_set_map_layout_nrow_ncol_only_one_raises"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-08 12:40:26+00:00
|
mit
| 3,789 |
|
matheuscas__pycpfcnpj-16
|
diff --git a/README.md b/README.md
index 2bb5252..9bbf26f 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,19 @@ Expected output:
>>> 49384063495
>>> 20788274885880
```
+
+And you also can generate CPF or CǸPJ with punctuation marks. :)
+
+```python
+from pycpfcnpj import gen
+gen.cpf_with_punctuation()
+gen.cnpj_with_punctuation()
+
+Expected output:
+>>> 048.891.866-97
+>>> 63.212.638/0361-35
+```
+
Have fun!
In portuguese:
@@ -108,6 +121,19 @@ Expected output:
>>> 20788274885880
```
+E você também pode gerar CPF ou CNPJ com pontuação :)
+
+```python
+from pycpfcnpj import gen
+gen.cpf_with_punctuation()
+gen.cnpj_with_punctuation()
+
+Expected output:
+>>> 048.891.866-97
+>>> 63.212.638/0361-35
+```
+
+
Divirta-se!
Changelog
@@ -118,3 +144,6 @@ Changelog
1.2
- Use `sys` rather than `six` to check python's version and keeps this project 100% free of dependencies.
+
+1.3
+- Generate CPF and CNPJ numbers with punctuation marks.
\ No newline at end of file
diff --git a/pycpfcnpj/gen.py b/pycpfcnpj/gen.py
index 4f86ffa..2b47d44 100644
--- a/pycpfcnpj/gen.py
+++ b/pycpfcnpj/gen.py
@@ -16,3 +16,13 @@ def cnpj():
while not cnpj_module.validate(cnpj_ramdom):
cnpj_ramdom = ''.join(random.choice(string.digits) for i in range(14))
return cnpj_ramdom
+
+
+def cpf_with_punctuation():
+ cpf_ramdom = cpf()
+ return '{}.{}.{}-{}'.format(cpf_ramdom[:3], cpf_ramdom[3:6], cpf_ramdom[6:9], cpf_ramdom[9:])
+
+
+def cnpj_with_punctuation():
+ cnpj_ramdom = cnpj()
+ return '{}.{}.{}/{}-{}'.format(cnpj_ramdom[:2], cnpj_ramdom[2:5], cnpj_ramdom[5:8], cnpj_ramdom[8:12], cnpj_ramdom[12:])
\ No newline at end of file
|
matheuscas/pycpfcnpj
|
775aa198de297538d77fcaf2df7ef4d0e94efbd2
|
diff --git a/tests/gen_test.py b/tests/gen_test.py
new file mode 100644
index 0000000..a2933a9
--- /dev/null
+++ b/tests/gen_test.py
@@ -0,0 +1,27 @@
+import unittest
+from pycpfcnpj import gen, cpf, cnpj
+
+class GenerateCPFTest(unittest.TestCase):
+ """docstring for GenerateCPFTest"""
+ def setUp(self):
+ self.masked_valid_cpf = gen.cpf_with_punctuation()
+
+ def test_validate_masked_cnpj_true(self):
+ self.assertTrue(cpf.validate(self.masked_valid_cpf))
+
+ def test_valif_cpf_without_mask_true(self):
+ cpf_result =(self.masked_valid_cpf.replace(".","")).replace("-","")
+ self.assertTrue(cpf.validate(cpf_result))
+
+
+class GenerateCNPJTest(unittest.TestCase):
+ """docstring for GenerateCNPJTest"""
+ def setUp(self):
+ self.masked_valid_cnpj = gen.cnpj_with_punctuation()
+
+ def test_validate_masked_cnpj_true(self):
+ self.assertTrue(cnpj.validate(self.masked_valid_cnpj))
+
+ def test_valid_cnpj_without_mask_true(self):
+ cnpj_result =(self.masked_valid_cnpj.replace(".","")).replace("-","")
+ self.assertTrue(cnpj.validate(cnpj_result))
\ No newline at end of file
|
Generates numbers with punctuation marks
After the release 1.1, that handles input numbers with punctuation marks, it would be also nice generate numbers with correct punctuation marks to each type of number, CPF and CNPJ.
|
0.0
|
775aa198de297538d77fcaf2df7ef4d0e94efbd2
|
[
"tests/gen_test.py::GenerateCPFTest::test_validate_masked_cnpj_true",
"tests/gen_test.py::GenerateCPFTest::test_valif_cpf_without_mask_true",
"tests/gen_test.py::GenerateCNPJTest::test_valid_cnpj_without_mask_true",
"tests/gen_test.py::GenerateCNPJTest::test_validate_masked_cnpj_true"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-10-24 03:25:23+00:00
|
mit
| 3,790 |
|
matrix-org__matrix-synapse-ldap3-151
|
diff --git a/README.rst b/README.rst
index 362c697..817ccad 100644
--- a/README.rst
+++ b/README.rst
@@ -18,12 +18,12 @@ Installation
Usage
-----
-Example synapse config:
+Example Synapse configuration:
.. code:: yaml
- password_providers:
- - module: "ldap_auth_provider.LdapAuthProvider"
+ modules:
+ - module: "ldap_auth_provider.LdapAuthProviderModule"
config:
enabled: true
uri: "ldap://ldap.example.com:389"
@@ -48,8 +48,8 @@ Default HA strategy of ldap3.ServerPool is employed, so first available server i
.. code:: yaml
- password_providers:
- - module: "ldap_auth_provider.LdapAuthProvider"
+ modules:
+ - module: "ldap_auth_provider.LdapAuthProviderModule"
config:
enabled: true
uri:
@@ -76,8 +76,8 @@ in search mode is provided below:
.. code:: yaml
- password_providers:
- - module: "ldap_auth_provider.LdapAuthProvider"
+ modules:
+ - module: "ldap_auth_provider.LdapAuthProviderModule"
config:
enabled: true
mode: "search"
@@ -116,8 +116,8 @@ Let's say you have several domains in the ``example.com`` forest:
.. code:: yaml
- password_providers:
- - module: "ldap_auth_provider.LdapAuthProvider"
+ modules:
+ - module: "ldap_auth_provider.LdapAuthProviderModule"
config:
enabled: true
mode: "search"
diff --git a/ldap_auth_provider.py b/ldap_auth_provider.py
index 0a67720..44d9a23 100644
--- a/ldap_auth_provider.py
+++ b/ldap_auth_provider.py
@@ -23,6 +23,7 @@ import ldap3.core.exceptions
import synapse
from pkg_resources import parse_version
from synapse.module_api import ModuleApi
+from synapse.types import JsonDict
from twisted.internet import threads
__version__ = "0.1.5"
@@ -690,6 +691,51 @@ class LdapAuthProvider:
return (login, domain, localpart)
+class LdapAuthProviderModule(LdapAuthProvider):
+ """
+ Wrapper for the LDAP Authentication Provider that supports the new generic module interface,
+ rather than the Password Authentication Provider module interface.
+ """
+
+ def __init__(self, config, api: "ModuleApi"):
+ # The Module API is API-compatible in such a way that it's a drop-in
+ # replacement for the account handler, where this module is concerned.
+ super().__init__(config, account_handler=api)
+
+ # Register callbacks, since the generic module API requires us to
+ # explicitly tell it what callbacks we want.
+ api.register_password_auth_provider_callbacks(
+ auth_checkers={
+ (SUPPORTED_LOGIN_TYPE, SUPPORTED_LOGIN_FIELDS): self.wrapped_check_auth
+ },
+ check_3pid_auth=self.wrapped_check_3pid_auth,
+ )
+
+ async def wrapped_check_auth(
+ self, username: str, login_type: str, login_dict: JsonDict
+ ) -> Optional[Tuple[str, None]]:
+ """
+ Wrapper between the old-style `check_auth` interface and the new one.
+ """
+ result = await self.check_auth(username, login_type, login_dict)
+ if result is None:
+ return None
+ else:
+ return result, None
+
+ async def wrapped_check_3pid_auth(
+ self, medium: str, address: str, password: str
+ ) -> Optional[Tuple[str, None]]:
+ """
+ Wrapper between the old-style `check_3pid_auth` interface and the new one.
+ """
+ result = await self.check_3pid_auth(medium, address, password)
+ if result is None:
+ return None
+ else:
+ return result, None
+
+
def _require_keys(config: Dict[str, Any], required: Iterable[str]) -> None:
missing = [key for key in required if key not in config]
if missing:
|
matrix-org/matrix-synapse-ldap3
|
9c3be4659a54b495fa421cb6adcacf2d590e9c7a
|
diff --git a/tests/__init__.py b/tests/__init__.py
index 7fceac4..606f707 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -14,7 +14,7 @@ try:
except ImportError:
from io import BytesIO
-from ldap_auth_provider import LdapAuthProvider
+from ldap_auth_provider import LdapAuthProviderModule
LDIF = b"""\
dn: dc=org
@@ -168,13 +168,13 @@ async def create_ldap_server(ldap_server_type: Type[LDAPServer] = LDAPServer):
return _LdapServer(listener)
-def create_auth_provider(server, account_handler, config=None):
- "Creates an LdapAuthProvider from an LDAP server and a mock account_handler"
+def create_auth_provider(server, api, config=None):
+ "Creates an LdapAuthProviderModule from an LDAP server and a mock Module API"
if config:
- config = LdapAuthProvider.parse_config(config)
+ config = LdapAuthProviderModule.parse_config(config)
else:
- config = LdapAuthProvider.parse_config(
+ config = LdapAuthProviderModule.parse_config(
{
"enabled": True,
"uri": "ldap://localhost:%d" % server.listener.getHost().port,
@@ -187,7 +187,7 @@ def create_auth_provider(server, account_handler, config=None):
}
)
- return LdapAuthProvider(config, account_handler=account_handler)
+ return LdapAuthProviderModule(config, api=api)
def make_awaitable(result: Any) -> Awaitable[Any]:
diff --git a/tests/test_ad.py b/tests/test_ad.py
index 2bdbb79..1e5cd5b 100644
--- a/tests/test_ad.py
+++ b/tests/test_ad.py
@@ -66,13 +66,19 @@ class AbstractLdapActiveDirectoryTestCase:
self.ldap_server = yield ensureDeferred(
create_ldap_server(_ActiveDirectoryLDAPServer)
)
- account_handler = Mock(spec_set=["check_user_exists", "get_qualified_user_id"])
- account_handler.check_user_exists.return_value = make_awaitable(True)
- account_handler.get_qualified_user_id = get_qualified_user_id
+ module_api = Mock(
+ spec_set=[
+ "check_user_exists",
+ "get_qualified_user_id",
+ "register_password_auth_provider_callbacks",
+ ]
+ )
+ module_api.check_user_exists.return_value = make_awaitable(True)
+ module_api.get_qualified_user_id = get_qualified_user_id
self.auth_provider = create_auth_provider(
self.ldap_server,
- account_handler,
+ module_api,
config=self.getConfig(),
)
diff --git a/tests/test_simple.py b/tests/test_simple.py
index 6d99ccc..0ffaf7f 100644
--- a/tests/test_simple.py
+++ b/tests/test_simple.py
@@ -33,13 +33,19 @@ class LdapSimpleTestCase(unittest.TestCase):
@defer.inlineCallbacks
def setUp(self):
self.ldap_server = yield defer.ensureDeferred(create_ldap_server())
- account_handler = Mock(spec_set=["check_user_exists", "get_qualified_user_id"])
- account_handler.check_user_exists.return_value = make_awaitable(True)
- account_handler.get_qualified_user_id = get_qualified_user_id
+ module_api = Mock(
+ spec_set=[
+ "check_user_exists",
+ "get_qualified_user_id",
+ "register_password_auth_provider_callbacks",
+ ]
+ )
+ module_api.check_user_exists.return_value = make_awaitable(True)
+ module_api.get_qualified_user_id = get_qualified_user_id
self.auth_provider = create_auth_provider(
self.ldap_server,
- account_handler,
+ module_api,
config={
"enabled": True,
"uri": "ldap://localhost:%d" % self.ldap_server.listener.getHost().port,
@@ -94,13 +100,19 @@ class LdapSearchTestCase(unittest.TestCase):
@defer.inlineCallbacks
def setUp(self):
self.ldap_server = yield defer.ensureDeferred(create_ldap_server())
- account_handler = Mock(spec_set=["check_user_exists", "get_qualified_user_id"])
- account_handler.check_user_exists.return_value = make_awaitable(True)
- account_handler.get_qualified_user_id = get_qualified_user_id
+ module_api = Mock(
+ spec_set=[
+ "check_user_exists",
+ "get_qualified_user_id",
+ "register_password_auth_provider_callbacks",
+ ]
+ )
+ module_api.check_user_exists.return_value = make_awaitable(True)
+ module_api.get_qualified_user_id = get_qualified_user_id
self.auth_provider = create_auth_provider(
self.ldap_server,
- account_handler,
+ module_api,
config={
"enabled": True,
"uri": "ldap://localhost:%d" % self.ldap_server.listener.getHost().port,
|
Port the module to Synapse's pluggable modules
**Is your feature request related to a problem? Please describe.**
The password_providers: module interface has been deprecated and matrix-synapse-ldap3 does not seem to support the new generic module interface.
**Describe the solution you'd like**
Could you please port the module to the new generic module interface.
**Describe alternatives you've considered**
**Additional context**
Here is the error I get if I try to use the module with the generic interface:
```
2021-11-03 08:37:00,307 - root - 345 - WARNING - main - ***** STARTING SERVER *****
2021-11-03 08:37:00,308 - root - 346 - WARNING - main - Server /opt/venvs/matrix-synapse/lib/python3.7/site-packages/synapse/app/homeserver.py version 1.46.0
2021-11-03 08:37:00,484 - synapse.app._base - 214 - CRITICAL - sentinel - Error during startup
Traceback (most recent call last):
File "/opt/venvs/matrix-synapse/lib/python3.7/site-packages/synapse/app/_base.py", line 199, in wrapper
await cb(*args, **kwargs)
File "/opt/venvs/matrix-synapse/lib/python3.7/site-packages/synapse/app/homeserver.py", line 374, in start
await _base.start(hs)
File "/opt/venvs/matrix-synapse/lib/python3.7/site-packages/synapse/app/_base.py", line 390, in start
module(config=config, api=module_api)
TypeError: __init__() got an unexpected keyword argument 'api'
```
|
0.0
|
9c3be4659a54b495fa421cb6adcacf2d590e9c7a
|
[
"tests/test_ad.py::LdapActiveDirectoryTestCase::test_correct_pwd",
"tests/test_ad.py::LdapActiveDirectoryTestCase::test_email_login",
"tests/test_ad.py::LdapActiveDirectoryTestCase::test_incorrect_pwd",
"tests/test_ad.py::LdapActiveDirectoryTestCase::test_single_email",
"tests/test_ad.py::LdapActiveDirectoryDefaultDomainTestCase::test_correct_pwd",
"tests/test_ad.py::LdapActiveDirectoryDefaultDomainTestCase::test_email_login",
"tests/test_ad.py::LdapActiveDirectoryDefaultDomainTestCase::test_incorrect_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_correct_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_incorrect_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_no_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_unknown_user",
"tests/test_simple.py::LdapSearchTestCase::test_correct_pwd_search_mode",
"tests/test_simple.py::LdapSearchTestCase::test_incorrect_pwd_search_mode",
"tests/test_simple.py::LdapSearchTestCase::test_unknown_user_search_mode"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-12-31 11:44:17+00:00
|
apache-2.0
| 3,791 |
|
matrix-org__matrix-synapse-ldap3-163
|
diff --git a/ldap_auth_provider.py b/ldap_auth_provider.py
index 9398350..dcefe15 100644
--- a/ldap_auth_provider.py
+++ b/ldap_auth_provider.py
@@ -133,6 +133,8 @@ class LdapAuthProvider:
except ActiveDirectoryUPNException:
return None
+ localpart = localpart.lower()
+
try:
server = self._get_server()
logger.debug("Attempting LDAP connection with %s", self.ldap_uris)
diff --git a/setup.cfg b/setup.cfg
index 92c3c4c..8b0779c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -31,7 +31,7 @@ dev =
types-setuptools
# for linting
- black == 21.9b0
+ black == 22.3.0
flake8 == 4.0.1
isort == 5.9.3
|
matrix-org/matrix-synapse-ldap3
|
9b8ba73b43b91095be925d80a4c25d6631ff99dd
|
diff --git a/tests/test_simple.py b/tests/test_simple.py
index 0ffaf7f..6e570b0 100644
--- a/tests/test_simple.py
+++ b/tests/test_simple.py
@@ -95,6 +95,15 @@ class LdapSimpleTestCase(unittest.TestCase):
)
self.assertFalse(result)
+ @defer.inlineCallbacks
+ def test_uppercase_username(self):
+ result = yield defer.ensureDeferred(
+ self.auth_provider.check_auth(
+ "BOB", "m.login.password", {"password": "secret"}
+ )
+ )
+ self.assertEqual(result, "@bob:test")
+
class LdapSearchTestCase(unittest.TestCase):
@defer.inlineCallbacks
|
Can login only with lowercase username
Hello,
it looks like that, when the user tries to login with uppercase or a combination of uppercase and lowercase, the login fails.
The only way to login using the Active Directory credentials is to use only lowercase.
In the configuration we have:
attributes:
uid: "sAMAccountName"
mail: "mail"
name: "displayName"
Is there a way to allow the users to login without caring about the case sensitivity?
Thank you in advance
|
0.0
|
9b8ba73b43b91095be925d80a4c25d6631ff99dd
|
[
"tests/test_simple.py::LdapSimpleTestCase::test_uppercase_username"
] |
[
"tests/test_simple.py::LdapSimpleTestCase::test_correct_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_incorrect_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_no_pwd",
"tests/test_simple.py::LdapSimpleTestCase::test_unknown_user",
"tests/test_simple.py::LdapSearchTestCase::test_correct_pwd_search_mode",
"tests/test_simple.py::LdapSearchTestCase::test_incorrect_pwd_search_mode",
"tests/test_simple.py::LdapSearchTestCase::test_unknown_user_search_mode"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-25 23:26:55+00:00
|
apache-2.0
| 3,792 |
|
matrix-org__python-canonicaljson-46
|
diff --git a/README.rst b/README.rst
index 9311e6c..af0c212 100644
--- a/README.rst
+++ b/README.rst
@@ -17,7 +17,7 @@ Features
* Encodes the JSON as UTF-8.
* Can encode ``frozendict`` immutable dictionaries.
-Supports Python versions 3.5 and newer.
+Supports Python versions 3.7 and newer.
.. _`RFC 7159`: https://tools.ietf.org/html/rfc7159
diff --git a/canonicaljson.py b/canonicaljson.py
index 89913ff..654e34a 100644
--- a/canonicaljson.py
+++ b/canonicaljson.py
@@ -16,23 +16,21 @@
# limitations under the License.
import platform
+from typing import Optional, Type
-from frozendict import frozendict
+frozendict_type: Optional[Type]
+try:
+ from frozendict import frozendict as frozendict_type
+except ImportError:
+ frozendict_type = None # pragma: no cover
__version__ = "1.5.0"
def _default(obj): # pragma: no cover
- if type(obj) is frozendict:
- # fishing the protected dict out of the object is a bit nasty,
- # but we don't really want the overhead of copying the dict.
- try:
- return obj._dict
- except AttributeError:
- # When the C implementation of frozendict is used,
- # there isn't a `_dict` attribute with a dict
- # so we resort to making a copy of the frozendict
- return dict(obj)
+ if type(obj) is frozendict_type:
+ # If frozendict is available and used, cast `obj` into a dict
+ return dict(obj)
raise TypeError(
"Object of type %s is not JSON serializable" % obj.__class__.__name__
)
diff --git a/setup.py b/setup.py
index 1c2cc94..ed59aca 100755
--- a/setup.py
+++ b/setup.py
@@ -49,8 +49,11 @@ setup(
# simplerjson versions before 3.14.0 had a bug with some characters
# (e.g. \u2028) if ensure_ascii was set to false.
"simplejson>=3.14.0",
- "frozendict>=1.0",
],
+ extras_require={
+ # frozendict support can be enabled using the `canonicaljson[frozendict]` syntax
+ "frozendict": ["frozendict>=1.0"],
+ },
zip_safe=True,
long_description=read_file(("README.rst",)),
keywords="json",
@@ -58,7 +61,7 @@ setup(
author_email="[email protected]",
url="https://github.com/matrix-org/python-canonicaljson",
license="Apache License, Version 2.0",
- python_requires="~=3.5",
+ python_requires="~=3.7",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
diff --git a/tox.ini b/tox.ini
index 768a346..2895be7 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = packaging, pep8, py35, py36, py37, py38, py39, py310, pypy3
+envlist = packaging, pep8, py37, py38, py39, py310, pypy3
[testenv]
deps =
@@ -16,13 +16,13 @@ deps =
commands = check-manifest
[testenv:pep8]
-basepython = python3.6
+basepython = python3.7
deps =
flake8
commands = flake8 .
[testenv:black]
-basepython = python3.6
+basepython = python3.7
deps =
- black
+ black==21.9b0
commands = python -m black --check --diff .
|
matrix-org/python-canonicaljson
|
e5d6d75ce03a60cb0ffa821b9914362bd0d47207
|
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml
index 3c8180b..00de968 100644
--- a/.github/workflows/tests.yaml
+++ b/.github/workflows/tests.yaml
@@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
- python-version: '3.6'
+ python-version: '3.7'
- run: pip install tox
- run: tox -e ${{ matrix.toxenv }}
@@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: ['3.5', '3.6', '3.7', '3.8', '3.9', '3.10', 'pypy3']
+ python-version: ['3.7', '3.8', '3.9', '3.10', 'pypy-3.7']
steps:
- uses: actions/checkout@v2
diff --git a/test_canonicaljson.py b/test_canonicaljson.py
index 949e511..0e081c0 100644
--- a/test_canonicaljson.py
+++ b/test_canonicaljson.py
@@ -14,18 +14,18 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+
from math import inf, nan
from canonicaljson import (
encode_canonical_json,
encode_pretty_printed_json,
+ frozendict_type,
iterencode_canonical_json,
iterencode_pretty_printed_json,
set_json_library,
)
-from frozendict import frozendict
-
import unittest
from unittest import mock
@@ -108,13 +108,18 @@ class TestCanonicalJson(unittest.TestCase):
b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}',
)
+ @unittest.skipIf(
+ frozendict_type is None,
+ "If `frozendict` is not available, skip test",
+ )
def test_frozen_dict(self):
self.assertEqual(
- encode_canonical_json(frozendict({"a": 1})),
+ encode_canonical_json(frozendict_type({"a": 1})),
b'{"a":1}',
)
self.assertEqual(
- encode_pretty_printed_json(frozendict({"a": 1})), b'{\n "a": 1\n}'
+ encode_pretty_printed_json(frozendict_type({"a": 1})),
+ b'{\n "a": 1\n}',
)
def test_unknown_type(self):
|
On Python 3.10, must use a sufficiently new frozendict version
andrewsh [noticed](https://matrix.to/#/!FeyNfPFYiGSPyHoALL:jki.re/$16371923830Lmnkh:shadura.me?via=matrix.org&via=sw1v.org&via=uhoreg.ca) the following
> FYI https://buildd.debian.org/status/fetch.php?pkg=matrix-synapse&arch=all&ver=1.47.0-1&stamp=1637184874&raw=0
```
I: pybuild base:237: python3.10 setup.py clean
Traceback (most recent call last):
File "/<<PKGBUILDDIR>>/setup.py", line 84, in <module>
version = exec_file(("synapse", "__init__.py"))["__version__"]
File "/<<PKGBUILDDIR>>/setup.py", line 80, in exec_file
exec(code, result)
File "<string>", line 44, in <module>
File "/usr/lib/python3/dist-packages/canonicaljson.py", line 20, in <module>
from frozendict import frozendict
File "/usr/lib/python3/dist-packages/frozendict/__init__.py", line 16, in <module>
class frozendict(collections.Mapping):
AttributeError: module 'collections' has no attribute 'Mapping'
E: pybuild pybuild:354: clean: plugin distutils failed with: exit code=1: python3.10 setup.py clean
```
The above from frozendict 1.2.
This was fine in 3.9, but failed in 3.10. The Python 3.9 docs for the collection module says:
> Deprecated since version 3.3, will be removed in version 3.10: Moved Collections Abstract Base Classes to the collections.abc module. For backwards compatibility, they continue to be visible in this module through Python 3.9.
We should support Python 3.10. I'd suggest we ought to raise the required version of frozendict. I don't know if there's a way to make that conditional on 3.10? We should start by finding out the first version of frozendict that is supported by Python 3.10; I'd guess we want the first version where `frozendict` inherits from `dict`.
(Though come to think of it, it's odd that a frozendict inherits from dict, because it has a strictly smaller feature set (no-mutability).)
|
0.0
|
e5d6d75ce03a60cb0ffa821b9914362bd0d47207
|
[
"test_canonicaljson.py::TestCanonicalJson::test_ascii",
"test_canonicaljson.py::TestCanonicalJson::test_encode_canonical",
"test_canonicaljson.py::TestCanonicalJson::test_encode_pretty_printed",
"test_canonicaljson.py::TestCanonicalJson::test_frozen_dict",
"test_canonicaljson.py::TestCanonicalJson::test_invalid_float_values",
"test_canonicaljson.py::TestCanonicalJson::test_set_json",
"test_canonicaljson.py::TestCanonicalJson::test_unknown_type"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-28 12:59:54+00:00
|
apache-2.0
| 3,793 |
|
matrix-org__python-canonicaljson-59
|
diff --git a/README.rst b/README.rst
index af0c212..03baff3 100644
--- a/README.rst
+++ b/README.rst
@@ -15,7 +15,7 @@ Features
U+0056, to keep the output as small as possible.
* Uses the shortest escape sequence for each escaped character.
* Encodes the JSON as UTF-8.
-* Can encode ``frozendict`` immutable dictionaries.
+* Can be configured to encode custom types unknown to the stdlib JSON encoder.
Supports Python versions 3.7 and newer.
@@ -59,3 +59,20 @@ The underlying JSON implementation can be chosen with the following:
which uses the standard library json module).
.. _simplejson: https://simplejson.readthedocs.io/
+
+A preserialisation hook allows you to encode objects which aren't encodable by the
+standard library ``JSONEncoder``.
+
+.. code:: python
+
+ import canonicaljson
+ from typing import Dict
+
+ class CustomType:
+ pass
+
+ def callback(c: CustomType) -> Dict[str, str]:
+ return {"Hello": "world!"}
+
+ canonicaljson.register_preserialisation_callback(CustomType, callback)
+ assert canonicaljson.encode_canonical_json(CustomType()) == b'{"Hello":"world!"}'
diff --git a/setup.cfg b/setup.cfg
index 4b707de..60417f4 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -34,12 +34,6 @@ install_requires =
typing_extensions>=4.0.0; python_version < '3.8'
-[options.extras_require]
-# frozendict support can be enabled using the `canonicaljson[frozendict]` syntax
-frozendict =
- frozendict>=1.0
-
-
[options.package_data]
canonicaljson = py.typed
diff --git a/src/canonicaljson/__init__.py b/src/canonicaljson/__init__.py
index 2e33b66..24ed332 100644
--- a/src/canonicaljson/__init__.py
+++ b/src/canonicaljson/__init__.py
@@ -13,33 +13,56 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
+import functools
import platform
-from typing import Any, Generator, Iterator, Optional, Type
+from typing import Any, Callable, Generator, Iterator, Type, TypeVar
try:
from typing import Protocol
except ImportError: # pragma: no cover
from typing_extensions import Protocol # type: ignore[assignment]
-frozendict_type: Optional[Type[Any]]
-try:
- from frozendict import frozendict as frozendict_type
-except ImportError:
- frozendict_type = None # pragma: no cover
__version__ = "1.6.5"
-def _default(obj: object) -> object: # pragma: no cover
- if type(obj) is frozendict_type:
- # If frozendict is available and used, cast `obj` into a dict
- return dict(obj) # type: ignore[call-overload]
[email protected]
+def _preprocess_for_serialisation(obj: object) -> object: # pragma: no cover
+ """Transform an `obj` into something the JSON library knows how to encode.
+
+ This is only called for types that the JSON library does not recognise.
+ """
raise TypeError(
"Object of type %s is not JSON serializable" % obj.__class__.__name__
)
+T = TypeVar("T")
+
+
+def register_preserialisation_callback(
+ data_type: Type[T], callback: Callable[[T], object]
+) -> None:
+ """
+ Register a `callback` to preprocess `data_type` objects unknown to the JSON encoder.
+
+ When canonicaljson encodes an object `x` at runtime that its JSON library does not
+ know how to encode, it will
+ - select a `callback`,
+ - compute `y = callback(x)`, then
+ - JSON-encode `y` and return the result.
+
+ The `callback` should return an object that is JSON-serialisable by the stdlib
+ json module.
+
+ If this is called multiple times with the same `data_type`, the most recently
+ registered callback is used when serialising that `data_type`.
+ """
+ if data_type is object:
+ raise ValueError("Cannot register callback for the `object` type")
+ _preprocess_for_serialisation.register(data_type, callback)
+
+
class Encoder(Protocol): # pragma: no cover
def encode(self, data: object) -> str:
pass
@@ -77,7 +100,7 @@ def set_json_library(json_lib: JsonLibrary) -> None:
allow_nan=False,
separators=(",", ":"),
sort_keys=True,
- default=_default,
+ default=_preprocess_for_serialisation,
)
global _pretty_encoder
@@ -86,7 +109,7 @@ def set_json_library(json_lib: JsonLibrary) -> None:
allow_nan=False,
indent=4,
sort_keys=True,
- default=_default,
+ default=_preprocess_for_serialisation,
)
diff --git a/tox.ini b/tox.ini
index a893107..63b9d58 100644
--- a/tox.ini
+++ b/tox.ini
@@ -33,7 +33,6 @@ commands = python -m black --check --diff src tests
[testenv:mypy]
deps =
mypy==1.0
- types-frozendict==2.0.8
types-simplejson==3.17.5
types-setuptools==57.4.14
commands = mypy src tests
|
matrix-org/python-canonicaljson
|
2aa9eb5a0b9bcbdbb10cca9b4a9732a0b8ecf803
|
diff --git a/tests/test_canonicaljson.py b/tests/test_canonicaljson.py
index f1fac9a..44422d5 100644
--- a/tests/test_canonicaljson.py
+++ b/tests/test_canonicaljson.py
@@ -13,16 +13,17 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+from unittest.mock import Mock
from math import inf, nan
from canonicaljson import (
encode_canonical_json,
encode_pretty_printed_json,
- frozendict_type,
iterencode_canonical_json,
iterencode_pretty_printed_json,
set_json_library,
+ register_preserialisation_callback,
)
import unittest
@@ -107,22 +108,6 @@ class TestCanonicalJson(unittest.TestCase):
b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}',
)
- @unittest.skipIf(
- frozendict_type is None,
- "If `frozendict` is not available, skip test",
- )
- def test_frozen_dict(self) -> None:
- # For mypy's benefit:
- assert frozendict_type is not None
- self.assertEqual(
- encode_canonical_json(frozendict_type({"a": 1})),
- b'{"a":1}',
- )
- self.assertEqual(
- encode_pretty_printed_json(frozendict_type({"a": 1})),
- b'{\n "a": 1\n}',
- )
-
def test_unknown_type(self) -> None:
class Unknown(object):
pass
@@ -167,3 +152,46 @@ class TestCanonicalJson(unittest.TestCase):
from canonicaljson import json # type: ignore[attr-defined]
set_json_library(json)
+
+ def test_encode_unknown_class_raises(self) -> None:
+ class C:
+ pass
+
+ with self.assertRaises(Exception):
+ encode_canonical_json(C())
+
+ def test_preserialisation_callback(self) -> None:
+ class C:
+ pass
+
+ # Naughty: this alters the global state of the module. However this
+ # `C` class is limited to this test only, so this shouldn't affect
+ # other types and other tests.
+ register_preserialisation_callback(C, lambda c: "I am a C instance")
+
+ result = encode_canonical_json(C())
+ self.assertEqual(result, b'"I am a C instance"')
+
+ def test_cannot_register_preserialisation_callback_for_object(self) -> None:
+ with self.assertRaises(Exception):
+ register_preserialisation_callback(
+ object, lambda c: "shouldn't be able to do this"
+ )
+
+ def test_most_recent_preserialisation_callback_called(self) -> None:
+ class C:
+ pass
+
+ callback1 = Mock(return_value="callback 1 was called")
+ callback2 = Mock(return_value="callback 2 was called")
+
+ # Naughty: this alters the global state of the module. However this
+ # `C` class is limited to this test only, so this shouldn't affect
+ # other types and other tests.
+ register_preserialisation_callback(C, callback1)
+ register_preserialisation_callback(C, callback2)
+
+ encode_canonical_json(C())
+
+ callback1.assert_not_called()
+ callback2.assert_called_once()
|
Add support for immutabledict
https://github.com/matrix-org/synapse/pull/15113#issuecomment-1437447601
|
0.0
|
2aa9eb5a0b9bcbdbb10cca9b4a9732a0b8ecf803
|
[
"tests/test_canonicaljson.py::TestCanonicalJson::test_ascii",
"tests/test_canonicaljson.py::TestCanonicalJson::test_cannot_register_preserialisation_callback_for_object",
"tests/test_canonicaljson.py::TestCanonicalJson::test_encode_canonical",
"tests/test_canonicaljson.py::TestCanonicalJson::test_encode_pretty_printed",
"tests/test_canonicaljson.py::TestCanonicalJson::test_encode_unknown_class_raises",
"tests/test_canonicaljson.py::TestCanonicalJson::test_invalid_float_values",
"tests/test_canonicaljson.py::TestCanonicalJson::test_most_recent_preserialisation_callback_called",
"tests/test_canonicaljson.py::TestCanonicalJson::test_preserialisation_callback",
"tests/test_canonicaljson.py::TestCanonicalJson::test_set_json",
"tests/test_canonicaljson.py::TestCanonicalJson::test_unknown_type"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-14 13:24:35+00:00
|
apache-2.0
| 3,794 |
|
matrix-org__sydent-461
|
diff --git a/changelog.d/461.misc b/changelog.d/461.misc
new file mode 100644
index 0000000..e4b16d6
--- /dev/null
+++ b/changelog.d/461.misc
@@ -0,0 +1,1 @@
+Fix a bug introduced in Sydent 2.5.0 where calls to `/_matrix/identity/api/v1/validate/email/requestToken` would fail with an HTTP 500 Internal Server Error if arguments were given as a query string or as a www-form-urlencoded body.
\ No newline at end of file
diff --git a/sydent/http/servlets/__init__.py b/sydent/http/servlets/__init__.py
index 3d8b1e2..de758cf 100644
--- a/sydent/http/servlets/__init__.py
+++ b/sydent/http/servlets/__init__.py
@@ -49,9 +49,13 @@ def get_args(
Helper function to get arguments for an HTTP request.
Currently takes args from the top level keys of a json object or
www-form-urlencoded for backwards compatibility on v1 endpoints only.
- Returns a tuple (error, args) where if error is non-null,
- the request is malformed. Otherwise, args contains the
- parameters passed.
+
+ ⚠️ BEWARE ⚠. If a v1 request provides its args in urlencoded form (either in
+ a POST body or as URL query parameters), then we'll return `Dict[str, str]`.
+ The caller may need to interpret these strings as e.g. an `int`, `bool`, etc.
+ Arguments given as a json body are processed with `json.JSONDecoder.decode`,
+ and so are automatically deserialised to a Python type. The caller should
+ still validate that these have the correct type!
:param request: The request received by the servlet.
:param args: The args to look for in the request's parameters.
@@ -60,6 +64,10 @@ def get_args(
:raises: MatrixRestError if required is True and a given parameter
was not found in the request's query parameters.
+ :raises: MatrixRestError if we the request body contains bad JSON.
+ :raises: MatrixRestError if arguments are given in www-form-urlencodedquery
+ form, and some argument name or value is not a valid UTF-8-encoded
+ string.
:return: A dict containing the requested args and their values. String values
are of type unicode.
diff --git a/sydent/http/servlets/emailservlet.py b/sydent/http/servlets/emailservlet.py
index 11ac04c..d23ed96 100644
--- a/sydent/http/servlets/emailservlet.py
+++ b/sydent/http/servlets/emailservlet.py
@@ -50,9 +50,29 @@ class EmailRequestCodeServlet(Resource):
args = get_args(request, ("email", "client_secret", "send_attempt"))
email = args["email"]
- sendAttempt = args["send_attempt"]
clientSecret = args["client_secret"]
+ try:
+ # if we got this via the v1 API in a querystring or urlencoded body,
+ # then the values in args will be a string. So check that
+ # send_attempt is an int.
+ #
+ # NB: We don't check if we're processing a url-encoded v1 request.
+ # This means we accept string representations of integers for
+ # `send_attempt` in v2 requests, and in v1 requests that supply a
+ # JSON body. This is contrary to the spec and leaves me with a dirty
+ # feeling I can't quite shake off.
+ #
+ # Where's Raymond Hettinger when you need him? (THUMP) There must be
+ # a better way!
+ sendAttempt = int(args["send_attempt"])
+ except (TypeError, ValueError):
+ request.setResponseCode(400)
+ return {
+ "errcode": "M_INVALID_PARAM",
+ "error": f"send_attempt should be an integer (got {args['send_attempt']}",
+ }
+
if not is_valid_client_secret(clientSecret):
request.setResponseCode(400)
return {
|
matrix-org/sydent
|
001c046140b7839c5e92a995b6befece52f317fd
|
diff --git a/tests/test_email.py b/tests/test_email.py
index 1420fc2..b7f48c1 100644
--- a/tests/test_email.py
+++ b/tests/test_email.py
@@ -48,7 +48,7 @@ class TestRequestCode(unittest.TestCase):
request, channel = make_request(
self.sydent.reactor,
"POST",
- "/_matrix/identity/v1/validate/email/requestToken",
+ "/_matrix/identity/api/v1/validate/email/requestToken",
{
"email": "test@test",
"client_secret": "oursecret",
@@ -62,13 +62,29 @@ class TestRequestCode(unittest.TestCase):
email_contents = smtp.sendmail.call_args[0][2].decode("utf-8")
self.assertIn("Confirm your email address for Matrix", email_contents)
+ def test_request_code_via_url_query_params(self):
+ self.sydent.run()
+ url = (
+ "/_matrix/identity/api/v1/validate/email/requestToken?"
+ "email=test@test"
+ "&client_secret=oursecret"
+ "&send_attempt=0"
+ )
+ request, channel = make_request(self.sydent.reactor, "POST", url)
+ smtp = self._render_request(request)
+ self.assertEqual(channel.code, 200)
+
+ # Ensure the email is as expected.
+ email_contents = smtp.sendmail.call_args[0][2].decode("utf-8")
+ self.assertIn("Confirm your email address for Matrix", email_contents)
+
def test_branded_request_code(self):
self.sydent.run()
request, channel = make_request(
self.sydent.reactor,
"POST",
- "/_matrix/identity/v1/validate/email/requestToken?brand=vector-im",
+ "/_matrix/identity/api/v1/validate/email/requestToken?brand=vector-im",
{
"email": "test@test",
"client_secret": "oursecret",
|
Email validator incorrectly handling `sendAttempt`
Introduced in 57ba780bbd27fdffbb6fdf6c4044393f35cb4e16
The annotation for `sendAttempt` is incorrect. It is a `str`. Mypy cannot spot this because it is fed something of type `Any` GRRRRRR.
https://sentry.matrix.org/sentry/sydent/issues/234999/?query=is%3Aunresolved
|
0.0
|
001c046140b7839c5e92a995b6befece52f317fd
|
[
"tests/test_email.py::TestRequestCode::test_request_code_via_url_query_params"
] |
[
"tests/test_email.py::TestRequestCode::test_branded_request_code",
"tests/test_email.py::TestRequestCode::test_request_code"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_git_commit_hash",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-09 12:22:52+00:00
|
apache-2.0
| 3,795 |
|
matrix-org__sygnal-292
|
diff --git a/changelog.d/285.doc b/changelog.d/285.doc
new file mode 100644
index 0000000..fa45471
--- /dev/null
+++ b/changelog.d/285.doc
@@ -0,0 +1,1 @@
+Document the use of an iOS Notification Service Extension and the Push Gateway API as a workaround to trigger VoIP notifications on iOS.
\ No newline at end of file
diff --git a/changelog.d/292.bugfix b/changelog.d/292.bugfix
new file mode 100644
index 0000000..ef41c7e
--- /dev/null
+++ b/changelog.d/292.bugfix
@@ -0,0 +1,1 @@
+Fix a bug introduced in Sygnal 0.7.0 where a malformed `default_payload` could cause an internal server error.
diff --git a/docs/applications.md b/docs/applications.md
index b102d84..53eeaf1 100644
--- a/docs/applications.md
+++ b/docs/applications.md
@@ -175,6 +175,40 @@ An example `data` dictionary to specify on `POST /_matrix/client/r0/pushers/set`
[APNs documentation]: https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
+#### VoIP (voice calls and video calls) notifications on iOS
+
+iOS is capable of displaying an on-screen call notification (with answer/deny buttons)
+and playing a ringtone.
+
+However, this requires sending a special kind of push notification.
+Sygnal is not able to send this type of push notification because a VoIP call may
+begin as a result of an encrypted message, so Sygnal has no way to know that a given
+message should initiate a VoIP call.
+
+
+##### Recent iOS (≥ 14.5) versions
+
+As of iOS 14.5, your iOS application can register a Notification Service Extension that,
+upon receiving a relevant VoIP notification, calls [`reportNewIncomingVoIPPushPayload`][iOSReportVoIP]
+to trigger a VoIP notification display on the device.
+
+[iOSReportVoIP]: https://developer.apple.com/documentation/callkit/cxprovider/3727263-reportnewincomingvoippushpayload
+
+
+##### Old iOS (< 14.5) versions
+
+For old iOS versions, a workaround is for your iOS application to register a Notification Service Extension
+that, upon receiving a relevant VoIP notification, makes an HTTP request to Sygnal's
+[`/_matrix/push/v1/notify`](https://spec.matrix.org/latest/push-gateway-api/#post_matrixpushv1notify)
+endpoint in order to trigger the correct type of notification.
+(There was no interface to do this on-device.)
+
+The Notification Service Extension of *Element iOS*, [available here][ElementNSE],
+may be useful for reference.
+
+[ElementNSE]: https://github.com/vector-im/element-ios/blob/034e253fb19092ef16b5262293d5c32db96aec22/RiotNSE/NotificationService.swift
+
+
### Firebase Cloud Messaging
The client will receive a message with an FCM `data` payload with this structure:
diff --git a/sygnal/apnspushkin.py b/sygnal/apnspushkin.py
index c7abf26..c4d495b 100644
--- a/sygnal/apnspushkin.py
+++ b/sygnal/apnspushkin.py
@@ -283,10 +283,22 @@ class ApnsPushkin(ConcurrencyLimitedPushkin):
with self.sygnal.tracer.start_span(
"apns_dispatch", tags=span_tags, child_of=context.opentracing_span
) as span_parent:
+ # Before we build the payload, check that the default_payload is not
+ # malformed and reject the pushkey if it is
+
+ default_payload = {}
+
+ if device.data:
+ default_payload = device.data.get("default_payload", {})
+ if not isinstance(default_payload, dict):
+ log.error(
+ "default_payload is malformed, this value must be a dict."
+ )
+ return [device.pushkey]
if n.event_id and not n.type:
payload: Optional[Dict[str, Any]] = self._get_payload_event_id_only(
- n, device
+ n, default_payload
)
else:
payload = self._get_payload_full(n, device, log)
@@ -336,7 +348,7 @@ class ApnsPushkin(ConcurrencyLimitedPushkin):
raise NotificationDispatchException("Retried too many times.")
def _get_payload_event_id_only(
- self, n: Notification, device: Device
+ self, n: Notification, default_payload: Dict[str, Any]
) -> Dict[str, Any]:
"""
Constructs a payload for a notification where we know only the event ID.
@@ -350,8 +362,7 @@ class ApnsPushkin(ConcurrencyLimitedPushkin):
"""
payload = {}
- if device.data:
- payload.update(device.data.get("default_payload", {}))
+ payload.update(default_payload)
if n.room_id:
payload["room_id"] = n.room_id
diff --git a/sygnal/gcmpushkin.py b/sygnal/gcmpushkin.py
index e895489..ca68d68 100644
--- a/sygnal/gcmpushkin.py
+++ b/sygnal/gcmpushkin.py
@@ -18,7 +18,7 @@ import json
import logging
import time
from io import BytesIO
-from typing import TYPE_CHECKING, Any, AnyStr, Dict, List, Tuple
+from typing import TYPE_CHECKING, Any, AnyStr, Dict, List, Optional, Tuple
from opentracing import Span, logs, tags
from prometheus_client import Counter, Gauge, Histogram
@@ -347,16 +347,21 @@ class GcmPushkin(ConcurrencyLimitedPushkin):
with self.sygnal.tracer.start_span(
"gcm_dispatch", tags=span_tags, child_of=context.opentracing_span
) as span_parent:
+ # TODO: Implement collapse_key to queue only one message per room.
+ failed: List[str] = []
+
data = GcmPushkin._build_data(n, device)
+
+ # Reject pushkey if default_payload is misconfigured
+ if data is None:
+ failed.append(device.pushkey)
+
headers = {
"User-Agent": ["sygnal"],
"Content-Type": ["application/json"],
"Authorization": ["key=%s" % (self.api_key,)],
}
- # TODO: Implement collapse_key to queue only one message per room.
- failed: List[str] = []
-
body = self.base_request_body.copy()
body["data"] = data
body["priority"] = "normal" if n.prio == "low" else "high"
@@ -409,7 +414,7 @@ class GcmPushkin(ConcurrencyLimitedPushkin):
return failed
@staticmethod
- def _build_data(n: Notification, device: Device) -> Dict[str, Any]:
+ def _build_data(n: Notification, device: Device) -> Optional[Dict[str, Any]]:
"""
Build the payload data to be sent.
Args:
@@ -418,12 +423,19 @@ class GcmPushkin(ConcurrencyLimitedPushkin):
will be sent.
Returns:
- JSON-compatible dict
+ JSON-compatible dict or None if the default_payload is misconfigured
"""
data = {}
if device.data:
- data.update(device.data.get("default_payload", {}))
+ default_payload = device.data.get("default_payload", {})
+ if isinstance(default_payload, dict):
+ data.update(default_payload)
+ else:
+ logger.error(
+ "default_payload was misconfigured, this value must be a dict."
+ )
+ return None
for attr in [
"event_id",
|
matrix-org/sygnal
|
9d2d1a4f1cd8d7252945d850641b4a56a94667d3
|
diff --git a/tests/test_apns.py b/tests/test_apns.py
index b7b6774..32ccd28 100644
--- a/tests/test_apns.py
+++ b/tests/test_apns.py
@@ -40,6 +40,13 @@ DEVICE_EXAMPLE_WITH_DEFAULT_PAYLOAD = {
},
}
+DEVICE_EXAMPLE_WITH_BAD_DEFAULT_PAYLOAD = {
+ "app_id": "com.example.apns",
+ "pushkey": "badpayload",
+ "pushkey_ts": 42,
+ "data": {"default_payload": None},
+}
+
class ApnsTestCase(testutils.TestCase):
def setUp(self):
@@ -264,6 +271,15 @@ class ApnsTestCase(testutils.TestCase):
self.assertEqual({"rejected": []}, resp)
+ def test_misconfigured_payload_is_rejected(self):
+ """Test that a malformed default_payload causes pushkey to be rejected"""
+
+ resp = self._request(
+ self._make_dummy_notification([DEVICE_EXAMPLE_WITH_BAD_DEFAULT_PAYLOAD])
+ )
+
+ self.assertEqual({"rejected": ["badpayload"]}, resp)
+
def test_rejection(self):
"""
Tests the rejection case: a rejection response from APNS leads to us
diff --git a/tests/test_gcm.py b/tests/test_gcm.py
index 0ad609e..d705751 100644
--- a/tests/test_gcm.py
+++ b/tests/test_gcm.py
@@ -34,6 +34,16 @@ DEVICE_EXAMPLE_WITH_DEFAULT_PAYLOAD = {
}
},
}
+
+DEVICE_EXAMPLE_WITH_BAD_DEFAULT_PAYLOAD = {
+ "app_id": "com.example.gcm",
+ "pushkey": "badpayload",
+ "pushkey_ts": 42,
+ "data": {
+ "default_payload": None,
+ },
+}
+
DEVICE_EXAMPLE_IOS = {
"app_id": "com.example.gcm.ios",
"pushkey": "spqr",
@@ -118,6 +128,22 @@ class GcmTestCase(testutils.TestCase):
self.assertEqual(resp, {"rejected": []})
self.assertEqual(gcm.num_requests, 1)
+ def test_misformed_default_payload_rejected(self):
+ """
+ Tests that a non-dict default_payload is rejected.
+ """
+ gcm = self.get_test_pushkin("com.example.gcm")
+ gcm.preload_with_response(
+ 200, {"results": [{"message_id": "msg42", "registration_id": "badpayload"}]}
+ )
+
+ resp = self._request(
+ self._make_dummy_notification([DEVICE_EXAMPLE_WITH_BAD_DEFAULT_PAYLOAD])
+ )
+
+ self.assertEqual(resp, {"rejected": ["badpayload"]})
+ self.assertEqual(gcm.num_requests, 1)
+
def test_rejected(self):
"""
Tests the rejected case: a pushkey rejected to GCM leads to Sygnal
|
`TypeError: 'NoneType' object is not iterable` in apnspushkin.py and gcmpushkin.py
In gcmpushkin.py and apnspushkin.py, we attempt to use `device.data["default_payload"]` as a dictionary without verifying its type. Since `device.data` is arbitrary client or homeserver-supplied JSON, this can lead to errors. We ought to check the type of `device.data["default_payload"]` before using it:
https://github.com/matrix-org/sygnal/blob/v0.11.0/sygnal/gcmpushkin.py#L425-L426
https://github.com/matrix-org/sygnal/blob/v0.11.0/sygnal/apnspushkin.py#L353-L354
For reference, webpushpushkin.py does include a check:
https://github.com/matrix-org/sygnal/blob/v0.11.0/sygnal/webpushpushkin.py#L245-L248
|
0.0
|
9d2d1a4f1cd8d7252945d850641b4a56a94667d3
|
[
"tests/test_apns.py::ApnsTestCase::test_misconfigured_payload_is_rejected",
"tests/test_gcm.py::GcmTestCase::test_misformed_default_payload_rejected"
] |
[
"tests/test_apns.py::ApnsTestCase::test_expected",
"tests/test_apns.py::ApnsTestCase::test_expected_badge_only_with_default_payload",
"tests/test_apns.py::ApnsTestCase::test_expected_event_id_only_with_default_payload",
"tests/test_apns.py::ApnsTestCase::test_expected_full_with_default_payload",
"tests/test_apns.py::ApnsTestCase::test_no_retry_on_4xx",
"tests/test_apns.py::ApnsTestCase::test_payload_truncation",
"tests/test_apns.py::ApnsTestCase::test_payload_truncation_test_validity",
"tests/test_apns.py::ApnsTestCase::test_rejection",
"tests/test_apns.py::ApnsTestCase::test_retry_on_5xx",
"tests/test_gcm.py::GcmTestCase::test_batching",
"tests/test_gcm.py::GcmTestCase::test_batching_individual_failure",
"tests/test_gcm.py::GcmTestCase::test_expected",
"tests/test_gcm.py::GcmTestCase::test_expected_with_default_payload",
"tests/test_gcm.py::GcmTestCase::test_fcm_options",
"tests/test_gcm.py::GcmTestCase::test_rejected"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-05 22:43:24+00:00
|
apache-2.0
| 3,796 |
|
matrix-org__sygnal-315
|
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 38eea13..a2d2a7d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -65,7 +65,7 @@ changes into our repo.
Some other points to follow:
- * Please base your changes on the `master` branch.
+ * Please base your changes on the `main` branch.
* Please follow the [code style requirements](#code-style).
diff --git a/README.md b/README.md
index 7bcd196..b4e67fe 100644
--- a/README.md
+++ b/README.md
@@ -3,11 +3,11 @@ Introduction
Sygnal is a reference Push Gateway for [Matrix](https://matrix.org/).
-See <https://matrix.org/docs/spec/client_server/r0.5.0#id134> for a high
+See https://spec.matrix.org/latest/push-gateway-api/#overview for a high
level overview of how notifications work in Matrix.
-<https://matrix.org/docs/spec/push_gateway/r0.1.0> describes the
-protocol that Matrix Home Servers use to send notifications to Push
+The [Matrix Specification](https://spec.matrix.org/latest/push-gateway-api/)
+describes the protocol that Matrix Home Servers use to send notifications to Push
Gateways such as Sygnal.
@@ -31,7 +31,7 @@ are to be handled. Each app should be given its own subsection, with the
key of that subsection being the app's `app_id`. Keys in this section
take the form of the `app_id`, as specified when setting up a Matrix
pusher (see
-<https://matrix.org/docs/spec/client_server/r0.5.0#post-matrix-client-r0-pushers-set>).
+https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3pushersset).
See the sample configuration for examples.
@@ -103,9 +103,9 @@ If you wish, you can instead configure a HTTP CONNECT proxy in
Pusher `data` configuration
===========================
-The following parameters can be specified in the [data]{.title-ref}
+The following parameters can be specified in the `data`
dictionary which is given when configuring the pusher via
-[POST /_matrix/client/r0/pushers/set](https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-pushers-set):
+[POST /_matrix/client/v3/pushers/set](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3pushersset):
- `default_payload`: a dictionary which defines the basic payload to
be sent to the notification service. Sygnal will merge information
diff --git a/changelog.d/315.misc b/changelog.d/315.misc
new file mode 100644
index 0000000..1dc6d71
--- /dev/null
+++ b/changelog.d/315.misc
@@ -0,0 +1,1 @@
+Don't attempt delivery of notification if we have rejected pushkey.
diff --git a/changelog.d/316.doc b/changelog.d/316.doc
new file mode 100644
index 0000000..9f77e30
--- /dev/null
+++ b/changelog.d/316.doc
@@ -0,0 +1,1 @@
+Update outdated links in `README.md`.
diff --git a/changelog.d/317.doc b/changelog.d/317.doc
new file mode 100644
index 0000000..c3011ff
--- /dev/null
+++ b/changelog.d/317.doc
@@ -0,0 +1,1 @@
+Change `master` to `main` branch in `CONTRIBUTING.md`.
diff --git a/sygnal/apnspushkin.py b/sygnal/apnspushkin.py
index e47374d..c3f18ac 100644
--- a/sygnal/apnspushkin.py
+++ b/sygnal/apnspushkin.py
@@ -311,8 +311,9 @@ class ApnsPushkin(ConcurrencyLimitedPushkin):
if device.data:
default_payload = device.data.get("default_payload", {})
if not isinstance(default_payload, dict):
- log.error(
- "default_payload is malformed, this value must be a dict."
+ log.warning(
+ "Rejecting pushkey due to misconfigured default_payload, "
+ "please ensure that default_payload is a dict."
)
return [device.pushkey]
diff --git a/sygnal/gcmpushkin.py b/sygnal/gcmpushkin.py
index 955f8d0..f725b51 100644
--- a/sygnal/gcmpushkin.py
+++ b/sygnal/gcmpushkin.py
@@ -352,9 +352,13 @@ class GcmPushkin(ConcurrencyLimitedPushkin):
data = GcmPushkin._build_data(n, device)
- # Reject pushkey if default_payload is misconfigured
+ # Reject pushkey(s) if default_payload is misconfigured
if data is None:
- failed.append(device.pushkey)
+ log.warning(
+ "Rejecting pushkey(s) due to misconfigured default_payload, "
+ "please ensure that default_payload is a dict."
+ )
+ return pushkeys
headers = {
"User-Agent": ["sygnal"],
@@ -432,7 +436,7 @@ class GcmPushkin(ConcurrencyLimitedPushkin):
if isinstance(default_payload, dict):
data.update(default_payload)
else:
- logger.error(
+ logger.warning(
"default_payload was misconfigured, this value must be a dict."
)
return None
|
matrix-org/sygnal
|
fce0d2ac953900a253b40134b18d3319f7d050fe
|
diff --git a/tests/test_gcm.py b/tests/test_gcm.py
index d705751..dcb685b 100644
--- a/tests/test_gcm.py
+++ b/tests/test_gcm.py
@@ -142,7 +142,7 @@ class GcmTestCase(testutils.TestCase):
)
self.assertEqual(resp, {"rejected": ["badpayload"]})
- self.assertEqual(gcm.num_requests, 1)
+ self.assertEqual(gcm.num_requests, 0)
def test_rejected(self):
"""
|
"default_payload was misconfigured, this value must be a dict" error is noisy
**Describe the bug**
As of https://github.com/matrix-org/sygnal/pull/292 we now check that `default_payload` is a dictionary before interacting with it. `default_payload` is a user-supplied dictionary which is set when a client sets up their pusher via [`POST /_matrix/client/v3/pushers/set`](https://spec.matrix.org/v1.3/client-server-api/#post_matrixclientv3pushersset).
While we now successfully catch when clients set this value incorrectly, raising an error means that this we get notified via Sentry when it happens - and as this data is user-supplied, we can't really do much about it, making the error noise.
This issue proposes to downgrade the log from an error to a warning. Such instances will then still be logged, but not show up in Sentry/potentially alarm sysadmins.
|
0.0
|
fce0d2ac953900a253b40134b18d3319f7d050fe
|
[
"tests/test_gcm.py::GcmTestCase::test_misformed_default_payload_rejected"
] |
[
"tests/test_gcm.py::GcmTestCase::test_batching",
"tests/test_gcm.py::GcmTestCase::test_batching_individual_failure",
"tests/test_gcm.py::GcmTestCase::test_expected",
"tests/test_gcm.py::GcmTestCase::test_expected_with_default_payload",
"tests/test_gcm.py::GcmTestCase::test_fcm_options",
"tests/test_gcm.py::GcmTestCase::test_rejected"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-26 17:57:23+00:00
|
apache-2.0
| 3,797 |
|
matrix-org__synapse-12358
|
diff --git a/changelog.d/12354.misc b/changelog.d/12354.misc
new file mode 100644
index 000000000..e3b8950fa
--- /dev/null
+++ b/changelog.d/12354.misc
@@ -0,0 +1,1 @@
+Update docstrings for `ReadWriteLock` tests.
diff --git a/changelog.d/12358.misc b/changelog.d/12358.misc
new file mode 100644
index 000000000..fcacbcba5
--- /dev/null
+++ b/changelog.d/12358.misc
@@ -0,0 +1,1 @@
+Fix a long-standing bug where `Linearizer`s could get stuck if a cancellation were to happen at the wrong time.
diff --git a/changelog.d/12366.misc b/changelog.d/12366.misc
new file mode 100644
index 000000000..33d8e6c71
--- /dev/null
+++ b/changelog.d/12366.misc
@@ -0,0 +1,1 @@
+Make `StreamToken.from_string` and `RoomStreamToken.parse` propagate cancellations instead of replacing them with `SynapseError`s.
diff --git a/synapse/types.py b/synapse/types.py
index 6bbefb6fa..9ac688b23 100644
--- a/synapse/types.py
+++ b/synapse/types.py
@@ -39,6 +39,7 @@ from typing_extensions import TypedDict
from unpaddedbase64 import decode_base64
from zope.interface import Interface
+from twisted.internet.defer import CancelledError
from twisted.internet.interfaces import (
IReactorCore,
IReactorPluggableNameResolver,
@@ -540,6 +541,8 @@ class RoomStreamToken:
stream=stream,
instance_map=frozendict(instance_map),
)
+ except CancelledError:
+ raise
except Exception:
pass
raise SynapseError(400, "Invalid room stream token %r" % (string,))
@@ -705,6 +708,8 @@ class StreamToken:
return cls(
await RoomStreamToken.parse(store, keys[0]), *(int(k) for k in keys[1:])
)
+ except CancelledError:
+ raise
except Exception:
raise SynapseError(400, "Invalid stream token")
diff --git a/synapse/util/async_helpers.py b/synapse/util/async_helpers.py
index 4b2a16a6a..650e44de2 100644
--- a/synapse/util/async_helpers.py
+++ b/synapse/util/async_helpers.py
@@ -453,7 +453,11 @@ class Linearizer:
#
# This needs to happen while we hold the lock. We could put it on the
# exit path, but that would slow down the uncontended case.
- await self._clock.sleep(0)
+ try:
+ await self._clock.sleep(0)
+ except CancelledError:
+ self._release_lock(key, entry)
+ raise
return entry
|
matrix-org/synapse
|
800ba87cc881856adae19ec40485578356398639
|
diff --git a/tests/util/test_linearizer.py b/tests/util/test_linearizer.py
index c2a209e63..47a1cfbdc 100644
--- a/tests/util/test_linearizer.py
+++ b/tests/util/test_linearizer.py
@@ -13,7 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from typing import Callable, Hashable, Tuple
+from typing import Hashable, Tuple
+
+from typing_extensions import Protocol
from twisted.internet import defer, reactor
from twisted.internet.base import ReactorBase
@@ -25,10 +27,15 @@ from synapse.util.async_helpers import Linearizer
from tests import unittest
+class UnblockFunction(Protocol):
+ def __call__(self, pump_reactor: bool = True) -> None:
+ ...
+
+
class LinearizerTestCase(unittest.TestCase):
def _start_task(
self, linearizer: Linearizer, key: Hashable
- ) -> Tuple["Deferred[None]", "Deferred[None]", Callable[[], None]]:
+ ) -> Tuple["Deferred[None]", "Deferred[None]", UnblockFunction]:
"""Starts a task which acquires the linearizer lock, blocks, then completes.
Args:
@@ -52,11 +59,12 @@ class LinearizerTestCase(unittest.TestCase):
d = defer.ensureDeferred(task())
- def unblock() -> None:
+ def unblock(pump_reactor: bool = True) -> None:
unblock_d.callback(None)
# The next task, if it exists, will acquire the lock and require a kick of
# the reactor to advance.
- self._pump()
+ if pump_reactor:
+ self._pump()
return d, acquired_d, unblock
@@ -212,3 +220,38 @@ class LinearizerTestCase(unittest.TestCase):
)
unblock3()
self.successResultOf(d3)
+
+ def test_cancellation_during_sleep(self) -> None:
+ """Tests cancellation during the sleep just after waiting for a `Linearizer`."""
+ linearizer = Linearizer()
+
+ key = object()
+
+ d1, acquired_d1, unblock1 = self._start_task(linearizer, key)
+ self.assertTrue(acquired_d1.called)
+
+ # Create a second task, waiting for the first task.
+ d2, acquired_d2, _ = self._start_task(linearizer, key)
+ self.assertFalse(acquired_d2.called)
+
+ # Create a third task, waiting for the second task.
+ d3, acquired_d3, unblock3 = self._start_task(linearizer, key)
+ self.assertFalse(acquired_d3.called)
+
+ # Once the first task completes, cancel the waiting second task while it is
+ # sleeping just after acquiring the lock.
+ unblock1(pump_reactor=False)
+ self.successResultOf(d1)
+ d2.cancel()
+ self._pump()
+
+ self.assertTrue(d2.called)
+ self.failureResultOf(d2, CancelledError)
+
+ # The third task should continue running.
+ self.assertTrue(
+ acquired_d3.called,
+ "Third task did not get the lock after the second task was cancelled",
+ )
+ unblock3()
+ self.successResultOf(d3)
diff --git a/tests/util/test_rwlock.py b/tests/util/test_rwlock.py
index 0c8422619..5da04362a 100644
--- a/tests/util/test_rwlock.py
+++ b/tests/util/test_rwlock.py
@@ -40,8 +40,8 @@ class ReadWriteLockTestCase(unittest.TestCase):
Returns:
A tuple of three `Deferred`s:
- * A `Deferred` that resolves with `return_value` once the reader or writer
- completes successfully.
+ * A cancellable `Deferred` for the entire read or write operation that
+ resolves with `return_value` on successful completion.
* A `Deferred` that resolves once the reader or writer acquires the lock.
* A `Deferred` that blocks the reader or writer. Must be resolved by the
caller to allow the reader or writer to release the lock and complete.
@@ -87,8 +87,8 @@ class ReadWriteLockTestCase(unittest.TestCase):
Returns:
A tuple of two `Deferred`s:
- * A `Deferred` that resolves with `return_value` once the reader completes
- successfully.
+ * A cancellable `Deferred` for the entire read operation that resolves with
+ `return_value` on successful completion.
* A `Deferred` that resolves once the reader acquires the lock.
"""
d, acquired_d, unblock_d = self._start_reader_or_writer(
@@ -106,8 +106,8 @@ class ReadWriteLockTestCase(unittest.TestCase):
Returns:
A tuple of two `Deferred`s:
- * A `Deferred` that resolves with `return_value` once the writer completes
- successfully.
+ * A cancellable `Deferred` for the entire write operation that resolves
+ with `return_value` on successful completion.
* A `Deferred` that resolves once the writer acquires the lock.
"""
d, acquired_d, unblock_d = self._start_reader_or_writer(
|
`Linearizer` can get stuck due to cancellation
Once a `Linearizer` task acquires the lock, it does a 0-duration sleep to reset the call stack:
https://github.com/matrix-org/synapse/blob/605d161d7d585847fd1bb98d14d5281daeac8e86/synapse/util/async_helpers.py#L466
In the rare event that the task is cancelled while sleeping, the lock is not released and the `Linearizer` becomes stuck.
Can be reproduced by modifying the cancellation test slightly. Cancelling the 2nd task after 1st task releases the lock (instead of before) will make the test get stuck indefinitely:
```py
with cm1:
pass
d2.cancel()
```
instead of
https://github.com/matrix-org/synapse/blob/release-v1.53/tests/util/test_linearizer.py#L159-L162
|
0.0
|
800ba87cc881856adae19ec40485578356398639
|
[
"tests/util/test_linearizer.py::LinearizerTestCase::test_cancellation_during_sleep"
] |
[
"tests/util/test_linearizer.py::LinearizerTestCase::test_cancellation",
"tests/util/test_linearizer.py::LinearizerTestCase::test_linearizer",
"tests/util/test_linearizer.py::LinearizerTestCase::test_linearizer_is_queued",
"tests/util/test_linearizer.py::LinearizerTestCase::test_lots_of_queued_things",
"tests/util/test_linearizer.py::LinearizerTestCase::test_multiple_entries",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_cancellation_while_holding_read_lock",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_cancellation_while_holding_write_lock",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_cancellation_while_waiting_for_read_lock",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_cancellation_while_waiting_for_write_lock",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_lock_handoff_to_nonblocking_writer",
"tests/util/test_rwlock.py::ReadWriteLockTestCase::test_rwlock"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-01 18:15:52+00:00
|
apache-2.0
| 3,798 |
|
matrix-org__synapse-12657
|
diff --git a/changelog.d/12656.misc b/changelog.d/12656.misc
new file mode 100644
index 000000000..8a8743e61
--- /dev/null
+++ b/changelog.d/12656.misc
@@ -0,0 +1,1 @@
+Prevent memory leak from reoccurring when presence is disabled.
diff --git a/changelog.d/12657.bugfix b/changelog.d/12657.bugfix
new file mode 100644
index 000000000..7547ca40a
--- /dev/null
+++ b/changelog.d/12657.bugfix
@@ -0,0 +1,1 @@
+Fix a long-standing bug where rooms containing power levels with string values could not be upgraded.
diff --git a/synapse/events/utils.py b/synapse/events/utils.py
index 026dcde8d..ac91c5eb5 100644
--- a/synapse/events/utils.py
+++ b/synapse/events/utils.py
@@ -22,6 +22,7 @@ from typing import (
Iterable,
List,
Mapping,
+ MutableMapping,
Optional,
Union,
)
@@ -580,10 +581,20 @@ class EventClientSerializer:
]
-def copy_power_levels_contents(
- old_power_levels: Mapping[str, Union[int, Mapping[str, int]]]
+_PowerLevel = Union[str, int]
+
+
+def copy_and_fixup_power_levels_contents(
+ old_power_levels: Mapping[str, Union[_PowerLevel, Mapping[str, _PowerLevel]]]
) -> Dict[str, Union[int, Dict[str, int]]]:
- """Copy the content of a power_levels event, unfreezing frozendicts along the way
+ """Copy the content of a power_levels event, unfreezing frozendicts along the way.
+
+ We accept as input power level values which are strings, provided they represent an
+ integer, e.g. `"`100"` instead of 100. Such strings are converted to integers
+ in the returned dictionary (hence "fixup" in the function name).
+
+ Note that future room versions will outlaw such stringy power levels (see
+ https://github.com/matrix-org/matrix-spec/issues/853).
Raises:
TypeError if the input does not look like a valid power levels event content
@@ -592,29 +603,47 @@ def copy_power_levels_contents(
raise TypeError("Not a valid power-levels content: %r" % (old_power_levels,))
power_levels: Dict[str, Union[int, Dict[str, int]]] = {}
- for k, v in old_power_levels.items():
-
- if isinstance(v, int):
- power_levels[k] = v
- continue
+ for k, v in old_power_levels.items():
if isinstance(v, collections.abc.Mapping):
h: Dict[str, int] = {}
power_levels[k] = h
for k1, v1 in v.items():
- # we should only have one level of nesting
- if not isinstance(v1, int):
- raise TypeError(
- "Invalid power_levels value for %s.%s: %r" % (k, k1, v1)
- )
- h[k1] = v1
- continue
+ _copy_power_level_value_as_integer(v1, h, k1)
- raise TypeError("Invalid power_levels value for %s: %r" % (k, v))
+ else:
+ _copy_power_level_value_as_integer(v, power_levels, k)
return power_levels
+def _copy_power_level_value_as_integer(
+ old_value: object,
+ power_levels: MutableMapping[str, Any],
+ key: str,
+) -> None:
+ """Set `power_levels[key]` to the integer represented by `old_value`.
+
+ :raises TypeError: if `old_value` is not an integer, nor a base-10 string
+ representation of an integer.
+ """
+ if isinstance(old_value, int):
+ power_levels[key] = old_value
+ return
+
+ if isinstance(old_value, str):
+ try:
+ parsed_value = int(old_value, base=10)
+ except ValueError:
+ # Fall through to the final TypeError.
+ pass
+ else:
+ power_levels[key] = parsed_value
+ return
+
+ raise TypeError(f"Invalid power_levels value for {key}: {old_value}")
+
+
def validate_canonicaljson(value: Any) -> None:
"""
Ensure that the JSON object is valid according to the rules of canonical JSON.
diff --git a/synapse/handlers/presence.py b/synapse/handlers/presence.py
index d078162c2..268481ec1 100644
--- a/synapse/handlers/presence.py
+++ b/synapse/handlers/presence.py
@@ -659,27 +659,28 @@ class PresenceHandler(BasePresenceHandler):
)
now = self.clock.time_msec()
- for state in self.user_to_current_state.values():
- self.wheel_timer.insert(
- now=now, obj=state.user_id, then=state.last_active_ts + IDLE_TIMER
- )
- self.wheel_timer.insert(
- now=now,
- obj=state.user_id,
- then=state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
- )
- if self.is_mine_id(state.user_id):
+ if self._presence_enabled:
+ for state in self.user_to_current_state.values():
self.wheel_timer.insert(
- now=now,
- obj=state.user_id,
- then=state.last_federation_update_ts + FEDERATION_PING_INTERVAL,
+ now=now, obj=state.user_id, then=state.last_active_ts + IDLE_TIMER
)
- else:
self.wheel_timer.insert(
now=now,
obj=state.user_id,
- then=state.last_federation_update_ts + FEDERATION_TIMEOUT,
+ then=state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
)
+ if self.is_mine_id(state.user_id):
+ self.wheel_timer.insert(
+ now=now,
+ obj=state.user_id,
+ then=state.last_federation_update_ts + FEDERATION_PING_INTERVAL,
+ )
+ else:
+ self.wheel_timer.insert(
+ now=now,
+ obj=state.user_id,
+ then=state.last_federation_update_ts + FEDERATION_TIMEOUT,
+ )
# Set of users who have presence in the `user_to_current_state` that
# have not yet been persisted
@@ -804,6 +805,13 @@ class PresenceHandler(BasePresenceHandler):
This is currently used to bump the max presence stream ID without changing any
user's presence (see PresenceHandler.add_users_to_send_full_presence_to).
"""
+ if not self._presence_enabled:
+ # We shouldn't get here if presence is disabled, but we check anyway
+ # to ensure that we don't a) send out presence federation and b)
+ # don't add things to the wheel timer that will never be handled.
+ logger.warning("Tried to update presence states when presence is disabled")
+ return
+
now = self.clock.time_msec()
with Measure(self.clock, "presence_update_states"):
@@ -1229,6 +1237,10 @@ class PresenceHandler(BasePresenceHandler):
):
raise SynapseError(400, "Invalid presence state")
+ # If presence is disabled, no-op
+ if not self.hs.config.server.use_presence:
+ return
+
user_id = target_user.to_string()
prev_state = await self.current_state_for_user(user_id)
diff --git a/synapse/handlers/room.py b/synapse/handlers/room.py
index b31f00b51..604eb6ec1 100644
--- a/synapse/handlers/room.py
+++ b/synapse/handlers/room.py
@@ -57,7 +57,7 @@ from synapse.api.filtering import Filter
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
from synapse.event_auth import validate_event_for_room_version
from synapse.events import EventBase
-from synapse.events.utils import copy_power_levels_contents
+from synapse.events.utils import copy_and_fixup_power_levels_contents
from synapse.federation.federation_client import InvalidResponseError
from synapse.handlers.federation import get_domains_from_state
from synapse.handlers.relations import BundledAggregations
@@ -337,13 +337,13 @@ class RoomCreationHandler:
# 50, but if the default PL in a room is 50 or more, then we set the
# required PL above that.
- pl_content = dict(old_room_pl_state.content)
- users_default = int(pl_content.get("users_default", 0))
+ pl_content = copy_and_fixup_power_levels_contents(old_room_pl_state.content)
+ users_default: int = pl_content.get("users_default", 0) # type: ignore[assignment]
restricted_level = max(users_default + 1, 50)
updated = False
for v in ("invite", "events_default"):
- current = int(pl_content.get(v, 0))
+ current: int = pl_content.get(v, 0) # type: ignore[assignment]
if current < restricted_level:
logger.debug(
"Setting level for %s in %s to %i (was %i)",
@@ -380,7 +380,9 @@ class RoomCreationHandler:
"state_key": "",
"room_id": new_room_id,
"sender": requester.user.to_string(),
- "content": old_room_pl_state.content,
+ "content": copy_and_fixup_power_levels_contents(
+ old_room_pl_state.content
+ ),
},
ratelimit=False,
)
@@ -471,7 +473,7 @@ class RoomCreationHandler:
# dict so we can't just copy.deepcopy it.
initial_state[
(EventTypes.PowerLevels, "")
- ] = power_levels = copy_power_levels_contents(
+ ] = power_levels = copy_and_fixup_power_levels_contents(
initial_state[(EventTypes.PowerLevels, "")]
)
diff --git a/synapse/util/wheel_timer.py b/synapse/util/wheel_timer.py
index e108adc46..177e198e7 100644
--- a/synapse/util/wheel_timer.py
+++ b/synapse/util/wheel_timer.py
@@ -11,17 +11,20 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-from typing import Generic, List, TypeVar
+import logging
+from typing import Generic, Hashable, List, Set, TypeVar
-T = TypeVar("T")
+import attr
+logger = logging.getLogger(__name__)
+
+T = TypeVar("T", bound=Hashable)
-class _Entry(Generic[T]):
- __slots__ = ["end_key", "queue"]
- def __init__(self, end_key: int) -> None:
- self.end_key: int = end_key
- self.queue: List[T] = []
[email protected](slots=True, frozen=True, auto_attribs=True)
+class _Entry(Generic[T]):
+ end_key: int
+ elements: Set[T] = attr.Factory(set)
class WheelTimer(Generic[T]):
@@ -48,17 +51,27 @@ class WheelTimer(Generic[T]):
then: When to return the object strictly after.
"""
then_key = int(then / self.bucket_size) + 1
+ now_key = int(now / self.bucket_size)
if self.entries:
min_key = self.entries[0].end_key
max_key = self.entries[-1].end_key
+ if min_key < now_key - 10:
+ # If we have ten buckets that are due and still nothing has
+ # called `fetch()` then we likely have a bug that is causing a
+ # memory leak.
+ logger.warning(
+ "Inserting into a wheel timer that hasn't been read from recently. Item: %s",
+ obj,
+ )
+
if then_key <= max_key:
# The max here is to protect against inserts for times in the past
- self.entries[max(min_key, then_key) - min_key].queue.append(obj)
+ self.entries[max(min_key, then_key) - min_key].elements.add(obj)
return
- next_key = int(now / self.bucket_size) + 1
+ next_key = now_key + 1
if self.entries:
last_key = self.entries[-1].end_key
else:
@@ -71,7 +84,7 @@ class WheelTimer(Generic[T]):
# to insert. This ensures there are no gaps.
self.entries.extend(_Entry(key) for key in range(last_key, then_key + 1))
- self.entries[-1].queue.append(obj)
+ self.entries[-1].elements.add(obj)
def fetch(self, now: int) -> List[T]:
"""Fetch any objects that have timed out
@@ -84,11 +97,11 @@ class WheelTimer(Generic[T]):
"""
now_key = int(now / self.bucket_size)
- ret = []
+ ret: List[T] = []
while self.entries and self.entries[0].end_key <= now_key:
- ret.extend(self.entries.pop(0).queue)
+ ret.extend(self.entries.pop(0).elements)
return ret
def __len__(self) -> int:
- return sum(len(entry.queue) for entry in self.entries)
+ return sum(len(entry.elements) for entry in self.entries)
|
matrix-org/synapse
|
2607b3e1816341b3b8534077bd5d3a4daf3a3d15
|
diff --git a/tests/events/test_utils.py b/tests/events/test_utils.py
index 00ad19e44..b1c47efac 100644
--- a/tests/events/test_utils.py
+++ b/tests/events/test_utils.py
@@ -17,7 +17,7 @@ from synapse.api.room_versions import RoomVersions
from synapse.events import make_event_from_dict
from synapse.events.utils import (
SerializeEventConfig,
- copy_power_levels_contents,
+ copy_and_fixup_power_levels_contents,
prune_event,
serialize_event,
)
@@ -529,7 +529,7 @@ class CopyPowerLevelsContentTestCase(unittest.TestCase):
}
def _test(self, input):
- a = copy_power_levels_contents(input)
+ a = copy_and_fixup_power_levels_contents(input)
self.assertEqual(a["ban"], 50)
self.assertEqual(a["events"]["m.room.name"], 100)
@@ -547,3 +547,40 @@ class CopyPowerLevelsContentTestCase(unittest.TestCase):
def test_frozen(self):
input = freeze(self.test_content)
self._test(input)
+
+ def test_stringy_integers(self):
+ """String representations of decimal integers are converted to integers."""
+ input = {
+ "a": "100",
+ "b": {
+ "foo": 99,
+ "bar": "-98",
+ },
+ "d": "0999",
+ }
+ output = copy_and_fixup_power_levels_contents(input)
+ expected_output = {
+ "a": 100,
+ "b": {
+ "foo": 99,
+ "bar": -98,
+ },
+ "d": 999,
+ }
+
+ self.assertEqual(output, expected_output)
+
+ def test_strings_that_dont_represent_decimal_integers(self) -> None:
+ """Should raise when given inputs `s` for which `int(s, base=10)` raises."""
+ for invalid_string in ["0x123", "123.0", "123.45", "hello", "0b1", "0o777"]:
+ with self.assertRaises(TypeError):
+ copy_and_fixup_power_levels_contents({"a": invalid_string})
+
+ def test_invalid_types_raise_type_error(self) -> None:
+ with self.assertRaises(TypeError):
+ copy_and_fixup_power_levels_contents({"a": ["hello", "grandma"]}) # type: ignore[arg-type]
+ copy_and_fixup_power_levels_contents({"a": None}) # type: ignore[arg-type]
+
+ def test_invalid_nesting_raises_type_error(self) -> None:
+ with self.assertRaises(TypeError):
+ copy_and_fixup_power_levels_contents({"a": {"b": {"c": 1}}})
diff --git a/tests/rest/client/test_upgrade_room.py b/tests/rest/client/test_upgrade_room.py
index b7d0f42da..c86fc5df0 100644
--- a/tests/rest/client/test_upgrade_room.py
+++ b/tests/rest/client/test_upgrade_room.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
+from unittest.mock import patch
from twisted.test.proto_helpers import MemoryReactor
@@ -167,6 +168,49 @@ class UpgradeRoomTest(unittest.HomeserverTestCase):
)
self.assertNotIn(self.other, power_levels["users"])
+ def test_stringy_power_levels(self) -> None:
+ """The room upgrade converts stringy power levels to proper integers."""
+ # Retrieve the room's current power levels.
+ power_levels = self.helper.get_state(
+ self.room_id,
+ "m.room.power_levels",
+ tok=self.creator_token,
+ )
+
+ # Set creator's power level to the string "100" instead of the integer `100`.
+ power_levels["users"][self.creator] = "100"
+
+ # Synapse refuses to accept new stringy power level events. Bypass this by
+ # neutering the validation.
+ with patch("synapse.events.validator.jsonschema.validate"):
+ # Note: https://github.com/matrix-org/matrix-spec/issues/853 plans to forbid
+ # string power levels in new rooms. For this test to have a clean
+ # conscience, we ought to ensure it's upgrading from a sufficiently old
+ # version of room.
+ self.helper.send_state(
+ self.room_id,
+ "m.room.power_levels",
+ body=power_levels,
+ tok=self.creator_token,
+ )
+
+ # Upgrade the room. Check the homeserver reports success.
+ channel = self._upgrade_room()
+ self.assertEqual(200, channel.code, channel.result)
+
+ # Extract the new room ID.
+ new_room_id = channel.json_body["replacement_room"]
+
+ # Fetch the new room's power level event.
+ new_power_levels = self.helper.get_state(
+ new_room_id,
+ "m.room.power_levels",
+ tok=self.creator_token,
+ )
+
+ # We should now have an integer power level.
+ self.assertEqual(new_power_levels["users"][self.creator], 100, new_power_levels)
+
def test_space(self) -> None:
"""Test upgrading a space."""
|
Cannot upgrade room with malformed PL event
Some rooms have malformed power-levels events. Upgrading such a room can result in errors such as:
```
2022-04-24 07:26:33,207 - synapse.http.server - 104 - ERROR - POST-17431419 - Failed handle request via 'RoomUpgradeRestServlet': <XForwardedForRequest at 0x7f2066147418 method='POST' uri='/_matrix/client/r0/rooms/!room%3Amatrix.org/upgrade' clientproto='HTTP/1.1' site='8080'>
Capture point (most recent call last):
File "/usr/local/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/synapse/src/synapse/app/homeserver.py", line 460, in <module>
main()
File "/home/synapse/src/synapse/app/homeserver.py", line 456, in main
run(hs)
File "/home/synapse/src/synapse/app/homeserver.py", line 442, in run
logger=logger,
File "/home/synapse/src/synapse/app/_base.py", line 180, in start_reactor
run()
File "/home/synapse/src/synapse/app/_base.py", line 162, in run
run_command()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/base.py", line 1315, in run
self.mainLoop()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/base.py", line 1325, in mainLoop
reactorBaseSelf.runUntilCurrent()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/base.py", line 964, in runUntilCurrent
f(*a, **kw)
File "/home/synapse/src/synapse/storage/databases/main/events_worker.py", line 914, in fire
d.callback(row_dict)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 661, in callback
self._startRunCallbacks(result)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 763, in _startRunCallbacks
self._runCallbacks()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 858, in _runCallbacks
current.result, *args, **kwargs
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 1750, in gotResult
current_context.run(_inlineCallbacks, r, gen, status)
Traceback (most recent call last):
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 1660, in _inlineCallbacks
result = current_context.run(gen.send, result)
File "/home/synapse/src/synapse/util/caches/response_cache.py", line 246, in cb
return await callback(*args, **kwargs)
File "/home/synapse/src/synapse/handlers/room.py", line 270, in _upgrade_room
tombstone_event_id=tombstone_event.event_id,
File "/home/synapse/src/synapse/handlers/room.py", line 475, in clone_existing_room
initial_state[(EventTypes.PowerLevels, "")]
File "/home/synapse/src/synapse/events/utils.py", line 597, in copy_power_levels_contents
"Invalid power_levels value for %s.%s: %r" % (k, k1, v1)
TypeError: Invalid power_levels value for users.@example:matrix.org: '0'
```
|
0.0
|
2607b3e1816341b3b8534077bd5d3a4daf3a3d15
|
[
"tests/events/test_utils.py::PruneEventTestCase::test_alias_event",
"tests/events/test_utils.py::PruneEventTestCase::test_basic_keys",
"tests/events/test_utils.py::PruneEventTestCase::test_content",
"tests/events/test_utils.py::PruneEventTestCase::test_create",
"tests/events/test_utils.py::PruneEventTestCase::test_join_rules",
"tests/events/test_utils.py::PruneEventTestCase::test_member",
"tests/events/test_utils.py::PruneEventTestCase::test_minimal",
"tests/events/test_utils.py::PruneEventTestCase::test_power_levels",
"tests/events/test_utils.py::PruneEventTestCase::test_redacts",
"tests/events/test_utils.py::PruneEventTestCase::test_unsigned",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_all_fields_if_empty",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_fail_if_fields_not_str",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_nops_with_array_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_nops_with_non_dict_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_nops_with_unknown_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_works_with_dot_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_works_with_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_works_with_nested_dot_keys",
"tests/events/test_utils.py::SerializeEventTestCase::test_event_fields_works_with_nested_keys",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_frozen",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_invalid_nesting_raises_type_error",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_invalid_types_raise_type_error",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_strings_that_dont_represent_decimal_integers",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_stringy_integers",
"tests/events/test_utils.py::CopyPowerLevelsContentTestCase::test_unfrozen",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_not_in_room",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_power_levels",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_power_levels_tombstone",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_power_levels_user_default",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_space",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_stringy_power_levels",
"tests/rest/client/test_upgrade_room.py::UpgradeRoomTest::test_upgrade"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-05-06 15:19:34+00:00
|
apache-2.0
| 3,799 |
|
matrix-org__synapse-13223
|
diff --git a/changelog.d/13223.bugfix b/changelog.d/13223.bugfix
new file mode 100644
index 000000000..6ee3aed91
--- /dev/null
+++ b/changelog.d/13223.bugfix
@@ -0,0 +1,1 @@
+Fix bug where notification counts would get stuck after a highlighted message. Broke in v1.62.0.
diff --git a/synapse/storage/databases/main/event_push_actions.py b/synapse/storage/databases/main/event_push_actions.py
index a3edcbb39..1a951ac02 100644
--- a/synapse/storage/databases/main/event_push_actions.py
+++ b/synapse/storage/databases/main/event_push_actions.py
@@ -1016,9 +1016,14 @@ class EventPushActionsWorkerStore(ReceiptsWorkerStore, StreamWorkerStore, SQLBas
upd.stream_ordering
FROM (
SELECT user_id, room_id, count(*) as cnt,
- max(stream_ordering) as stream_ordering
- FROM event_push_actions
- WHERE ? < stream_ordering AND stream_ordering <= ?
+ max(ea.stream_ordering) as stream_ordering
+ FROM event_push_actions AS ea
+ LEFT JOIN event_push_summary AS old USING (user_id, room_id)
+ WHERE ? < ea.stream_ordering AND ea.stream_ordering <= ?
+ AND (
+ old.last_receipt_stream_ordering IS NULL
+ OR old.last_receipt_stream_ordering < ea.stream_ordering
+ )
AND %s = 1
GROUP BY user_id, room_id
) AS upd
|
matrix-org/synapse
|
a962c5a56de69c03848646f25991fabe6e4c39d1
|
diff --git a/tests/storage/test_event_push_actions.py b/tests/storage/test_event_push_actions.py
index e68126777..e8c53f16d 100644
--- a/tests/storage/test_event_push_actions.py
+++ b/tests/storage/test_event_push_actions.py
@@ -196,6 +196,13 @@ class EventPushActionsStoreTestCase(HomeserverTestCase):
_mark_read(10, 10)
_assert_counts(0, 0)
+ _inject_actions(11, HIGHLIGHT)
+ _assert_counts(1, 1)
+ _mark_read(11, 11)
+ _assert_counts(0, 0)
+ _rotate(11)
+ _assert_counts(0, 0)
+
def test_find_first_stream_ordering_after_ts(self) -> None:
def add_event(so: int, ts: int) -> None:
self.get_success(
|
Unread count keeps showing up for some rooms
### Description
A private room I’m in keeps showing a (2) unread message count on client launch, both on Element Web and Android, even after I cleared cache.
### Steps to reproduce
- got some messages in a specific private room
- read them on Element Web (the count disappears)
- left home, started Element Android, the count appeared again for that room but no new message was visible; opening the room here makes the count go away again
- went back home, started Element Web again, the same count was back again.
- read the room again, did a clear cache & reload, the count is back again.
This all happened within the past 24 hours. During that time, I also have had counts appear on direct conversations with no new events while the Web client was running. That is not as reproducible though.
### Homeserver
matrix.org
### Synapse Version
1.61.0
### Installation Method
_No response_
### Platform
:shrug: matrix.org
### Relevant log output
```shell
I don’t have access to that.
```
### Anything else that would be useful to know?
_No response_
|
0.0
|
a962c5a56de69c03848646f25991fabe6e4c39d1
|
[
"tests/storage/test_event_push_actions.py::EventPushActionsStoreTestCase::test_count_aggregation"
] |
[
"tests/storage/test_event_push_actions.py::EventPushActionsStoreTestCase::test_find_first_stream_ordering_after_ts",
"tests/storage/test_event_push_actions.py::EventPushActionsStoreTestCase::test_get_unread_push_actions_for_user_in_range_for_email",
"tests/storage/test_event_push_actions.py::EventPushActionsStoreTestCase::test_get_unread_push_actions_for_user_in_range_for_http"
] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-08 11:09:24+00:00
|
apache-2.0
| 3,800 |
|
matrix-org__synapse-4618
|
diff --git a/changelog.d/4618.bugfix b/changelog.d/4618.bugfix
new file mode 100644
index 000000000..22115a020
--- /dev/null
+++ b/changelog.d/4618.bugfix
@@ -0,0 +1,1 @@
+Fix failure to start when not TLS certificate was given even if TLS was disabled.
diff --git a/synapse/app/_base.py b/synapse/app/_base.py
index 50fd17c0b..5b0ca312e 100644
--- a/synapse/app/_base.py
+++ b/synapse/app/_base.py
@@ -213,12 +213,13 @@ def refresh_certificate(hs):
Refresh the TLS certificates that Synapse is using by re-reading them from
disk and updating the TLS context factories to use them.
"""
- hs.config.read_certificate_from_disk()
if not hs.config.has_tls_listener():
- # nothing else to do here
+ # attempt to reload the certs for the good of the tls_fingerprints
+ hs.config.read_certificate_from_disk(require_cert_and_key=False)
return
+ hs.config.read_certificate_from_disk(require_cert_and_key=True)
hs.tls_server_context_factory = context_factory.ServerContextFactory(hs.config)
if hs._listening_services:
diff --git a/synapse/config/tls.py b/synapse/config/tls.py
index 86e6eb80d..57f117a14 100644
--- a/synapse/config/tls.py
+++ b/synapse/config/tls.py
@@ -23,7 +23,7 @@ from unpaddedbase64 import encode_base64
from OpenSSL import crypto
-from synapse.config._base import Config
+from synapse.config._base import Config, ConfigError
logger = logging.getLogger(__name__)
@@ -45,6 +45,19 @@ class TlsConfig(Config):
self.tls_certificate_file = self.abspath(config.get("tls_certificate_path"))
self.tls_private_key_file = self.abspath(config.get("tls_private_key_path"))
+
+ if self.has_tls_listener():
+ if not self.tls_certificate_file:
+ raise ConfigError(
+ "tls_certificate_path must be specified if TLS-enabled listeners are "
+ "configured."
+ )
+ if not self.tls_private_key_file:
+ raise ConfigError(
+ "tls_certificate_path must be specified if TLS-enabled listeners are "
+ "configured."
+ )
+
self._original_tls_fingerprints = config.get("tls_fingerprints", [])
if self._original_tls_fingerprints is None:
@@ -105,26 +118,40 @@ class TlsConfig(Config):
days_remaining = (expires_on - now).days
return days_remaining
- def read_certificate_from_disk(self):
- """
- Read the certificates from disk.
+ def read_certificate_from_disk(self, require_cert_and_key):
"""
- self.tls_certificate = self.read_tls_certificate()
+ Read the certificates and private key from disk.
- if self.has_tls_listener():
+ Args:
+ require_cert_and_key (bool): set to True to throw an error if the certificate
+ and key file are not given
+ """
+ if require_cert_and_key:
self.tls_private_key = self.read_tls_private_key()
+ self.tls_certificate = self.read_tls_certificate()
+ elif self.tls_certificate_file:
+ # we only need the certificate for the tls_fingerprints. Reload it if we
+ # can, but it's not a fatal error if we can't.
+ try:
+ self.tls_certificate = self.read_tls_certificate()
+ except Exception as e:
+ logger.info(
+ "Unable to read TLS certificate (%s). Ignoring as no "
+ "tls listeners enabled.", e,
+ )
self.tls_fingerprints = list(self._original_tls_fingerprints)
- # Check that our own certificate is included in the list of fingerprints
- # and include it if it is not.
- x509_certificate_bytes = crypto.dump_certificate(
- crypto.FILETYPE_ASN1, self.tls_certificate
- )
- sha256_fingerprint = encode_base64(sha256(x509_certificate_bytes).digest())
- sha256_fingerprints = set(f["sha256"] for f in self.tls_fingerprints)
- if sha256_fingerprint not in sha256_fingerprints:
- self.tls_fingerprints.append({u"sha256": sha256_fingerprint})
+ if self.tls_certificate:
+ # Check that our own certificate is included in the list of fingerprints
+ # and include it if it is not.
+ x509_certificate_bytes = crypto.dump_certificate(
+ crypto.FILETYPE_ASN1, self.tls_certificate
+ )
+ sha256_fingerprint = encode_base64(sha256(x509_certificate_bytes).digest())
+ sha256_fingerprints = set(f["sha256"] for f in self.tls_fingerprints)
+ if sha256_fingerprint not in sha256_fingerprints:
+ self.tls_fingerprints.append({u"sha256": sha256_fingerprint})
def default_config(self, config_dir_path, server_name, **kwargs):
base_key_name = os.path.join(config_dir_path, server_name)
|
matrix-org/synapse
|
46b8a79b3a418ad6795e903588d1f8e12f547e2c
|
diff --git a/tests/config/test_tls.py b/tests/config/test_tls.py
index d8fd18a9c..c260d3359 100644
--- a/tests/config/test_tls.py
+++ b/tests/config/test_tls.py
@@ -65,7 +65,7 @@ s4niecZKPBizL6aucT59CsunNmmb5Glq8rlAcU+1ZTZZzGYqVYhF6axB9Qg=
t = TestConfig()
t.read_config(config)
- t.read_certificate_from_disk()
+ t.read_certificate_from_disk(require_cert_and_key=False)
warnings = self.flushWarnings()
self.assertEqual(len(warnings), 1)
|
Synapse should not require TLS certificate files
Testing with 0.99rc4, it seems like:
- regardless of the `no_tls` setting's value (`False` or `True`), Synapse would still try to load `tls_certificate_path` or `tls_private_key_path` (I'm not sure which one now, but it does try to read it and fails with an exception if it's missing or not a valid file)
- the comment in `homeserver.yaml` about `no_tls` seems backward ("Setting no_tls to False will do so (and avoid the need to give synapse a TLS private key).") I guess this should say `True`, rather than `False`
----------
I wish to use Synapse with a reverse-proxy and this issue is a blocker for that. I'd rather not provide any certificate files to Synapse at all.
Now, looking at #2840, unless something changed, it seems like Synapse may really need to access the certificate file.
This leads to all sorts of pain, especially when automated renewal is involved.
Not only do we need to renew the certificate and reload the reverse-proxy (no downtime there), but we also need to **restart** Synapse at the same time (reloading doesn't seem possible as explained in #1180).
|
0.0
|
46b8a79b3a418ad6795e903588d1f8e12f547e2c
|
[
"tests/config/test_tls.py::TLSConfigTests::test_warn_self_signed"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-11 21:52:08+00:00
|
apache-2.0
| 3,801 |
|
matrix-org__synapse-4942
|
diff --git a/changelog.d/4942.bugfix b/changelog.d/4942.bugfix
new file mode 100644
index 000000000..590d80d58
--- /dev/null
+++ b/changelog.d/4942.bugfix
@@ -0,0 +1,1 @@
+Fix bug where presence updates were sent to all servers in a room when a new server joined, rather than to just the new server.
diff --git a/synapse/federation/send_queue.py b/synapse/federation/send_queue.py
index 04d04a445..0240b339b 100644
--- a/synapse/federation/send_queue.py
+++ b/synapse/federation/send_queue.py
@@ -55,7 +55,12 @@ class FederationRemoteSendQueue(object):
self.is_mine_id = hs.is_mine_id
self.presence_map = {} # Pending presence map user_id -> UserPresenceState
- self.presence_changed = SortedDict() # Stream position -> user_id
+ self.presence_changed = SortedDict() # Stream position -> list[user_id]
+
+ # Stores the destinations we need to explicitly send presence to about a
+ # given user.
+ # Stream position -> (user_id, destinations)
+ self.presence_destinations = SortedDict()
self.keyed_edu = {} # (destination, key) -> EDU
self.keyed_edu_changed = SortedDict() # stream position -> (destination, key)
@@ -77,7 +82,7 @@ class FederationRemoteSendQueue(object):
for queue_name in [
"presence_map", "presence_changed", "keyed_edu", "keyed_edu_changed",
- "edus", "device_messages", "pos_time",
+ "edus", "device_messages", "pos_time", "presence_destinations",
]:
register(queue_name, getattr(self, queue_name))
@@ -121,6 +126,15 @@ class FederationRemoteSendQueue(object):
for user_id in uids
)
+ keys = self.presence_destinations.keys()
+ i = self.presence_destinations.bisect_left(position_to_delete)
+ for key in keys[:i]:
+ del self.presence_destinations[key]
+
+ user_ids.update(
+ user_id for user_id, _ in self.presence_destinations.values()
+ )
+
to_del = [
user_id for user_id in self.presence_map if user_id not in user_ids
]
@@ -209,6 +223,20 @@ class FederationRemoteSendQueue(object):
self.notifier.on_new_replication_data()
+ def send_presence_to_destinations(self, states, destinations):
+ """As per FederationSender
+
+ Args:
+ states (list[UserPresenceState])
+ destinations (list[str])
+ """
+ for state in states:
+ pos = self._next_pos()
+ self.presence_map.update({state.user_id: state for state in states})
+ self.presence_destinations[pos] = (state.user_id, destinations)
+
+ self.notifier.on_new_replication_data()
+
def send_device_messages(self, destination):
"""As per FederationSender"""
pos = self._next_pos()
@@ -261,6 +289,16 @@ class FederationRemoteSendQueue(object):
state=self.presence_map[user_id],
)))
+ # Fetch presence to send to destinations
+ i = self.presence_destinations.bisect_right(from_token)
+ j = self.presence_destinations.bisect_right(to_token) + 1
+
+ for pos, (user_id, dests) in self.presence_destinations.items()[i:j]:
+ rows.append((pos, PresenceDestinationsRow(
+ state=self.presence_map[user_id],
+ destinations=list(dests),
+ )))
+
# Fetch changes keyed edus
i = self.keyed_edu_changed.bisect_right(from_token)
j = self.keyed_edu_changed.bisect_right(to_token) + 1
@@ -357,6 +395,29 @@ class PresenceRow(BaseFederationRow, namedtuple("PresenceRow", (
buff.presence.append(self.state)
+class PresenceDestinationsRow(BaseFederationRow, namedtuple("PresenceDestinationsRow", (
+ "state", # UserPresenceState
+ "destinations", # list[str]
+))):
+ TypeId = "pd"
+
+ @staticmethod
+ def from_data(data):
+ return PresenceDestinationsRow(
+ state=UserPresenceState.from_dict(data["state"]),
+ destinations=data["dests"],
+ )
+
+ def to_data(self):
+ return {
+ "state": self.state.as_dict(),
+ "dests": self.destinations,
+ }
+
+ def add_to_buffer(self, buff):
+ buff.presence_destinations.append((self.state, self.destinations))
+
+
class KeyedEduRow(BaseFederationRow, namedtuple("KeyedEduRow", (
"key", # tuple(str) - the edu key passed to send_edu
"edu", # Edu
@@ -428,6 +489,7 @@ TypeToRow = {
Row.TypeId: Row
for Row in (
PresenceRow,
+ PresenceDestinationsRow,
KeyedEduRow,
EduRow,
DeviceRow,
@@ -437,6 +499,7 @@ TypeToRow = {
ParsedFederationStreamData = namedtuple("ParsedFederationStreamData", (
"presence", # list(UserPresenceState)
+ "presence_destinations", # list of tuples of UserPresenceState and destinations
"keyed_edus", # dict of destination -> { key -> Edu }
"edus", # dict of destination -> [Edu]
"device_destinations", # set of destinations
@@ -458,6 +521,7 @@ def process_rows_for_federation(transaction_queue, rows):
buff = ParsedFederationStreamData(
presence=[],
+ presence_destinations=[],
keyed_edus={},
edus={},
device_destinations=set(),
@@ -476,6 +540,11 @@ def process_rows_for_federation(transaction_queue, rows):
if buff.presence:
transaction_queue.send_presence(buff.presence)
+ for state, destinations in buff.presence_destinations:
+ transaction_queue.send_presence_to_destinations(
+ states=[state], destinations=destinations,
+ )
+
for destination, edu_map in iteritems(buff.keyed_edus):
for key, edu in edu_map.items():
transaction_queue.send_edu(edu, key)
diff --git a/synapse/federation/sender/__init__.py b/synapse/federation/sender/__init__.py
index 1dc041752..4f0f93910 100644
--- a/synapse/federation/sender/__init__.py
+++ b/synapse/federation/sender/__init__.py
@@ -371,7 +371,7 @@ class FederationSender(object):
return
# First we queue up the new presence by user ID, so multiple presence
- # updates in quick successtion are correctly handled
+ # updates in quick succession are correctly handled.
# We only want to send presence for our own users, so lets always just
# filter here just in case.
self.pending_presence.update({
@@ -402,6 +402,23 @@ class FederationSender(object):
finally:
self._processing_pending_presence = False
+ def send_presence_to_destinations(self, states, destinations):
+ """Send the given presence states to the given destinations.
+
+ Args:
+ states (list[UserPresenceState])
+ destinations (list[str])
+ """
+
+ if not states or not self.hs.config.use_presence:
+ # No-op if presence is disabled.
+ return
+
+ for destination in destinations:
+ if destination == self.server_name:
+ continue
+ self._get_per_destination_queue(destination).send_presence(states)
+
@measure_func("txnqueue._process_presence")
@defer.inlineCallbacks
def _process_presence_inner(self, states):
diff --git a/synapse/handlers/presence.py b/synapse/handlers/presence.py
index 37e87fc05..e85c49742 100644
--- a/synapse/handlers/presence.py
+++ b/synapse/handlers/presence.py
@@ -31,9 +31,11 @@ from prometheus_client import Counter
from twisted.internet import defer
-from synapse.api.constants import PresenceState
+import synapse.metrics
+from synapse.api.constants import EventTypes, Membership, PresenceState
from synapse.api.errors import SynapseError
from synapse.metrics import LaterGauge
+from synapse.metrics.background_process_metrics import run_as_background_process
from synapse.storage.presence import UserPresenceState
from synapse.types import UserID, get_domain_from_id
from synapse.util.async_helpers import Linearizer
@@ -98,6 +100,7 @@ class PresenceHandler(object):
self.hs = hs
self.is_mine = hs.is_mine
self.is_mine_id = hs.is_mine_id
+ self.server_name = hs.hostname
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.wheel_timer = WheelTimer()
@@ -132,9 +135,6 @@ class PresenceHandler(object):
)
)
- distributor = hs.get_distributor()
- distributor.observe("user_joined_room", self.user_joined_room)
-
active_presence = self.store.take_presence_startup_info()
# A dictionary of the current state of users. This is prefilled with
@@ -220,6 +220,15 @@ class PresenceHandler(object):
LaterGauge("synapse_handlers_presence_wheel_timer_size", "", [],
lambda: len(self.wheel_timer))
+ # Used to handle sending of presence to newly joined users/servers
+ if hs.config.use_presence:
+ self.notifier.add_replication_callback(self.notify_new_event)
+
+ # Presence is best effort and quickly heals itself, so lets just always
+ # stream from the current state when we restart.
+ self._event_pos = self.store.get_current_events_token()
+ self._event_processing = False
+
@defer.inlineCallbacks
def _on_shutdown(self):
"""Gets called when shutting down. This lets us persist any updates that
@@ -750,31 +759,6 @@ class PresenceHandler(object):
yield self._update_states([prev_state.copy_and_replace(**new_fields)])
- @defer.inlineCallbacks
- def user_joined_room(self, user, room_id):
- """Called (via the distributor) when a user joins a room. This funciton
- sends presence updates to servers, either:
- 1. the joining user is a local user and we send their presence to
- all servers in the room.
- 2. the joining user is a remote user and so we send presence for all
- local users in the room.
- """
- # We only need to send presence to servers that don't have it yet. We
- # don't need to send to local clients here, as that is done as part
- # of the event stream/sync.
- # TODO: Only send to servers not already in the room.
- if self.is_mine(user):
- state = yield self.current_state_for_user(user.to_string())
-
- self._push_to_remotes([state])
- else:
- user_ids = yield self.store.get_users_in_room(room_id)
- user_ids = list(filter(self.is_mine_id, user_ids))
-
- states = yield self.current_state_for_users(user_ids)
-
- self._push_to_remotes(list(states.values()))
-
@defer.inlineCallbacks
def get_presence_list(self, observer_user, accepted=None):
"""Returns the presence for all users in their presence list.
@@ -945,6 +929,140 @@ class PresenceHandler(object):
rows = yield self.store.get_all_presence_updates(last_id, current_id)
defer.returnValue(rows)
+ def notify_new_event(self):
+ """Called when new events have happened. Handles users and servers
+ joining rooms and require being sent presence.
+ """
+
+ if self._event_processing:
+ return
+
+ @defer.inlineCallbacks
+ def _process_presence():
+ assert not self._event_processing
+
+ self._event_processing = True
+ try:
+ yield self._unsafe_process()
+ finally:
+ self._event_processing = False
+
+ run_as_background_process("presence.notify_new_event", _process_presence)
+
+ @defer.inlineCallbacks
+ def _unsafe_process(self):
+ # Loop round handling deltas until we're up to date
+ while True:
+ with Measure(self.clock, "presence_delta"):
+ deltas = yield self.store.get_current_state_deltas(self._event_pos)
+ if not deltas:
+ return
+
+ yield self._handle_state_delta(deltas)
+
+ self._event_pos = deltas[-1]["stream_id"]
+
+ # Expose current event processing position to prometheus
+ synapse.metrics.event_processing_positions.labels("presence").set(
+ self._event_pos
+ )
+
+ @defer.inlineCallbacks
+ def _handle_state_delta(self, deltas):
+ """Process current state deltas to find new joins that need to be
+ handled.
+ """
+ for delta in deltas:
+ typ = delta["type"]
+ state_key = delta["state_key"]
+ room_id = delta["room_id"]
+ event_id = delta["event_id"]
+ prev_event_id = delta["prev_event_id"]
+
+ logger.debug("Handling: %r %r, %s", typ, state_key, event_id)
+
+ if typ != EventTypes.Member:
+ continue
+
+ event = yield self.store.get_event(event_id)
+ if event.content.get("membership") != Membership.JOIN:
+ # We only care about joins
+ continue
+
+ if prev_event_id:
+ prev_event = yield self.store.get_event(prev_event_id)
+ if prev_event.content.get("membership") == Membership.JOIN:
+ # Ignore changes to join events.
+ continue
+
+ yield self._on_user_joined_room(room_id, state_key)
+
+ @defer.inlineCallbacks
+ def _on_user_joined_room(self, room_id, user_id):
+ """Called when we detect a user joining the room via the current state
+ delta stream.
+
+ Args:
+ room_id (str)
+ user_id (str)
+
+ Returns:
+ Deferred
+ """
+
+ if self.is_mine_id(user_id):
+ # If this is a local user then we need to send their presence
+ # out to hosts in the room (who don't already have it)
+
+ # TODO: We should be able to filter the hosts down to those that
+ # haven't previously seen the user
+
+ state = yield self.current_state_for_user(user_id)
+ hosts = yield self.state.get_current_hosts_in_room(room_id)
+
+ # Filter out ourselves.
+ hosts = set(host for host in hosts if host != self.server_name)
+
+ self.federation.send_presence_to_destinations(
+ states=[state],
+ destinations=hosts,
+ )
+ else:
+ # A remote user has joined the room, so we need to:
+ # 1. Check if this is a new server in the room
+ # 2. If so send any presence they don't already have for
+ # local users in the room.
+
+ # TODO: We should be able to filter the users down to those that
+ # the server hasn't previously seen
+
+ # TODO: Check that this is actually a new server joining the
+ # room.
+
+ user_ids = yield self.state.get_current_user_in_room(room_id)
+ user_ids = list(filter(self.is_mine_id, user_ids))
+
+ states = yield self.current_state_for_users(user_ids)
+
+ # Filter out old presence, i.e. offline presence states where
+ # the user hasn't been active for a week. We can change this
+ # depending on what we want the UX to be, but at the least we
+ # should filter out offline presence where the state is just the
+ # default state.
+ now = self.clock.time_msec()
+ states = [
+ state for state in states.values()
+ if state.state != PresenceState.OFFLINE
+ or now - state.last_active_ts < 7 * 24 * 60 * 60 * 1000
+ or state.status_msg is not None
+ ]
+
+ if states:
+ self.federation.send_presence_to_destinations(
+ states=states,
+ destinations=[get_domain_from_id(user_id)],
+ )
+
def should_notify(old_state, new_state):
"""Decides if a presence state change should be sent to interested parties.
|
matrix-org/synapse
|
4eeb2c2f0757cee4b258143dfa6aa6588d020175
|
diff --git a/tests/handlers/test_presence.py b/tests/handlers/test_presence.py
index fc2b646ba..94c6080e3 100644
--- a/tests/handlers/test_presence.py
+++ b/tests/handlers/test_presence.py
@@ -16,7 +16,11 @@
from mock import Mock, call
-from synapse.api.constants import PresenceState
+from signedjson.key import generate_signing_key
+
+from synapse.api.constants import EventTypes, Membership, PresenceState
+from synapse.events import room_version_to_event_format
+from synapse.events.builder import EventBuilder
from synapse.handlers.presence import (
FEDERATION_PING_INTERVAL,
FEDERATION_TIMEOUT,
@@ -26,7 +30,9 @@ from synapse.handlers.presence import (
handle_timeout,
handle_update,
)
+from synapse.rest.client.v1 import room
from synapse.storage.presence import UserPresenceState
+from synapse.types import UserID, get_domain_from_id
from tests import unittest
@@ -405,3 +411,171 @@ class PresenceTimeoutTestCase(unittest.TestCase):
self.assertIsNotNone(new_state)
self.assertEquals(state, new_state)
+
+
+class PresenceJoinTestCase(unittest.HomeserverTestCase):
+ """Tests remote servers get told about presence of users in the room when
+ they join and when new local users join.
+ """
+
+ user_id = "@test:server"
+
+ servlets = [room.register_servlets]
+
+ def make_homeserver(self, reactor, clock):
+ hs = self.setup_test_homeserver(
+ "server", http_client=None,
+ federation_sender=Mock(),
+ )
+ return hs
+
+ def prepare(self, reactor, clock, hs):
+ self.federation_sender = hs.get_federation_sender()
+ self.event_builder_factory = hs.get_event_builder_factory()
+ self.federation_handler = hs.get_handlers().federation_handler
+ self.presence_handler = hs.get_presence_handler()
+
+ # self.event_builder_for_2 = EventBuilderFactory(hs)
+ # self.event_builder_for_2.hostname = "test2"
+
+ self.store = hs.get_datastore()
+ self.state = hs.get_state_handler()
+ self.auth = hs.get_auth()
+
+ # We don't actually check signatures in tests, so lets just create a
+ # random key to use.
+ self.random_signing_key = generate_signing_key("ver")
+
+ def test_remote_joins(self):
+ # We advance time to something that isn't 0, as we use 0 as a special
+ # value.
+ self.reactor.advance(1000000000000)
+
+ # Create a room with two local users
+ room_id = self.helper.create_room_as(self.user_id)
+ self.helper.join(room_id, "@test2:server")
+
+ # Mark test2 as online, test will be offline with a last_active of 0
+ self.presence_handler.set_state(
+ UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE},
+ )
+ self.reactor.pump([0]) # Wait for presence updates to be handled
+
+ #
+ # Test that a new server gets told about existing presence
+ #
+
+ self.federation_sender.reset_mock()
+
+ # Add a new remote server to the room
+ self._add_new_user(room_id, "@alice:server2")
+
+ # We shouldn't have sent out any local presence *updates*
+ self.federation_sender.send_presence.assert_not_called()
+
+ # When new server is joined we send it the local users presence states.
+ # We expect to only see user @test2:server, as @test:server is offline
+ # and has a zero last_active_ts
+ expected_state = self.get_success(
+ self.presence_handler.current_state_for_user("@test2:server")
+ )
+ self.assertEqual(expected_state.state, PresenceState.ONLINE)
+ self.federation_sender.send_presence_to_destinations.assert_called_once_with(
+ destinations=["server2"], states=[expected_state]
+ )
+
+ #
+ # Test that only the new server gets sent presence and not existing servers
+ #
+
+ self.federation_sender.reset_mock()
+ self._add_new_user(room_id, "@bob:server3")
+
+ self.federation_sender.send_presence.assert_not_called()
+ self.federation_sender.send_presence_to_destinations.assert_called_once_with(
+ destinations=["server3"], states=[expected_state]
+ )
+
+ def test_remote_gets_presence_when_local_user_joins(self):
+ # We advance time to something that isn't 0, as we use 0 as a special
+ # value.
+ self.reactor.advance(1000000000000)
+
+ # Create a room with one local users
+ room_id = self.helper.create_room_as(self.user_id)
+
+ # Mark test as online
+ self.presence_handler.set_state(
+ UserID.from_string("@test:server"), {"presence": PresenceState.ONLINE},
+ )
+
+ # Mark test2 as online, test will be offline with a last_active of 0.
+ # Note we don't join them to the room yet
+ self.presence_handler.set_state(
+ UserID.from_string("@test2:server"), {"presence": PresenceState.ONLINE},
+ )
+
+ # Add servers to the room
+ self._add_new_user(room_id, "@alice:server2")
+ self._add_new_user(room_id, "@bob:server3")
+
+ self.reactor.pump([0]) # Wait for presence updates to be handled
+
+ #
+ # Test that when a local join happens remote servers get told about it
+ #
+
+ self.federation_sender.reset_mock()
+
+ # Join local user to room
+ self.helper.join(room_id, "@test2:server")
+
+ self.reactor.pump([0]) # Wait for presence updates to be handled
+
+ # We shouldn't have sent out any local presence *updates*
+ self.federation_sender.send_presence.assert_not_called()
+
+ # We expect to only send test2 presence to server2 and server3
+ expected_state = self.get_success(
+ self.presence_handler.current_state_for_user("@test2:server")
+ )
+ self.assertEqual(expected_state.state, PresenceState.ONLINE)
+ self.federation_sender.send_presence_to_destinations.assert_called_once_with(
+ destinations=set(("server2", "server3")),
+ states=[expected_state]
+ )
+
+ def _add_new_user(self, room_id, user_id):
+ """Add new user to the room by creating an event and poking the federation API.
+ """
+
+ hostname = get_domain_from_id(user_id)
+
+ room_version = self.get_success(self.store.get_room_version(room_id))
+
+ builder = EventBuilder(
+ state=self.state,
+ auth=self.auth,
+ store=self.store,
+ clock=self.clock,
+ hostname=hostname,
+ signing_key=self.random_signing_key,
+ format_version=room_version_to_event_format(room_version),
+ room_id=room_id,
+ type=EventTypes.Member,
+ sender=user_id,
+ state_key=user_id,
+ content={"membership": Membership.JOIN}
+ )
+
+ prev_event_ids = self.get_success(
+ self.store.get_latest_event_ids_in_room(room_id)
+ )
+
+ event = self.get_success(builder.build(prev_event_ids))
+
+ self.get_success(self.federation_handler.on_receive_pdu(hostname, event))
+
+ # Check that it was successfully persisted.
+ self.get_success(self.store.get_event(event.event_id))
+ self.get_success(self.store.get_event(event.event_id))
|
we send presence updates to all the servers that our users share rooms with, whenever a remote user joins any of those rooms
I suspect this is the root cause of #2514 and a bunch of other similar reports like #1429 and #3490.
Whenever a remote user joins a room, we look for any local users that are in that room, and then, for each local user, send out presence updates to *all* the servers that user shares a room with.
|
0.0
|
4eeb2c2f0757cee4b258143dfa6aa6588d020175
|
[
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_no_timeout"
] |
[
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_sync_timeout",
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_last_active",
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_federation_timeout",
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_federation_ping",
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_sync_online",
"tests/handlers/test_presence.py::PresenceTimeoutTestCase::test_idle_timer",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_online_to_online_last_active_noop",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_online_to_idle",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_online_to_offline",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_remote_ping_timer",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_online_to_online",
"tests/handlers/test_presence.py::PresenceUpdateTestCase::test_online_to_online_last_active"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-26 14:53:53+00:00
|
apache-2.0
| 3,802 |
|
matrix-org__synapse-5593
|
diff --git a/changelog.d/5593.bugfix b/changelog.d/5593.bugfix
new file mode 100644
index 000000000..e981589ac
--- /dev/null
+++ b/changelog.d/5593.bugfix
@@ -0,0 +1,1 @@
+Fix regression in 1.1rc1 where OPTIONS requests to the media repo would fail.
diff --git a/synapse/http/server.py b/synapse/http/server.py
index f067c163c..d993161a3 100644
--- a/synapse/http/server.py
+++ b/synapse/http/server.py
@@ -65,8 +65,8 @@ def wrap_json_request_handler(h):
The handler method must have a signature of "handle_foo(self, request)",
where "request" must be a SynapseRequest.
- The handler must return a deferred. If the deferred succeeds we assume that
- a response has been sent. If the deferred fails with a SynapseError we use
+ The handler must return a deferred or a coroutine. If the deferred succeeds
+ we assume that a response has been sent. If the deferred fails with a SynapseError we use
it to send a JSON response with the appropriate HTTP reponse code. If the
deferred fails with any other type of error we send a 500 reponse.
"""
@@ -353,16 +353,22 @@ class DirectServeResource(resource.Resource):
"""
Render the request, using an asynchronous render handler if it exists.
"""
- render_callback_name = "_async_render_" + request.method.decode("ascii")
+ async_render_callback_name = "_async_render_" + request.method.decode("ascii")
- if hasattr(self, render_callback_name):
- # Call the handler
- callback = getattr(self, render_callback_name)
- defer.ensureDeferred(callback(request))
+ # Try and get the async renderer
+ callback = getattr(self, async_render_callback_name, None)
- return NOT_DONE_YET
- else:
- super().render(request)
+ # No async renderer for this request method.
+ if not callback:
+ return super().render(request)
+
+ resp = callback(request)
+
+ # If it's a coroutine, turn it into a Deferred
+ if isinstance(resp, types.CoroutineType):
+ defer.ensureDeferred(resp)
+
+ return NOT_DONE_YET
def _options_handler(request):
diff --git a/synapse/rest/media/v1/preview_url_resource.py b/synapse/rest/media/v1/preview_url_resource.py
index 0337b64dc..053346fb8 100644
--- a/synapse/rest/media/v1/preview_url_resource.py
+++ b/synapse/rest/media/v1/preview_url_resource.py
@@ -95,6 +95,7 @@ class PreviewUrlResource(DirectServeResource):
)
def render_OPTIONS(self, request):
+ request.setHeader(b"Allow", b"OPTIONS, GET")
return respond_with_json(request, 200, {}, send_cors=True)
@wrap_json_request_handler
diff --git a/synapse/util/logcontext.py b/synapse/util/logcontext.py
index 6b0d2deea..9e1b53780 100644
--- a/synapse/util/logcontext.py
+++ b/synapse/util/logcontext.py
@@ -24,6 +24,7 @@ See doc/log_contexts.rst for details on how this works.
import logging
import threading
+import types
from twisted.internet import defer, threads
@@ -528,8 +529,9 @@ def run_in_background(f, *args, **kwargs):
return from the function, and that the sentinel context is set once the
deferred returned by the function completes.
- Useful for wrapping functions that return a deferred which you don't yield
- on (for instance because you want to pass it to deferred.gatherResults()).
+ Useful for wrapping functions that return a deferred or coroutine, which you don't
+ yield or await on (for instance because you want to pass it to
+ deferred.gatherResults()).
Note that if you completely discard the result, you should make sure that
`f` doesn't raise any deferred exceptions, otherwise a scary-looking
@@ -544,6 +546,9 @@ def run_in_background(f, *args, **kwargs):
# by synchronous exceptions, so let's turn them into Failures.
return defer.fail()
+ if isinstance(res, types.CoroutineType):
+ res = defer.ensureDeferred(res)
+
if not isinstance(res, defer.Deferred):
return res
|
matrix-org/synapse
|
f8b52eb8c5fc4c723fad49df7a5339c1239b34be
|
diff --git a/tests/rest/media/v1/test_url_preview.py b/tests/rest/media/v1/test_url_preview.py
index 8fe596186..976652aee 100644
--- a/tests/rest/media/v1/test_url_preview.py
+++ b/tests/rest/media/v1/test_url_preview.py
@@ -460,3 +460,15 @@ class URLPreviewTests(unittest.HomeserverTestCase):
"error": "DNS resolution failure during URL preview generation",
},
)
+
+ def test_OPTIONS(self):
+ """
+ OPTIONS returns the OPTIONS.
+ """
+ request, channel = self.make_request(
+ "OPTIONS", "url_preview?url=http://example.com", shorthand=False
+ )
+ request.render(self.preview_url)
+ self.pump()
+ self.assertEqual(channel.code, 200)
+ self.assertEqual(channel.json_body, {})
diff --git a/tests/util/test_logcontext.py b/tests/util/test_logcontext.py
index 8adaee3c8..8d69fbf11 100644
--- a/tests/util/test_logcontext.py
+++ b/tests/util/test_logcontext.py
@@ -39,24 +39,17 @@ class LoggingContextTestCase(unittest.TestCase):
callback_completed = [False]
- def test():
+ with LoggingContext() as context_one:
context_one.request = "one"
- d = function()
+
+ # fire off function, but don't wait on it.
+ d2 = logcontext.run_in_background(function)
def cb(res):
- self._check_test_key("one")
callback_completed[0] = True
return res
- d.addCallback(cb)
-
- return d
-
- with LoggingContext() as context_one:
- context_one.request = "one"
-
- # fire off function, but don't wait on it.
- logcontext.run_in_background(test)
+ d2.addCallback(cb)
self._check_test_key("one")
@@ -105,6 +98,22 @@ class LoggingContextTestCase(unittest.TestCase):
return self._test_run_in_background(testfunc)
+ def test_run_in_background_with_coroutine(self):
+ async def testfunc():
+ self._check_test_key("one")
+ d = Clock(reactor).sleep(0)
+ self.assertIs(LoggingContext.current_context(), LoggingContext.sentinel)
+ await d
+ self._check_test_key("one")
+
+ return self._test_run_in_background(testfunc)
+
+ def test_run_in_background_with_nonblocking_coroutine(self):
+ async def testfunc():
+ self._check_test_key("one")
+
+ return self._test_run_in_background(testfunc)
+
@defer.inlineCallbacks
def test_make_deferred_yieldable(self):
# a function which retuns an incomplete deferred, but doesn't follow
|
media upload is broken
It gives a 500:
```
2019-07-02 12:33:34,534 - synapse.access.http.8008 - 233 - INFO - OPTIONS-12451- 2001:8b0:ba7a:e98f:74ca:71dd:a262:d20e - 8008 - Received request: OPTIONS /_matrix/media/v1/upload
2019-07-02 12:33:34,535 - twisted - 253 - CRITICAL - OPTIONS-12451-
RuntimeError: Producer was not unregistered for b'/_matrix/media/v1/upload'
2019-07-02 12:33:34,535 - synapse.access.http.8008 - 302 - INFO - OPTIONS-12451- 2001:8b0:ba7a:e98f:74ca:71dd:a262:d20e - 8008 - {None} Processed request: 0.001sec/-0.001sec (0.000sec, 0.000sec) (0.000sec/0.000sec/0) 471B 500 "OPTIONS /_matrix/media/v1/upload HTTP/1.1" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100
2019-07-02 12:33:34,637 - synapse.access.http.8008 - 233 - INFO - OPTIONS-12452- 2001:8b0:ba7a:e98f:74ca:71dd:a262:d20e - 8008 - Received request: OPTIONS /_matrix/media/v1/upload?filename=cat_confused.gif
2019-07-02 12:33:34,638 - twisted - 253 - CRITICAL - OPTIONS-12452-
RuntimeError: Producer was not unregistered for b'/_matrix/media/v1/upload?filename=cat_confused.gif'
2019-07-02 12:33:34,638 - synapse.access.http.8008 - 302 - INFO - OPTIONS-12452- 2001:8b0:ba7a:e98f:74ca:71dd:a262:d20e - 8008 - {None} Processed request: 0.001sec/-0.000sec (0.000sec, 0.000sec) (0.000sec/0.000sec/0) 497B 500 "OPTIONS /_matrix/media/v1/upload?filename=cat_confused.gif HTTP/1.1" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Ge
```
|
0.0
|
f8b52eb8c5fc4c723fad49df7a5339c1239b34be
|
[
"tests/util/test_logcontext.py::LoggingContextTestCase::test_run_in_background_with_coroutine",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_run_in_background_with_nonblocking_coroutine"
] |
[
"tests/util/test_logcontext.py::LoggingContextTestCase::test_make_deferred_yieldable",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_make_deferred_yieldable_on_non_deferred",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_make_deferred_yieldable_with_chained_deferreds",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_nested_logging_context",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_run_in_background_with_blocking_fn",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_run_in_background_with_chained_deferred",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_run_in_background_with_non_blocking_fn",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_sleep",
"tests/util/test_logcontext.py::LoggingContextTestCase::test_with_context"
] |
{
"failed_lite_validators": [
"has_media",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-02 12:52:19+00:00
|
apache-2.0
| 3,803 |
|
matrix-org__synapse-6888
|
diff --git a/changelog.d/6888.feature b/changelog.d/6888.feature
new file mode 100644
index 000000000..1b7ac0c82
--- /dev/null
+++ b/changelog.d/6888.feature
@@ -0,0 +1,1 @@
+The result of a user directory search can now be filtered via the spam checker.
diff --git a/changelog.d/6905.doc b/changelog.d/6905.doc
index ca10b3830..be0e698af 100644
--- a/changelog.d/6905.doc
+++ b/changelog.d/6905.doc
@@ -1,1 +1,1 @@
-Mention in `ACME.md` that ACMEv1 is deprecated and explain what it means for Synapse admins.
+Update Synapse's documentation to warn about the deprecation of ACME v1.
diff --git a/docs/spam_checker.md b/docs/spam_checker.md
index 97ff17f95..5b5f5000b 100644
--- a/docs/spam_checker.md
+++ b/docs/spam_checker.md
@@ -54,6 +54,9 @@ class ExampleSpamChecker:
def user_may_publish_room(self, userid, room_id):
return True # allow publishing of all rooms
+
+ def check_username_for_spam(self, user_profile):
+ return False # allow all usernames
```
## Configuration
diff --git a/synapse/events/spamcheck.py b/synapse/events/spamcheck.py
index 5a907718d..0a13fca9a 100644
--- a/synapse/events/spamcheck.py
+++ b/synapse/events/spamcheck.py
@@ -15,6 +15,7 @@
# limitations under the License.
import inspect
+from typing import Dict
from synapse.spam_checker_api import SpamCheckerApi
@@ -125,3 +126,29 @@ class SpamChecker(object):
return True
return self.spam_checker.user_may_publish_room(userid, room_id)
+
+ def check_username_for_spam(self, user_profile: Dict[str, str]) -> bool:
+ """Checks if a user ID or display name are considered "spammy" by this server.
+
+ If the server considers a username spammy, then it will not be included in
+ user directory results.
+
+ Args:
+ user_profile: The user information to check, it contains the keys:
+ * user_id
+ * display_name
+ * avatar_url
+
+ Returns:
+ True if the user is spammy.
+ """
+ if self.spam_checker is None:
+ return False
+
+ # For backwards compatibility, if the method does not exist on the spam checker, fallback to not interfering.
+ checker = getattr(self.spam_checker, "check_username_for_spam", None)
+ if not checker:
+ return False
+ # Make a copy of the user profile object to ensure the spam checker
+ # cannot modify it.
+ return checker(user_profile.copy())
diff --git a/synapse/handlers/user_directory.py b/synapse/handlers/user_directory.py
index 81aa58dc8..722760c59 100644
--- a/synapse/handlers/user_directory.py
+++ b/synapse/handlers/user_directory.py
@@ -52,6 +52,7 @@ class UserDirectoryHandler(StateDeltasHandler):
self.is_mine_id = hs.is_mine_id
self.update_user_directory = hs.config.update_user_directory
self.search_all_users = hs.config.user_directory_search_all_users
+ self.spam_checker = hs.get_spam_checker()
# The current position in the current_state_delta stream
self.pos = None
@@ -65,7 +66,7 @@ class UserDirectoryHandler(StateDeltasHandler):
# we start populating the user directory
self.clock.call_later(0, self.notify_new_event)
- def search_users(self, user_id, search_term, limit):
+ async def search_users(self, user_id, search_term, limit):
"""Searches for users in directory
Returns:
@@ -82,7 +83,16 @@ class UserDirectoryHandler(StateDeltasHandler):
]
}
"""
- return self.store.search_user_dir(user_id, search_term, limit)
+ results = await self.store.search_user_dir(user_id, search_term, limit)
+
+ # Remove any spammy users from the results.
+ results["results"] = [
+ user
+ for user in results["results"]
+ if not self.spam_checker.check_username_for_spam(user)
+ ]
+
+ return results
def notify_new_event(self):
"""Called when there may be more deltas to process
|
matrix-org/synapse
|
361de49c90fd1f35adc4a6bca8206e50e7f15454
|
diff --git a/tests/handlers/test_user_directory.py b/tests/handlers/test_user_directory.py
index 26071059d..0a4765fff 100644
--- a/tests/handlers/test_user_directory.py
+++ b/tests/handlers/test_user_directory.py
@@ -147,6 +147,98 @@ class UserDirectoryTestCase(unittest.HomeserverTestCase):
s = self.get_success(self.handler.search_users(u1, "user3", 10))
self.assertEqual(len(s["results"]), 0)
+ def test_spam_checker(self):
+ """
+ A user which fails to the spam checks will not appear in search results.
+ """
+ u1 = self.register_user("user1", "pass")
+ u1_token = self.login(u1, "pass")
+ u2 = self.register_user("user2", "pass")
+ u2_token = self.login(u2, "pass")
+
+ # We do not add users to the directory until they join a room.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 0)
+
+ room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
+ self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
+ self.helper.join(room, user=u2, tok=u2_token)
+
+ # Check we have populated the database correctly.
+ shares_private = self.get_users_who_share_private_rooms()
+ public_users = self.get_users_in_public_rooms()
+
+ self.assertEqual(
+ self._compress_shared(shares_private), set([(u1, u2, room), (u2, u1, room)])
+ )
+ self.assertEqual(public_users, [])
+
+ # We get one search result when searching for user2 by user1.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 1)
+
+ # Configure a spam checker that does not filter any users.
+ spam_checker = self.hs.get_spam_checker()
+
+ class AllowAll(object):
+ def check_username_for_spam(self, user_profile):
+ # Allow all users.
+ return False
+
+ spam_checker.spam_checker = AllowAll()
+
+ # The results do not change:
+ # We get one search result when searching for user2 by user1.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 1)
+
+ # Configure a spam checker that filters all users.
+ class BlockAll(object):
+ def check_username_for_spam(self, user_profile):
+ # All users are spammy.
+ return True
+
+ spam_checker.spam_checker = BlockAll()
+
+ # User1 now gets no search results for any of the other users.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 0)
+
+ def test_legacy_spam_checker(self):
+ """
+ A spam checker without the expected method should be ignored.
+ """
+ u1 = self.register_user("user1", "pass")
+ u1_token = self.login(u1, "pass")
+ u2 = self.register_user("user2", "pass")
+ u2_token = self.login(u2, "pass")
+
+ # We do not add users to the directory until they join a room.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 0)
+
+ room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
+ self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
+ self.helper.join(room, user=u2, tok=u2_token)
+
+ # Check we have populated the database correctly.
+ shares_private = self.get_users_who_share_private_rooms()
+ public_users = self.get_users_in_public_rooms()
+
+ self.assertEqual(
+ self._compress_shared(shares_private), set([(u1, u2, room), (u2, u1, room)])
+ )
+ self.assertEqual(public_users, [])
+
+ # Configure a spam checker.
+ spam_checker = self.hs.get_spam_checker()
+ # The spam checker doesn't need any methods, so create a bare object.
+ spam_checker.spam_checker = object()
+
+ # We get one search result when searching for user2 by user1.
+ s = self.get_success(self.handler.search_users(u1, "user2", 10))
+ self.assertEqual(len(s["results"]), 1)
+
def _compress_shared(self, shared):
"""
Compress a list of users who share rooms dicts to a list of tuples.
|
Homeserver configuration options to tweak user directory behaviour
I'd like an option, perhaps in homeserver.yaml, to provide a list of regex patterns for the homeserver to exclude from user directory search results.
|
0.0
|
361de49c90fd1f35adc4a6bca8206e50e7f15454
|
[
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_spam_checker"
] |
[
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_handle_local_profile_change_with_support_user",
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_initial",
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_initial_share_all_users",
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_legacy_spam_checker",
"tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_private_room",
"tests/handlers/test_user_directory.py::TestUserDirSearchDisabled::test_disabling_room_list"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-11 15:00:46+00:00
|
apache-2.0
| 3,804 |
|
matrix-org__synapse-7045
|
diff --git a/changelog.d/6309.misc b/changelog.d/6309.misc
new file mode 100644
index 000000000..1aa729461
--- /dev/null
+++ b/changelog.d/6309.misc
@@ -0,0 +1,1 @@
+Add type hints to `logging/context.py`.
diff --git a/changelog.d/7030.feature b/changelog.d/7030.feature
new file mode 100644
index 000000000..fcfdb8d8a
--- /dev/null
+++ b/changelog.d/7030.feature
@@ -0,0 +1,1 @@
+Break down monthly active users by `appservice_id` and emit via Prometheus.
diff --git a/changelog.d/7045.misc b/changelog.d/7045.misc
new file mode 100644
index 000000000..74c1abea5
--- /dev/null
+++ b/changelog.d/7045.misc
@@ -0,0 +1,1 @@
+Add a type check to `is_verified` when processing room keys.
diff --git a/synapse/app/homeserver.py b/synapse/app/homeserver.py
index c2a334a2b..e0fdddfdc 100644
--- a/synapse/app/homeserver.py
+++ b/synapse/app/homeserver.py
@@ -298,6 +298,11 @@ class SynapseHomeServer(HomeServer):
# Gauges to expose monthly active user control metrics
current_mau_gauge = Gauge("synapse_admin_mau:current", "Current MAU")
+current_mau_by_service_gauge = Gauge(
+ "synapse_admin_mau_current_mau_by_service",
+ "Current MAU by service",
+ ["app_service"],
+)
max_mau_gauge = Gauge("synapse_admin_mau:max", "MAU Limit")
registered_reserved_users_mau_gauge = Gauge(
"synapse_admin_mau:registered_reserved_users",
@@ -585,12 +590,20 @@ def run(hs):
@defer.inlineCallbacks
def generate_monthly_active_users():
current_mau_count = 0
+ current_mau_count_by_service = {}
reserved_users = ()
store = hs.get_datastore()
if hs.config.limit_usage_by_mau or hs.config.mau_stats_only:
current_mau_count = yield store.get_monthly_active_count()
+ current_mau_count_by_service = (
+ yield store.get_monthly_active_count_by_service()
+ )
reserved_users = yield store.get_registered_reserved_users()
current_mau_gauge.set(float(current_mau_count))
+
+ for app_service, count in current_mau_count_by_service.items():
+ current_mau_by_service_gauge.labels(app_service).set(float(count))
+
registered_reserved_users_mau_gauge.set(float(len(reserved_users)))
max_mau_gauge.set(float(hs.config.max_mau_value))
diff --git a/synapse/logging/context.py b/synapse/logging/context.py
index 1b940842f..1eccc0e83 100644
--- a/synapse/logging/context.py
+++ b/synapse/logging/context.py
@@ -27,10 +27,15 @@ import inspect
import logging
import threading
import types
-from typing import Any, List
+from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union
+
+from typing_extensions import Literal
from twisted.internet import defer, threads
+if TYPE_CHECKING:
+ from synapse.logging.scopecontextmanager import _LogContextScope
+
logger = logging.getLogger(__name__)
try:
@@ -91,7 +96,7 @@ class ContextResourceUsage(object):
"evt_db_fetch_count",
]
- def __init__(self, copy_from=None):
+ def __init__(self, copy_from: "Optional[ContextResourceUsage]" = None) -> None:
"""Create a new ContextResourceUsage
Args:
@@ -101,27 +106,28 @@ class ContextResourceUsage(object):
if copy_from is None:
self.reset()
else:
- self.ru_utime = copy_from.ru_utime
- self.ru_stime = copy_from.ru_stime
- self.db_txn_count = copy_from.db_txn_count
+ # FIXME: mypy can't infer the types set via reset() above, so specify explicitly for now
+ self.ru_utime = copy_from.ru_utime # type: float
+ self.ru_stime = copy_from.ru_stime # type: float
+ self.db_txn_count = copy_from.db_txn_count # type: int
- self.db_txn_duration_sec = copy_from.db_txn_duration_sec
- self.db_sched_duration_sec = copy_from.db_sched_duration_sec
- self.evt_db_fetch_count = copy_from.evt_db_fetch_count
+ self.db_txn_duration_sec = copy_from.db_txn_duration_sec # type: float
+ self.db_sched_duration_sec = copy_from.db_sched_duration_sec # type: float
+ self.evt_db_fetch_count = copy_from.evt_db_fetch_count # type: int
- def copy(self):
+ def copy(self) -> "ContextResourceUsage":
return ContextResourceUsage(copy_from=self)
- def reset(self):
+ def reset(self) -> None:
self.ru_stime = 0.0
self.ru_utime = 0.0
self.db_txn_count = 0
- self.db_txn_duration_sec = 0
- self.db_sched_duration_sec = 0
+ self.db_txn_duration_sec = 0.0
+ self.db_sched_duration_sec = 0.0
self.evt_db_fetch_count = 0
- def __repr__(self):
+ def __repr__(self) -> str:
return (
"<ContextResourceUsage ru_stime='%r', ru_utime='%r', "
"db_txn_count='%r', db_txn_duration_sec='%r', "
@@ -135,7 +141,7 @@ class ContextResourceUsage(object):
self.evt_db_fetch_count,
)
- def __iadd__(self, other):
+ def __iadd__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
"""Add another ContextResourceUsage's stats to this one's.
Args:
@@ -149,7 +155,7 @@ class ContextResourceUsage(object):
self.evt_db_fetch_count += other.evt_db_fetch_count
return self
- def __isub__(self, other):
+ def __isub__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
self.ru_utime -= other.ru_utime
self.ru_stime -= other.ru_stime
self.db_txn_count -= other.db_txn_count
@@ -158,17 +164,20 @@ class ContextResourceUsage(object):
self.evt_db_fetch_count -= other.evt_db_fetch_count
return self
- def __add__(self, other):
+ def __add__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
res = ContextResourceUsage(copy_from=self)
res += other
return res
- def __sub__(self, other):
+ def __sub__(self, other: "ContextResourceUsage") -> "ContextResourceUsage":
res = ContextResourceUsage(copy_from=self)
res -= other
return res
+LoggingContextOrSentinel = Union["LoggingContext", "LoggingContext.Sentinel"]
+
+
class LoggingContext(object):
"""Additional context for log formatting. Contexts are scoped within a
"with" block.
@@ -201,7 +210,14 @@ class LoggingContext(object):
class Sentinel(object):
"""Sentinel to represent the root context"""
- __slots__ = [] # type: List[Any]
+ __slots__ = ["previous_context", "alive", "request", "scope"]
+
+ def __init__(self) -> None:
+ # Minimal set for compatibility with LoggingContext
+ self.previous_context = None
+ self.alive = None
+ self.request = None
+ self.scope = None
def __str__(self):
return "sentinel"
@@ -235,7 +251,7 @@ class LoggingContext(object):
sentinel = Sentinel()
- def __init__(self, name=None, parent_context=None, request=None):
+ def __init__(self, name=None, parent_context=None, request=None) -> None:
self.previous_context = LoggingContext.current_context()
self.name = name
@@ -250,7 +266,7 @@ class LoggingContext(object):
self.request = None
self.tag = ""
self.alive = True
- self.scope = None
+ self.scope = None # type: Optional[_LogContextScope]
self.parent_context = parent_context
@@ -261,13 +277,13 @@ class LoggingContext(object):
# the request param overrides the request from the parent context
self.request = request
- def __str__(self):
+ def __str__(self) -> str:
if self.request:
return str(self.request)
return "%s@%x" % (self.name, id(self))
@classmethod
- def current_context(cls):
+ def current_context(cls) -> LoggingContextOrSentinel:
"""Get the current logging context from thread local storage
Returns:
@@ -276,7 +292,9 @@ class LoggingContext(object):
return getattr(cls.thread_local, "current_context", cls.sentinel)
@classmethod
- def set_current_context(cls, context):
+ def set_current_context(
+ cls, context: LoggingContextOrSentinel
+ ) -> LoggingContextOrSentinel:
"""Set the current logging context in thread local storage
Args:
context(LoggingContext): The context to activate.
@@ -291,7 +309,7 @@ class LoggingContext(object):
context.start()
return current
- def __enter__(self):
+ def __enter__(self) -> "LoggingContext":
"""Enters this logging context into thread local storage"""
old_context = self.set_current_context(self)
if self.previous_context != old_context:
@@ -304,7 +322,7 @@ class LoggingContext(object):
return self
- def __exit__(self, type, value, traceback):
+ def __exit__(self, type, value, traceback) -> None:
"""Restore the logging context in thread local storage to the state it
was before this context was entered.
Returns:
@@ -318,7 +336,6 @@ class LoggingContext(object):
logger.warning(
"Expected logging context %s but found %s", self, current
)
- self.previous_context = None
self.alive = False
# if we have a parent, pass our CPU usage stats on
@@ -330,7 +347,7 @@ class LoggingContext(object):
# reset them in case we get entered again
self._resource_usage.reset()
- def copy_to(self, record):
+ def copy_to(self, record) -> None:
"""Copy logging fields from this context to a log record or
another LoggingContext
"""
@@ -341,14 +358,14 @@ class LoggingContext(object):
# we also track the current scope:
record.scope = self.scope
- def copy_to_twisted_log_entry(self, record):
+ def copy_to_twisted_log_entry(self, record) -> None:
"""
Copy logging fields from this context to a Twisted log record.
"""
record["request"] = self.request
record["scope"] = self.scope
- def start(self):
+ def start(self) -> None:
if get_thread_id() != self.main_thread:
logger.warning("Started logcontext %s on different thread", self)
return
@@ -358,7 +375,7 @@ class LoggingContext(object):
if not self.usage_start:
self.usage_start = get_thread_resource_usage()
- def stop(self):
+ def stop(self) -> None:
if get_thread_id() != self.main_thread:
logger.warning("Stopped logcontext %s on different thread", self)
return
@@ -378,7 +395,7 @@ class LoggingContext(object):
self.usage_start = None
- def get_resource_usage(self):
+ def get_resource_usage(self) -> ContextResourceUsage:
"""Get resources used by this logcontext so far.
Returns:
@@ -398,11 +415,13 @@ class LoggingContext(object):
return res
- def _get_cputime(self):
+ def _get_cputime(self) -> Tuple[float, float]:
"""Get the cpu usage time so far
Returns: Tuple[float, float]: seconds in user mode, seconds in system mode
"""
+ assert self.usage_start is not None
+
current = get_thread_resource_usage()
# Indicate to mypy that we know that self.usage_start is None.
@@ -430,13 +449,13 @@ class LoggingContext(object):
return utime_delta, stime_delta
- def add_database_transaction(self, duration_sec):
+ def add_database_transaction(self, duration_sec: float) -> None:
if duration_sec < 0:
raise ValueError("DB txn time can only be non-negative")
self._resource_usage.db_txn_count += 1
self._resource_usage.db_txn_duration_sec += duration_sec
- def add_database_scheduled(self, sched_sec):
+ def add_database_scheduled(self, sched_sec: float) -> None:
"""Record a use of the database pool
Args:
@@ -447,7 +466,7 @@ class LoggingContext(object):
raise ValueError("DB scheduling time can only be non-negative")
self._resource_usage.db_sched_duration_sec += sched_sec
- def record_event_fetch(self, event_count):
+ def record_event_fetch(self, event_count: int) -> None:
"""Record a number of events being fetched from the db
Args:
@@ -464,10 +483,10 @@ class LoggingContextFilter(logging.Filter):
missing fields
"""
- def __init__(self, **defaults):
+ def __init__(self, **defaults) -> None:
self.defaults = defaults
- def filter(self, record):
+ def filter(self, record) -> Literal[True]:
"""Add each fields from the logging contexts to the record.
Returns:
True to include the record in the log output.
@@ -492,12 +511,13 @@ class PreserveLoggingContext(object):
__slots__ = ["current_context", "new_context", "has_parent"]
- def __init__(self, new_context=None):
+ def __init__(self, new_context: Optional[LoggingContext] = None) -> None:
if new_context is None:
- new_context = LoggingContext.sentinel
- self.new_context = new_context
+ self.new_context = LoggingContext.sentinel # type: LoggingContextOrSentinel
+ else:
+ self.new_context = new_context
- def __enter__(self):
+ def __enter__(self) -> None:
"""Captures the current logging context"""
self.current_context = LoggingContext.set_current_context(self.new_context)
@@ -506,7 +526,7 @@ class PreserveLoggingContext(object):
if not self.current_context.alive:
logger.debug("Entering dead context: %s", self.current_context)
- def __exit__(self, type, value, traceback):
+ def __exit__(self, type, value, traceback) -> None:
"""Restores the current logging context"""
context = LoggingContext.set_current_context(self.current_context)
@@ -525,7 +545,9 @@ class PreserveLoggingContext(object):
logger.debug("Restoring dead context: %s", self.current_context)
-def nested_logging_context(suffix, parent_context=None):
+def nested_logging_context(
+ suffix: str, parent_context: Optional[LoggingContext] = None
+) -> LoggingContext:
"""Creates a new logging context as a child of another.
The nested logging context will have a 'request' made up of the parent context's
@@ -546,10 +568,12 @@ def nested_logging_context(suffix, parent_context=None):
Returns:
LoggingContext: new logging context.
"""
- if parent_context is None:
- parent_context = LoggingContext.current_context()
+ if parent_context is not None:
+ context = parent_context # type: LoggingContextOrSentinel
+ else:
+ context = LoggingContext.current_context()
return LoggingContext(
- parent_context=parent_context, request=parent_context.request + "-" + suffix
+ parent_context=context, request=str(context.request) + "-" + suffix
)
@@ -654,7 +678,10 @@ def make_deferred_yieldable(deferred):
return deferred
-def _set_context_cb(result, context):
+ResultT = TypeVar("ResultT")
+
+
+def _set_context_cb(result: ResultT, context: LoggingContext) -> ResultT:
"""A callback function which just sets the logging context"""
LoggingContext.set_current_context(context)
return result
diff --git a/synapse/storage/data_stores/main/monthly_active_users.py b/synapse/storage/data_stores/main/monthly_active_users.py
index 1507a14e0..925bc5691 100644
--- a/synapse/storage/data_stores/main/monthly_active_users.py
+++ b/synapse/storage/data_stores/main/monthly_active_users.py
@@ -43,13 +43,40 @@ class MonthlyActiveUsersWorkerStore(SQLBaseStore):
def _count_users(txn):
sql = "SELECT COALESCE(count(*), 0) FROM monthly_active_users"
-
txn.execute(sql)
(count,) = txn.fetchone()
return count
return self.db.runInteraction("count_users", _count_users)
+ @cached(num_args=0)
+ def get_monthly_active_count_by_service(self):
+ """Generates current count of monthly active users broken down by service.
+ A service is typically an appservice but also includes native matrix users.
+ Since the `monthly_active_users` table is populated from the `user_ips` table
+ `config.track_appservice_user_ips` must be set to `true` for this
+ method to return anything other than native matrix users.
+
+ Returns:
+ Deferred[dict]: dict that includes a mapping between app_service_id
+ and the number of occurrences.
+
+ """
+
+ def _count_users_by_service(txn):
+ sql = """
+ SELECT COALESCE(appservice_id, 'native'), COALESCE(count(*), 0)
+ FROM monthly_active_users
+ LEFT JOIN users ON monthly_active_users.user_id=users.name
+ GROUP BY appservice_id;
+ """
+
+ txn.execute(sql)
+ result = txn.fetchall()
+ return dict(result)
+
+ return self.db.runInteraction("count_users_by_service", _count_users_by_service)
+
@defer.inlineCallbacks
def get_registered_reserved_users(self):
"""Of the reserved threepids defined in config, which are associated
@@ -291,6 +318,9 @@ class MonthlyActiveUsersStore(MonthlyActiveUsersWorkerStore):
)
self._invalidate_cache_and_stream(txn, self.get_monthly_active_count, ())
+ self._invalidate_cache_and_stream(
+ txn, self.get_monthly_active_count_by_service, ()
+ )
self._invalidate_cache_and_stream(
txn, self.user_last_seen_monthly_active, (user_id,)
)
|
matrix-org/synapse
|
87972f07e5da0760ca5e11e62b1bda8c49f6f606
|
diff --git a/synapse/handlers/e2e_room_keys.py b/synapse/handlers/e2e_room_keys.py
index f1b4424a0..9abaf13b8 100644
--- a/synapse/handlers/e2e_room_keys.py
+++ b/synapse/handlers/e2e_room_keys.py
@@ -207,6 +207,13 @@ class E2eRoomKeysHandler(object):
changed = False # if anything has changed, we need to update the etag
for room_id, room in iteritems(room_keys["rooms"]):
for session_id, room_key in iteritems(room["sessions"]):
+ if not isinstance(room_key["is_verified"], bool):
+ msg = (
+ "is_verified must be a boolean in keys for session %s in"
+ "room %s" % (session_id, room_id)
+ )
+ raise SynapseError(400, msg, Codes.INVALID_PARAM)
+
log_kv(
{
"message": "Trying to upload room key",
diff --git a/tests/storage/test_monthly_active_users.py b/tests/storage/test_monthly_active_users.py
index 3c78faab4..bc53bf095 100644
--- a/tests/storage/test_monthly_active_users.py
+++ b/tests/storage/test_monthly_active_users.py
@@ -303,3 +303,45 @@ class MonthlyActiveUsersTestCase(unittest.HomeserverTestCase):
self.pump()
self.store.upsert_monthly_active_user.assert_not_called()
+
+ def test_get_monthly_active_count_by_service(self):
+ appservice1_user1 = "@appservice1_user1:example.com"
+ appservice1_user2 = "@appservice1_user2:example.com"
+
+ appservice2_user1 = "@appservice2_user1:example.com"
+ native_user1 = "@native_user1:example.com"
+
+ service1 = "service1"
+ service2 = "service2"
+ native = "native"
+
+ self.store.register_user(
+ user_id=appservice1_user1, password_hash=None, appservice_id=service1
+ )
+ self.store.register_user(
+ user_id=appservice1_user2, password_hash=None, appservice_id=service1
+ )
+ self.store.register_user(
+ user_id=appservice2_user1, password_hash=None, appservice_id=service2
+ )
+ self.store.register_user(user_id=native_user1, password_hash=None)
+ self.pump()
+
+ count = self.store.get_monthly_active_count_by_service()
+ self.assertEqual({}, self.get_success(count))
+
+ self.store.upsert_monthly_active_user(native_user1)
+ self.store.upsert_monthly_active_user(appservice1_user1)
+ self.store.upsert_monthly_active_user(appservice1_user2)
+ self.store.upsert_monthly_active_user(appservice2_user1)
+ self.pump()
+
+ count = self.store.get_monthly_active_count()
+ self.assertEqual(4, self.get_success(count))
+
+ count = self.store.get_monthly_active_count_by_service()
+ result = self.get_success(count)
+
+ self.assertEqual(2, result[service1])
+ self.assertEqual(1, result[service2])
+ self.assertEqual(1, result[native])
|
can't adapt type 'dict' when doing something with room keys
```
[homeserver_1] 2020-03-04 17:46:42,842 - synapse.http.server - 110 - ERROR - PUT-58- Failed handle request via 'RoomKeysServlet': <XForwardedForRequest at 0x7fd4f193bd68 method='PUT' uri='/_matrix/client/unstable/room_keys/keys?version=2' clientproto='HTTP/1.0' site=8118>
Traceback (most recent call last):
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/http/server.py", line 78, in wrapped_request_handler
await h(self, request)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/http/server.py", line 331, in _async_render
callback_return = await callback_return
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/rest/client/v2_alpha/room_keys.py", line 134, in on_PUT
ret = await self.e2e_room_keys_handler.upload_room_keys(user_id, version, body)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/internet/defer.py", line 1416, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/failure.py", line 491, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/handlers/e2e_room_keys.py", line 226, in upload_room_keys
user_id, version, room_id, session_id, room_key
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/internet/defer.py", line 1416, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/failure.py", line 491, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/data_stores/main/e2e_room_keys.py", line 55, in update_e2e_room_key
desc="update_e2e_room_key",
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/internet/defer.py", line 1416, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/failure.py", line 491, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 495, in runInteraction
**kwargs
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/internet/defer.py", line 1416, in _inlineCallbacks
result = result.throwExceptionIntoGenerator(g)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/failure.py", line 491, in throwExceptionIntoGenerator
return g.throw(self.type, self.value, self.tb)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 543, in runWithConnection
self._db_pool.runWithConnection(inner_func, *args, **kwargs)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/threadpool.py", line 250, in inContext
result = inContext.theWork()
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/threadpool.py", line 266, in <lambda>
inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/context.py", line 85, in callWithContext
return func(*args,**kw)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/enterprise/adbapi.py", line 306, in _runWithConnection
compat.reraise(excValue, excTraceback)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/python/compat.py", line 464, in reraise
raise exception.with_traceback(traceback)
File "/home/matrix/synapse/lib/python3.6/site-packages/twisted/enterprise/adbapi.py", line 297, in _runWithConnection
result = func(conn, *args, **kw)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 540, in inner_func
return func(conn, *args, **kwargs)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 378, in new_transaction
r = func(cursor, *args, **kwargs)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 1211, in simple_update_one_txn
rowcount = cls.simple_update_txn(txn, table, keyvalues, updatevalues)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 1181, in simple_update_txn
txn.execute(update_sql, list(updatevalues.values()) + list(keyvalues.values()))
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 175, in execute
self._do_execute(self.txn.execute, sql, *args)
File "/home/matrix/synapse/lib/python3.6/site-packages/synapse/storage/database.py", line 201, in _do_execute
return func(sql, *args)
psycopg2.ProgrammingError: can't adapt type 'dict'
[homeserver_1] 2020-03-04 17:46:42,941 - synapse.access.http.8118 - 302 - INFO - PUT-58- 174.3.196.16 - 8118 - {@travis:t2l.io} Processed request: 0.144sec/0.000sec (0.093sec, 0.000sec) (0.002sec/0.047sec/3) 67B 500 "PUT /_matrix/client/unstable/room_keys/keys?version=2 HTTP/1.0" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36" [0 dbevts]
```
Synapse 1.11.1
|
0.0
|
87972f07e5da0760ca5e11e62b1bda8c49f6f606
|
[
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_get_monthly_active_count_by_service"
] |
[
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_can_insert_and_count_mau",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_get_reserved_real_user_account",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_initialise_reserved_users",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_no_users_when_not_tracking",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_populate_monthly_users_is_guest",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_populate_monthly_users_should_not_update",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_populate_monthly_users_should_update",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_reap_monthly_active_users",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_reap_monthly_active_users_reserved_users",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_support_user_not_add_to_mau_limits",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_track_monthly_users_without_cap",
"tests/storage/test_monthly_active_users.py::MonthlyActiveUsersTestCase::test_user_last_seen_monthly_active"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-06 11:06:53+00:00
|
apache-2.0
| 3,805 |
|
matrix-org__synapse-7094
|
diff --git a/changelog.d/7094.misc b/changelog.d/7094.misc
new file mode 100644
index 000000000..aa093ee3c
--- /dev/null
+++ b/changelog.d/7094.misc
@@ -0,0 +1,1 @@
+Improve performance when making HTTPS requests to sygnal, sydent, etc, by sharing the SSL context object between connections.
diff --git a/synapse/crypto/context_factory.py b/synapse/crypto/context_factory.py
index e93f0b370..a5a2a7815 100644
--- a/synapse/crypto/context_factory.py
+++ b/synapse/crypto/context_factory.py
@@ -75,7 +75,7 @@ class ServerContextFactory(ContextFactory):
@implementer(IPolicyForHTTPS)
-class ClientTLSOptionsFactory(object):
+class FederationPolicyForHTTPS(object):
"""Factory for Twisted SSLClientConnectionCreators that are used to make connections
to remote servers for federation.
@@ -103,15 +103,15 @@ class ClientTLSOptionsFactory(object):
# let us do).
minTLS = _TLS_VERSION_MAP[config.federation_client_minimum_tls_version]
- self._verify_ssl = CertificateOptions(
+ _verify_ssl = CertificateOptions(
trustRoot=trust_root, insecurelyLowerMinimumTo=minTLS
)
- self._verify_ssl_context = self._verify_ssl.getContext()
- self._verify_ssl_context.set_info_callback(self._context_info_cb)
+ self._verify_ssl_context = _verify_ssl.getContext()
+ self._verify_ssl_context.set_info_callback(_context_info_cb)
- self._no_verify_ssl = CertificateOptions(insecurelyLowerMinimumTo=minTLS)
- self._no_verify_ssl_context = self._no_verify_ssl.getContext()
- self._no_verify_ssl_context.set_info_callback(self._context_info_cb)
+ _no_verify_ssl = CertificateOptions(insecurelyLowerMinimumTo=minTLS)
+ self._no_verify_ssl_context = _no_verify_ssl.getContext()
+ self._no_verify_ssl_context.set_info_callback(_context_info_cb)
def get_options(self, host: bytes):
@@ -136,23 +136,6 @@ class ClientTLSOptionsFactory(object):
return SSLClientConnectionCreator(host, ssl_context, should_verify)
- @staticmethod
- def _context_info_cb(ssl_connection, where, ret):
- """The 'information callback' for our openssl context object."""
- # we assume that the app_data on the connection object has been set to
- # a TLSMemoryBIOProtocol object. (This is done by SSLClientConnectionCreator)
- tls_protocol = ssl_connection.get_app_data()
- try:
- # ... we further assume that SSLClientConnectionCreator has set the
- # '_synapse_tls_verifier' attribute to a ConnectionVerifier object.
- tls_protocol._synapse_tls_verifier.verify_context_info_cb(
- ssl_connection, where
- )
- except: # noqa: E722, taken from the twisted implementation
- logger.exception("Error during info_callback")
- f = Failure()
- tls_protocol.failVerification(f)
-
def creatorForNetloc(self, hostname, port):
"""Implements the IPolicyForHTTPS interace so that this can be passed
directly to agents.
@@ -160,6 +143,43 @@ class ClientTLSOptionsFactory(object):
return self.get_options(hostname)
+@implementer(IPolicyForHTTPS)
+class RegularPolicyForHTTPS(object):
+ """Factory for Twisted SSLClientConnectionCreators that are used to make connections
+ to remote servers, for other than federation.
+
+ Always uses the same OpenSSL context object, which uses the default OpenSSL CA
+ trust root.
+ """
+
+ def __init__(self):
+ trust_root = platformTrust()
+ self._ssl_context = CertificateOptions(trustRoot=trust_root).getContext()
+ self._ssl_context.set_info_callback(_context_info_cb)
+
+ def creatorForNetloc(self, hostname, port):
+ return SSLClientConnectionCreator(hostname, self._ssl_context, True)
+
+
+def _context_info_cb(ssl_connection, where, ret):
+ """The 'information callback' for our openssl context objects.
+
+ Note: Once this is set as the info callback on a Context object, the Context should
+ only be used with the SSLClientConnectionCreator.
+ """
+ # we assume that the app_data on the connection object has been set to
+ # a TLSMemoryBIOProtocol object. (This is done by SSLClientConnectionCreator)
+ tls_protocol = ssl_connection.get_app_data()
+ try:
+ # ... we further assume that SSLClientConnectionCreator has set the
+ # '_synapse_tls_verifier' attribute to a ConnectionVerifier object.
+ tls_protocol._synapse_tls_verifier.verify_context_info_cb(ssl_connection, where)
+ except: # noqa: E722, taken from the twisted implementation
+ logger.exception("Error during info_callback")
+ f = Failure()
+ tls_protocol.failVerification(f)
+
+
@implementer(IOpenSSLClientConnectionCreator)
class SSLClientConnectionCreator(object):
"""Creates openssl connection objects for client connections.
diff --git a/synapse/http/client.py b/synapse/http/client.py
index d4c285445..379754582 100644
--- a/synapse/http/client.py
+++ b/synapse/http/client.py
@@ -244,9 +244,6 @@ class SimpleHttpClient(object):
pool.maxPersistentPerHost = max((100 * CACHE_SIZE_FACTOR, 5))
pool.cachedConnectionTimeout = 2 * 60
- # The default context factory in Twisted 14.0.0 (which we require) is
- # BrowserLikePolicyForHTTPS which will do regular cert validation
- # 'like a browser'
self.agent = ProxyAgent(
self.reactor,
connectTimeout=15,
diff --git a/synapse/http/federation/matrix_federation_agent.py b/synapse/http/federation/matrix_federation_agent.py
index 647d26dc5..f5f917f5a 100644
--- a/synapse/http/federation/matrix_federation_agent.py
+++ b/synapse/http/federation/matrix_federation_agent.py
@@ -45,7 +45,7 @@ class MatrixFederationAgent(object):
Args:
reactor (IReactor): twisted reactor to use for underlying requests
- tls_client_options_factory (ClientTLSOptionsFactory|None):
+ tls_client_options_factory (FederationPolicyForHTTPS|None):
factory to use for fetching client tls options, or none to disable TLS.
_srv_resolver (SrvResolver|None):
diff --git a/synapse/server.py b/synapse/server.py
index fd2f69e92..1b980371d 100644
--- a/synapse/server.py
+++ b/synapse/server.py
@@ -26,7 +26,6 @@ import logging
import os
from twisted.mail.smtp import sendmail
-from twisted.web.client import BrowserLikePolicyForHTTPS
from synapse.api.auth import Auth
from synapse.api.filtering import Filtering
@@ -35,6 +34,7 @@ from synapse.appservice.api import ApplicationServiceApi
from synapse.appservice.scheduler import ApplicationServiceScheduler
from synapse.config.homeserver import HomeServerConfig
from synapse.crypto import context_factory
+from synapse.crypto.context_factory import RegularPolicyForHTTPS
from synapse.crypto.keyring import Keyring
from synapse.events.builder import EventBuilderFactory
from synapse.events.spamcheck import SpamChecker
@@ -310,7 +310,7 @@ class HomeServer(object):
return (
InsecureInterceptableContextFactory()
if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
- else BrowserLikePolicyForHTTPS()
+ else RegularPolicyForHTTPS()
)
def build_simple_http_client(self):
@@ -420,7 +420,7 @@ class HomeServer(object):
return PusherPool(self)
def build_http_client(self):
- tls_client_options_factory = context_factory.ClientTLSOptionsFactory(
+ tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory)
|
matrix-org/synapse
|
5e477c1debfd932ced56ec755204d6ead4ce8ec8
|
diff --git a/tests/config/test_tls.py b/tests/config/test_tls.py
index 1be6ff563..ec32d4b1c 100644
--- a/tests/config/test_tls.py
+++ b/tests/config/test_tls.py
@@ -23,7 +23,7 @@ from OpenSSL import SSL
from synapse.config._base import Config, RootConfig
from synapse.config.tls import ConfigError, TlsConfig
-from synapse.crypto.context_factory import ClientTLSOptionsFactory
+from synapse.crypto.context_factory import FederationPolicyForHTTPS
from tests.unittest import TestCase
@@ -180,12 +180,13 @@ s4niecZKPBizL6aucT59CsunNmmb5Glq8rlAcU+1ZTZZzGYqVYhF6axB9Qg=
t = TestConfig()
t.read_config(config, config_dir_path="", data_dir_path="")
- cf = ClientTLSOptionsFactory(t)
+ cf = FederationPolicyForHTTPS(t)
+ options = _get_ssl_context_options(cf._verify_ssl_context)
# The context has had NO_TLSv1_1 and NO_TLSv1_0 set, but not NO_TLSv1_2
- self.assertNotEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1, 0)
- self.assertNotEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1_1, 0)
- self.assertEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1_2, 0)
+ self.assertNotEqual(options & SSL.OP_NO_TLSv1, 0)
+ self.assertNotEqual(options & SSL.OP_NO_TLSv1_1, 0)
+ self.assertEqual(options & SSL.OP_NO_TLSv1_2, 0)
def test_tls_client_minimum_set_passed_through_1_0(self):
"""
@@ -195,12 +196,13 @@ s4niecZKPBizL6aucT59CsunNmmb5Glq8rlAcU+1ZTZZzGYqVYhF6axB9Qg=
t = TestConfig()
t.read_config(config, config_dir_path="", data_dir_path="")
- cf = ClientTLSOptionsFactory(t)
+ cf = FederationPolicyForHTTPS(t)
+ options = _get_ssl_context_options(cf._verify_ssl_context)
# The context has not had any of the NO_TLS set.
- self.assertEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1, 0)
- self.assertEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1_1, 0)
- self.assertEqual(cf._verify_ssl._options & SSL.OP_NO_TLSv1_2, 0)
+ self.assertEqual(options & SSL.OP_NO_TLSv1, 0)
+ self.assertEqual(options & SSL.OP_NO_TLSv1_1, 0)
+ self.assertEqual(options & SSL.OP_NO_TLSv1_2, 0)
def test_acme_disabled_in_generated_config_no_acme_domain_provied(self):
"""
@@ -273,7 +275,7 @@ s4niecZKPBizL6aucT59CsunNmmb5Glq8rlAcU+1ZTZZzGYqVYhF6axB9Qg=
t = TestConfig()
t.read_config(config, config_dir_path="", data_dir_path="")
- cf = ClientTLSOptionsFactory(t)
+ cf = FederationPolicyForHTTPS(t)
# Not in the whitelist
opts = cf.get_options(b"notexample.com")
@@ -282,3 +284,10 @@ s4niecZKPBizL6aucT59CsunNmmb5Glq8rlAcU+1ZTZZzGYqVYhF6axB9Qg=
# Caught by the wildcard
opts = cf.get_options(idna.encode("テスト.ドメイン.テスト"))
self.assertFalse(opts._verifier._verify_certs)
+
+
+def _get_ssl_context_options(ssl_context: SSL.Context) -> int:
+ """get the options bits from an openssl context object"""
+ # the OpenSSL.SSL.Context wrapper doesn't expose get_options, so we have to
+ # use the low-level interface
+ return SSL._lib.SSL_CTX_get_options(ssl_context._context)
diff --git a/tests/http/federation/test_matrix_federation_agent.py b/tests/http/federation/test_matrix_federation_agent.py
index cfcd98ff7..fdc1d918f 100644
--- a/tests/http/federation/test_matrix_federation_agent.py
+++ b/tests/http/federation/test_matrix_federation_agent.py
@@ -31,7 +31,7 @@ from twisted.web.http_headers import Headers
from twisted.web.iweb import IPolicyForHTTPS
from synapse.config.homeserver import HomeServerConfig
-from synapse.crypto.context_factory import ClientTLSOptionsFactory
+from synapse.crypto.context_factory import FederationPolicyForHTTPS
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent
from synapse.http.federation.srv_resolver import Server
from synapse.http.federation.well_known_resolver import (
@@ -79,7 +79,7 @@ class MatrixFederationAgentTests(unittest.TestCase):
self._config = config = HomeServerConfig()
config.parse_config_dict(config_dict, "", "")
- self.tls_factory = ClientTLSOptionsFactory(config)
+ self.tls_factory = FederationPolicyForHTTPS(config)
self.well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds)
self.had_well_known_cache = TTLCache("test_cache", timer=self.reactor.seconds)
@@ -715,7 +715,7 @@ class MatrixFederationAgentTests(unittest.TestCase):
config = default_config("test", parse=True)
# Build a new agent and WellKnownResolver with a different tls factory
- tls_factory = ClientTLSOptionsFactory(config)
+ tls_factory = FederationPolicyForHTTPS(config)
agent = MatrixFederationAgent(
reactor=self.reactor,
tls_client_options_factory=tls_factory,
|
OpenSSL contexts are not shared between non-federation connections
... ie, each connection to a sydent/sygnal/etc gets its own OpenSSL context
|
0.0
|
5e477c1debfd932ced56ec755204d6ead4ce8ec8
|
[
"tests/config/test_tls.py::TLSConfigTests::test_acme_disabled_in_generated_config_no_acme_domain_provied",
"tests/config/test_tls.py::TLSConfigTests::test_acme_enabled_in_generated_config_domain_provided",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_1_point_3_exists",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_1_point_3_missing",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_default",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_set",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_set_passed_through_1_0",
"tests/config/test_tls.py::TLSConfigTests::test_tls_client_minimum_set_passed_through_1_2",
"tests/config/test_tls.py::TLSConfigTests::test_warn_self_signed",
"tests/config/test_tls.py::TLSConfigTests::test_whitelist_idna_failure",
"tests/config/test_tls.py::TLSConfigTests::test_whitelist_idna_result",
"tests/http/federation/test_matrix_federation_agent.py::TestCachePeriodFromHeaders::test_cache_control",
"tests/http/federation/test_matrix_federation_agent.py::TestCachePeriodFromHeaders::test_expires"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-17 16:19:52+00:00
|
apache-2.0
| 3,806 |
|
matrix-org__synapse-8591
|
diff --git a/changelog.d/8569.misc b/changelog.d/8569.misc
new file mode 100644
index 000000000..3b6e0625e
--- /dev/null
+++ b/changelog.d/8569.misc
@@ -0,0 +1,1 @@
+Fix mypy not properly checking across the codebase, additionally, fix a typing assertion error in `handlers/auth.py`.
\ No newline at end of file
diff --git a/changelog.d/8589.removal b/changelog.d/8589.removal
new file mode 100644
index 000000000..b80f29d6b
--- /dev/null
+++ b/changelog.d/8589.removal
@@ -0,0 +1,1 @@
+Drop unused `device_max_stream_id` table.
diff --git a/changelog.d/8591.misc b/changelog.d/8591.misc
new file mode 100644
index 000000000..8f16bc3e7
--- /dev/null
+++ b/changelog.d/8591.misc
@@ -0,0 +1,1 @@
+ Move metric registration code down into `LruCache`.
diff --git a/synapse/handlers/auth.py b/synapse/handlers/auth.py
index 1d1ddc224..8619fbb98 100644
--- a/synapse/handlers/auth.py
+++ b/synapse/handlers/auth.py
@@ -1122,20 +1122,22 @@ class AuthHandler(BaseHandler):
Whether self.hash(password) == stored_hash.
"""
- def _do_validate_hash():
+ def _do_validate_hash(checked_hash: bytes):
# Normalise the Unicode in the password
pw = unicodedata.normalize("NFKC", password)
return bcrypt.checkpw(
pw.encode("utf8") + self.hs.config.password_pepper.encode("utf8"),
- stored_hash,
+ checked_hash,
)
if stored_hash:
if not isinstance(stored_hash, bytes):
stored_hash = stored_hash.encode("ascii")
- return await defer_to_thread(self.hs.get_reactor(), _do_validate_hash)
+ return await defer_to_thread(
+ self.hs.get_reactor(), _do_validate_hash, stored_hash
+ )
else:
return False
diff --git a/synapse/storage/databases/main/schema/delta/58/21drop_device_max_stream_id.sql b/synapse/storage/databases/main/schema/delta/58/21drop_device_max_stream_id.sql
new file mode 100644
index 000000000..01ea6eddc
--- /dev/null
+++ b/synapse/storage/databases/main/schema/delta/58/21drop_device_max_stream_id.sql
@@ -0,0 +1,1 @@
+DROP TABLE device_max_stream_id;
diff --git a/synapse/util/caches/lrucache.py b/synapse/util/caches/lrucache.py
index 3b471d8fd..60bb6ff64 100644
--- a/synapse/util/caches/lrucache.py
+++ b/synapse/util/caches/lrucache.py
@@ -124,6 +124,10 @@ class LruCache(Generic[KT, VT]):
else:
self.max_size = int(max_size)
+ # register_cache might call our "set_cache_factor" callback; there's nothing to
+ # do yet when we get resized.
+ self._on_resize = None # type: Optional[Callable[[],None]]
+
if cache_name is not None:
metrics = register_cache(
"lru_cache",
@@ -332,7 +336,10 @@ class LruCache(Generic[KT, VT]):
return key in cache
self.sentinel = object()
+
+ # make sure that we clear out any excess entries after we get resized.
self._on_resize = evict
+
self.get = cache_get
self.set = cache_set
self.setdefault = cache_set_default
@@ -383,6 +390,7 @@ class LruCache(Generic[KT, VT]):
new_size = int(self._original_max_size * factor)
if new_size != self.max_size:
self.max_size = new_size
- self._on_resize()
+ if self._on_resize:
+ self._on_resize()
return True
return False
diff --git a/tox.ini b/tox.ini
index 4d132eff4..6d0815378 100644
--- a/tox.ini
+++ b/tox.ini
@@ -158,7 +158,6 @@ commands=
coverage html
[testenv:mypy]
-skip_install = True
deps =
{[base]deps}
mypy==0.782
|
matrix-org/synapse
|
8f27b7fde12978a7e5b3833a2d989a9b0456d857
|
diff --git a/tests/util/test_lrucache.py b/tests/util/test_lrucache.py
index f12834eda..a739a6aaa 100644
--- a/tests/util/test_lrucache.py
+++ b/tests/util/test_lrucache.py
@@ -19,7 +19,8 @@ from mock import Mock
from synapse.util.caches.lrucache import LruCache
from synapse.util.caches.treecache import TreeCache
-from .. import unittest
+from tests import unittest
+from tests.unittest import override_config
class LruCacheTestCase(unittest.HomeserverTestCase):
@@ -83,6 +84,11 @@ class LruCacheTestCase(unittest.HomeserverTestCase):
cache.clear()
self.assertEquals(len(cache), 0)
+ @override_config({"caches": {"per_cache_factors": {"mycache": 10}}})
+ def test_special_size(self):
+ cache = LruCache(10, "mycache")
+ self.assertEqual(cache.max_size, 100)
+
class LruCacheCallbacksTestCase(unittest.HomeserverTestCase):
def test_get(self):
|
AttributeError: 'LruCache' object has no attribute '_on_resize'
I'm getting the following after updating `a9a8f2972..85c56445f`
```
2020-10-19 13:52:34,985 - synapse.federation.federation_server - 927 - ERROR - PUT-181 - Failed to handle edu 'm.typing'
Traceback (most recent call last):
File "/home/erikj/synapse/synapse/federation/federation_server.py", line 923, in on_edu
await handler(origin, content)
File "/home/erikj/synapse/synapse/handlers/typing.py", line 328, in _recv_edu
users = await self.store.get_users_in_room(room_id)
File "/home/erikj/synapse/synapse/util/caches/descriptors.py", line 153, in __get__
if expected_thread is not threading.current_thread():
File "/home/erikj/synapse/synapse/util/caches/deferred_cache.py", line 93, in __init__
File "/home/erikj/synapse/synapse/util/caches/lrucache.py", line 128, in __init__
File "/home/erikj/synapse/synapse/util/caches/__init__.py", line 120, in register_cache
metric_name = "cache_%s_%s" % (cache_type, cache_name)
File "/home/erikj/synapse/synapse/config/cache.py", line 83, in add_resizable_cache
properties.resize_all_caches_func()
File "/home/erikj/synapse/synapse/config/cache.py", line 208, in resize_all_caches
callback(new_factor)
File "/home/erikj/synapse/synapse/util/caches/lrucache.py", line 386, in set_cache_factor
AttributeError: 'LruCache' object has no attribute '_on_resize'
```
|
0.0
|
8f27b7fde12978a7e5b3833a2d989a9b0456d857
|
[
"tests/util/test_lrucache.py::LruCacheTestCase::test_special_size",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_clear"
] |
[
"tests/util/test_lrucache.py::LruCacheTestCase::test_clear",
"tests/util/test_lrucache.py::LruCacheTestCase::test_del_multi",
"tests/util/test_lrucache.py::LruCacheTestCase::test_eviction",
"tests/util/test_lrucache.py::LruCacheTestCase::test_get_set",
"tests/util/test_lrucache.py::LruCacheTestCase::test_pop",
"tests/util/test_lrucache.py::LruCacheTestCase::test_setdefault",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_del_multi",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_eviction",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_get",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_multi_get",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_pop",
"tests/util/test_lrucache.py::LruCacheCallbacksTestCase::test_set",
"tests/util/test_lrucache.py::LruCacheSizedTestCase::test_evict"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-19 17:08:07+00:00
|
apache-2.0
| 3,807 |
|
matrix-org__synapse-8708
|
diff --git a/changelog.d/8706.doc b/changelog.d/8706.doc
new file mode 100644
index 000000000..96a0427e7
--- /dev/null
+++ b/changelog.d/8706.doc
@@ -0,0 +1,1 @@
+Document experimental support for running multiple event persisters.
diff --git a/changelog.d/8708.misc b/changelog.d/8708.misc
new file mode 100644
index 000000000..be679fb0f
--- /dev/null
+++ b/changelog.d/8708.misc
@@ -0,0 +1,1 @@
+Block attempts by clients to send server ACLs, or redactions of server ACLs, that would result in the local server being blocked from the room.
diff --git a/docs/workers.md b/docs/workers.md
index cd1f823b7..4e046bdb3 100644
--- a/docs/workers.md
+++ b/docs/workers.md
@@ -319,6 +319,18 @@ stream_writers:
events: event_persister1
```
+The `events` stream also experimentally supports having multiple writers, where
+work is sharded between them by room ID. Note that you *must* restart all worker
+instances when adding or removing event persisters. An example `stream_writers`
+configuration with multiple writers:
+
+```yaml
+stream_writers:
+ events:
+ - event_persister1
+ - event_persister2
+```
+
#### Background tasks
There is also *experimental* support for moving background tasks to a separate
diff --git a/mypy.ini b/mypy.ini
index 1ece2ba08..fc9f8d805 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -13,6 +13,7 @@ files =
synapse/config,
synapse/event_auth.py,
synapse/events/builder.py,
+ synapse/events/validator.py,
synapse/events/spamcheck.py,
synapse/federation,
synapse/handlers/_base.py,
diff --git a/synapse/events/validator.py b/synapse/events/validator.py
index 5f9af8529..f8f3b1a31 100644
--- a/synapse/events/validator.py
+++ b/synapse/events/validator.py
@@ -13,20 +13,26 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from typing import Union
+
from synapse.api.constants import MAX_ALIAS_LENGTH, EventTypes, Membership
from synapse.api.errors import Codes, SynapseError
from synapse.api.room_versions import EventFormatVersions
+from synapse.config.homeserver import HomeServerConfig
+from synapse.events import EventBase
+from synapse.events.builder import EventBuilder
from synapse.events.utils import validate_canonicaljson
+from synapse.federation.federation_server import server_matches_acl_event
from synapse.types import EventID, RoomID, UserID
class EventValidator:
- def validate_new(self, event, config):
+ def validate_new(self, event: EventBase, config: HomeServerConfig):
"""Validates the event has roughly the right format
Args:
- event (FrozenEvent): The event to validate.
- config (Config): The homeserver's configuration.
+ event: The event to validate.
+ config: The homeserver's configuration.
"""
self.validate_builder(event)
@@ -76,12 +82,18 @@ class EventValidator:
if event.type == EventTypes.Retention:
self._validate_retention(event)
- def _validate_retention(self, event):
+ if event.type == EventTypes.ServerACL:
+ if not server_matches_acl_event(config.server_name, event):
+ raise SynapseError(
+ 400, "Can't create an ACL event that denies the local server"
+ )
+
+ def _validate_retention(self, event: EventBase):
"""Checks that an event that defines the retention policy for a room respects the
format enforced by the spec.
Args:
- event (FrozenEvent): The event to validate.
+ event: The event to validate.
"""
if not event.is_state():
raise SynapseError(code=400, msg="must be a state event")
@@ -116,13 +128,10 @@ class EventValidator:
errcode=Codes.BAD_JSON,
)
- def validate_builder(self, event):
+ def validate_builder(self, event: Union[EventBase, EventBuilder]):
"""Validates that the builder/event has roughly the right format. Only
checks values that we expect a proto event to have, rather than all the
fields an event would have
-
- Args:
- event (EventBuilder|FrozenEvent)
"""
strings = ["room_id", "sender", "type"]
diff --git a/synapse/handlers/message.py b/synapse/handlers/message.py
index ca5602c13..c6791fb91 100644
--- a/synapse/handlers/message.py
+++ b/synapse/handlers/message.py
@@ -1138,6 +1138,9 @@ class EventCreationHandler:
if original_event.room_id != event.room_id:
raise SynapseError(400, "Cannot redact event from a different room")
+ if original_event.type == EventTypes.ServerACL:
+ raise AuthError(403, "Redacting server ACL events is not permitted")
+
prev_state_ids = await context.get_prev_state_ids()
auth_events_ids = self.auth.compute_auth_events(
event, prev_state_ids, for_verification=True
|
matrix-org/synapse
|
d04c2d19b360356bacc754a2f592ccfd8d6536b3
|
diff --git a/tests/handlers/test_message.py b/tests/handlers/test_message.py
index 2e0fea04a..8b57081cb 100644
--- a/tests/handlers/test_message.py
+++ b/tests/handlers/test_message.py
@@ -154,3 +154,60 @@ class EventCreationTestCase(unittest.HomeserverTestCase):
# Check that we've deduplicated the events.
self.assertEqual(len(events), 2)
self.assertEqual(events[0].event_id, events[1].event_id)
+
+
+class ServerAclValidationTestCase(unittest.HomeserverTestCase):
+ servlets = [
+ admin.register_servlets,
+ login.register_servlets,
+ room.register_servlets,
+ ]
+
+ def prepare(self, reactor, clock, hs):
+ self.user_id = self.register_user("tester", "foobar")
+ self.access_token = self.login("tester", "foobar")
+ self.room_id = self.helper.create_room_as(self.user_id, tok=self.access_token)
+
+ def test_allow_server_acl(self):
+ """Test that sending an ACL that blocks everyone but ourselves works.
+ """
+
+ self.helper.send_state(
+ self.room_id,
+ EventTypes.ServerACL,
+ body={"allow": [self.hs.hostname]},
+ tok=self.access_token,
+ expect_code=200,
+ )
+
+ def test_deny_server_acl_block_outselves(self):
+ """Test that sending an ACL that blocks ourselves does not work.
+ """
+ self.helper.send_state(
+ self.room_id,
+ EventTypes.ServerACL,
+ body={},
+ tok=self.access_token,
+ expect_code=400,
+ )
+
+ def test_deny_redact_server_acl(self):
+ """Test that attempting to redact an ACL is blocked.
+ """
+
+ body = self.helper.send_state(
+ self.room_id,
+ EventTypes.ServerACL,
+ body={"allow": [self.hs.hostname]},
+ tok=self.access_token,
+ expect_code=200,
+ )
+ event_id = body["event_id"]
+
+ # Redaction of event should fail.
+ path = "/_matrix/client/r0/rooms/%s/redact/%s" % (self.room_id, event_id)
+ request, channel = self.make_request(
+ "POST", path, content={}, access_token=self.access_token
+ )
+ self.render(request)
+ self.assertEqual(int(channel.result["code"]), 403)
|
Deny server ACL events in C-S API which would block the server
Its quite easy to accidentally send a server ACL event that blocks everyone, including the current server. I can't think of a time when you would want to block your own server, so lets just deny client requests that try to set ACLs that would block the current server
|
0.0
|
d04c2d19b360356bacc754a2f592ccfd8d6536b3
|
[
"tests/handlers/test_message.py::ServerAclValidationTestCase::test_deny_redact_server_acl",
"tests/handlers/test_message.py::ServerAclValidationTestCase::test_deny_server_acl_block_outselves"
] |
[
"tests/handlers/test_message.py::EventCreationTestCase::test_duplicated_txn_id",
"tests/handlers/test_message.py::EventCreationTestCase::test_duplicated_txn_id_one_call",
"tests/handlers/test_message.py::ServerAclValidationTestCase::test_allow_server_acl"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-03 10:21:21+00:00
|
apache-2.0
| 3,808 |
|
matthewwardrop__formulaic-11
|
diff --git a/formulaic/materializers/base.py b/formulaic/materializers/base.py
index bc7f7be..dd76082 100644
--- a/formulaic/materializers/base.py
+++ b/formulaic/materializers/base.py
@@ -295,7 +295,7 @@ class FormulaMaterializer(metaclass=InterfaceMeta):
return values.get('__kind__') == 'categorical'
return False
- def _check_for_nulls(self, name, values, drop_rows):
+ def _check_for_nulls(self, name, values, na_action, drop_rows):
pass # pragma: no cover
def _encode_evaled_factor(self, factor, encoder_state, drop_rows, reduced_rank=False):
diff --git a/formulaic/materializers/pandas.py b/formulaic/materializers/pandas.py
index 943e5cf..d9b9b44 100644
--- a/formulaic/materializers/pandas.py
+++ b/formulaic/materializers/pandas.py
@@ -16,6 +16,7 @@ class PandasMaterializer(FormulaMaterializer):
REGISTRY_NAME = 'pandas'
DEFAULT_FOR = ['pandas.core.frame.DataFrame']
+ @override
def _init(self, sparse=False):
self.config.sparse = sparse
diff --git a/formulaic/parser/parser.py b/formulaic/parser/parser.py
index 34e8a8e..dab6bc2 100644
--- a/formulaic/parser/parser.py
+++ b/formulaic/parser/parser.py
@@ -36,7 +36,7 @@ class FormulaParser:
terms = arg.to_terms()
if len(terms) > 1 or list(terms)[0] != '0':
raise FormulaParsingError("Unary negation is only implemented for '0', where it is substituted for '1'.")
- return {Term(factors=[Factor('1', eval_method='literal')])}
+ return {Term(factors=[Factor('1', eval_method='literal')])} # pragma: no cover; All zero handling is currently done in the token pre-processor.
return [
Operator("~", arity=2, precedence=-100, associativity=None, to_terms=formula_separator_expansion),
@@ -86,11 +86,21 @@ class FormulaParser:
tokens.insert(0, one)
tokens.insert(1, plus)
- # Replace "0" with "-1"
+ # Replace all "0"s with "-1"
+ zero_index = -1
try:
- zero_index = tokens.index('0')
- if tokens[zero_index - 1] == '+':
- tokens[zero_index - 1] = minus
+ while True:
+ zero_index = tokens.index('0', zero_index + 1)
+ if zero_index - 1 < 0 or tokens[zero_index - 1] == '~':
+ tokens.pop(zero_index)
+ zero_index -= 1
+ continue
+ elif tokens[zero_index - 1] == '+':
+ tokens[zero_index - 1] = minus
+ elif tokens[zero_index - 1] == '-':
+ tokens[zero_index - 1] = plus
+ else:
+ raise FormulaParsingError(f"Unrecognised use of `0` at index: {tokens[zero_index-1].source_start}.")
tokens[zero_index] = one
except ValueError:
pass
|
matthewwardrop/formulaic
|
88b985aaf4d3f7138e04c3258542253c5c4f3f62
|
diff --git a/tests/parser/test_parser.py b/tests/parser/test_parser.py
index a5d4e2f..7b64ae9 100644
--- a/tests/parser/test_parser.py
+++ b/tests/parser/test_parser.py
@@ -18,7 +18,7 @@ FORMULA_TO_TOKENS = {
# Test translation of '0'
'0': ['1', '-', '1'],
- '0 ~': ['0', '~', '1']
+ '0 ~': ['~', '1']
}
FORMULA_TO_TERMS = {
@@ -34,6 +34,13 @@ FORMULA_TO_TERMS = {
'(a - a) + b': ['1', 'b'],
'a + (b - a)': ['1', 'a', 'b'],
+ # Check that "0" -> "-1" substitution works as expected
+ '0 + 0': [],
+ '0 + 0 + 1': ['1'],
+ '0 + 0 + 1 + 0': [],
+ '0 - 0': ['1'],
+ '0 ~ 0': ([], ),
+
# Formula separators
'~ a + b': (['1', 'a', 'b'], ),
'a ~ b + c': (['a'], ['1', 'b', 'c']),
@@ -80,4 +87,8 @@ class TestFormulaParser:
def test_invalid_unary_negation(self):
with pytest.raises(FormulaParsingError):
- assert PARSER.get_terms('(-10)')
+ PARSER.get_terms('(-10)')
+
+ def test_invalid_use_of_zero(self):
+ with pytest.raises(FormulaParsingError):
+ PARSER.get_terms('a * 0')
|
BUG: Repeated constant-like terms are incorrectly parsed
Formulas like `0 + 0 + 1 + x` are incorrectly parsed and result in a DataFrame that looks like:
```
from formulaic import model_matrix
from pandas import DataFrame
df = DataFrame([[0],[1],[2],[3],[4]],columns=["x"])
dep = model_matrix("0 + 0 + 1 + x", df, ensure_full_rank=False)
print(DataFrame(dep))
```
```
Intercept Intercept x
0 0.0 1.0 0
1 0.0 1.0 1
2 0.0 1.0 2
3 0.0 1.0 3
4 0.0 1.0 4
```
`0 + 0 + 1` should evaluate to just `1 +`
|
0.0
|
88b985aaf4d3f7138e04c3258542253c5c4f3f62
|
[
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[0",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[0",
"tests/parser/test_parser.py::TestFormulaParser::test_invalid_use_of_zero"
] |
[
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[-tokens0]",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[1-tokens3]",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[a-tokens4]",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[a",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[~",
"tests/parser/test_parser.py::TestFormulaParser::test_get_tokens[0-tokens8]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[-terms0]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a-terms1]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[(a",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[~",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a:b-terms17]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[(a+b):(c+d)-terms19]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[(a+b)**2-terms20]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[(a+b)**3-terms21]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a/b-terms22]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[(a+b)/c-terms23]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a/(b+c)-terms24]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[a/(b+c-b)-terms25]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[+1-terms26]",
"tests/parser/test_parser.py::TestFormulaParser::test_to_terms[-0-terms27]",
"tests/parser/test_parser.py::TestFormulaParser::test_invalid_unary_negation"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-13 16:32:35+00:00
|
mit
| 3,809 |
|
matthewwardrop__formulaic-166
|
diff --git a/formulaic/materializers/base.py b/formulaic/materializers/base.py
index 9a097eb..6393769 100644
--- a/formulaic/materializers/base.py
+++ b/formulaic/materializers/base.py
@@ -186,14 +186,7 @@ class FormulaMaterializer(metaclass=FormulaMaterializerMeta):
# the shared transform state pool.
model_specs._map(
lambda ms: ms.transform_state.update(
- {
- factor.expr: factor_evaluation_model_spec.transform_state[
- factor.expr
- ]
- for term in ms.formula
- for factor in term.factors
- if factor.expr in factor_evaluation_model_spec.transform_state
- }
+ factor_evaluation_model_spec.transform_state
)
)
|
matthewwardrop/formulaic
|
02e40e24681c0814aadf6f753bb98c6716b7678e
|
diff --git a/tests/materializers/test_pandas.py b/tests/materializers/test_pandas.py
index 889616e..b85cda4 100644
--- a/tests/materializers/test_pandas.py
+++ b/tests/materializers/test_pandas.py
@@ -472,3 +472,12 @@ class TestPandasMaterializer:
),
):
PandasMaterializer(data).get_model_matrix("I(a)")
+
+ def test_transform_state_with_inconsistent_formatting(self, data):
+ ms1 = PandasMaterializer(data).get_model_matrix("bs(a, df=4)").model_spec
+ ms2 = PandasMaterializer(data).get_model_matrix("bs( `a`, df = 4) ").model_spec
+ assert ms1.transform_state == ms2.transform_state
+
+ def test_nested_transform_state(self, data):
+ ms = PandasMaterializer(data).get_model_matrix("bs(bs(a))").model_spec
+ assert {"bs(a)", "bs(bs(a))"}.issubset(ms.transform_state)
|
`model_spec.transform_state` bugged when formula is not correctly written
In case the given formula is not correctly written i.e., with extra or forgotten spaces then the `transform_state` dictionary keys does not match and the dictionary results in `{}`. Here is an example:
`import numpy as np
import pandas as pd
from formulaic import Formula
df = pd.DataFrame({
'y': np.linspace(1,5,10),
'x': np.linspace(0,1,10),
})
\# Formula well written
y, X = Formula('y ~ bs(x, df=4) ').get_model_matrix(df)
print(X.model_spec.__dict__["transform_state"])
`
results in `{'bs(x, df=4)': {'lower_bound': 0.0, 'upper_bound': 1.0, 'knots': [0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0]}}` while
`\# Formula not well written (note the whitespaces)
y, X = Formula('y ~ bs( x, df = 4) ').get_model_matrix(df)
print(X.model_spec.__dict__["transform_state"])
`
results in `{}`
I am using Formulaic version 0.6.6
|
0.0
|
02e40e24681c0814aadf6f753bb98c6716b7678e
|
[
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_transform_state_with_inconsistent_formatting",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_nested_transform_state"
] |
[
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_edge_cases",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_invalid_output",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[pandas-a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[pandas-A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[pandas-C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[pandas-A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[pandas-A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[numpy-a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[numpy-A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[numpy-C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[numpy-A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[numpy-A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[sparse-a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[sparse-A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[sparse-C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[sparse-A:a-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[sparse-A:B-tests4]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_state",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_factor_evaluation_edge_cases",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test__is_categorical",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_encoding_edge_cases",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_empty",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_index_maintained",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_category_reordering",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_term_clustering",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_model_spec_pickleable",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_no_levels_encoding",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_none_values",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_quoted_python_args",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_lookup_nonexistent_variable"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-09 22:53:08+00:00
|
mit
| 3,810 |
|
matthewwardrop__formulaic-43
|
diff --git a/formulaic/materializers/base.py b/formulaic/materializers/base.py
index b28766d..877ffb1 100644
--- a/formulaic/materializers/base.py
+++ b/formulaic/materializers/base.py
@@ -5,7 +5,7 @@ import itertools
import operator
from abc import abstractmethod
from collections import defaultdict, OrderedDict
-from typing import Any, Dict, Iterable, Set, TYPE_CHECKING
+from typing import Any, Dict, Generator, List, Iterable, Set, Tuple, TYPE_CHECKING
from interface_meta import InterfaceMeta, inherit_docs
@@ -20,7 +20,7 @@ from formulaic.model_matrix import ModelMatrix
from formulaic.utils.layered_mapping import LayeredMapping
from formulaic.utils.stateful_transforms import stateful_eval
-from formulaic.parser.types import Factor
+from formulaic.parser.types import Factor, Term
from formulaic.transforms import TRANSFORMS
from .types import EvaluatedFactor, FactorValues, ScopedFactor, ScopedTerm
@@ -560,7 +560,12 @@ class FormulaMaterializer(metaclass=FormulaMaterializerMeta):
# Methods related to ModelMatrix output
- def _enforce_structure(self, cols, spec, drop_rows):
+ def _enforce_structure(
+ self,
+ cols: List[Tuple[Term, List[ScopedTerm], Dict[str, Any]]],
+ spec,
+ drop_rows: set,
+ ) -> Generator[Tuple[Term, List[ScopedTerm], Dict[str, Any]]]:
# TODO: Verify that imputation strategies are intuitive and make sense.
assert len(cols) == len(spec.structure)
for i in range(len(cols)):
@@ -580,15 +585,12 @@ class FormulaMaterializer(metaclass=FormulaMaterializerMeta):
f"Term `{cols[i][0]}` has generated insufficient columns compared to specification: generated {list(scoped_cols)}, expecting {target_cols}."
)
scoped_cols = {name: col for name in target_cols}
- elif (
- len(scoped_cols) == len(target_cols)
- and list(scoped_cols) != target_cols
- ):
+ elif set(scoped_cols) != set(target_cols):
raise FactorEncodingError(
f"Term `{cols[i][0]}` has generated columns that are inconsistent with specification: generated {list(scoped_cols)}, expecting {target_cols}."
)
- yield cols[i][0], cols[i][1], scoped_cols
+ yield cols[i][0], cols[i][1], {col: scoped_cols[col] for col in target_cols}
def _get_columns_for_term(self, factors, spec, scale=1):
"""
|
matthewwardrop/formulaic
|
5e75e05e323cfca9a442b92a9e344f30145fe46c
|
diff --git a/tests/materializers/test_pandas.py b/tests/materializers/test_pandas.py
index 59d7093..f290288 100644
--- a/tests/materializers/test_pandas.py
+++ b/tests/materializers/test_pandas.py
@@ -311,3 +311,34 @@ class TestPandasMaterializer:
mm = PandasMaterializer(data).get_model_matrix("1 + a + A")
assert list(mm.index) == [0, 2, 4, 8, 10]
assert not numpy.any(pandas.isnull(mm))
+
+ def test_category_reordering(self):
+ data = pandas.DataFrame({"A": ["a", "b", "c"]})
+ data2 = pandas.DataFrame({"A": ["c", "b", "a"]})
+ data3 = pandas.DataFrame(
+ {"A": pandas.Categorical(["c", "b", "a"], categories=["c", "b", "a"])}
+ )
+
+ m = PandasMaterializer(data).get_model_matrix("A + 0", ensure_full_rank=False)
+ assert list(m.columns) == ["A[T.a]", "A[T.b]", "A[T.c]"]
+ assert list(m.model_spec.get_model_matrix(data3).columns) == [
+ "A[T.a]",
+ "A[T.b]",
+ "A[T.c]",
+ ]
+
+ m2 = PandasMaterializer(data2).get_model_matrix("A + 0", ensure_full_rank=False)
+ assert list(m2.columns) == ["A[T.a]", "A[T.b]", "A[T.c]"]
+ assert list(m2.model_spec.get_model_matrix(data3).columns) == [
+ "A[T.a]",
+ "A[T.b]",
+ "A[T.c]",
+ ]
+
+ m3 = PandasMaterializer(data3).get_model_matrix("A + 0", ensure_full_rank=False)
+ assert list(m3.columns) == ["A[T.c]", "A[T.b]", "A[T.a]"]
+ assert list(m3.model_spec.get_model_matrix(data).columns) == [
+ "A[T.c]",
+ "A[T.b]",
+ "A[T.a]",
+ ]
|
Bug handling categorical features?
I am training a model with a `pd.categorical` feature with categories not following alphabetic order. During prediction I pass this categorical feature as string. When transforming getting the model matrix using `X.model_spec.get_model_matrix(x_string)`, the string feature is transformed to a pd.categorical with features alphabetically ordered resulting in` FactorEncodingError: Term categorical feature has generated columns that are inconsistent with specification`. The number and name of columns is the same but the other is different.
I use this code to replicate this error:
```import pandas as pd
from formulaic import model_matrix
from random import shuffle
import numpy as np
for cat_order in [['A','G','B','D','E','F'], ['A','B','D','E','F']]:
# Define the model matrix
examples = cat_order*2
shuffle(examples)
df = pd.DataFrame({'y': [i for i, _ in enumerate(examples)], 'a':pd.Categorical(examples, cat_order)})
y, X = model_matrix("y ~ C(a)", df)
# Check if we can transform a categorical feature with specified order, a noncateegorical feature
# into a model matrix
from formulaic.errors import FactorEncodingError
df_test = pd.DataFrame({
'y': [17,18],
'a': pd.Categorical(['A','B'], cat_order),
})
df_testb = pd.DataFrame({
'y': [17,18],
'a': ['A','B'],
})
print('categorical order',cat_order)
for df, ftype in [(df_test,'cat'),(df_testb,'non-cat')]:
try:
X.model_spec.get_model_matrix(df)
print(f'{ftype} passes')
except FactorEncodingError:
print(f'{ftype} does not pass')
```
outputs:
```
categorical order ['A', 'G', 'B', 'D', 'E', 'F']
cat passes
non-cat does not pass
categorical order ['A', 'B', 'D', 'E', 'F']
cat passes
non-cat passes
```
|
0.0
|
5e75e05e323cfca9a442b92a9e344f30145fe46c
|
[
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_category_reordering"
] |
[
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix[a:A-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_numpy[a:A-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_sparse[a:A-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_get_model_matrix_invalid_output",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[a-tests0]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[A-tests1]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[C(A)-tests2]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_na_handling[a:A-tests3]",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_state",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_factor_evaluation_edge_cases",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test__is_categorical",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_encoding_edge_cases",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_empty",
"tests/materializers/test_pandas.py::TestPandasMaterializer::test_index_maintained"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-10-12 05:04:12+00:00
|
mit
| 3,811 |
|
matthewwithanm__python-markdownify-110
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index cab4f36..86226d2 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -376,10 +376,16 @@ class MarkdownConverter(object):
return '\n\n' + text + '\n\n'
def convert_td(self, el, text, convert_as_inline):
- return ' ' + text.strip().replace("\n", " ") + ' |'
+ colspan = 1
+ if 'colspan' in el.attrs:
+ colspan = int(el['colspan'])
+ return ' ' + text.strip().replace("\n", " ") + ' |' * colspan
def convert_th(self, el, text, convert_as_inline):
- return ' ' + text + ' |'
+ colspan = 1
+ if 'colspan' in el.attrs:
+ colspan = int(el['colspan'])
+ return ' ' + text.strip().replace("\n", " ") + ' |' * colspan
def convert_tr(self, el, text, convert_as_inline):
cells = el.find_all(['td', 'th'])
@@ -392,7 +398,13 @@ class MarkdownConverter(object):
underline = ''
if is_headrow and not el.previous_sibling:
# first row and is headline: print headline underline
- underline += '| ' + ' | '.join(['---'] * len(cells)) + ' |' + '\n'
+ full_colspan = 0
+ for cell in cells:
+ if "colspan" in cell.attrs:
+ full_colspan += int(cell["colspan"])
+ else:
+ full_colspan += 1
+ underline += '| ' + ' | '.join(['---'] * full_colspan) + ' |' + '\n'
elif (not el.previous_sibling
and (el.parent.name == 'table'
or (el.parent.name == 'tbody'
|
matthewwithanm/python-markdownify
|
57d4f379236fdda75c7359d664ecf4aea8bcb157
|
diff --git a/tests/test_tables.py b/tests/test_tables.py
index 42f3a25..9120c29 100644
--- a/tests/test_tables.py
+++ b/tests/test_tables.py
@@ -209,6 +209,23 @@ table_with_caption = """TEXT<table><caption>Caption</caption>
</tbody>
</table>"""
+table_with_colspan = """<table>
+ <tr>
+ <th colspan="2">Name</th>
+ <th>Age</th>
+ </tr>
+ <tr>
+ <td>Jill</td>
+ <td>Smith</td>
+ <td>50</td>
+ </tr>
+ <tr>
+ <td>Eve</td>
+ <td>Jackson</td>
+ <td>94</td>
+ </tr>
+</table>"""
+
def test_table():
assert md(table) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
@@ -222,3 +239,4 @@ def test_table():
assert md(table_missing_head) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
assert md(table_body) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
assert md(table_with_caption) == 'TEXT\n\nCaption\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n\n'
+ assert md(table_with_colspan) == '\n\n| Name | | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
|
Table merge cell horizontally
### Summary
`colspan` attribute ignored in conversion, causing problems.
### Description
In HTML, the `colspan` attribute of `<td>` and `<th>` extends the cell to span multiple columns.
Currently, all cells are handled the same, causing inconsistent numbers of columns on each row of the table.
|
0.0
|
57d4f379236fdda75c7359d664ecf4aea8bcb157
|
[
"tests/test_tables.py::test_table"
] |
[] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-02-02 21:26:12+00:00
|
mit
| 3,812 |
|
matthewwithanm__python-markdownify-114
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index b67c32b..cab4f36 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -369,6 +369,12 @@ class MarkdownConverter(object):
def convert_table(self, el, text, convert_as_inline):
return '\n\n' + text + '\n'
+ def convert_caption(self, el, text, convert_as_inline):
+ return text + '\n'
+
+ def convert_figcaption(self, el, text, convert_as_inline):
+ return '\n\n' + text + '\n\n'
+
def convert_td(self, el, text, convert_as_inline):
return ' ' + text.strip().replace("\n", " ") + ' |'
|
matthewwithanm/python-markdownify
|
e4df41225da327aeb1ca5acd87be02518f8f8865
|
diff --git a/tests/test_conversions.py b/tests/test_conversions.py
index ae56837..1e685f3 100644
--- a/tests/test_conversions.py
+++ b/tests/test_conversions.py
@@ -74,6 +74,11 @@ def test_br():
assert md('a<br />b<br />c', newline_style=BACKSLASH) == 'a\\\nb\\\nc'
+def test_caption():
+ assert md('TEXT<figure><figcaption>Caption</figcaption><span>SPAN</span></figure>') == 'TEXT\n\nCaption\n\nSPAN'
+ assert md('<figure><span>SPAN</span><figcaption>Caption</figcaption></figure>TEXT') == 'SPAN\n\nCaption\n\nTEXT'
+
+
def test_code():
inline_tests('code', '`')
assert md('<code>*this_should_not_escape*</code>') == '`*this_should_not_escape*`'
diff --git a/tests/test_tables.py b/tests/test_tables.py
index ebbb146..9be876d 100644
--- a/tests/test_tables.py
+++ b/tests/test_tables.py
@@ -201,6 +201,14 @@ table_body = """<table>
</tbody>
</table>"""
+table_with_caption = """TEXT<table><caption>Caption</caption>
+ <tbody><tr><td>Firstname</td>
+ <td>Lastname</td>
+ <td>Age</td>
+ </tr>
+ </tbody>
+</table>"""
+
def test_table():
assert md(table) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
@@ -213,3 +221,4 @@ def test_table():
assert md(table_missing_text) == '\n\n| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |\n\n'
assert md(table_missing_head) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
assert md(table_body) == '\n\n| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
+ assert md(table_with_caption) == 'TEXT\n\nCaption\n| Firstname | Lastname | Age |\n\n'
|
Blank lines are missing around figure and table captions
For `<table>` elements, a newline is missing between the `<caption>` element and the first `|` (pipe) character in the table structure:
```
from markdownify import markdownify as md
md('TEXT<table><caption>Caption</caption><tr><td>CELL</td></tr></tbody></table>') # > 'TEXT\n\nCaption| CELL |\n\n'
# ^^^^^^^^
```
For `<figure>` elements, blank lines are missing around `<figcaption>` elements at the top or bottom of the figure:
```
from markdownify import markdownify as md
md('TEXT<figure><figcaption>Caption</figcaption><span>SPAN</span></figure>') # > 'TEXTCaptionSPAN'
# ^^^^^^^^^
md('<figure><span>SPAN</span><figcaption>Caption</figcaption></figure>TEXT') # > 'SPANCaptionTEXT'
# ^^^^^^^^^
```
These tests use inline text content and no newlines to test the worst-case output scenario (no extra newlines in input propagating to output).
|
0.0
|
e4df41225da327aeb1ca5acd87be02518f8f8865
|
[
"tests/test_conversions.py::test_caption"
] |
[
"tests/test_conversions.py::test_a",
"tests/test_conversions.py::test_a_spaces",
"tests/test_conversions.py::test_a_with_title",
"tests/test_conversions.py::test_a_shortcut",
"tests/test_conversions.py::test_a_no_autolinks",
"tests/test_conversions.py::test_b",
"tests/test_conversions.py::test_b_spaces",
"tests/test_conversions.py::test_blockquote",
"tests/test_conversions.py::test_blockquote_with_nested_paragraph",
"tests/test_conversions.py::test_blockquote_with_paragraph",
"tests/test_conversions.py::test_blockquote_nested",
"tests/test_conversions.py::test_br",
"tests/test_conversions.py::test_code",
"tests/test_conversions.py::test_del",
"tests/test_conversions.py::test_div",
"tests/test_conversions.py::test_em",
"tests/test_conversions.py::test_header_with_space",
"tests/test_conversions.py::test_h1",
"tests/test_conversions.py::test_h2",
"tests/test_conversions.py::test_hn",
"tests/test_conversions.py::test_hn_chained",
"tests/test_conversions.py::test_hn_nested_tag_heading_style",
"tests/test_conversions.py::test_hn_nested_simple_tag",
"tests/test_conversions.py::test_hn_nested_img",
"tests/test_conversions.py::test_hn_atx_headings",
"tests/test_conversions.py::test_hn_atx_closed_headings",
"tests/test_conversions.py::test_head",
"tests/test_conversions.py::test_hr",
"tests/test_conversions.py::test_i",
"tests/test_conversions.py::test_img",
"tests/test_conversions.py::test_kbd",
"tests/test_conversions.py::test_p",
"tests/test_conversions.py::test_pre",
"tests/test_conversions.py::test_script",
"tests/test_conversions.py::test_style",
"tests/test_conversions.py::test_s",
"tests/test_conversions.py::test_samp",
"tests/test_conversions.py::test_strong",
"tests/test_conversions.py::test_strong_em_symbol",
"tests/test_conversions.py::test_sub",
"tests/test_conversions.py::test_sup",
"tests/test_conversions.py::test_lang",
"tests/test_conversions.py::test_lang_callback"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-03-15 20:10:52+00:00
|
mit
| 3,813 |
|
matthewwithanm__python-markdownify-117
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index 86226d2..0945916 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -48,6 +48,8 @@ def abstract_inline_conversion(markup_fn):
"""
def implementation(self, el, text, convert_as_inline):
markup = markup_fn(self)
+ if el.find_parent(['pre', 'code', 'kbd', 'samp']):
+ return text
prefix, suffix, text = chomp(text)
if not text:
return ''
|
matthewwithanm/python-markdownify
|
74ddc408cca3a8b59c070daffaae34ef2593f9e1
|
diff --git a/tests/test_conversions.py b/tests/test_conversions.py
index 1e685f3..9652143 100644
--- a/tests/test_conversions.py
+++ b/tests/test_conversions.py
@@ -87,6 +87,16 @@ def test_code():
assert md('<code><span>*this_should_not_escape*</span></code>') == '`*this_should_not_escape*`'
assert md('<code>this should\t\tnormalize</code>') == '`this should normalize`'
assert md('<code><span>this should\t\tnormalize</span></code>') == '`this should normalize`'
+ assert md('<code>foo<b>bar</b>baz</code>') == '`foobarbaz`'
+ assert md('<kbd>foo<i>bar</i>baz</kbd>') == '`foobarbaz`'
+ assert md('<samp>foo<del> bar </del>baz</samp>') == '`foo bar baz`'
+ assert md('<samp>foo <del>bar</del> baz</samp>') == '`foo bar baz`'
+ assert md('<code>foo<em> bar </em>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<code> bar </code>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<strong> bar </strong>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<s> bar </s>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<sup>bar</sup>baz</code>', sup_symbol='^') == '`foobarbaz`'
+ assert md('<code>foo<sub>bar</sub>baz</code>', sub_symbol='^') == '`foobarbaz`'
def test_del():
@@ -215,6 +225,17 @@ def test_pre():
assert md('<pre><span>*this_should_not_escape*</span></pre>') == '\n```\n*this_should_not_escape*\n```\n'
assert md('<pre>\t\tthis should\t\tnot normalize</pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
assert md('<pre><span>\t\tthis should\t\tnot normalize</span></pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
+ assert md('<pre>foo<b>\nbar\n</b>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<i>\nbar\n</i>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo\n<i>bar</i>\nbaz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<i>\n</i>baz</pre>') == '\n```\nfoo\nbaz\n```\n'
+ assert md('<pre>foo<del>\nbar\n</del>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<em>\nbar\n</em>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<code>\nbar\n</code>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<strong>\nbar\n</strong>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<s>\nbar\n</s>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<sup>\nbar\n</sup>baz</pre>', sup_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<sub>\nbar\n</sub>baz</pre>', sub_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
def test_script():
|
Inline styles within `<pre>`/`<code>` blocks should be ignored
Markdown has no provision for inline styles within preformatted content (unless extensions/etc. are used).
However, inline styles are incorrectly applied within `<code>` and `<pre>` blocks (note the `**` in these examples):
```
from markdownify import markdownify as md
md('<code><b>text</b></code>') # > '`**text**`'
md('<pre><b>text</b></pre>') # > '\n```\n**text**\n```\n'
```
and because content is interpreted literally in Markdown preformatted content, the extra styling characters are interpreted as literal content characters instead.
|
0.0
|
74ddc408cca3a8b59c070daffaae34ef2593f9e1
|
[
"tests/test_conversions.py::test_code",
"tests/test_conversions.py::test_pre"
] |
[
"tests/test_conversions.py::test_a",
"tests/test_conversions.py::test_a_spaces",
"tests/test_conversions.py::test_a_with_title",
"tests/test_conversions.py::test_a_shortcut",
"tests/test_conversions.py::test_a_no_autolinks",
"tests/test_conversions.py::test_b",
"tests/test_conversions.py::test_b_spaces",
"tests/test_conversions.py::test_blockquote",
"tests/test_conversions.py::test_blockquote_with_nested_paragraph",
"tests/test_conversions.py::test_blockquote_with_paragraph",
"tests/test_conversions.py::test_blockquote_nested",
"tests/test_conversions.py::test_br",
"tests/test_conversions.py::test_caption",
"tests/test_conversions.py::test_del",
"tests/test_conversions.py::test_div",
"tests/test_conversions.py::test_em",
"tests/test_conversions.py::test_header_with_space",
"tests/test_conversions.py::test_h1",
"tests/test_conversions.py::test_h2",
"tests/test_conversions.py::test_hn",
"tests/test_conversions.py::test_hn_chained",
"tests/test_conversions.py::test_hn_nested_tag_heading_style",
"tests/test_conversions.py::test_hn_nested_simple_tag",
"tests/test_conversions.py::test_hn_nested_img",
"tests/test_conversions.py::test_hn_atx_headings",
"tests/test_conversions.py::test_hn_atx_closed_headings",
"tests/test_conversions.py::test_head",
"tests/test_conversions.py::test_hr",
"tests/test_conversions.py::test_i",
"tests/test_conversions.py::test_img",
"tests/test_conversions.py::test_kbd",
"tests/test_conversions.py::test_p",
"tests/test_conversions.py::test_script",
"tests/test_conversions.py::test_style",
"tests/test_conversions.py::test_s",
"tests/test_conversions.py::test_samp",
"tests/test_conversions.py::test_strong",
"tests/test_conversions.py::test_strong_em_symbol",
"tests/test_conversions.py::test_sub",
"tests/test_conversions.py::test_sup",
"tests/test_conversions.py::test_lang",
"tests/test_conversions.py::test_lang_callback"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-04-03 20:02:27+00:00
|
mit
| 3,814 |
|
matthewwithanm__python-markdownify-118
|
diff --git a/README.rst b/README.rst
index 51888ea..a0cd678 100644
--- a/README.rst
+++ b/README.rst
@@ -123,6 +123,11 @@ escape_underscores
If set to ``False``, do not escape ``_`` to ``\_`` in text.
Defaults to ``True``.
+escape_misc
+ If set to ``False``, do not escape miscellaneous punctuation characters
+ that sometimes have Markdown significance in text.
+ Defaults to ``True``.
+
keep_inline_images_in
Images are converted to their alt-text when the images are located inside
headlines or table cells. If some inline images should be converted to
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index 86226d2..eaa6ded 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -48,6 +48,8 @@ def abstract_inline_conversion(markup_fn):
"""
def implementation(self, el, text, convert_as_inline):
markup = markup_fn(self)
+ if el.find_parent(['pre', 'code', 'kbd', 'samp']):
+ return text
prefix, suffix, text = chomp(text)
if not text:
return ''
@@ -69,6 +71,7 @@ class MarkdownConverter(object):
default_title = False
escape_asterisks = True
escape_underscores = True
+ escape_misc = True
heading_style = UNDERLINED
keep_inline_images_in = []
newline_style = SPACES
@@ -199,6 +202,9 @@ class MarkdownConverter(object):
def escape(self, text):
if not text:
return ''
+ if self.options['escape_misc']:
+ text = re.sub(r'([\\&<`[>~#=+|-])', r'\\\1', text)
+ text = re.sub(r'([0-9])([.)])', r'\1\\\2', text)
if self.options['escape_asterisks']:
text = text.replace('*', r'\*')
if self.options['escape_underscores']:
|
matthewwithanm/python-markdownify
|
74ddc408cca3a8b59c070daffaae34ef2593f9e1
|
diff --git a/tests/test_conversions.py b/tests/test_conversions.py
index 1e685f3..9652143 100644
--- a/tests/test_conversions.py
+++ b/tests/test_conversions.py
@@ -87,6 +87,16 @@ def test_code():
assert md('<code><span>*this_should_not_escape*</span></code>') == '`*this_should_not_escape*`'
assert md('<code>this should\t\tnormalize</code>') == '`this should normalize`'
assert md('<code><span>this should\t\tnormalize</span></code>') == '`this should normalize`'
+ assert md('<code>foo<b>bar</b>baz</code>') == '`foobarbaz`'
+ assert md('<kbd>foo<i>bar</i>baz</kbd>') == '`foobarbaz`'
+ assert md('<samp>foo<del> bar </del>baz</samp>') == '`foo bar baz`'
+ assert md('<samp>foo <del>bar</del> baz</samp>') == '`foo bar baz`'
+ assert md('<code>foo<em> bar </em>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<code> bar </code>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<strong> bar </strong>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<s> bar </s>baz</code>') == '`foo bar baz`'
+ assert md('<code>foo<sup>bar</sup>baz</code>', sup_symbol='^') == '`foobarbaz`'
+ assert md('<code>foo<sub>bar</sub>baz</code>', sub_symbol='^') == '`foobarbaz`'
def test_del():
@@ -215,6 +225,17 @@ def test_pre():
assert md('<pre><span>*this_should_not_escape*</span></pre>') == '\n```\n*this_should_not_escape*\n```\n'
assert md('<pre>\t\tthis should\t\tnot normalize</pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
assert md('<pre><span>\t\tthis should\t\tnot normalize</span></pre>') == '\n```\n\t\tthis should\t\tnot normalize\n```\n'
+ assert md('<pre>foo<b>\nbar\n</b>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<i>\nbar\n</i>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo\n<i>bar</i>\nbaz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<i>\n</i>baz</pre>') == '\n```\nfoo\nbaz\n```\n'
+ assert md('<pre>foo<del>\nbar\n</del>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<em>\nbar\n</em>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<code>\nbar\n</code>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<strong>\nbar\n</strong>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<s>\nbar\n</s>baz</pre>') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<sup>\nbar\n</sup>baz</pre>', sup_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
+ assert md('<pre>foo<sub>\nbar\n</sub>baz</pre>', sub_symbol='^') == '\n```\nfoo\nbar\nbaz\n```\n'
def test_script():
diff --git a/tests/test_escaping.py b/tests/test_escaping.py
index 2f3a83e..eaef77d 100644
--- a/tests/test_escaping.py
+++ b/tests/test_escaping.py
@@ -12,7 +12,7 @@ def test_underscore():
def test_xml_entities():
- assert md('&') == '&'
+ assert md('&') == r'\&'
def test_named_entities():
@@ -25,4 +25,23 @@ def test_hexadecimal_entities():
def test_single_escaping_entities():
- assert md('&amp;') == '&'
+ assert md('&amp;') == r'\&'
+
+
+def text_misc():
+ assert md('\\*') == r'\\\*'
+ assert md('<foo>') == r'\<foo\>'
+ assert md('# foo') == r'\# foo'
+ assert md('> foo') == r'\> foo'
+ assert md('~~foo~~') == r'\~\~foo\~\~'
+ assert md('foo\n===\n') == 'foo\n\\=\\=\\=\n'
+ assert md('---\n') == '\\-\\-\\-\n'
+ assert md('+ x\n+ y\n') == '\\+ x\n\\+ y\n'
+ assert md('`x`') == r'\`x\`'
+ assert md('[text](link)') == r'\[text](link)'
+ assert md('1. x') == r'1\. x'
+ assert md('not a number. x') == r'not a number. x'
+ assert md('1) x') == r'1\) x'
+ assert md('not a number) x') == r'not a number) x'
+ assert md('|not table|') == r'\|not table\|'
+ assert md(r'\ <foo> &amp; | ` `', escape_misc=False) == r'\ <foo> & | ` `'
|
Angle brackets <> aren't escaped.
```py
>>> markdownify('text<text>')
'text<text>'
```
In at least some flavours of Markdown, this would need to be `text\<text\>` instead. As an example, GitHub-flavoured Markdown gives
text<text>
and
text\<text\>
without and with backslashes respectively.
|
0.0
|
74ddc408cca3a8b59c070daffaae34ef2593f9e1
|
[
"tests/test_conversions.py::test_code",
"tests/test_conversions.py::test_pre",
"tests/test_escaping.py::test_xml_entities",
"tests/test_escaping.py::test_single_escaping_entities"
] |
[
"tests/test_conversions.py::test_a",
"tests/test_conversions.py::test_a_spaces",
"tests/test_conversions.py::test_a_with_title",
"tests/test_conversions.py::test_a_shortcut",
"tests/test_conversions.py::test_a_no_autolinks",
"tests/test_conversions.py::test_b",
"tests/test_conversions.py::test_b_spaces",
"tests/test_conversions.py::test_blockquote",
"tests/test_conversions.py::test_blockquote_with_nested_paragraph",
"tests/test_conversions.py::test_blockquote_with_paragraph",
"tests/test_conversions.py::test_blockquote_nested",
"tests/test_conversions.py::test_br",
"tests/test_conversions.py::test_caption",
"tests/test_conversions.py::test_del",
"tests/test_conversions.py::test_div",
"tests/test_conversions.py::test_em",
"tests/test_conversions.py::test_header_with_space",
"tests/test_conversions.py::test_h1",
"tests/test_conversions.py::test_h2",
"tests/test_conversions.py::test_hn",
"tests/test_conversions.py::test_hn_chained",
"tests/test_conversions.py::test_hn_nested_tag_heading_style",
"tests/test_conversions.py::test_hn_nested_simple_tag",
"tests/test_conversions.py::test_hn_nested_img",
"tests/test_conversions.py::test_hn_atx_headings",
"tests/test_conversions.py::test_hn_atx_closed_headings",
"tests/test_conversions.py::test_head",
"tests/test_conversions.py::test_hr",
"tests/test_conversions.py::test_i",
"tests/test_conversions.py::test_img",
"tests/test_conversions.py::test_kbd",
"tests/test_conversions.py::test_p",
"tests/test_conversions.py::test_script",
"tests/test_conversions.py::test_style",
"tests/test_conversions.py::test_s",
"tests/test_conversions.py::test_samp",
"tests/test_conversions.py::test_strong",
"tests/test_conversions.py::test_strong_em_symbol",
"tests/test_conversions.py::test_sub",
"tests/test_conversions.py::test_sup",
"tests/test_conversions.py::test_lang",
"tests/test_conversions.py::test_lang_callback",
"tests/test_escaping.py::test_asterisks",
"tests/test_escaping.py::test_underscore",
"tests/test_escaping.py::test_named_entities",
"tests/test_escaping.py::test_hexadecimal_entities"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-04-03 20:32:32+00:00
|
mit
| 3,815 |
|
matthewwithanm__python-markdownify-23
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index eeaaf74..da04ebf 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -6,6 +6,7 @@ import six
convert_heading_re = re.compile(r'convert_h(\d+)')
line_beginning_re = re.compile(r'^', re.MULTILINE)
whitespace_re = re.compile(r'[\t ]+')
+all_whitespace_re = re.compile(r'[\s]+')
html_heading_re = re.compile(r'h[1-6]')
@@ -83,12 +84,18 @@ class MarkdownConverter(object):
if not children_only and isHeading:
convert_children_as_inline = True
+ # Remove whitespace-only textnodes in lists
+ if node.name in ['ol', 'ul', 'li']:
+ for el in node.children:
+ if isinstance(el, NavigableString) and six.text_type(el).strip() == '':
+ el.extract()
+
# Convert the children first
for el in node.children:
if isinstance(el, Comment):
continue
elif isinstance(el, NavigableString):
- text += self.process_text(six.text_type(el))
+ text += self.process_text(el)
else:
text += self.process_tag(el, convert_children_as_inline)
@@ -99,7 +106,10 @@ class MarkdownConverter(object):
return text
- def process_text(self, text):
+ def process_text(self, el):
+ text = six.text_type(el)
+ if el.parent.name == 'li':
+ return escape(all_whitespace_re.sub(' ', text or '')).rstrip()
return escape(whitespace_re.sub(' ', text or ''))
def __getattr__(self, attr):
@@ -199,6 +209,9 @@ class MarkdownConverter(object):
# Ignoring convert_to_inline for list.
nested = False
+ before_paragraph = False
+ if el.next_sibling and el.next_sibling.name not in ['ul', 'ol']:
+ before_paragraph = True
while el:
if el.name == 'li':
nested = True
@@ -207,7 +220,7 @@ class MarkdownConverter(object):
if nested:
# remove trailing newline if nested
return '\n' + self.indent(text, 1).rstrip()
- return '\n' + text + '\n'
+ return text + ('\n' if before_paragraph else '')
convert_ul = convert_list
convert_ol = convert_list
|
matthewwithanm/python-markdownify
|
f59f9f9a5482f95595654258497366fcca5792e8
|
diff --git a/tests/test_conversions.py b/tests/test_conversions.py
index 9d25940..caac0fd 100644
--- a/tests/test_conversions.py
+++ b/tests/test_conversions.py
@@ -2,7 +2,7 @@ from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCOR
import re
-nested_uls = re.sub(r'\s+', '', """
+nested_uls = """
<ul>
<li>1
<ul>
@@ -19,7 +19,26 @@ nested_uls = re.sub(r'\s+', '', """
</li>
<li>2</li>
<li>3</li>
- </ul>""")
+ </ul>"""
+
+nested_ols = """
+ <ol>
+ <li>1
+ <ol>
+ <li>a
+ <ol>
+ <li>I</li>
+ <li>II</li>
+ <li>III</li>
+ </ol>
+ </li>
+ <li>b</li>
+ <li>c</li>
+ </ol>
+ </li>
+ <li>2</li>
+ <li>3</li>
+ </ul>"""
table = re.sub(r'\s+', '', """
@@ -253,8 +272,8 @@ def test_i():
def test_ol():
- assert md('<ol><li>a</li><li>b</li></ol>') == '\n1. a\n2. b\n\n'
- assert md('<ol start="3"><li>a</li><li>b</li></ol>') == '\n3. a\n4. b\n\n'
+ assert md('<ol><li>a</li><li>b</li></ol>') == '1. a\n2. b\n'
+ assert md('<ol start="3"><li>a</li><li>b</li></ol>') == '3. a\n4. b\n'
def test_p():
@@ -266,11 +285,15 @@ def test_strong():
def test_ul():
- assert md('<ul><li>a</li><li>b</li></ul>') == '\n* a\n* b\n\n'
+ assert md('<ul><li>a</li><li>b</li></ul>') == '* a\n* b\n'
+
+
+def test_nested_ols():
+ assert md(nested_ols) == '\n1. 1\n\t1. a\n\t\t1. I\n\t\t2. II\n\t\t3. III\n\t2. b\n\t3. c\n2. 2\n3. 3\n'
def test_inline_ul():
- assert md('<p>foo</p><ul><li>a</li><li>b</li></ul><p>bar</p>') == 'foo\n\n\n* a\n* b\n\nbar\n\n'
+ assert md('<p>foo</p><ul><li>a</li><li>b</li></ul><p>bar</p>') == 'foo\n\n* a\n* b\n\nbar\n\n'
def test_nested_uls():
@@ -278,11 +301,11 @@ def test_nested_uls():
Nested ULs should alternate bullet characters.
"""
- assert md(nested_uls) == '\n* 1\n\t+ a\n\t\t- I\n\t\t- II\n\t\t- III\n\t+ b\n\t+ c\n* 2\n* 3\n\n'
+ assert md(nested_uls) == '\n* 1\n\t+ a\n\t\t- I\n\t\t- II\n\t\t- III\n\t+ b\n\t+ c\n* 2\n* 3\n'
def test_bullets():
- assert md(nested_uls, bullets='-') == '\n- 1\n\t- a\n\t\t- I\n\t\t- II\n\t\t- III\n\t- b\n\t- c\n- 2\n- 3\n\n'
+ assert md(nested_uls, bullets='-') == '\n- 1\n\t- a\n\t\t- I\n\t\t- II\n\t\t- III\n\t- b\n\t- c\n- 2\n- 3\n'
def test_img():
|
ordered list issue
Hello :)
I encountered a probleme markdownifying ordered lists:
given `html = '<ol>\n<li>a</li>\n<li>b</li>\n<li>c</li>\n</ol>'`
the ol node list is: `['\n', <li>w</li>, '\n', <li>t</li>, '\n', <li>f</li>, '\n']`
as `bullet = '%s.' % (parent.index(el) + 1)`,
the result is:
```
: markdownify(html)
: ' 2. a\n 4. b\n 6. c\n '
```
<=>
```
2. a
4. b
6. c
```
I could preprocess my html input before passing it to markdonify but I'm affraid to loose "meaningfull linebreaks" if such things even exist ^^
I think this might be handled in the library, what do you think?
Thank you !
|
0.0
|
f59f9f9a5482f95595654258497366fcca5792e8
|
[
"tests/test_conversions.py::test_ol",
"tests/test_conversions.py::test_ul",
"tests/test_conversions.py::test_nested_ols",
"tests/test_conversions.py::test_inline_ul",
"tests/test_conversions.py::test_nested_uls",
"tests/test_conversions.py::test_bullets"
] |
[
"tests/test_conversions.py::test_chomp",
"tests/test_conversions.py::test_a",
"tests/test_conversions.py::test_a_spaces",
"tests/test_conversions.py::test_a_with_title",
"tests/test_conversions.py::test_a_shortcut",
"tests/test_conversions.py::test_a_no_autolinks",
"tests/test_conversions.py::test_b",
"tests/test_conversions.py::test_b_spaces",
"tests/test_conversions.py::test_blockquote",
"tests/test_conversions.py::test_blockquote_with_paragraph",
"tests/test_conversions.py::test_nested_blockquote",
"tests/test_conversions.py::test_br",
"tests/test_conversions.py::test_em",
"tests/test_conversions.py::test_em_spaces",
"tests/test_conversions.py::test_h1",
"tests/test_conversions.py::test_h2",
"tests/test_conversions.py::test_hn",
"tests/test_conversions.py::test_hn_chained",
"tests/test_conversions.py::test_hn_nested_tag_heading_style",
"tests/test_conversions.py::test_hn_nested_simple_tag",
"tests/test_conversions.py::test_hn_nested_img",
"tests/test_conversions.py::test_hr",
"tests/test_conversions.py::test_head",
"tests/test_conversions.py::test_atx_headings",
"tests/test_conversions.py::test_atx_closed_headings",
"tests/test_conversions.py::test_i",
"tests/test_conversions.py::test_p",
"tests/test_conversions.py::test_strong",
"tests/test_conversions.py::test_img",
"tests/test_conversions.py::test_div",
"tests/test_conversions.py::test_table",
"tests/test_conversions.py::test_strong_em_symbol",
"tests/test_conversions.py::test_newline_style"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-26 18:01:47+00:00
|
mit
| 3,816 |
|
matthewwithanm__python-markdownify-34
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index 6d93e47..5c008d3 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -1,4 +1,4 @@
-from bs4 import BeautifulSoup, NavigableString
+from bs4 import BeautifulSoup, NavigableString, Comment
import re
import six
@@ -75,7 +75,9 @@ class MarkdownConverter(object):
# Convert the children first
for el in node.children:
- if isinstance(el, NavigableString):
+ if isinstance(el, Comment):
+ continue
+ elif isinstance(el, NavigableString):
text += self.process_text(six.text_type(el))
else:
text += self.process_tag(el, convert_children_as_inline)
|
matthewwithanm/python-markdownify
|
77d1e99bd5246193138d7646882f3e72c04ce26f
|
diff --git a/tests/test_advanced.py b/tests/test_advanced.py
index 4c480d7..7ee61d2 100644
--- a/tests/test_advanced.py
+++ b/tests/test_advanced.py
@@ -4,3 +4,13 @@ from markdownify import markdownify as md
def test_nested():
text = md('<p>This is an <a href="http://example.com/">example link</a>.</p>')
assert text == 'This is an [example link](http://example.com/).\n\n'
+
+
+def test_ignore_comments():
+ text = md("<!-- This is a comment -->")
+ assert text == ""
+
+
+def test_ignore_comments_with_other_tags():
+ text = md("<!-- This is a comment --><a href='http://example.com/'>example link</a>")
+ assert text == "[example link](http://example.com/)"
|
Exclude comments
Currently markdownify allows to parse comments, might not very common to see comments (`<!--` & `-->`) in HTML however when you're working with someones HTML code anything can happen.
### Did write a test to check that:
```python
def test_comments():
text = md("<!-- This is a comment -->")
assert text == ""
```
The test above should pass, however, the response is ` This is a comment ` and it shouldn't be.
### Possible solutions:
- Do not parse at all the comments
- Enable to blacklist or exclude the comments on `strip` parameters or wtv
Awesome work BTW
|
0.0
|
77d1e99bd5246193138d7646882f3e72c04ce26f
|
[
"tests/test_advanced.py::test_ignore_comments",
"tests/test_advanced.py::test_ignore_comments_with_other_tags"
] |
[
"tests/test_advanced.py::test_nested"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-02-05 19:44:50+00:00
|
mit
| 3,817 |
|
matthewwithanm__python-markdownify-36
|
diff --git a/markdownify/__init__.py b/markdownify/__init__.py
index 88e158e..0b2a620 100644
--- a/markdownify/__init__.py
+++ b/markdownify/__init__.py
@@ -252,6 +252,23 @@ class MarkdownConverter(object):
return '' % (alt, src, title_part)
+ def convert_table(self, el, text, convert_as_inline):
+ rows = el.find_all('tr')
+ text_data = []
+ for row in rows:
+ headers = row.find_all('th')
+ columns = row.find_all('td')
+ if len(headers) > 0:
+ headers = [head.text.strip() for head in headers]
+ text_data.append('| ' + ' | '.join(headers) + ' |')
+ text_data.append('| ' + ' | '.join(['---'] * len(headers)) + ' |')
+ elif len(columns) > 0:
+ columns = [colm.text.strip() for colm in columns]
+ text_data.append('| ' + ' | '.join(columns) + ' |')
+ else:
+ continue
+ return '\n'.join(text_data)
+
def markdownify(html, **options):
return MarkdownConverter(**options).convert(html)
|
matthewwithanm/python-markdownify
|
d4882b86b9c308699fa73dfe79747799f19c5192
|
diff --git a/tests/test_conversions.py b/tests/test_conversions.py
index 68b44c6..6dcf9a6 100644
--- a/tests/test_conversions.py
+++ b/tests/test_conversions.py
@@ -22,6 +22,76 @@ nested_uls = re.sub(r'\s+', '', """
</ul>""")
+table = re.sub(r'\s+', '', """
+<table>
+ <tr>
+ <th>Firstname</th>
+ <th>Lastname</th>
+ <th>Age</th>
+ </tr>
+ <tr>
+ <td>Jill</td>
+ <td>Smith</td>
+ <td>50</td>
+ </tr>
+ <tr>
+ <td>Eve</td>
+ <td>Jackson</td>
+ <td>94</td>
+ </tr>
+</table>
+""")
+
+
+table_head_body = re.sub(r'\s+', '', """
+<table>
+ <thead>
+ <tr>
+ <th>Firstname</th>
+ <th>Lastname</th>
+ <th>Age</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Jill</td>
+ <td>Smith</td>
+ <td>50</td>
+ </tr>
+ <tr>
+ <td>Eve</td>
+ <td>Jackson</td>
+ <td>94</td>
+ </tr>
+ </tbody>
+</table>
+""")
+
+table_missing_text = re.sub(r'\s+', '', """
+<table>
+ <thead>
+ <tr>
+ <th></th>
+ <th>Lastname</th>
+ <th>Age</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>Jill</td>
+ <td></td>
+ <td>50</td>
+ </tr>
+ <tr>
+ <td>Eve</td>
+ <td>Jackson</td>
+ <td>94</td>
+ </tr>
+ </tbody>
+</table>
+""")
+
+
def test_chomp():
assert md(' <b></b> ') == ' '
assert md(' <b> </b> ') == ' '
@@ -222,6 +292,12 @@ def test_div():
assert md('Hello</div> World') == 'Hello World'
+def test_table():
+ assert md(table) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
+ assert md(table_head_body) == '| Firstname | Lastname | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |'
+ assert md(table_missing_text) == '| | Lastname | Age |\n| --- | --- | --- |\n| Jill | | 50 |\n| Eve | Jackson | 94 |'
+
+
def test_strong_em_symbol():
assert md('<strong>Hello</strong>', strong_em_symbol=UNDERSCORE) == '__Hello__'
assert md('<b>Hello</b>', strong_em_symbol=UNDERSCORE) == '__Hello__'
|
Support tables
Currently `table`s are not supported. Would be great to see basic support for
|
0.0
|
d4882b86b9c308699fa73dfe79747799f19c5192
|
[
"tests/test_conversions.py::test_table"
] |
[
"tests/test_conversions.py::test_chomp",
"tests/test_conversions.py::test_a",
"tests/test_conversions.py::test_a_spaces",
"tests/test_conversions.py::test_a_with_title",
"tests/test_conversions.py::test_a_shortcut",
"tests/test_conversions.py::test_a_no_autolinks",
"tests/test_conversions.py::test_b",
"tests/test_conversions.py::test_b_spaces",
"tests/test_conversions.py::test_blockquote",
"tests/test_conversions.py::test_blockquote_with_paragraph",
"tests/test_conversions.py::test_nested_blockquote",
"tests/test_conversions.py::test_br",
"tests/test_conversions.py::test_em",
"tests/test_conversions.py::test_em_spaces",
"tests/test_conversions.py::test_h1",
"tests/test_conversions.py::test_h2",
"tests/test_conversions.py::test_hn",
"tests/test_conversions.py::test_hn_chained",
"tests/test_conversions.py::test_hn_nested_tag_heading_style",
"tests/test_conversions.py::test_hn_nested_simple_tag",
"tests/test_conversions.py::test_hn_nested_img",
"tests/test_conversions.py::test_hr",
"tests/test_conversions.py::test_head",
"tests/test_conversions.py::test_atx_headings",
"tests/test_conversions.py::test_atx_closed_headings",
"tests/test_conversions.py::test_i",
"tests/test_conversions.py::test_ol",
"tests/test_conversions.py::test_p",
"tests/test_conversions.py::test_strong",
"tests/test_conversions.py::test_ul",
"tests/test_conversions.py::test_inline_ul",
"tests/test_conversions.py::test_nested_uls",
"tests/test_conversions.py::test_bullets",
"tests/test_conversions.py::test_img",
"tests/test_conversions.py::test_div",
"tests/test_conversions.py::test_strong_em_symbol",
"tests/test_conversions.py::test_newline_style"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-08 19:25:36+00:00
|
mit
| 3,818 |
|
mattjmcnaughton__sdep-30
|
diff --git a/docs/cli.rst b/docs/cli.rst
index ab80b6a..62fcaee 100644
--- a/docs/cli.rst
+++ b/docs/cli.rst
@@ -61,6 +61,12 @@ options can be set in configuration files:
**Optional**
+- :command:`INDEX_SUFFIX`: When hosting with Amazon S3, it is necessary to
+ specify an index suffix, which is appended to all urls ending in :command:`/`. The
+ default value is :command:`index.html`.
+- :command:`ERROR_KEY`: The S3 key of the file Amazon should serve in case of
+ error (i.e. incorrect url). The default value is :command:`404.html`.
+
Environment Variables
~~~~~~~~~~~~~~~~~~~~~
diff --git a/sdep/app.py b/sdep/app.py
index ecf518f..ad923f8 100644
--- a/sdep/app.py
+++ b/sdep/app.py
@@ -28,12 +28,6 @@ class Sdep(object):
# Constant names of AWS objects.
BUCKET_NAME = "bucket_name"
- # Default index and error.
- # @TODO This specification is temporary, as eventually we will make these
- # configurable options with `Config`.
- DEFAULT_INDEX_SUFFIX = "index.html"
- DEFAULT_ERROR_KEY = "404.html"
-
def __init__(self, config):
self._config = config
self._s3_client = self._establish_s3_client()
@@ -199,10 +193,10 @@ class Sdep(object):
"""
website_config = {
"IndexDocument": {
- "Suffix": self.DEFAULT_INDEX_SUFFIX
+ "Suffix": self._config.get(Config.INDEX_SUFFIX_FIELD)
},
"ErrorDocument": {
- "Key": self.DEFAULT_ERROR_KEY
+ "Key": self._config.get(Config.ERROR_KEY_FIELD)
}
}
diff --git a/sdep/config.py b/sdep/config.py
index 636f97a..22298f8 100644
--- a/sdep/config.py
+++ b/sdep/config.py
@@ -65,6 +65,8 @@ class Config(object):
AWS_SECRET_ACCESS_KEY_FIELD = "aws_secret_access_key"
SITE_DIR_FIELD = "site_dir"
DOMAIN_FIELD = "domain"
+ INDEX_SUFFIX_FIELD = "index_suffix"
+ ERROR_KEY_FIELD = "error_key"
def __init__(self, config_file=None, test_mode=False):
# @TODO I wonder if it would make more sense for the `Config` class to
@@ -144,13 +146,11 @@ class Config(object):
ConfigImproperFormatError: If vital configuration data is either in
the incorrect format or nonexistent.
"""
- for field in self.required_config_fields(env=True):
- value = os.environ.get(field)
-
- if value is None:
- raise ConfigImproperFormatError
- else:
- self._config_hash[field.lower()] = value
+ self._config_hash = self._parse_from_store(
+ self.required_config_fields(env=True),
+ self.optional_config_fields(env=True),
+ os.environ
+ )
def _parse_from_config_file(self, config_file):
"""
@@ -172,15 +172,46 @@ class Config(object):
except (IOError, json.JSONDecodeError):
raise ConfigImproperFormatError
- # @TODO Should a common helper method implement this functionality
- # for both `_parse_from_config_file` and `_parse_from_env`.
- for field in self.required_config_fields(env=False):
- value = config_data.get(field)
+ self._config_hash = self._parse_from_store(
+ self.required_config_fields(env=False),
+ self.optional_config_fields(env=False),
+ config_data
+ )
+
+ @classmethod
+ def _parse_from_store(cls, required_fields, optional_fields, data_store):
+ """
+ Parse the configuration from a data store object (i.e. the json hash or
+ `os.environ`). This method is useful because the process for parsing the
+ data from either the environment or a configuration file shares many of
+ the same components. Abstracting to a single method ensures less
+ duplicate code.
+
+ Args:
+ required_fields (list): A list of the required fields.
+ optional_fields (list): A list of the optional fields.
+ data_store (dict): A dictionary containing key/value pairs with the
+ fields as a key.
+
+ Returns:
+ dict: A configuration dictionary.
+ """
+ # Start with all of the defaults filled in. We will overwrite with any
+ # specified info.
+ config_hash = cls._optional_fields_and_defaults()
+
+ fields = [(f, True) for f in required_fields] + [(f, False) for f in optional_fields]
+
+ for field, required in fields:
+ value = data_store.get(field)
if value is None:
- raise ConfigImproperFormatError
+ if required:
+ raise ConfigImproperFormatError
else:
- self._config_hash[field.lower()] = value
+ config_hash[field.lower()] = value
+
+ return config_hash
@classmethod
def required_config_fields(cls, env=False):
@@ -207,8 +238,8 @@ class Config(object):
else:
return required_fields
- @staticmethod
- def optional_config_fields(env=False):
+ @classmethod
+ def optional_config_fields(cls, env=False):
"""
Return the optinal configuration fields either in `snake_case` or in all
upper-case `snake_case`, depending on whether the `env` flag is set.
@@ -220,23 +251,40 @@ class Config(object):
Returns:
[str]: A list of optional configuration fields.
"""
- optional_fields = []
+ optional_fields = list(cls._optional_fields_and_defaults().keys())
if env:
return [field.upper() for field in optional_fields]
else:
return optional_fields
+ @classmethod
+ def _optional_fields_and_defaults(cls):
+ """
+ Return a dictionary of optional fields and their defaults.
+
+ Returns:
+ dict: Optional fields and their defaults.
+ """
+ return {
+ cls.INDEX_SUFFIX_FIELD: "index.html",
+ cls.ERROR_KEY_FIELD: "404.html"
+ }
+
def _prepopulate_config(self):
"""
Prepopulate this instance of `Config` with sensible default values which
we can use when testing.
"""
- # @TODO Determine a better method for automatically including all
- # `required` variables.
- self._config_hash = {
+ populate_hash = {
self.AWS_ACCESS_KEY_ID_FIELD: "MY_ACCESS_KEY",
self.AWS_SECRET_ACCESS_KEY_FIELD: "MY_SECRET_KEY",
self.SITE_DIR_FIELD: "./static",
self.DOMAIN_FIELD: "sdep-test.com"
}
+
+ self._config_hash = self._parse_from_store(
+ self.required_config_fields(env=False),
+ self.optional_config_fields(env=False),
+ populate_hash
+ )
|
mattjmcnaughton/sdep
|
be2be4bbfbdb2442fa446174055bb6cf61c4125b
|
diff --git a/tests/test_app.py b/tests/test_app.py
index 8dd700f..08b5da0 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -117,9 +117,8 @@ class SdepTestCase(unittest.TestCase):
# with `Config`.
resp = self._s3_client.get_bucket_website(Bucket=bucket_name)
- self.assertEqual(resp["IndexDocument"]["Suffix"],
- Sdep.DEFAULT_INDEX_SUFFIX)
- self.assertEqual(resp["ErrorDocument"]["Key"], Sdep.DEFAULT_ERROR_KEY)
+ self.assertNotEqual(resp["IndexDocument"]["Suffix"], None)
+ self.assertNotEqual(resp["ErrorDocument"]["Key"], None)
@classmethod
def _create_test_upload_dir(cls):
diff --git a/tests/test_config.py b/tests/test_config.py
index 0feb7be..a1be9d8 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -35,7 +35,7 @@ class ConfigTestCase(unittest.TestCase):
config_file = self._create_config_file()
config = Config(config_file=config_file)
- for field in Config.required_config_fields():
+ for field in self._all_fields():
self.assertNotEqual(config.get(field), None)
os.remove(config_file)
@@ -51,7 +51,7 @@ class ConfigTestCase(unittest.TestCase):
with patch.dict(os.environ, environ_dict, clear=True):
config = Config()
- for field in Config.required_config_fields():
+ for field in self._all_fields():
self.assertNotEqual(config.get(field), None)
def test_find_config_in_curr_dir(self):
@@ -71,7 +71,7 @@ class ConfigTestCase(unittest.TestCase):
config = Config()
self.assertEqual(config_in_curr, Config.locate_config_file())
- for field in Config.required_config_fields():
+ for field in self._all_fields():
self.assertNotEqual(config.get(field), None)
for temp_dir in [temp_dirs.current, temp_dirs.home]:
@@ -97,13 +97,12 @@ class ConfigTestCase(unittest.TestCase):
config = Config()
self.assertEqual(config_in_home, Config.locate_config_file())
- for field in Config.required_config_fields():
+ for field in self._all_fields():
self.assertNotEqual(config.get(field), None)
for temp_dir in [temp_dirs.current, temp_dirs.home]:
shutil.rmtree(temp_dir, ignore_errors=True)
-
def test_bad_config(self):
"""
Test loading the configuration from a file with an improperly specified
@@ -114,15 +113,23 @@ class ConfigTestCase(unittest.TestCase):
with self.assertRaises(ConfigParseError):
Config(config_file=config_file)
- @staticmethod
- def _config_dict():
+ @classmethod
+ def _config_dict(cls):
"""
A dictionary of property formatted config.
Returns:
dict: A properly formatted config.
"""
- return {field: str(uuid.uuid4()) for field in Config.required_config_fields()}
+ base_dict = {field: str(uuid.uuid4()) for field in cls._all_fields()}
+
+ # Remove one of the optional fields so that we can test the default value
+ # being filled in.
+
+ field_to_remove = Config.optional_config_fields()[0]
+ del base_dict[field_to_remove]
+
+ return base_dict
@classmethod
def _create_mock_dirs(cls):
@@ -176,3 +183,13 @@ class ConfigTestCase(unittest.TestCase):
bad_config_file.write(json.dumps({}))
return file_name
+
+ @staticmethod
+ def _all_fields():
+ """
+ Helper method to return all configuration fields.
+
+ Returns:
+ list: List of the strings for all configuration fields.
+ """
+ return Config.required_config_fields() + Config.optional_config_fields()
|
Add `index_suffix` and `error_key` as optional fields
When telling AWS to have our bucket perform like a website, with this [boto call](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_bucket_website), we have the option of specifying which suffix will represent an index file (currently `index.html`) and the file to display when there is an error (currently `404.html`). Make both of these configurable options with sensible defaults.
|
0.0
|
be2be4bbfbdb2442fa446174055bb6cf61c4125b
|
[
"tests/test_config.py::ConfigTestCase::test_find_config_in_curr_dir",
"tests/test_config.py::ConfigTestCase::test_find_config_in_home_dir",
"tests/test_config.py::ConfigTestCase::test_load_config_from_env",
"tests/test_config.py::ConfigTestCase::test_load_config_from_file"
] |
[
"tests/test_config.py::ConfigTestCase::test_bad_config"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-06-01 21:15:26+00:00
|
mit
| 3,819 |
|
matze__pkgconfig-39
|
diff --git a/data/fake-dld-pkg.pc b/data/fake-dld-pkg.pc
new file mode 100644
index 0000000..ba5d551
--- /dev/null
+++ b/data/fake-dld-pkg.pc
@@ -0,0 +1,9 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include
+
+Name: BetaPkg
+Description: fake package with a digit-letter-digit version number for testing
+Requires:
+Version: 1.2.3b4
diff --git a/data/fake-openssl.pc b/data/fake-openssl.pc
new file mode 100644
index 0000000..6f35813
--- /dev/null
+++ b/data/fake-openssl.pc
@@ -0,0 +1,10 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib/x86_64-linux-gnu
+includedir=${prefix}/include
+
+Name: OpenSSL
+Description: Secure Sockets Layer and cryptography libraries and tools
+Requires: libssl libcrypto
+Version: 1.1.0j
+
diff --git a/pkgconfig/pkgconfig.py b/pkgconfig/pkgconfig.py
index 3deb97f..a792a0d 100644
--- a/pkgconfig/pkgconfig.py
+++ b/pkgconfig/pkgconfig.py
@@ -35,11 +35,33 @@ def _compare_versions(v1, v2):
Compare two version strings and return -1, 0 or 1 depending on the equality
of the subset of matching version numbers.
- The implementation is taken from the top answer at
+ The implementation is inspired by the top answer at
http://stackoverflow.com/a/1714190/997768.
"""
def normalize(v):
- return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]
+ # strip trailing .0 or .00 or .0.0 or ...
+ v = re.sub(r'(\.0+)*$', '', v)
+ result = []
+ for part in v.split('.'):
+ # just digits
+ m = re.match(r'^(\d+)$', part)
+ if m:
+ result.append(int(m.group(1)))
+ continue
+ # digits letters
+ m = re.match(r'^(\d+)([a-zA-Z]+)$', part)
+ if m:
+ result.append(int(m.group(1)))
+ result.append(m.group(2))
+ continue
+ # digits letters digits
+ m = re.match(r'^(\d+)([a-zA-Z]+)(\d+)$', part)
+ if m:
+ result.append(int(m.group(1)))
+ result.append(m.group(2))
+ result.append(int(m.group(3)))
+ continue
+ return tuple(result)
n1 = normalize(v1)
n2 = normalize(v2)
@@ -49,7 +71,7 @@ def _compare_versions(v1, v2):
def _split_version_specifier(spec):
"""Splits version specifiers in the form ">= 0.1.2" into ('0.1.2', '>=')"""
- m = re.search(r'([<>=]?=?)?\s*((\d*\.)*\d*)', spec)
+ m = re.search(r'([<>=]?=?)?\s*([0-9.a-zA-Z]+)', spec)
return m.group(2), m.group(1)
|
matze/pkgconfig
|
a9b8ff127a9f5e96a75bc23422d2d1eb67bb4175
|
diff --git a/test_pkgconfig.py b/test_pkgconfig.py
index 8786ff3..ea68573 100644
--- a/test_pkgconfig.py
+++ b/test_pkgconfig.py
@@ -8,7 +8,7 @@ PACKAGE_NAME = 'fake-gtk+-3.0'
def test_exists():
assert pkgconfig.exists(PACKAGE_NAME)
-
+ assert pkgconfig.exists('fake-openssl')
@pytest.mark.parametrize("version,expected",[
('3.2.1', True),
@@ -23,8 +23,58 @@ def test_version(version, expected):
assert pkgconfig.installed(PACKAGE_NAME, version) == expected
[email protected]("version,expected",[
+ ('1.1.0j', True),
+ ('==1.1.0j', True),
+ ('==1.1.0k', False),
+ ('>= 1.1.0', True),
+ ('> 1.2.0', False),
+ ('< 1.2.0', True),
+ ('< 1.1.0', False),
+ ('>= 1.1', True),
+ ('> 1.2', False),
+ ('< 1.2', True),
+ ('< 1.1', False),
+ ('>= 1.1.0c', True),
+ ('>= 1.1.0k', False),
+ # PLEASE NOTE:
+ # the letters have no semantics, except string ordering, see also the
+ # comment in the test below.
+ # comparing release with beta, like "1.2.3" > "1.2.3b" does not work.
+])
+def test_openssl(version, expected):
+ assert pkgconfig.installed('fake-openssl', version) == expected
+
+
[email protected]("version,expected",[
+ ('1.2.3b4', True),
+ ('==1.2.3b4', True),
+ ('==1.2.3', False),
+ ('>= 1.2.3b3', True),
+ ('< 1.2.3b5', True),
+ # PLEASE NOTE:
+ # sadly, when looking at all (esp. non-python) libraries out there, there
+ # is no agreement on the semantics of letters appended to version numbers.
+ # e.g. for a release candidate, some might use "c", but other also might
+ # use "rc" or whatever. stuff like openssl does not use the letters to
+ # represent release status, but rather minor updates using a-z.
+ # so, as there is no real standard / agreement, we can NOT assume any
+ # advanced semantics here (like we could for python packages).
+ # thus we do NOT implement any special semantics for the letters,
+ # except string ordering
+ # thus, comparing a version with a letter-digits appendix to one without
+ # may or may not give the desired result.
+ # e.g. python packages use a1 for alpha 1, b2 for beta 2, c3 for release
+ # candidate 3 and <nothing> for release.
+ # we do not implement this semantics, "1.2.3" > "1.2.3b1" does not work.
+])
+def test_dld_pkg(version, expected):
+ assert pkgconfig.installed('fake-dld-pkg', version) == expected
+
+
def test_modversion():
assert pkgconfig.modversion(PACKAGE_NAME) == '3.2.1'
+ assert pkgconfig.modversion('fake-openssl') == '1.1.0j'
def test_cflags():
|
openssl version parsing error
pkgconfig crashes while checking the openssl version number:
```
>>> pkgconfig.installed('openssl', '>= 1.1.0')
Traceback (most recent call last):
File "/home/user/w/borg-env/lib/python3.5/site-packages/pkgconfig/pkgconfig.py", line 161, in installed
result = _compare_versions(modversion, number)
File "/home/user/w/borg-env/lib/python3.5/site-packages/pkgconfig/pkgconfig.py", line 44, in _compare_versions
n1 = normalize(v1)
File "/home/user/w/borg-env/lib/python3.5/site-packages/pkgconfig/pkgconfig.py", line 42, in normalize
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]
File "/home/user/w/borg-env/lib/python3.5/site-packages/pkgconfig/pkgconfig.py", line 42, in <listcomp>
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]
ValueError: invalid literal for int() with base 10: '0j'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/w/borg-env/lib/python3.5/site-packages/pkgconfig/pkgconfig.py", line 164, in installed
raise ValueError(msg)
ValueError: >= 1.1.0 is not a correct version specifier
```
It's on Debian 9:
```
ii openssl 1.1.0j-1~deb9u1 amd64 Secure Sockets Layer toolkit - cryptographic utility
```
Note: openssl 1.1 is incompatible to 1.0, so while the check for a specific update release (like `j`) is maybe not that important (except for security fixes, early bug fixes), the check for 1.1 vs. 1.0 is fundamentally important.
|
0.0
|
a9b8ff127a9f5e96a75bc23422d2d1eb67bb4175
|
[
"test_pkgconfig.py::test_exists",
"test_pkgconfig.py::test_openssl[1.1.0j-True]",
"test_pkgconfig.py::test_openssl[==1.1.0j-True]",
"test_pkgconfig.py::test_openssl[>=",
"test_pkgconfig.py::test_openssl[<",
"test_pkgconfig.py::test_dld_pkg[1.2.3b4-True]",
"test_pkgconfig.py::test_dld_pkg[==1.2.3b4-True]",
"test_pkgconfig.py::test_dld_pkg[>=",
"test_pkgconfig.py::test_dld_pkg[<",
"test_pkgconfig.py::test_modversion"
] |
[
"test_pkgconfig.py::test_version[3.2.1-True]",
"test_pkgconfig.py::test_version[==3.2.1-True]",
"test_pkgconfig.py::test_version[==3.2.2-False]",
"test_pkgconfig.py::test_version[>",
"test_pkgconfig.py::test_version[<=",
"test_pkgconfig.py::test_version[<",
"test_pkgconfig.py::test_openssl[==1.1.0k-False]",
"test_pkgconfig.py::test_openssl[>",
"test_pkgconfig.py::test_dld_pkg[==1.2.3-False]",
"test_pkgconfig.py::test_cflags",
"test_pkgconfig.py::test_libs",
"test_pkgconfig.py::test_libs_static",
"test_pkgconfig.py::test_parse",
"test_pkgconfig.py::test_parse_static",
"test_pkgconfig.py::test_listall",
"test_pkgconfig.py::test_variables"
] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-12 15:36:44+00:00
|
mit
| 3,820 |
|
maxfischer2781__asyncstdlib-105
|
diff --git a/.codecov.yml b/.codecov.yml
new file mode 100644
index 0000000..d19a3b7
--- /dev/null
+++ b/.codecov.yml
@@ -0,0 +1,3 @@
+ignore:
+ # type tests are not execute, so there is no code coverage
+ - "typetests"
diff --git a/asyncstdlib/_lrucache.pyi b/asyncstdlib/_lrucache.pyi
new file mode 100644
index 0000000..38794cc
--- /dev/null
+++ b/asyncstdlib/_lrucache.pyi
@@ -0,0 +1,61 @@
+from ._typing import AC, Protocol, R as R, TypedDict
+from typing import (
+ Any,
+ Awaitable,
+ Callable,
+ NamedTuple,
+ Optional,
+ overload,
+)
+
+class CacheInfo(NamedTuple):
+ hits: int
+ misses: int
+ maxsize: Optional[int]
+ currsize: int
+
+class CacheParameters(TypedDict):
+ maxsize: Optional[int]
+ typed: bool
+
+class LRUAsyncCallable(Protocol[AC]):
+ __call__: AC
+ @overload
+ def __get__(
+ self: LRUAsyncCallable[AC],
+ instance: None,
+ owner: Optional[type] = ...,
+ ) -> LRUAsyncCallable[AC]: ...
+ @overload
+ def __get__(
+ self: LRUAsyncCallable[Callable[..., Awaitable[R]]],
+ instance: object,
+ owner: Optional[type] = ...,
+ ) -> LRUAsyncBoundCallable[Callable[..., Awaitable[R]]]: ...
+ @property
+ def __wrapped__(self) -> AC: ...
+ def cache_parameters(self) -> CacheParameters: ...
+ def cache_info(self) -> CacheInfo: ...
+ def cache_clear(self) -> None: ...
+ def cache_discard(self, *args: Any, **kwargs: Any) -> None: ...
+
+class LRUAsyncBoundCallable(LRUAsyncCallable[AC]):
+ __self__: object
+ __call__: AC
+ def __get__(
+ self: LRUAsyncBoundCallable[AC],
+ instance: Any,
+ owner: Optional[type] = ...,
+ ) -> LRUAsyncBoundCallable[AC]: ...
+ def __init__(self, lru: LRUAsyncCallable[AC], __self__: object) -> None: ...
+ @property
+ def __wrapped__(self) -> AC: ...
+ @property
+ def __func__(self) -> LRUAsyncCallable[AC]: ...
+
+@overload
+def lru_cache(maxsize: AC, typed: bool = ...) -> LRUAsyncCallable[AC]: ...
+@overload
+def lru_cache(
+ maxsize: Optional[int] = ..., typed: bool = ...
+) -> Callable[[AC], LRUAsyncCallable[AC]]: ...
diff --git a/asyncstdlib/itertools.py b/asyncstdlib/itertools.py
index fc12573..f6f06ee 100644
--- a/asyncstdlib/itertools.py
+++ b/asyncstdlib/itertools.py
@@ -148,33 +148,54 @@ class chain(AsyncIterator[T]):
The resulting iterator consecutively iterates over and yields all values from
each of the ``iterables``. This is similar to converting all ``iterables`` to
sequences and concatenating them, but lazily exhausts each iterable.
+
+ The ``chain`` assumes ownership of its ``iterables`` and closes them reliably
+ when the ``chain`` is closed. Pass the ``iterables`` via a :py:class:`tuple` to
+ ``chain.from_iterable`` to avoid closing all iterables but those already processed.
"""
- __slots__ = ("_impl",)
+ __slots__ = ("_iterator", "_owned_iterators")
- def __init__(self, *iterables: AnyIterable[T]):
- async def impl() -> AsyncIterator[T]:
- for iterable in iterables:
+ @staticmethod
+ async def _chain_iterator(
+ any_iterables: AnyIterable[AnyIterable[T]],
+ ) -> AsyncGenerator[T, None]:
+ async with ScopedIter(any_iterables) as iterables:
+ async for iterable in iterables:
async with ScopedIter(iterable) as iterator:
async for item in iterator:
yield item
- self._impl = impl()
+ def __init__(
+ self, *iterables: AnyIterable[T], _iterables: AnyIterable[AnyIterable[T]] = ()
+ ):
+ self._iterator = self._chain_iterator(iterables or _iterables)
+ self._owned_iterators = (
+ iterable
+ for iterable in iterables
+ if isinstance(iterable, AsyncIterator) and hasattr(iterable, "aclose")
+ )
- @staticmethod
- async def from_iterable(iterable: AnyIterable[AnyIterable[T]]) -> AsyncIterator[T]:
+ @classmethod
+ def from_iterable(cls, iterable: AnyIterable[AnyIterable[T]]) -> "chain[T]":
"""
Alternate constructor for :py:func:`~.chain` that lazily exhausts
- iterables as well
+ the ``iterable`` of iterables as well
+
+ This is suitable for chaining iterables from a lazy or infinite ``iterable``.
+ In turn, closing the ``chain`` only closes those iterables
+ already fetched from ``iterable``.
"""
- async with ScopedIter(iterable) as iterables:
- async for sub_iterable in iterables:
- async with ScopedIter(sub_iterable) as iterator:
- async for item in iterator:
- yield item
+ return cls(_iterables=iterable)
def __anext__(self) -> Awaitable[T]:
- return self._impl.__anext__()
+ return self._iterator.__anext__()
+
+ async def aclose(self) -> None:
+ for iterable in self._owned_iterators:
+ if hasattr(iterable, "aclose"):
+ await iterable.aclose()
+ await self._iterator.aclose()
async def compress(
diff --git a/pyproject.toml b/pyproject.toml
index 1b46000..92cb0aa 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -43,8 +43,11 @@ doc = ["sphinx", "sphinxcontrib-trio"]
Documentation = "https://asyncstdlib.readthedocs.io/en/latest/"
Source = "https://github.com/maxfischer2781/asyncstdlib"
+[tool.flit.sdist]
+include = ["unittests"]
+
[tool.mypy]
-files = ["asyncstdlib/*.py"]
+files = ["asyncstdlib", "typetests"]
check_untyped_defs = true
no_implicit_optional = true
warn_redundant_casts = true
@@ -59,3 +62,8 @@ disallow_untyped_decorators = true
warn_return_any = true
no_implicit_reexport = true
strict_equality = true
+
+[tool.pytest.ini_options]
+testpaths = [
+ "unittests",
+]
|
maxfischer2781/asyncstdlib
|
ae606a9c117b063f842606087deedfc527483820
|
diff --git a/typetests/README.rst b/typetests/README.rst
new file mode 100644
index 0000000..361fa3e
--- /dev/null
+++ b/typetests/README.rst
@@ -0,0 +1,37 @@
+=================
+MyPy Type Testing
+=================
+
+This suite contains *type* tests for ``asyncstdlib``.
+These tests follow similar conventions to unittests but are checked by MyPy.
+
+Test Files
+==========
+
+Tests MUST be organised into files, with similar tests grouped together.
+Each test file SHOULD be called as per the pattern ``type_<scope>.py``,
+where ``<scope>`` describes what the tests cover;
+for example, ``test_functools.py`` type-tests the ``functools`` package.
+
+An individual test is a function, method or class and SHOULD be named
+with a `test_` or `Test` prefix for functions/methods or classes, respectively.
+A class SHOULD be considered a test if it contains any tests.
+Tests MUST contain statements to be type-checked:
+- plain statements required to be type consistent,
+ such as passing parameters of expected correct type to a function.
+- assertions about types and exhaustiveness,
+ using `typing.assert_type` or `typing.assert_never`.
+- statements required to be type inconsistent with an expected type error,
+ such as passing parameters of wrong type with `# type: ignore[arg-type]`.
+
+Test files MAY contain non-test functions, methods or classes for use inside tests.
+These SHOULD be type-consistent and not require any type assertions or expected errors.
+
+Test Execution
+==============
+
+Tests MUST be checked by MyPy using
+the ``warn_unused_ignores`` configuration or ``--warn-unused-ignores`` command line
+option.
+This is required for negative type consistency checks,
+i.e. using expected type errors such as ``# type: ignore[arg-type]``.
diff --git a/typetests/test_functools.py b/typetests/test_functools.py
new file mode 100644
index 0000000..361971e
--- /dev/null
+++ b/typetests/test_functools.py
@@ -0,0 +1,23 @@
+from asyncstdlib import lru_cache
+
+
+@lru_cache()
+async def lru_function(a: int) -> int:
+ return a
+
+
+async def test_cache_parameters() -> None:
+ await lru_function(12)
+ await lru_function("wrong parameter type") # type: ignore[arg-type]
+
+
+class TestLRUMethod:
+ """
+ Test that `lru_cache` works on methods
+ """
+ @lru_cache()
+ async def cached(self) -> int:
+ return 1
+
+ async def test_implicit_self(self) -> int:
+ return await self.cached()
diff --git a/unittests/test_functools.py b/unittests/test_functools.py
index 9d13530..6e6e7dc 100644
--- a/unittests/test_functools.py
+++ b/unittests/test_functools.py
@@ -203,6 +203,32 @@ async def test_lru_cache_typed():
assert pingpong.cache_info().hits == (val + 1) * 2
+@sync
+async def test_lru_cache_method():
+ """
+ Test that the lru_cache can be used on methods
+ """
+
+ class SelfCached:
+ def __init__(self, ident: int):
+ self.ident = ident
+
+ @a.lru_cache()
+ async def pingpong(self, arg):
+ # return identifier of instance to separate cache entries per instance
+ return arg, self.ident
+
+ for iteration in range(4):
+ instance = SelfCached(iteration)
+ for val in range(20):
+ # 1 read initializes, 2 reads hit
+ assert await instance.pingpong(val) == (val, iteration)
+ assert await instance.pingpong(float(val)) == (val, iteration)
+ assert await instance.pingpong(val) == (val, iteration)
+ assert instance.pingpong.cache_info().misses == val + 1 + 20 * iteration
+ assert instance.pingpong.cache_info().hits == (val + 1 + 20 * iteration) * 2
+
+
@sync
async def test_lru_cache_bare():
@a.lru_cache
diff --git a/unittests/test_itertools.py b/unittests/test_itertools.py
index a4d3984..43ce466 100644
--- a/unittests/test_itertools.py
+++ b/unittests/test_itertools.py
@@ -87,6 +87,57 @@ async def test_chain(iterables):
)
+class ACloseFacade:
+ """Wrapper to check if an iterator has been closed"""
+
+ def __init__(self, iterable):
+ self.closed = False
+ self.__wrapped__ = iterable
+ self._iterator = a.iter(iterable)
+
+ async def __anext__(self):
+ if self.closed:
+ raise StopAsyncIteration()
+ return await self._iterator.__anext__()
+
+ def __aiter__(self):
+ return self
+
+ async def aclose(self):
+ if hasattr(self._iterator, "aclose"):
+ await self._iterator.aclose()
+ self.closed = True
+
+
[email protected]("iterables", chains)
+@sync
+async def test_chain_close_auto(iterables):
+ """Test that `chain` closes exhausted iterators"""
+ closeable_iterables = [ACloseFacade(iterable) for iterable in iterables]
+ assert await a.list(a.chain(*closeable_iterables)) == list(
+ itertools.chain(*iterables)
+ )
+ assert all(iterable.closed for iterable in closeable_iterables)
+
+
+# insert a known filled iterable since chain closes all that are exhausted
[email protected]("iterables", [([1], *chain) for chain in chains])
[email protected](
+ "chain_type, must_close",
+ [(lambda iterators: a.chain(*iterators), True), (a.chain.from_iterable, False)],
+)
+@sync
+async def test_chain_close_partial(iterables, chain_type, must_close):
+ """Test that `chain` closes owned iterators"""
+ closeable_iterables = [ACloseFacade(iterable) for iterable in iterables]
+ chain = chain_type(closeable_iterables)
+ assert await a.anext(chain) == next(itertools.chain(*iterables))
+ await chain.aclose()
+ assert all(iterable.closed == must_close for iterable in closeable_iterables[1:])
+ # closed chain must remain closed regardless of iterators
+ assert await a.anext(chain, "sentinel") == "sentinel"
+
+
compress_cases = [
(range(20), [idx % 2 for idx in range(20)]),
([1] * 5, [True, True, False, True, True]),
|
alru_cache decorator on a class method causes mypy error: Missing positional argument "self"
Thank you for the amazing project.
I'm trying to apply `alru_cache` on a class method, but mypy raises an error and a note:
```
error: Missing positional argument "self" in call to "f" of "X" [call-arg]
note: "__call__" is considered instance variable, to make it class variable use ClassVar[...]
```
below is the reproducible example tested with mypy 1.1.1 and asyncstdlib 3.10.5
``` python
from asyncstdlib.functools import lru_cache as alru_cache
class X:
@alru_cache()
async def f(self) -> int:
return 1
async def g(self) -> int:
return await self.f()
```
|
0.0
|
ae606a9c117b063f842606087deedfc527483820
|
[
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables0]",
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables1]",
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables2]"
] |
[
"unittests/test_functools.py::test_cached_property",
"unittests/test_functools.py::test_cache_property_nodict",
"unittests/test_functools.py::test_cache_property_order",
"unittests/test_functools.py::test_reduce",
"unittests/test_functools.py::test_reduce_misuse",
"unittests/test_functools.py::test_lru_cache_bounded",
"unittests/test_functools.py::test_lru_cache_unbounded",
"unittests/test_functools.py::test_lru_cache_empty",
"unittests/test_functools.py::test_lru_cache_typed",
"unittests/test_functools.py::test_lru_cache_method",
"unittests/test_functools.py::test_lru_cache_bare",
"unittests/test_functools.py::test_lru_cache_misuse",
"unittests/test_functools.py::test_lru_cache_concurrent[16]",
"unittests/test_functools.py::test_lru_cache_concurrent[None]",
"unittests/test_functools.py::test_cache",
"unittests/test_functools.py::test_caches_metadata[cache-None]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-None]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-0]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-1]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-256]",
"unittests/test_itertools.py::test_accumulate",
"unittests/test_itertools.py::test_accumulate_default",
"unittests/test_itertools.py::test_accumulate_misuse",
"unittests/test_itertools.py::test_cycle",
"unittests/test_itertools.py::test_chain[iterables0]",
"unittests/test_itertools.py::test_chain[iterables1]",
"unittests/test_itertools.py::test_chain[iterables2]",
"unittests/test_itertools.py::test_chain_close_auto[iterables0]",
"unittests/test_itertools.py::test_chain_close_auto[iterables1]",
"unittests/test_itertools.py::test_chain_close_auto[iterables2]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables0]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables1]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables2]",
"unittests/test_itertools.py::test_compress[data0-selectors0]",
"unittests/test_itertools.py::test_compress[data1-selectors1]",
"unittests/test_itertools.py::test_compress[data2-selectors2]",
"unittests/test_itertools.py::test_compress[data3-selectors3]",
"unittests/test_itertools.py::test_dropwhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_islice[slicing0-iterable0]",
"unittests/test_itertools.py::test_islice[slicing0-iterable1]",
"unittests/test_itertools.py::test_islice[slicing0-iterable2]",
"unittests/test_itertools.py::test_islice[slicing0-iterable3]",
"unittests/test_itertools.py::test_islice[slicing1-iterable0]",
"unittests/test_itertools.py::test_islice[slicing1-iterable1]",
"unittests/test_itertools.py::test_islice[slicing1-iterable2]",
"unittests/test_itertools.py::test_islice[slicing1-iterable3]",
"unittests/test_itertools.py::test_islice[slicing2-iterable0]",
"unittests/test_itertools.py::test_islice[slicing2-iterable1]",
"unittests/test_itertools.py::test_islice[slicing2-iterable2]",
"unittests/test_itertools.py::test_islice[slicing2-iterable3]",
"unittests/test_itertools.py::test_islice[slicing3-iterable0]",
"unittests/test_itertools.py::test_islice[slicing3-iterable1]",
"unittests/test_itertools.py::test_islice[slicing3-iterable2]",
"unittests/test_itertools.py::test_islice[slicing3-iterable3]",
"unittests/test_itertools.py::test_islice[slicing4-iterable0]",
"unittests/test_itertools.py::test_islice[slicing4-iterable1]",
"unittests/test_itertools.py::test_islice[slicing4-iterable2]",
"unittests/test_itertools.py::test_islice[slicing4-iterable3]",
"unittests/test_itertools.py::test_islice[slicing5-iterable0]",
"unittests/test_itertools.py::test_islice[slicing5-iterable1]",
"unittests/test_itertools.py::test_islice[slicing5-iterable2]",
"unittests/test_itertools.py::test_islice[slicing5-iterable3]",
"unittests/test_itertools.py::test_islice[slicing6-iterable0]",
"unittests/test_itertools.py::test_islice[slicing6-iterable1]",
"unittests/test_itertools.py::test_islice[slicing6-iterable2]",
"unittests/test_itertools.py::test_islice[slicing6-iterable3]",
"unittests/test_itertools.py::test_islice_exact[slicing0]",
"unittests/test_itertools.py::test_islice_exact[slicing1]",
"unittests/test_itertools.py::test_islice_exact[slicing2]",
"unittests/test_itertools.py::test_islice_exact[slicing3]",
"unittests/test_itertools.py::test_islice_exact[slicing4]",
"unittests/test_itertools.py::test_islice_scoped_iter",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable0]",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable1]",
"unittests/test_itertools.py::test_tee",
"unittests/test_itertools.py::test_tee_concurrent_locked",
"unittests/test_itertools.py::test_tee_concurrent_unlocked",
"unittests/test_itertools.py::test_pairwise",
"unittests/test_itertools.py::test_zip_longest",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable4]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable4]"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-21 16:35:05+00:00
|
mit
| 3,821 |
|
maxfischer2781__asyncstdlib-108
|
diff --git a/asyncstdlib/itertools.py b/asyncstdlib/itertools.py
index fc12573..f6f06ee 100644
--- a/asyncstdlib/itertools.py
+++ b/asyncstdlib/itertools.py
@@ -148,33 +148,54 @@ class chain(AsyncIterator[T]):
The resulting iterator consecutively iterates over and yields all values from
each of the ``iterables``. This is similar to converting all ``iterables`` to
sequences and concatenating them, but lazily exhausts each iterable.
+
+ The ``chain`` assumes ownership of its ``iterables`` and closes them reliably
+ when the ``chain`` is closed. Pass the ``iterables`` via a :py:class:`tuple` to
+ ``chain.from_iterable`` to avoid closing all iterables but those already processed.
"""
- __slots__ = ("_impl",)
+ __slots__ = ("_iterator", "_owned_iterators")
- def __init__(self, *iterables: AnyIterable[T]):
- async def impl() -> AsyncIterator[T]:
- for iterable in iterables:
+ @staticmethod
+ async def _chain_iterator(
+ any_iterables: AnyIterable[AnyIterable[T]],
+ ) -> AsyncGenerator[T, None]:
+ async with ScopedIter(any_iterables) as iterables:
+ async for iterable in iterables:
async with ScopedIter(iterable) as iterator:
async for item in iterator:
yield item
- self._impl = impl()
+ def __init__(
+ self, *iterables: AnyIterable[T], _iterables: AnyIterable[AnyIterable[T]] = ()
+ ):
+ self._iterator = self._chain_iterator(iterables or _iterables)
+ self._owned_iterators = (
+ iterable
+ for iterable in iterables
+ if isinstance(iterable, AsyncIterator) and hasattr(iterable, "aclose")
+ )
- @staticmethod
- async def from_iterable(iterable: AnyIterable[AnyIterable[T]]) -> AsyncIterator[T]:
+ @classmethod
+ def from_iterable(cls, iterable: AnyIterable[AnyIterable[T]]) -> "chain[T]":
"""
Alternate constructor for :py:func:`~.chain` that lazily exhausts
- iterables as well
+ the ``iterable`` of iterables as well
+
+ This is suitable for chaining iterables from a lazy or infinite ``iterable``.
+ In turn, closing the ``chain`` only closes those iterables
+ already fetched from ``iterable``.
"""
- async with ScopedIter(iterable) as iterables:
- async for sub_iterable in iterables:
- async with ScopedIter(sub_iterable) as iterator:
- async for item in iterator:
- yield item
+ return cls(_iterables=iterable)
def __anext__(self) -> Awaitable[T]:
- return self._impl.__anext__()
+ return self._iterator.__anext__()
+
+ async def aclose(self) -> None:
+ for iterable in self._owned_iterators:
+ if hasattr(iterable, "aclose"):
+ await iterable.aclose()
+ await self._iterator.aclose()
async def compress(
|
maxfischer2781/asyncstdlib
|
d20a48b35e6fd5d360c6a84b53e696684ecb5d98
|
diff --git a/unittests/test_itertools.py b/unittests/test_itertools.py
index a4d3984..43ce466 100644
--- a/unittests/test_itertools.py
+++ b/unittests/test_itertools.py
@@ -87,6 +87,57 @@ async def test_chain(iterables):
)
+class ACloseFacade:
+ """Wrapper to check if an iterator has been closed"""
+
+ def __init__(self, iterable):
+ self.closed = False
+ self.__wrapped__ = iterable
+ self._iterator = a.iter(iterable)
+
+ async def __anext__(self):
+ if self.closed:
+ raise StopAsyncIteration()
+ return await self._iterator.__anext__()
+
+ def __aiter__(self):
+ return self
+
+ async def aclose(self):
+ if hasattr(self._iterator, "aclose"):
+ await self._iterator.aclose()
+ self.closed = True
+
+
[email protected]("iterables", chains)
+@sync
+async def test_chain_close_auto(iterables):
+ """Test that `chain` closes exhausted iterators"""
+ closeable_iterables = [ACloseFacade(iterable) for iterable in iterables]
+ assert await a.list(a.chain(*closeable_iterables)) == list(
+ itertools.chain(*iterables)
+ )
+ assert all(iterable.closed for iterable in closeable_iterables)
+
+
+# insert a known filled iterable since chain closes all that are exhausted
[email protected]("iterables", [([1], *chain) for chain in chains])
[email protected](
+ "chain_type, must_close",
+ [(lambda iterators: a.chain(*iterators), True), (a.chain.from_iterable, False)],
+)
+@sync
+async def test_chain_close_partial(iterables, chain_type, must_close):
+ """Test that `chain` closes owned iterators"""
+ closeable_iterables = [ACloseFacade(iterable) for iterable in iterables]
+ chain = chain_type(closeable_iterables)
+ assert await a.anext(chain) == next(itertools.chain(*iterables))
+ await chain.aclose()
+ assert all(iterable.closed == must_close for iterable in closeable_iterables[1:])
+ # closed chain must remain closed regardless of iterators
+ assert await a.anext(chain, "sentinel") == "sentinel"
+
+
compress_cases = [
(range(20), [idx % 2 for idx in range(20)]),
([1] * 5, [True, True, False, True, True]),
|
Change in behavior of chain() between 3.10.5 and 3.10.6.
There is a subtle change in behavior introduced in the recent changes to `chain()`. Chain's iterator appears to be escaping from its "scope" when it is interrupted.
Here is an example program that produces different output. I'm using Python 3.11.2, but I don't think the Python version makes much difference.
```python
import asyncio
import asyncstdlib as asl
async def gen1(*args):
try:
for i in args:
yield i
finally:
print("FINALLY")
async def main():
nums = asl.chain(gen1(1, 2, 3))
nums = asl.takewhile(lambda x: x != 2, nums)
async for n in nums:
print(n)
print("ALL DONE")
asyncio.run(main())
```
## asyncstdlib 3.10.5 (correct output)
```
1
FINALLY
ALL DONE
```
## asyncstdlib 3.10.6 (incorrect output)
```
1
ALL DONE
FINALLY
```
|
0.0
|
d20a48b35e6fd5d360c6a84b53e696684ecb5d98
|
[
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables0]",
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables1]",
"unittests/test_itertools.py::test_chain_close_partial[<lambda>-True-iterables2]"
] |
[
"unittests/test_itertools.py::test_accumulate",
"unittests/test_itertools.py::test_accumulate_default",
"unittests/test_itertools.py::test_accumulate_misuse",
"unittests/test_itertools.py::test_cycle",
"unittests/test_itertools.py::test_chain[iterables0]",
"unittests/test_itertools.py::test_chain[iterables1]",
"unittests/test_itertools.py::test_chain[iterables2]",
"unittests/test_itertools.py::test_chain_close_auto[iterables0]",
"unittests/test_itertools.py::test_chain_close_auto[iterables1]",
"unittests/test_itertools.py::test_chain_close_auto[iterables2]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables0]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables1]",
"unittests/test_itertools.py::test_chain_close_partial[from_iterable-False-iterables2]",
"unittests/test_itertools.py::test_compress[data0-selectors0]",
"unittests/test_itertools.py::test_compress[data1-selectors1]",
"unittests/test_itertools.py::test_compress[data2-selectors2]",
"unittests/test_itertools.py::test_compress[data3-selectors3]",
"unittests/test_itertools.py::test_dropwhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_islice[slicing0-iterable0]",
"unittests/test_itertools.py::test_islice[slicing0-iterable1]",
"unittests/test_itertools.py::test_islice[slicing0-iterable2]",
"unittests/test_itertools.py::test_islice[slicing0-iterable3]",
"unittests/test_itertools.py::test_islice[slicing1-iterable0]",
"unittests/test_itertools.py::test_islice[slicing1-iterable1]",
"unittests/test_itertools.py::test_islice[slicing1-iterable2]",
"unittests/test_itertools.py::test_islice[slicing1-iterable3]",
"unittests/test_itertools.py::test_islice[slicing2-iterable0]",
"unittests/test_itertools.py::test_islice[slicing2-iterable1]",
"unittests/test_itertools.py::test_islice[slicing2-iterable2]",
"unittests/test_itertools.py::test_islice[slicing2-iterable3]",
"unittests/test_itertools.py::test_islice[slicing3-iterable0]",
"unittests/test_itertools.py::test_islice[slicing3-iterable1]",
"unittests/test_itertools.py::test_islice[slicing3-iterable2]",
"unittests/test_itertools.py::test_islice[slicing3-iterable3]",
"unittests/test_itertools.py::test_islice[slicing4-iterable0]",
"unittests/test_itertools.py::test_islice[slicing4-iterable1]",
"unittests/test_itertools.py::test_islice[slicing4-iterable2]",
"unittests/test_itertools.py::test_islice[slicing4-iterable3]",
"unittests/test_itertools.py::test_islice[slicing5-iterable0]",
"unittests/test_itertools.py::test_islice[slicing5-iterable1]",
"unittests/test_itertools.py::test_islice[slicing5-iterable2]",
"unittests/test_itertools.py::test_islice[slicing5-iterable3]",
"unittests/test_itertools.py::test_islice[slicing6-iterable0]",
"unittests/test_itertools.py::test_islice[slicing6-iterable1]",
"unittests/test_itertools.py::test_islice[slicing6-iterable2]",
"unittests/test_itertools.py::test_islice[slicing6-iterable3]",
"unittests/test_itertools.py::test_islice_exact[slicing0]",
"unittests/test_itertools.py::test_islice_exact[slicing1]",
"unittests/test_itertools.py::test_islice_exact[slicing2]",
"unittests/test_itertools.py::test_islice_exact[slicing3]",
"unittests/test_itertools.py::test_islice_exact[slicing4]",
"unittests/test_itertools.py::test_islice_scoped_iter",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable0]",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable1]",
"unittests/test_itertools.py::test_tee",
"unittests/test_itertools.py::test_tee_concurrent_locked",
"unittests/test_itertools.py::test_tee_concurrent_unlocked",
"unittests/test_itertools.py::test_pairwise",
"unittests/test_itertools.py::test_zip_longest",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable4]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable4]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-04-12 13:46:48+00:00
|
mit
| 3,822 |
|
maxfischer2781__asyncstdlib-12
|
diff --git a/asyncstdlib/itertools.py b/asyncstdlib/itertools.py
index b299840..dfdfd7f 100644
--- a/asyncstdlib/itertools.py
+++ b/asyncstdlib/itertools.py
@@ -199,22 +199,26 @@ async def islice(iterable: AnyIterable[T], *args: Optional[int]) -> AsyncIterato
s = slice(*args)
start, stop, step = s.start or 0, s.stop, s.step or 1
async with ScopedIter(iterable) as async_iter:
- # always consume the first ``start - 1`` items, even if the slice is empty
+ # always consume the first ``start`` items, even if the slice is empty
if start > 0:
async for _count, element in aenumerate(_borrow(async_iter), start=1):
if _count == start:
break
if stop is None:
async for idx, element in aenumerate(async_iter, start=0):
- if idx % step == 0:
+ if not idx % step:
yield element
+ elif stop <= start:
+ return
else:
- stop -= start
+ # We would actually check ``idx >= stop -1`` later on.
+ # Since we do that for every ``idx``, we subtract ``1`` once here.
+ stop -= start + 1
async for idx, element in aenumerate(async_iter, start=0):
- if idx >= stop:
- return
if not idx % step:
yield element
+ if idx >= stop:
+ return
async def starmap(
|
maxfischer2781/asyncstdlib
|
7d45d075877433a2effb0b3aa9ec949816b892ac
|
diff --git a/unittests/test_itertools.py b/unittests/test_itertools.py
index 21b1e8f..7585524 100644
--- a/unittests/test_itertools.py
+++ b/unittests/test_itertools.py
@@ -150,6 +150,28 @@ async def test_islice(iterable, slicing):
assert await a.list(a.islice(asyncify(iterable), *slicing)) == expected
+async def ayield_exactly(count: int):
+ for item in range(count):
+ yield item
+ assert False, "Too many `anext` items requested"
+
+
+@sync
[email protected](
+ "slicing", ((0,), (5,), (0, 20, 3), (5, 0, 1), (3, 50, 4)),
+)
+async def test_islice_exact(slicing):
+ """`isclice` consumes exactly as many items as needed"""
+ boundary = slice(*slicing) if len(slicing) > 1 else slice(0, slicing[0])
+ expected = list(range(boundary.stop)[boundary])
+ assert (
+ await a.list(
+ a.islice(ayield_exactly(max(boundary.start, boundary.stop)), *slicing)
+ )
+ == expected
+ )
+
+
starmap_cases = [
(lambda x, y: x + y, [(1, 2), (3, 4)]),
(lambda *args: sum(args), [range(i) for i in range(1, 10)]),
|
islice consumes too many items
The ``stop`` condition of ``islice`` is evaluated by *peeking* at the next item, then discarding it:
https://github.com/maxfischer2781/asyncstdlib/blob/7d45d075877433a2effb0b3aa9ec949816b892ac/asyncstdlib/itertools.py#L213-L217
This results in two undesirable behaviours:
- if the next item is available, it is discarded. Consecutive use of ``islice`` drops items.
- if the next item is not available, ``isclice`` blocks indefinitely.
|
0.0
|
7d45d075877433a2effb0b3aa9ec949816b892ac
|
[
"unittests/test_itertools.py::test_islice_exact[slicing0]",
"unittests/test_itertools.py::test_islice_exact[slicing1]",
"unittests/test_itertools.py::test_islice_exact[slicing2]",
"unittests/test_itertools.py::test_islice_exact[slicing3]",
"unittests/test_itertools.py::test_islice_exact[slicing4]"
] |
[
"unittests/test_itertools.py::test_accumulate",
"unittests/test_itertools.py::test_accumulate_default",
"unittests/test_itertools.py::test_accumulate_misuse",
"unittests/test_itertools.py::test_cycle",
"unittests/test_itertools.py::test_chain[iterables0]",
"unittests/test_itertools.py::test_chain[iterables1]",
"unittests/test_itertools.py::test_chain[iterables2]",
"unittests/test_itertools.py::test_compress[data0-selectors0]",
"unittests/test_itertools.py::test_compress[data1-selectors1]",
"unittests/test_itertools.py::test_compress[data2-selectors2]",
"unittests/test_itertools.py::test_compress[data3-selectors3]",
"unittests/test_itertools.py::test_dropwhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_islice[slicing0-iterable0]",
"unittests/test_itertools.py::test_islice[slicing0-iterable1]",
"unittests/test_itertools.py::test_islice[slicing0-iterable2]",
"unittests/test_itertools.py::test_islice[slicing0-iterable3]",
"unittests/test_itertools.py::test_islice[slicing1-iterable0]",
"unittests/test_itertools.py::test_islice[slicing1-iterable1]",
"unittests/test_itertools.py::test_islice[slicing1-iterable2]",
"unittests/test_itertools.py::test_islice[slicing1-iterable3]",
"unittests/test_itertools.py::test_islice[slicing2-iterable0]",
"unittests/test_itertools.py::test_islice[slicing2-iterable1]",
"unittests/test_itertools.py::test_islice[slicing2-iterable2]",
"unittests/test_itertools.py::test_islice[slicing2-iterable3]",
"unittests/test_itertools.py::test_islice[slicing3-iterable0]",
"unittests/test_itertools.py::test_islice[slicing3-iterable1]",
"unittests/test_itertools.py::test_islice[slicing3-iterable2]",
"unittests/test_itertools.py::test_islice[slicing3-iterable3]",
"unittests/test_itertools.py::test_islice[slicing4-iterable0]",
"unittests/test_itertools.py::test_islice[slicing4-iterable1]",
"unittests/test_itertools.py::test_islice[slicing4-iterable2]",
"unittests/test_itertools.py::test_islice[slicing4-iterable3]",
"unittests/test_itertools.py::test_islice[slicing5-iterable0]",
"unittests/test_itertools.py::test_islice[slicing5-iterable1]",
"unittests/test_itertools.py::test_islice[slicing5-iterable2]",
"unittests/test_itertools.py::test_islice[slicing5-iterable3]",
"unittests/test_itertools.py::test_islice[slicing6-iterable0]",
"unittests/test_itertools.py::test_islice[slicing6-iterable1]",
"unittests/test_itertools.py::test_islice[slicing6-iterable2]",
"unittests/test_itertools.py::test_islice[slicing6-iterable3]",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable0]",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable1]",
"unittests/test_itertools.py::test_tee",
"unittests/test_itertools.py::test_zip_longest",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable4]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable4]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-06-07 10:06:34+00:00
|
mit
| 3,823 |
|
maxfischer2781__asyncstdlib-14
|
diff --git a/asyncstdlib/asynctools.py b/asyncstdlib/asynctools.py
index 8b7682d..4de42f8 100644
--- a/asyncstdlib/asynctools.py
+++ b/asyncstdlib/asynctools.py
@@ -26,7 +26,7 @@ class AsyncIteratorBorrow(AsyncGenerator[T, S]):
# iterator.__aiter__ is likely to return iterator (e.g. for async def: yield)
# We wrap it in a separate async iterator/generator to hide its __aiter__.
try:
- wrapped_iterator: AsyncIterator[T, S] = self._wrapped_iterator(iterator)
+ wrapped_iterator: AsyncGenerator[T, S] = self._wrapped_iterator(iterator)
self.__anext__ = iterator.__anext__ # argument must be an async iterable!
except (AttributeError, TypeError):
raise TypeError(
@@ -48,7 +48,7 @@ class AsyncIteratorBorrow(AsyncGenerator[T, S]):
@staticmethod
async def _wrapped_iterator(
iterator: Union[AsyncIterator[T], AsyncGenerator[T, S]]
- ) -> AsyncIterator[T]:
+ ) -> AsyncGenerator[T, S]:
async for item in iterator:
yield item
@@ -58,20 +58,34 @@ class AsyncIteratorBorrow(AsyncGenerator[T, S]):
)
async def aclose(self):
- pass
+ wrapper_iterator = self.__aiter__()
+ # allow closing the intermediate wrapper
+ # this prevents a resource warning if the wrapper is GC'd
+ # the underlying iterator is NOT affected by this
+ await wrapper_iterator.aclose()
+ # disable direct asend/athrow to the underlying iterator
+ if hasattr(self, "asend"):
+ self.asend = wrapper_iterator.asend
+ if hasattr(self, "athrow"):
+ self.athrow = wrapper_iterator.athrow
class AsyncIteratorContext(AsyncContextManager[AsyncIterator[T]]):
- __slots__ = "__wrapped__", "_iterator"
+ __slots__ = "_borrowed_iter", "_iterator"
def __init__(self, iterable: AnyIterable[T]):
self._iterator: AsyncIterator[T] = aiter(iterable)
+ self._borrowed_iter = None
async def __aenter__(self) -> AsyncIterator[T]:
- return AsyncIteratorBorrow(self._iterator)
+ if self._borrowed_iter is not None:
+ raise RuntimeError("scoped_iter is not re-entrant")
+ borrowed_iter = self._borrowed_iter = AsyncIteratorBorrow(self._iterator)
+ return borrowed_iter
async def __aexit__(self, exc_type, exc_val, exc_tb):
+ await self._borrowed_iter.aclose()
await self._iterator.aclose()
return False
@@ -91,7 +105,8 @@ def borrow(iterator: AsyncIterator[T]) -> AsyncIteratorBorrow[T, None]:
:py:meth:`~agen.athrow` if the underlying iterator supports them as well;
this allows borrowing either an :py:class:`~collections.abc.AsyncIterator`
or :py:class:`~collections.abc.AsyncGenerator`. Regardless of iterator type,
- :py:meth:`~agen.aclose` is always provided and does nothing.
+ :py:meth:`~agen.aclose` is always provided; it closes only the borrowed
+ iterator, not the underlying iterator.
.. seealso:: Use :py:func:`~.scoped_iter` to ensure an (async) iterable
is eventually closed and only :term:`borrowed <borrowing>` until then.
|
maxfischer2781/asyncstdlib
|
1850256467dc3fca67b9139011c56fd3fae69938
|
diff --git a/unittests/test_asynctools.py b/unittests/test_asynctools.py
index 89f2be5..8bc3b3e 100644
--- a/unittests/test_asynctools.py
+++ b/unittests/test_asynctools.py
@@ -13,8 +13,6 @@ async def test_nested_lifetime():
values.append(await a.anext(a1))
async with a.scoped_iter(a1) as a2:
values.append(await a.anext(a2))
- print(a2)
- print(a1)
# original iterator is not closed by inner scope
async for value in a1:
values.append(value)
@@ -59,6 +57,48 @@ async def test_borrow_iterable():
assert values == [0, 1]
+class Closeable:
+ def __init__(self, iterator):
+ self.iterator = iterator
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ return await a.anext(self.iterator)
+
+ async def aclose(self):
+ await self.iterator.aclose()
+
+
[email protected](
+ "async_iterable_t",
+ [
+ lambda: asyncify(range(10)),
+ lambda: Closeable(asyncify(range(10))),
+ lambda: Uncloseable(asyncify(range(10))),
+ ],
+)
+@sync
+async def test_borrow_methods(async_iterable_t):
+ async_iterable = async_iterable_t()
+ values = []
+ async with a.scoped_iter(async_iterable) as a1:
+ values.append(await a.anext(a1))
+ assert hasattr(a1, "athrow") == hasattr(async_iterable, "athrow")
+ assert hasattr(a1, "asend") == hasattr(async_iterable, "asend")
+ assert values == [0]
+
+
+@sync
+async def test_scoped_iter_misuse():
+ scoped_iter = a.scoped_iter(asyncify(range(5)))
+ async with scoped_iter:
+ with pytest.raises(RuntimeError):
+ async with scoped_iter:
+ pytest.fail("may not enter scoped_iter twice")
+
+
@sync
async def test_borrow_misuse():
with pytest.raises(TypeError):
|
Intermediate iterators not cleaned up
The ``AsyncIteratorBorrow`` helper creates a wrapper async generator to prevent its underlying iterable from cleanup. The wrapper is never ``aclose``d, which may lead to a resource warning on certain versions of Python.
This has no functional effect, but leads to misleading warnings.
See https://stackoverflow.com/questions/62684213/asyncio-task-was-destroyed-but-it-is-pending
|
0.0
|
1850256467dc3fca67b9139011c56fd3fae69938
|
[
"unittests/test_asynctools.py::test_scoped_iter_misuse"
] |
[
"unittests/test_asynctools.py::test_nested_lifetime",
"unittests/test_asynctools.py::test_borrow_explicitly",
"unittests/test_asynctools.py::test_borrow_iterable",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>0]",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>1]",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>2]",
"unittests/test_asynctools.py::test_borrow_misuse"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-01 22:11:19+00:00
|
mit
| 3,824 |
|
maxfischer2781__asyncstdlib-24
|
diff --git a/asyncstdlib/builtins.py b/asyncstdlib/builtins.py
index 4091b8c..06eb44e 100644
--- a/asyncstdlib/builtins.py
+++ b/asyncstdlib/builtins.py
@@ -134,10 +134,12 @@ async def any(iterable: AnyIterable[T]) -> bool:
return False
-async def zip(*iterables: AnyIterable[T]) -> AsyncIterator[Tuple[T, ...]]:
+async def zip(*iterables: AnyIterable[T], strict=False) -> AsyncIterator[Tuple[T, ...]]:
"""
Create an async iterator that aggregates elements from each of the (async) iterables
+ :raises ValueError: if the ``iterables`` are not equal length and ``strict`` is set
+
The next element of ``zip`` is a :py:class:`tuple` of the next element of
each of its ``iterables``. As soon as any of its ``iterables`` is exhausted,
``zip`` is exhausted as well. This means that if ``zip`` receives *n* ``iterables``,
@@ -151,16 +153,19 @@ async def zip(*iterables: AnyIterable[T]) -> AsyncIterator[Tuple[T, ...]]:
If ``iterables`` is empty, the ``zip`` iterator is empty as well.
Multiple ``iterables`` may be mixed regular and async iterables.
+
+ When called with ``strict=True``, all ``iterables`` must be of same length;
+ in this mode ``zip`` raises :py:exc:`ValueError` if any ``iterables`` are not
+ exhausted with the others.
"""
if not iterables:
return
aiters = (*(aiter(it) for it in iterables),)
del iterables
try:
- while True:
- yield (*[await anext(it) for it in aiters],)
- except StopAsyncIteration:
- return
+ inner = _zip_inner(aiters) if not strict else _zip_inner_strict(aiters)
+ async for items in inner:
+ yield items
finally:
for iterator in aiters:
try:
@@ -171,6 +176,40 @@ async def zip(*iterables: AnyIterable[T]) -> AsyncIterator[Tuple[T, ...]]:
await aclose
+async def _zip_inner(aiters):
+ try:
+ while True:
+ yield (*[await anext(it) for it in aiters],)
+ except StopAsyncIteration:
+ return
+
+
+async def _zip_inner_strict(aiters):
+ tried = 0
+ try:
+ while True:
+ items = []
+ for tried, _aiter in _sync_builtins.enumerate(aiters): # noqa: B007
+ items.append(await anext(_aiter))
+ yield (*items,)
+ except StopAsyncIteration:
+ # after the first iterable provided an item, some later iterable was empty
+ if tried > 0:
+ plural = " " if tried == 1 else "s 1-"
+ raise ValueError(
+ f"zip() argument {tried+1} is shorter than argument{plural}{tried}"
+ )
+ # after the first iterable was empty, some later iterable may be not
+ sentinel = object()
+ for tried, _aiter in _sync_builtins.enumerate(aiters):
+ if await anext(_aiter, sentinel) is not sentinel:
+ plural = " " if tried == 1 else "s 1-"
+ raise ValueError(
+ f"zip() argument {tried+1} is longer than argument{plural}{tried}"
+ )
+ return
+
+
class SyncVariadic(Protocol[T, R]):
"""Type of a ``def`` function taking any number of arguments"""
diff --git a/docs/source/api/builtins.rst b/docs/source/api/builtins.rst
index 3cfc71b..f4c4c42 100644
--- a/docs/source/api/builtins.rst
+++ b/docs/source/api/builtins.rst
@@ -38,9 +38,13 @@ Iterator transforming
.. autofunction:: filter(function: (T) → (await) bool, iterable: (async) iter T)
:async-for: :T
-.. autofunction:: zip(*iterables: (async) iter T)
+.. autofunction:: zip(*iterables: (async) iter T, strict: bool = True)
:async-for: :(T, ...)
+ .. versionadded:: 3.10.0
+
+ The ``strict`` parameter.
+
.. autofunction:: map(function: (T, ...) → (await) R, iterable: (async) iter T, ...)
:async-for: :R
|
maxfischer2781/asyncstdlib
|
86ac8c5f6949fa1cf5c80d9586cf84a21eb5d092
|
diff --git a/unittests/test_builtins.py b/unittests/test_builtins.py
index 776867e..18ce9c7 100644
--- a/unittests/test_builtins.py
+++ b/unittests/test_builtins.py
@@ -57,6 +57,21 @@ async def test_zip():
assert False
+@sync
+async def test_zip_strict():
+ async for va, vb in a.zip(asyncify(range(5)), range(5), strict=True):
+ assert va == vb
+ with pytest.raises(ValueError):
+ async for _ in a.zip(asyncify(range(5)), range(6), strict=True):
+ pass
+ with pytest.raises(ValueError):
+ async for _ in a.zip(asyncify(range(6)), range(5), strict=True):
+ pass
+ with pytest.raises(ValueError):
+ async for _ in a.zip(*[range(5)] * 6, range(6), strict=True):
+ pass
+
+
@sync
async def test_zip_close_immediately():
closed = False
|
Add zip strict flag
Python 3.10 / [PEP 618](https://www.python.org/dev/peps/pep-0618/) will add a ``strict`` flag to ``zip``. When ``strict=True``, an exception is raised if the iterables are not of the same length.
|
0.0
|
86ac8c5f6949fa1cf5c80d9586cf84a21eb5d092
|
[
"unittests/test_builtins.py::test_zip_strict"
] |
[
"unittests/test_builtins.py::test_iter1",
"unittests/test_builtins.py::test_iter2",
"unittests/test_builtins.py::test_all",
"unittests/test_builtins.py::test_any",
"unittests/test_builtins.py::test_zip",
"unittests/test_builtins.py::test_zip_close_immediately",
"unittests/test_builtins.py::test_map_as",
"unittests/test_builtins.py::test_map_sa",
"unittests/test_builtins.py::test_map_aa",
"unittests/test_builtins.py::test_max_default",
"unittests/test_builtins.py::test_max_sa",
"unittests/test_builtins.py::test_min_default",
"unittests/test_builtins.py::test_min_sa",
"unittests/test_builtins.py::test_filter_as",
"unittests/test_builtins.py::test_filter_sa",
"unittests/test_builtins.py::test_filter_aa",
"unittests/test_builtins.py::test_filter_na",
"unittests/test_builtins.py::test_enumerate",
"unittests/test_builtins.py::test_sum",
"unittests/test_builtins.py::test_types",
"unittests/test_builtins.py::test_sorted_direct[True-sortable0]",
"unittests/test_builtins.py::test_sorted_direct[True-sortable1]",
"unittests/test_builtins.py::test_sorted_direct[True-sortable2]",
"unittests/test_builtins.py::test_sorted_direct[True-sortable3]",
"unittests/test_builtins.py::test_sorted_direct[True-sortable4]",
"unittests/test_builtins.py::test_sorted_direct[True-sortable5]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable0]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable1]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable2]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable3]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable4]",
"unittests/test_builtins.py::test_sorted_direct[False-sortable5]",
"unittests/test_builtins.py::test_sorted_stable"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-17 21:02:24+00:00
|
mit
| 3,825 |
|
maxfischer2781__asyncstdlib-49
|
diff --git a/asyncstdlib/functools.py b/asyncstdlib/functools.py
index 5bd874c..1e33091 100644
--- a/asyncstdlib/functools.py
+++ b/asyncstdlib/functools.py
@@ -116,14 +116,9 @@ class CachedProperty:
return self._get_attribute(instance)
async def _get_attribute(self, instance) -> T:
- attributes = instance.__dict__
- try:
- return attributes[self._name]
- except KeyError:
- value = await self.__wrapped__(instance)
- if self._name not in attributes:
- attributes[self._name] = AwaitableValue(value)
- return value
+ value = await self.__wrapped__(instance)
+ instance.__dict__[self._name] = AwaitableValue(value)
+ return value
cached_property = CachedProperty
|
maxfischer2781/asyncstdlib
|
2b7038d1f3e93c39ef5e6490e3566b79b632febe
|
diff --git a/unittests/test_functools.py b/unittests/test_functools.py
index d8257f5..9d13530 100644
--- a/unittests/test_functools.py
+++ b/unittests/test_functools.py
@@ -35,12 +35,11 @@ async def test_cache_property_nodict():
__slots__ = "a", "b"
def __init__(self, a, b):
- self.a = a
- self.b = b
+ pass # pragma: no cover
@a.cached_property
async def total(self):
- return self.a + self.b
+ pass # pragma: no cover
@multi_sync
@@ -62,7 +61,7 @@ async def test_cache_property_order():
val = Value(0)
await Schedule(check_increment(5), check_increment(12), check_increment(1337))
assert (await val.cached) != 0
- assert (await val.cached) == 5 # first value fetched
+ assert (await val.cached) == 1337 # last value fetched
@sync
|
Check functools.cached_property return value nesting
The handling of the return value in `functools.cached_property` appears to be too deeply/shallowly nested with awaitables. Wrapping of the original method means:
- `__wrapped__` is of type `(Self) -> await T`
- `value = await self.__wrapped__(instance)` is of type `T`
- `attributes[self._name] = AwaitableValue(value)` is of type `await T`
Now here comes the problem: The helper method has two `return` paths, one for `return value` (``... -> T``) and one for `return attributes[self._name]` (``... -> await T``)! It cannot be correct for both paths.
I assume the latter path is dead in the unit-tests, and I'm somewhat sure it cannot ever be reached. Either way, this should be tested and if necessary fixed or cleaned up.
|
0.0
|
2b7038d1f3e93c39ef5e6490e3566b79b632febe
|
[
"unittests/test_functools.py::test_cache_property_order"
] |
[
"unittests/test_functools.py::test_cached_property",
"unittests/test_functools.py::test_cache_property_nodict",
"unittests/test_functools.py::test_reduce",
"unittests/test_functools.py::test_reduce_misuse",
"unittests/test_functools.py::test_lru_cache_bounded",
"unittests/test_functools.py::test_lru_cache_unbounded",
"unittests/test_functools.py::test_lru_cache_empty",
"unittests/test_functools.py::test_lru_cache_typed",
"unittests/test_functools.py::test_lru_cache_bare",
"unittests/test_functools.py::test_lru_cache_misuse",
"unittests/test_functools.py::test_lru_cache_concurrent[16]",
"unittests/test_functools.py::test_lru_cache_concurrent[None]",
"unittests/test_functools.py::test_cache",
"unittests/test_functools.py::test_caches_metadata[cache-None]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-None]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-0]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-1]",
"unittests/test_functools.py::test_caches_metadata[<lambda>-256]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-06-27 12:54:36+00:00
|
mit
| 3,826 |
|
maxfischer2781__asyncstdlib-60
|
diff --git a/asyncstdlib/__init__.py b/asyncstdlib/__init__.py
index f972870..79ac930 100644
--- a/asyncstdlib/__init__.py
+++ b/asyncstdlib/__init__.py
@@ -35,7 +35,7 @@ from .itertools import (
)
from .asynctools import borrow, scoped_iter, await_each, apply, sync
-__version__ = "3.9.2"
+__version__ = "3.10.0"
__all__ = [
"anext",
diff --git a/asyncstdlib/asynctools.py b/asyncstdlib/asynctools.py
index 87b3c02..ee9b98f 100644
--- a/asyncstdlib/asynctools.py
+++ b/asyncstdlib/asynctools.py
@@ -326,7 +326,17 @@ async def apply(
)
+@overload
+def sync(function: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
+ ...
+
+
+@overload
def sync(function: Callable[..., T]) -> Callable[..., Awaitable[T]]:
+ ...
+
+
+def sync(function: Callable) -> Callable[..., Awaitable[T]]:
r"""
Wraps a callable to ensure its result can be ``await``\ ed
@@ -359,12 +369,13 @@ def sync(function: Callable[..., T]) -> Callable[..., Awaitable[T]]:
raise TypeError("function argument should be Callable")
if iscoroutinefunction(function):
- return function # type: ignore
+ return function
@wraps(function)
async def async_wrapped(*args, **kwargs):
result = function(*args, **kwargs)
-
+ if isinstance(result, Awaitable):
+ return await result
return result
return async_wrapped
diff --git a/docs/conf.py b/docs/conf.py
index 57fc7bf..19b4d73 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -49,7 +49,6 @@ extensions = [
'sphinx.ext.imgmath',
'sphinx.ext.viewcode',
'sphinxcontrib_trio',
- 'sphinxcontrib.contentui',
]
# Add any paths that contain templates here, relative to this directory.
diff --git a/docs/source/api/asynctools.rst b/docs/source/api/asynctools.rst
index 31f774d..bac8931 100644
--- a/docs/source/api/asynctools.rst
+++ b/docs/source/api/asynctools.rst
@@ -23,8 +23,7 @@ Iterator lifetime
Async transforming
==================
-.. autofunction:: sync(function:(...) -> T) -> (...) -> await T
- :async:
+.. autofunction:: sync(function: (...) -> (await) T) -> (...) -> await T
.. versionadded:: 3.9.3
diff --git a/docs/source/api/itertools.rst b/docs/source/api/itertools.rst
index 0a140ea..1685cf4 100644
--- a/docs/source/api/itertools.rst
+++ b/docs/source/api/itertools.rst
@@ -61,7 +61,7 @@ Iterator splitting
:for: :(async iter T, ...)
.. autofunction:: pairwise(iterable: (async) iter T)
- :for: :(T, T)
+ :async-for: :(T, T)
.. versionadded:: 3.10.0
diff --git a/pyproject.toml b/pyproject.toml
index 143b30a..7d3af30 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -29,7 +29,7 @@ test = [
"pytest-cov",
"mypy; implementation_name=='cpython'",
]
-doc = ["sphinx", "sphinxcontrib-contentui", "sphinxcontrib-trio"]
+doc = ["sphinx", "sphinxcontrib-trio"]
[tool.flit.metadata.urls]
Documentation = "https://asyncstdlib.readthedocs.io/en/latest/"
|
maxfischer2781/asyncstdlib
|
e26414dfd03390e0498aab0660246a0cf50b05e2
|
diff --git a/unittests/test_asynctools.py b/unittests/test_asynctools.py
index 088588c..fde3297 100644
--- a/unittests/test_asynctools.py
+++ b/unittests/test_asynctools.py
@@ -221,3 +221,17 @@ async def test_sync():
assert t1 == 110
assert t2 == 120
assert t3 == 125
+
+
+@sync
+async def test_sync_awaitable():
+ """Test any (…) -> await T is recognised"""
+
+ @a.sync
+ def nocoro_async(value):
+ async def coro():
+ return value
+
+ return coro()
+
+ assert await nocoro_async(5) == 5
|
Release 3.10
The [Python 3.10 release schedule](https://www.python.org/dev/peps/pep-0619/) assumes feature freeze for beta 1 @ Monday, 2021-05-03.
|
0.0
|
e26414dfd03390e0498aab0660246a0cf50b05e2
|
[
"unittests/test_asynctools.py::test_sync_awaitable"
] |
[
"unittests/test_asynctools.py::test_nested_lifetime",
"unittests/test_asynctools.py::test_nested_lifetime_closed_outer",
"unittests/test_asynctools.py::test_borrow_explicitly",
"unittests/test_asynctools.py::test_borrow_iterable",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>0]",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>1]",
"unittests/test_asynctools.py::test_borrow_methods[<lambda>2]",
"unittests/test_asynctools.py::test_scoped_iter_misuse",
"unittests/test_asynctools.py::test_borrow_misuse",
"unittests/test_asynctools.py::test_await_each",
"unittests/test_asynctools.py::test_apply_with_no_arguments",
"unittests/test_asynctools.py::test_apply_with_an_argument",
"unittests/test_asynctools.py::test_apply_with_keyword_arguments",
"unittests/test_asynctools.py::test_apply_with_an_argument_and_a_keyword_argument",
"unittests/test_asynctools.py::test_sync"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-08 18:45:17+00:00
|
mit
| 3,827 |
|
maxfischer2781__asyncstdlib-85
|
diff --git a/asyncstdlib/contextlib.py b/asyncstdlib/contextlib.py
index ea8d11d..52a98c7 100644
--- a/asyncstdlib/contextlib.py
+++ b/asyncstdlib/contextlib.py
@@ -90,7 +90,13 @@ class _AsyncGeneratorContextManager(Generic[T]):
raise RuntimeError("generator did not stop after __aexit__")
else:
try:
- await self.gen.athrow(exc_type, exc_val, exc_tb)
+ # We are being closed as part of (async) generator shutdown.
+ # Use `aclose` to have additional checks for the child to
+ # handle shutdown properly.
+ if exc_type is GeneratorExit:
+ result = await self.gen.aclose()
+ else:
+ result = await self.gen.athrow(exc_type, exc_val, exc_tb)
except StopAsyncIteration as exc:
return exc is not exc_tb
except RuntimeError as exc:
@@ -106,6 +112,16 @@ class _AsyncGeneratorContextManager(Generic[T]):
raise
return False
else:
+ # During shutdown, the child generator might be cleaned up early.
+ # In this case,
+ # - the child will return nothing/None,
+ # - we get cleaned up via GeneratorExit as well,
+ # and we should go on with our own cleanup.
+ # This might happen if the child mishandles GeneratorExit as well,
+ # but is the closest we can get to checking the situation.
+ # See https://github.com/maxfischer2781/asyncstdlib/issues/84
+ if exc_type is GeneratorExit and result is None:
+ return False
raise RuntimeError("generator did not stop after throw() in __aexit__")
|
maxfischer2781/asyncstdlib
|
c268dbd50331cf1cd163eff4753236b7470631a9
|
diff --git a/unittests/test_contextlib.py b/unittests/test_contextlib.py
index 7a5ae2f..22211d1 100644
--- a/unittests/test_contextlib.py
+++ b/unittests/test_contextlib.py
@@ -34,6 +34,8 @@ async def test_contextmanager():
@sync
async def test_contextmanager_no_yield():
+ """Test that it is an error for a context to not yield"""
+
@a.contextmanager
async def no_yield():
if False:
@@ -46,6 +48,8 @@ async def test_contextmanager_no_yield():
@sync
async def test_contextmanager_no_stop():
+ """Test that it is an error for a context to yield again after stopping"""
+
@a.contextmanager
async def no_stop():
yield
@@ -69,6 +73,8 @@ async def test_contextmanager_no_stop():
@sync
async def test_contextmanager_raise_asyncstop():
+ """Test that StopAsyncIteration may propagate out of a context block"""
+
@a.contextmanager
async def no_raise():
yield
@@ -113,6 +119,8 @@ async def test_contextmanager_raise_runtimeerror():
@sync
async def test_contextmanager_raise_same():
+ """Test that outer exceptions do not shadow inner/newer ones"""
+
@a.contextmanager
async def reraise():
try:
@@ -136,6 +144,65 @@ async def test_contextmanager_raise_same():
raise KeyError("outside")
+@sync
+async def test_contextmanager_raise_generatorexit():
+ """Test that shutdown via GeneratorExit is propagated"""
+
+ @a.contextmanager
+ async def no_op():
+ yield
+
+ with pytest.raises(GeneratorExit):
+ async with no_op():
+ raise GeneratorExit("used to tear down coroutines")
+
+ # during shutdown, generators may be killed in arbitrary order
+ # make sure we do not suppress GeneratorExit
+ with pytest.raises(GeneratorExit, match="inner"):
+ context = no_op()
+ async with context:
+ # simulate cleanup closing the child early
+ await context.gen.aclose()
+ raise GeneratorExit("inner")
+
+
+@sync
+async def test_contextmanager_no_suppress_generatorexit():
+ """Test that GeneratorExit is not suppressed"""
+
+ @a.contextmanager
+ async def no_op():
+ yield
+
+ exc = GeneratorExit("GE should not be replaced normally")
+ with pytest.raises(type(exc)) as exc_info:
+ async with no_op():
+ raise exc
+ assert exc_info.value is exc
+
+ @a.contextmanager
+ async def exit_ge():
+ try:
+ yield
+ except GeneratorExit:
+ pass
+
+ with pytest.raises(GeneratorExit):
+ async with exit_ge():
+ raise GeneratorExit("Resume teardown if child exited")
+
+ @a.contextmanager
+ async def ignore_ge():
+ try:
+ yield
+ except GeneratorExit:
+ yield
+
+ with pytest.raises(RuntimeError):
+ async with ignore_ge():
+ raise GeneratorExit("Warn if child does not exit")
+
+
@sync
async def test_nullcontext():
async with a.nullcontext(1337) as value:
|
Possible mishandling of GeneratorExit in contextmanager
There seems to be an error in `contextmanager.__aexit__` if the wrapped async generator was/is closed already. In this case, `GeneratorExit` kills the wrapped generator which then propagates onwards; however, when `__aexit__` attempts to close the wrapped generator it only expects `StopAsyncIteration` and assumes the `GeneratorExit` is an actual error.
Apparently, this is related to generator cleanup during shutdown when we have a sandwich of "async generator"->"contextmanager"->"async generator" (see also https://github.com/python-trio/trio/issues/2081). In this case it is ill-defined in which order the async generators are cleaned up and the inner generator may die before the outer one.
I have only been able to catch this in the wild by accident.
```none
unhandled exception during asyncio.run() shutdown
task: <Task finished coro=<async_generator_athrow()> exception=RuntimeError("can't send non-None value to a just-started coroutine",)>
RuntimeError: can't send non-None value to a just-started coroutine
an error occurred during closing of asynchronous generator <async_generator object Node.from_pool at 0x7f07722cee80>
asyncgen: <async_generator object Node.from_pool at 0x7f07722cee80>
Traceback (most recent call last):
File "/.../condor_accountant/_infosystem/nodes.py", line 34, in from_pool
yield cls(name, machine, __type, address)
GeneratorExit
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/.../condor_accountant/_infosystem/nodes.py", line 34, in from_pool
yield cls(name, machine, __type, address)
File "/.../pca_venv/lib64/python3.6/site-packages/asyncstdlib/contextlib.py", line 109, in __aexit__
raise RuntimeError("generator did not stop after throw() in __aexit__")
RuntimeError: generator did not stop after throw() in __aexit__
```
----------
Possibly related to #3.
|
0.0
|
c268dbd50331cf1cd163eff4753236b7470631a9
|
[
"unittests/test_contextlib.py::test_contextmanager_raise_generatorexit",
"unittests/test_contextlib.py::test_contextmanager_no_suppress_generatorexit"
] |
[
"unittests/test_contextlib.py::test_closing",
"unittests/test_contextlib.py::test_contextmanager",
"unittests/test_contextlib.py::test_contextmanager_no_yield",
"unittests/test_contextlib.py::test_contextmanager_no_stop",
"unittests/test_contextlib.py::test_contextmanager_raise_asyncstop",
"unittests/test_contextlib.py::test_contextmanager_raise_runtimeerror",
"unittests/test_contextlib.py::test_contextmanager_raise_same",
"unittests/test_contextlib.py::test_nullcontext",
"unittests/test_contextlib.py::test_exist_stack",
"unittests/test_contextlib.py::test_exit_stack_pop_all",
"unittests/test_contextlib.py::test_exit_stack_callback",
"unittests/test_contextlib.py::test_exit_stack_push",
"unittests/test_contextlib.py::test_exit_stack_stitch_context",
"unittests/test_contextlib.py::test_misuse_enter_context"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-05-16 16:56:15+00:00
|
mit
| 3,828 |
|
maxfischer2781__asyncstdlib-87
|
diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml
index 3bfabfc..f55528c 100644
--- a/.github/workflows/python-publish.yml
+++ b/.github/workflows/python-publish.yml
@@ -18,9 +18,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.x'
- name: Install dependencies
diff --git a/.github/workflows/verification.yml b/.github/workflows/verification.yml
index 4190131..f7627d3 100644
--- a/.github/workflows/verification.yml
+++ b/.github/workflows/verification.yml
@@ -6,9 +6,9 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: '3.9'
- name: Install dependencies
diff --git a/asyncstdlib/itertools.py b/asyncstdlib/itertools.py
index 5c64ab7..44f060c 100644
--- a/asyncstdlib/itertools.py
+++ b/asyncstdlib/itertools.py
@@ -17,7 +17,7 @@ from typing import (
)
from collections import deque
-from ._typing import T, R, T1, T2, T3, T4, T5, AnyIterable, ADD
+from ._typing import T, R, T1, T2, T3, T4, T5, AnyIterable, ADD, AsyncContextManager
from ._utility import public_module
from ._core import (
ScopedIter,
@@ -294,27 +294,45 @@ async def takewhile(
break
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection"""
+
+ async def __aenter__(self) -> None:
+ pass
+
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
+ return False
+
+
async def tee_peer(
iterator: AsyncIterator[T],
+ # the buffer specific to this peer
buffer: Deque[T],
+ # the buffers of all peers, including our own
peers: List[Deque[T]],
+ lock: AsyncContextManager[Any],
) -> AsyncGenerator[T, None]:
"""An individual iterator of a :py:func:`~.tee`"""
try:
while True:
if not buffer:
- try:
- item = await iterator.__anext__()
- except StopAsyncIteration:
- break
- else:
- # Append to all buffers, including our own. We'll fetch our
- # item from the buffer again, instead of yielding it directly.
- # This ensures the proper item ordering if any of our peers
- # are fetching items concurrently. They may have buffered their
- # item already.
- for peer_buffer in peers:
- peer_buffer.append(item)
+ async with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = await iterator.__anext__()
+ except StopAsyncIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
yield buffer.popleft()
finally:
# this peer is done – remove its buffer
@@ -322,6 +340,7 @@ async def tee_peer(
if peer_buffer is buffer:
peers.pop(idx)
break
+ # if we are the last peer, try and close the iterator
if not peers and hasattr(iterator, "aclose"):
await iterator.aclose() # type: ignore
@@ -355,14 +374,23 @@ class Tee(Generic[T]):
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
provide these items. Also, ``tee`` must internally buffer each item until the
last iterator has yielded it; if the most and least advanced iterator differ
- by most data, using a :py:class:`list` is faster (but not lazy).
+ by most data, using a :py:class:`list` is more efficient (but not lazy).
If the underlying iterable is concurrency safe (``anext`` may be awaited
concurrently) the resulting iterators are concurrency safe as well. Otherwise,
the iterators are safe if there is only ever one single "most advanced" iterator.
+ To enforce sequential use of ``anext``, provide a ``lock``
+ - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
+ and access is automatically synchronised.
"""
- def __init__(self, iterable: AnyIterable[T], n: int = 2):
+ def __init__(
+ self,
+ iterable: AnyIterable[T],
+ n: int = 2,
+ *,
+ lock: Optional[AsyncContextManager[Any]] = None,
+ ):
self._iterator = aiter(iterable)
self._buffers: List[Deque[T]] = [deque() for _ in range(n)]
self._children = tuple(
@@ -370,6 +398,7 @@ class Tee(Generic[T]):
iterator=self._iterator,
buffer=buffer,
peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
)
for buffer in self._buffers
)
@@ -377,7 +406,17 @@ class Tee(Generic[T]):
def __len__(self) -> int:
return len(self._children)
+ @overload
def __getitem__(self, item: int) -> AsyncIterator[T]:
+ ...
+
+ @overload
+ def __getitem__(self, item: slice) -> Tuple[AsyncIterator[T], ...]:
+ ...
+
+ def __getitem__(
+ self, item: Union[int, slice]
+ ) -> Union[AsyncIterator[T], Tuple[AsyncIterator[T], ...]]:
return self._children[item]
def __iter__(self) -> Iterator[AnyIterable[T]]:
diff --git a/docs/source/api/itertools.rst b/docs/source/api/itertools.rst
index 739573c..2610ed0 100644
--- a/docs/source/api/itertools.rst
+++ b/docs/source/api/itertools.rst
@@ -65,9 +65,13 @@ Iterator transforming
Iterator splitting
==================
-.. autofunction:: tee(iterable: (async) iter T, n: int = 2)
+.. autofunction:: tee(iterable: (async) iter T, n: int = 2, [*, lock: async with Any])
:for: :(async iter T, ...)
+ .. versionadded:: 3.10.5
+
+ The ``lock`` keyword parameter.
+
.. autofunction:: pairwise(iterable: (async) iter T)
:async-for: :(T, T)
|
maxfischer2781/asyncstdlib
|
eeb76f23e935d1f7e5a12ef68cf5c181fe20f692
|
diff --git a/.github/workflows/unittests.yml b/.github/workflows/unittests.yml
index fcb4308..889ece1 100644
--- a/.github/workflows/unittests.yml
+++ b/.github/workflows/unittests.yml
@@ -10,9 +10,9 @@ jobs:
python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', 'pypy-3.6', 'pypy-3.7']
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
diff --git a/unittests/test_itertools.py b/unittests/test_itertools.py
index 1a80065..904378d 100644
--- a/unittests/test_itertools.py
+++ b/unittests/test_itertools.py
@@ -1,10 +1,11 @@
import itertools
+import sys
import pytest
import asyncstdlib as a
-from .utility import sync, asyncify, awaitify
+from .utility import sync, asyncify, awaitify, multi_sync, Schedule, Switch, Lock
@sync
@@ -210,6 +211,56 @@ async def test_tee():
assert await a.list(iterator) == iterable
+@multi_sync
+async def test_tee_concurrent_locked():
+ """Test that properly uses a lock for synchronisation"""
+ items = [1, 2, 3, -5, 12, 78, -1, 111]
+
+ async def iter_values():
+ for item in items:
+ # switch to other tasks a few times to guarantees another runs
+ for _ in range(5):
+ await Switch()
+ yield item
+
+ async def test_peer(peer_tee):
+ assert await a.list(peer_tee) == items
+
+ head_peer, *peers = a.tee(iter_values(), n=len(items) // 2, lock=Lock())
+ await Schedule(*map(test_peer, peers))
+ await Switch()
+ results = [item async for item in head_peer]
+ assert results == items
+
+
+# see https://github.com/python/cpython/issues/74956
[email protected](
+ sys.version_info < (3, 8),
+ reason="async generators only protect against concurrent access since 3.8",
+)
+@multi_sync
+async def test_tee_concurrent_unlocked():
+ """Test that does not prevent concurrency without a lock"""
+ items = list(range(12))
+
+ async def iter_values():
+ for item in items:
+ # switch to other tasks a few times to guarantees another runs
+ for _ in range(5):
+ await Switch()
+ yield item
+
+ async def test_peer(peer_tee):
+ assert await a.list(peer_tee) == items
+
+ this, peer = a.tee(iter_values(), n=2)
+ await Schedule(test_peer(peer))
+ await Switch()
+ # underlying generator raises RuntimeError when `__anext__` is interleaved
+ with pytest.raises(RuntimeError):
+ await test_peer(this)
+
+
@sync
async def test_pairwise():
assert await a.list(a.pairwise(range(5))) == [(0, 1), (1, 2), (2, 3), (3, 4)]
diff --git a/unittests/utility.py b/unittests/utility.py
index 2710fe1..b475eda 100644
--- a/unittests/utility.py
+++ b/unittests/utility.py
@@ -85,12 +85,34 @@ class Switch:
yield self
+class Lock:
+ def __init__(self):
+ self._owned = False
+ self._waiting = []
+
+ async def __aenter__(self):
+ if self._owned:
+ # wait until it is our turn to take the lock
+ token = object()
+ self._waiting.append(token)
+ while self._owned or self._waiting[0] is not token:
+ await Switch()
+ # take the lock and remove our wait claim
+ self._owned = True
+ self._waiting.pop(0)
+ self._owned = True
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ self._owned = False
+
+
def multi_sync(test_case: Callable[..., Coroutine]):
"""
- Mark an ``async def`` test case to be run synchronously with chicldren
+ Mark an ``async def`` test case to be run synchronously with children
This emulates a primitive "event loop" which only responds
- to the :py:class:`PingPong`, :py:class:`Schedule` and :py:class:`Switch`.
+ to the :py:class:`PingPong`, :py:class:`Schedule`, :py:class:`Switch`
+ and :py:class:`Lock`.
"""
@wraps(test_case)
@@ -103,7 +125,7 @@ def multi_sync(test_case: Callable[..., Coroutine]):
event = coro.send(event)
except StopIteration as e:
result = e.args[0] if e.args else None
- assert result is None
+ assert result is None, f"got '{result!r}' expected 'None'"
else:
if isinstance(event, PingPong):
run_queue.appendleft((coro, event))
|
`tee()`'s iterators throw RuntimeError when consumed in parallel
Thanks for this library, I've been using it on a project recently and found it really useful.
The `tee()` function seems to have a bug. If the source is an async generator that awaits in-between yields, and the tee's iterators are consumed in parallel, the tee's iterators will throw `RuntimeError: anext(): asynchronous generator is already running`.
What's happening is that one of the tee()'s peer iterators calls `__anext__()` on the source, then while that call is being awaited, a second peer iterator also calls `__anext__()`. If the source is an async generator, it will throw a RuntimeError, as overlapping calls are not allowed.
Here's a test case that triggers the error: https://github.com/h4l/asyncstdlib/commit/680429354fce7ad22c535df74ff503c9f38ec313
And an asyncio program that triggers it:
```python
# tee_bug_asyncio_repo.py
import asyncio
import sys
import asyncstdlib as a
async def slow_iterable():
for x in range(3):
await asyncio.sleep(0.1)
yield x
async def main(*, n):
print(f"tee() with {n=}")
async with a.tee(slow_iterable(), n=n) as iterables:
results = await asyncio.gather(
*(asyncio.create_task(a.list(iterable)) for iterable in iterables)
)
print(results)
if __name__ == "__main__":
n = 2 if len(sys.argv) < 2 else int(sys.argv[1])
asyncio.run(main(n=n))
```
```
$ python tee_bug_asyncio_repo.py 1
tee() with n=1
[[0, 1, 2]]
$ python tee_bug_asyncio_repo.py 2
tee() with n=2
Traceback (most recent call last):
File "/workspaces/asyncstdlib/tee_bug_asyncio_repo.py", line 16, in main
results = await asyncio.gather(
File "/workspaces/asyncstdlib/asyncstdlib/builtins.py", line 656, in list
return [element async for element in aiter(iterable)]
File "/workspaces/asyncstdlib/asyncstdlib/builtins.py", line 656, in <listcomp>
return [element async for element in aiter(iterable)]
File "/workspaces/asyncstdlib/asyncstdlib/itertools.py", line 307, in tee_peer
item = await iterator.__anext__()
RuntimeError: anext(): asynchronous generator is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/workspaces/asyncstdlib/tee_bug_asyncio_repo.py", line 24, in <module>
asyncio.run(main(n=n))
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/workspaces/asyncstdlib/tee_bug_asyncio_repo.py", line 15, in main
async with a.tee(slow_iterable(), n=n) as iterables:
File "/workspaces/asyncstdlib/asyncstdlib/itertools.py", line 390, in __aexit__
await self.aclose()
File "/workspaces/asyncstdlib/asyncstdlib/itertools.py", line 395, in aclose
await child.aclose()
RuntimeError: aclose(): asynchronous generator is already running
```
|
0.0
|
eeb76f23e935d1f7e5a12ef68cf5c181fe20f692
|
[
"unittests/test_itertools.py::test_tee_concurrent_locked"
] |
[
"unittests/test_itertools.py::test_accumulate",
"unittests/test_itertools.py::test_accumulate_default",
"unittests/test_itertools.py::test_accumulate_misuse",
"unittests/test_itertools.py::test_cycle",
"unittests/test_itertools.py::test_chain[iterables0]",
"unittests/test_itertools.py::test_chain[iterables1]",
"unittests/test_itertools.py::test_chain[iterables2]",
"unittests/test_itertools.py::test_compress[data0-selectors0]",
"unittests/test_itertools.py::test_compress[data1-selectors1]",
"unittests/test_itertools.py::test_compress[data2-selectors2]",
"unittests/test_itertools.py::test_compress[data3-selectors3]",
"unittests/test_itertools.py::test_dropwhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_dropwhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable0-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable1-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable2-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable3-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable4-<lambda>]",
"unittests/test_itertools.py::test_takewhile[iterable5-<lambda>]",
"unittests/test_itertools.py::test_islice[slicing0-iterable0]",
"unittests/test_itertools.py::test_islice[slicing0-iterable1]",
"unittests/test_itertools.py::test_islice[slicing0-iterable2]",
"unittests/test_itertools.py::test_islice[slicing0-iterable3]",
"unittests/test_itertools.py::test_islice[slicing1-iterable0]",
"unittests/test_itertools.py::test_islice[slicing1-iterable1]",
"unittests/test_itertools.py::test_islice[slicing1-iterable2]",
"unittests/test_itertools.py::test_islice[slicing1-iterable3]",
"unittests/test_itertools.py::test_islice[slicing2-iterable0]",
"unittests/test_itertools.py::test_islice[slicing2-iterable1]",
"unittests/test_itertools.py::test_islice[slicing2-iterable2]",
"unittests/test_itertools.py::test_islice[slicing2-iterable3]",
"unittests/test_itertools.py::test_islice[slicing3-iterable0]",
"unittests/test_itertools.py::test_islice[slicing3-iterable1]",
"unittests/test_itertools.py::test_islice[slicing3-iterable2]",
"unittests/test_itertools.py::test_islice[slicing3-iterable3]",
"unittests/test_itertools.py::test_islice[slicing4-iterable0]",
"unittests/test_itertools.py::test_islice[slicing4-iterable1]",
"unittests/test_itertools.py::test_islice[slicing4-iterable2]",
"unittests/test_itertools.py::test_islice[slicing4-iterable3]",
"unittests/test_itertools.py::test_islice[slicing5-iterable0]",
"unittests/test_itertools.py::test_islice[slicing5-iterable1]",
"unittests/test_itertools.py::test_islice[slicing5-iterable2]",
"unittests/test_itertools.py::test_islice[slicing5-iterable3]",
"unittests/test_itertools.py::test_islice[slicing6-iterable0]",
"unittests/test_itertools.py::test_islice[slicing6-iterable1]",
"unittests/test_itertools.py::test_islice[slicing6-iterable2]",
"unittests/test_itertools.py::test_islice[slicing6-iterable3]",
"unittests/test_itertools.py::test_islice_exact[slicing0]",
"unittests/test_itertools.py::test_islice_exact[slicing1]",
"unittests/test_itertools.py::test_islice_exact[slicing2]",
"unittests/test_itertools.py::test_islice_exact[slicing3]",
"unittests/test_itertools.py::test_islice_exact[slicing4]",
"unittests/test_itertools.py::test_islice_scoped_iter",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable0]",
"unittests/test_itertools.py::test_starmap[<lambda>-iterable1]",
"unittests/test_itertools.py::test_tee",
"unittests/test_itertools.py::test_tee_concurrent_unlocked",
"unittests/test_itertools.py::test_pairwise",
"unittests/test_itertools.py::test_zip_longest",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[keys-divide-iterable4]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable0]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable1]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable2]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable3]",
"unittests/test_itertools.py::test_groupby[values-identity-iterable4]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable0]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable1]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable2]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable3]",
"unittests/test_itertools.py::test_groupby[values-modulo-iterable4]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable0]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable1]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable2]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable3]",
"unittests/test_itertools.py::test_groupby[values-divide-iterable4]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-01 10:12:54+00:00
|
mit
| 3,829 |
|
maxfischer2781__bootpeg-13
|
diff --git a/bootpeg/pika/act.py b/bootpeg/pika/act.py
index afa59bb..7f8aafd 100644
--- a/bootpeg/pika/act.py
+++ b/bootpeg/pika/act.py
@@ -4,7 +4,7 @@ Pika bottom-up Peg parser extension to transform parsed source
from typing import TypeVar, Any, Dict, Tuple
import re
-from .peg import Clause, D, Match, MemoTable, MemoKey, Literal, nested_str
+from .peg import Clause, D, Match, MemoTable, MemoKey, Literal, nested_str, Reference
from ..utility import mono, cache_hash
@@ -80,13 +80,42 @@ class Capture(Clause[D]):
return f"{self.name}={nested_str(self.sub_clauses[0])}"
+def captures(head: Clause):
+ if isinstance(head, Capture):
+ yield head
+ elif isinstance(head, Reference):
+ return
+ else:
+ for clause in head.sub_clauses:
+ yield from captures(clause)
+
+
+class ActionCaptureError(TypeError):
+ def __init__(self, missing, extra, rule):
+ self.missing = missing
+ self.extra = extra
+ self.rule = rule
+ msg = f"extra {', '.join(map(repr, extra))}" if extra else ""
+ msg += " and " if extra and missing else ""
+ msg += f"missing {', '.join(map(repr, missing))}" if missing else ""
+ super().__init__(f"{msg} captures: {self.rule}")
+
+
class Rule(Clause[D]):
__slots__ = ("sub_clauses", "action", "_hash")
- def __init__(self, sub_clause: Clause[D], action):
+ def __init__(self, sub_clause: Clause[D], action: "Action"):
self.sub_clauses = (sub_clause,)
self.action = action
self._hash = None
+ self._verify_captures()
+
+ def _verify_captures(self):
+ captured_names = {capture.name for capture in captures(self.sub_clauses[0])}
+ if captured_names.symmetric_difference(self.action.parameters):
+ additional = captured_names.difference(self.action.parameters)
+ missing = set(self.action.parameters) - captured_names
+ raise ActionCaptureError(missing=missing, extra=additional, rule=self)
@property
def maybe_zero(self):
@@ -123,7 +152,7 @@ class Discard:
class Action:
- __slots__ = ("literal", "_py_source", "_py_code")
+ __slots__ = ("literal", "_py_names", "_py_source", "_py_code")
# TODO: Define these via a PEG parser
unpack = re.compile(r"\.\*")
named = re.compile(r"(^|[ (])\.([a-zA-Z]+)")
@@ -131,24 +160,24 @@ class Action:
def __init__(self, literal: str):
self.literal = literal.strip()
+ self._py_names = tuple(match.group(2) for match in self.named.finditer(literal))
self._py_source = self._encode(self.literal)
self._py_code = compile(self._py_source, self._py_source, "eval")
+ @property
+ def parameters(self) -> Tuple[str, ...]:
+ """The parameter names used by the action"""
+ return self._py_names
+
def __call__(self, __namespace, *args, **kwargs):
- try:
- return eval(self._py_code, __namespace)(*args, **kwargs)
- except Exception as err:
- raise type(err)(f"{err} <{self._py_source}>")
-
- @classmethod
- def _encode(cls, literal):
- names = [
- f"{cls.mangle}{match.group(2)}" for match in cls.named.finditer(literal)
- ]
- body = cls.named.sub(
- rf"\1 {cls.mangle}\2", cls.unpack.sub(rf" {cls.mangle}all", literal)
+ return eval(self._py_code, __namespace)(*args, **kwargs)
+
+ def _encode(self, literal):
+ names = [f"{self.mangle}{name}" for name in self._py_names]
+ body = self.named.sub(
+ rf"\1 {self.mangle}\2", self.unpack.sub(rf" {self.mangle}all", literal)
)
- return f'lambda {cls.mangle}all, {", ".join(names)}: {body}'
+ return f'lambda {self.mangle}all, {", ".join(names)}: {body}'
def __eq__(self, other):
return isinstance(other, Action) and self.literal == other.literal
@@ -196,6 +225,8 @@ def postorder_transform(
matches = matches if matches else source[position : position + match.length]
try:
result = clause.action(namespace, matches, **captures)
+ except ActionCaptureError:
+ raise
except Exception as exc:
raise TransformFailure(clause, matches, captures, exc)
return (result,) if not isinstance(result, Discard) else (), {}
|
maxfischer2781/bootpeg
|
c0090c9cb553788d0c85a5958c19fa7872f28e7d
|
diff --git a/tests/test_boot.py b/tests/test_boot.py
index 63f0bcf..b1cd914 100644
--- a/tests/test_boot.py
+++ b/tests/test_boot.py
@@ -1,3 +1,5 @@
+import pytest
+
from bootpeg.pika import boot
@@ -24,3 +26,7 @@ def test_features():
opt_repeat = boot.boot(parser, 'rule:\n | [ " "+ ]\n')
non_repeat = boot.boot(parser, 'rule:\n | " "*\n')
assert opt_repeat.clauses == non_repeat.clauses
+ with pytest.raises(TypeError):
+ boot.boot(parser, 'rule:\n | [ " "+ ] { .missing }\n')
+ with pytest.raises(TypeError):
+ boot.boot(parser, 'rule:\n | extra=([ " "+ ]) { () }\n')
|
Verify Rule+Action captures
Both ``Rule`` and ``Action`` can statically derive their provided/supplied arguments. A ``Rule`` should check that its ``Action`` is compatible.
|
0.0
|
c0090c9cb553788d0c85a5958c19fa7872f28e7d
|
[
"tests/test_boot.py::test_features"
] |
[
"tests/test_boot.py::test_bootstrap",
"tests/test_boot.py::test_escalate"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-21 19:32:38+00:00
|
mit
| 3,830 |
|
maxfischer2781__bootpeg-16
|
diff --git a/bootpeg/grammars/__init__.py b/bootpeg/grammars/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/bootpeg/peg.peg b/bootpeg/grammars/bpeg.bpeg
similarity index 95%
rename from bootpeg/peg.peg
rename to bootpeg/grammars/bpeg.bpeg
index 8ae3681..c6bb48a 100644
--- a/bootpeg/peg.peg
+++ b/bootpeg/grammars/bpeg.bpeg
@@ -36,7 +36,7 @@ reference:
reject:
| "!" spaces expr=expr { Not(.expr) }
expr:
- | expr=(choice | sequence | repeat | delimited | capture | reference | group | optional | range | literal | reject | anything | nothing) { .expr }
+ | expr=(choice | sequence | repeat | delimited | capture | reference | group | optional | range | nothing | literal | reject | anything) { .expr }
rule:
| "|" spaces expr=expr spaces "{" body=(((!"}") .)+) "}" { Rule(.expr, Action(.body)) }
diff --git a/bootpeg/grammars/bpeg.py b/bootpeg/grammars/bpeg.py
new file mode 100644
index 0000000..477c619
--- /dev/null
+++ b/bootpeg/grammars/bpeg.py
@@ -0,0 +1,132 @@
+"""
+The default bootpeg grammar
+"""
+from typing import Union, NamedTuple, Mapping, Callable, Optional, Any
+from functools import singledispatch
+from pathlib import Path
+
+from ..pika.peg import (
+ Clause,
+ Nothing,
+ Anything,
+ Literal,
+ Sequence,
+ Choice,
+ Repeat,
+ Not,
+ Reference,
+ Parser,
+)
+from ..pika.act import Capture, Rule, transform
+from ..pika.front import Range, Delimited
+from ..pika.boot import namespace, bootpeg, boot
+
+
+@singledispatch
+def unparse(clause: Union[Clause, Parser], top=True) -> str:
+ """Format a ``clause`` according to bootpeg standard grammar"""
+ raise NotImplementedError(f"Cannot unparse {clause!r} as bpeg")
+
+
[email protected](Nothing)
+def unparse_nothing(clause: Nothing, top=True) -> str:
+ return '""'
+
+
[email protected](Anything)
+def unparse_anything(clause: Anything, top=True) -> str:
+ return "." * clause.length
+
+
[email protected](Literal)
+def unparse_literal(clause: Literal, top=True) -> str:
+ return repr(clause.value)
+
+
[email protected](Sequence)
+def unparse_sequence(clause: Sequence, top=True) -> str:
+ children = " ".join(
+ unparse(sub_clause, top=False) for sub_clause in clause.sub_clauses
+ )
+ return f"({children})" if not top else children
+
+
[email protected](Choice)
+def unparse_choice(clause: Choice, top=True) -> str:
+ children = " | ".join(
+ unparse(sub_clause, top=False) for sub_clause in clause.sub_clauses
+ )
+ return f"({children})" if not top else children
+
+
[email protected](Repeat)
+def unparse_repeat(clause: Repeat, top=True) -> str:
+ return unparse(clause.sub_clauses[0], top=False) + "+"
+
+
[email protected](Not)
+def unparse_not(clause: Not, top=True) -> str:
+ return "!" + unparse(clause.sub_clauses[0], top=False)
+
+
[email protected](Reference)
+def unparse_reference(clause: Reference, top=True) -> str:
+ return clause.target
+
+
[email protected](Capture)
+def unparse_capture(clause: Capture, top=True) -> str:
+ return f"{clause.name}={unparse(clause.sub_clauses[0], top=False)}"
+
+
[email protected](Rule)
+def unparse_rule(clause: Rule, top=True) -> str:
+ return f"| {unparse(clause.sub_clauses[0])} {{{clause.action.literal}}}"
+
+
[email protected](Range)
+def unparse_range(clause: Range, top=True) -> str:
+ return f"{clause.first!r} - {clause.last!r}"
+
+
[email protected](Delimited)
+def unparse_delimited(clause: Delimited, top=True) -> str:
+ first, last = clause.sub_clauses
+ return f"{unparse(first, top=False)} :: {unparse(last, top=False)}"
+
+
+class Actions(NamedTuple):
+ #: names available for translation actions
+ names: Mapping[str, Callable]
+ #: postprocessing callable
+ post: Callable[..., Any]
+
+
+#: :py:class:`~.Actions` needed to construct a Pika parser
+PikaActions = Actions(
+ names=namespace,
+ post=lambda *args, **kwargs: Parser(
+ "top",
+ **{name: clause for name, clause in args[0]},
+ ),
+)
+
+_parser_cache: Optional[Parser] = None
+grammar_path = Path(__file__).parent / "bpeg.bpeg"
+
+
+def _get_parser() -> Parser:
+ global _parser_cache
+ if _parser_cache is None:
+ parser = bootpeg()
+ # TODO: does translating twice offer any benefit?
+ parser = boot(parser, grammar_path.read_text())
+ _parser_cache = parser
+ return _parser_cache
+
+
+def parse(source, actions: Actions = PikaActions):
+ head, memo = _get_parser().parse(source)
+ assert head.length == len(source)
+ args, kwargs = transform(head, memo, actions.names)
+ return actions.post(*args, **kwargs)
diff --git a/bootpeg/pika/act.py b/bootpeg/pika/act.py
index 7f8aafd..54c94c8 100644
--- a/bootpeg/pika/act.py
+++ b/bootpeg/pika/act.py
@@ -1,7 +1,7 @@
"""
Pika bottom-up Peg parser extension to transform parsed source
"""
-from typing import TypeVar, Any, Dict, Tuple
+from typing import TypeVar, Any, Dict, Tuple, Mapping
import re
from .peg import Clause, D, Match, MemoTable, MemoKey, Literal, nested_str, Reference
@@ -201,13 +201,13 @@ class TransformFailure(Exception):
self.exc = exc
-def transform(head: Match, memo: MemoTable, namespace: Dict[str, Any]):
+def transform(head: Match, memo: MemoTable, namespace: Mapping[str, Any]):
return postorder_transform(head, memo.source, namespace)
# TODO: Use trampoline/coroutines for infinite depth
def postorder_transform(
- match: Match, source: D, namespace: Dict[str, Any]
+ match: Match, source: D, namespace: Mapping[str, Any]
) -> Tuple[Any, Dict[str, Any]]:
matches, captures = (), {}
for sub_match in match.sub_matches:
diff --git a/bootpeg/pika/boot.peg b/bootpeg/pika/boot.bpeg
similarity index 100%
rename from bootpeg/pika/boot.peg
rename to bootpeg/pika/boot.bpeg
diff --git a/bootpeg/pika/boot.py b/bootpeg/pika/boot.py
index c06827d..ddc9521 100644
--- a/bootpeg/pika/boot.py
+++ b/bootpeg/pika/boot.py
@@ -1,3 +1,5 @@
+from typing import Optional
+
import string
import time
import pathlib
@@ -129,7 +131,8 @@ namespace = {
end_line = Reference("end_line") # Literal("\n")
-parser = Parser(
+#: Minimal parser required to bootstrap the actual parser
+min_parser = Parser(
"top",
literal=Rule(
Choice(
@@ -292,8 +295,8 @@ parser = Parser(
Action(".*"),
),
)
-boot_path = pathlib.Path(__file__).parent / "boot.peg"
-full_path = pathlib.Path(__file__).parent.parent / "peg.peg"
+boot_path = pathlib.Path(__file__).parent / "boot.bpeg"
+full_path = pathlib.Path(__file__).parent.parent / "grammars" / "bpeg.bpeg"
def boot(base_parser: Parser, source: str) -> Parser:
@@ -306,7 +309,20 @@ def boot(base_parser: Parser, source: str) -> Parser:
)
+_parser_cache: Optional[Parser] = None
+
+
+def bootpeg() -> Parser:
+ """Provide the basic bootpeg Pika parser"""
+ global _parser_cache
+ if _parser_cache is None:
+ with open(boot_path) as boot_peg_stream:
+ _parser_cache = boot(min_parser, boot_peg_stream.read())
+ return _parser_cache
+
+
if __name__ == "__main__":
+ parser = bootpeg()
for iteration in range(2):
with open(boot_path) as boot_peg:
print("Generation:", iteration)
@@ -318,7 +334,7 @@ if __name__ == "__main__":
for iteration in range(2, 4):
with open(full_path) as base_peg:
print("Generation:", iteration)
- display(parser)
+ display(min_parser)
parser = range_parse(
base_peg.read(),
parser,
diff --git a/bootpeg/pika/front.py b/bootpeg/pika/front.py
index aac0c50..f81cb3d 100644
--- a/bootpeg/pika/front.py
+++ b/bootpeg/pika/front.py
@@ -19,6 +19,7 @@ from .peg import (
D,
)
from .act import Debug, Capture, Rule, transform, Action, Discard
+from ..utility import cache_hash
__all__ = [
# peg
@@ -42,6 +43,7 @@ __all__ = [
"chain",
"either",
"Range",
+ "Delimited",
]
@@ -76,7 +78,7 @@ class Range(Terminal[D]):
maybe_zero = False
def __init__(self, first: D, last: D):
- assert len(first) == len(last) > 0
+ assert len(first) == len(last) > 0, "Range bounds must be of same length"
self.first = first
self.last = last
self._length = len(first)
@@ -109,7 +111,7 @@ class Delimited(Clause[D]):
A pair of clauses with arbitrary intermediate filler
"""
- __slots__ = ("sub_clauses",)
+ __slots__ = ("sub_clauses", "_hash")
@property
def maybe_zero(self):
@@ -118,6 +120,7 @@ class Delimited(Clause[D]):
def __init__(self, start: Clause[D], stop: Clause[D]):
self.sub_clauses = start, stop
+ self._hash = None
@property
def triggers(self) -> "Tuple[Clause[D]]":
@@ -135,6 +138,13 @@ class Delimited(Clause[D]):
return Match(offset + tail.length, (head, tail), at, self)
return None
+ def __eq__(self, other):
+ return isinstance(other, Delimited) and self.sub_clauses == other.sub_clauses
+
+ @cache_hash
+ def __hash__(self):
+ return hash(self.sub_clauses)
+
def __repr__(self):
start, stop = self.sub_clauses
return f"{self.__class__.__name__}(start={start!r}, stop={stop!r})"
|
maxfischer2781/bootpeg
|
2edb9fcd1925163ec05ee121e942fea55f97ed5a
|
diff --git a/tests/test_boot.py b/tests/test_boot.py
index b1cd914..50d7c04 100644
--- a/tests/test_boot.py
+++ b/tests/test_boot.py
@@ -5,24 +5,22 @@ from bootpeg.pika import boot
def test_bootstrap():
boot_peg = boot.boot_path.read_text()
- parser = boot.parser
+ parser = boot.min_parser
# ensure each parser handles itself
for _ in range(2):
parser = boot.boot(parser, boot_peg)
def test_escalate():
- boot_peg = boot.boot_path.read_text()
full_peg = boot.full_path.read_text()
- parser = boot.boot(boot.parser, boot_peg)
+ parser = boot.bootpeg()
for _ in range(2):
parser = boot.boot(parser, full_peg)
def test_features():
- boot_peg = boot.boot_path.read_text()
full_peg = boot.full_path.read_text()
- parser = boot.boot(boot.boot(boot.parser, boot_peg), full_peg)
+ parser = boot.boot(boot.bootpeg(), full_peg)
opt_repeat = boot.boot(parser, 'rule:\n | [ " "+ ]\n')
non_repeat = boot.boot(parser, 'rule:\n | " "*\n')
assert opt_repeat.clauses == non_repeat.clauses
diff --git a/tests/test_grammars/__init__.py b/tests/test_grammars/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_grammars/test_bpeg.py b/tests/test_grammars/test_bpeg.py
new file mode 100644
index 0000000..953f3b5
--- /dev/null
+++ b/tests/test_grammars/test_bpeg.py
@@ -0,0 +1,41 @@
+import pytest
+
+from bootpeg.grammars import bpeg
+from bootpeg.pika.front import (
+ Rule,
+ Literal,
+ Nothing,
+ Anything,
+ Sequence,
+ Choice,
+ Repeat,
+ Not,
+ Range,
+ Delimited,
+)
+
+
+clauses = [
+ Nothing(),
+ Anything(1),
+ *(Literal(literal) for literal in ("A", "x", "ß", " ")),
+ Sequence(Literal("A"), Literal("B"), Literal("A")),
+ Sequence(Literal(" "), Literal(" ")),
+ Choice(Literal("a"), Literal("b"), Nothing()),
+ Repeat(Literal("x")),
+ Repeat(Sequence(Literal("x"), Literal("y"), Literal("z"))),
+ Not(Literal("a")),
+ Range("a", "b"),
+ Delimited(Literal("'"), Literal("'")),
+]
+
+
[email protected]("clause", clauses)
+def test_roundtrip(clause):
+ clause = clause
+ literal = bpeg.unparse(clause)
+ assert literal
+ parsed_rule: Rule = bpeg.parse(f"parse_test:\n | {literal}\n").clauses[
+ "parse_test"
+ ]
+ assert parsed_rule.sub_clauses[0] == clause
|
Factor out pretty-formatting
The pretty-printing of clauses and rules currently uses ``__str__``. This spreads out the pretty-formatting format and makes it impossible to have several representations (PEP 617, EBNF, PEG, ...). The ``nested_str`` helper is also a symptom of this.
This formatting should be factored out to explicit helpers. ``functools.singledispatch`` can be used to combine the ease of per-clause ``__str__`` with other requirements.
|
0.0
|
2edb9fcd1925163ec05ee121e942fea55f97ed5a
|
[
"tests/test_boot.py::test_bootstrap",
"tests/test_boot.py::test_escalate",
"tests/test_boot.py::test_features",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause0]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause1]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause2]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause3]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause4]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause5]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause6]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause7]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause8]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause9]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause10]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause11]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause12]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause13]"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-29 18:19:46+00:00
|
mit
| 3,831 |
|
maxfischer2781__bootpeg-23
|
diff --git a/bootpeg/grammars/bpeg.bpeg b/bootpeg/grammars/bpeg.bpeg
index db1d421..9996a58 100644
--- a/bootpeg/grammars/bpeg.bpeg
+++ b/bootpeg/grammars/bpeg.bpeg
@@ -11,9 +11,9 @@ end_line:
literal:
| ('"' :: '"') | ("'" :: "'") { Literal(.*[1:-1]) }
range:
- | first=literal spaces "-" spaces last=literal { Range(.first.value, .last.value) }
+ | first=literal spaces "-" ~ spaces last=literal { Range(.first.value, .last.value) }
delimited:
- | start=expr spaces "::" spaces stop=expr { Delimited(.start, .stop) }
+ | start=expr spaces "::" ~ spaces stop=expr { Delimited(.start, .stop) }
terminal:
| term=(range | nothing | literal | anything) { .term }
@@ -24,26 +24,28 @@ identifier:
| ( ( "a" - "z" ) | ( "A" - "Z" ) | "_" )+ { .* }
optional:
- | "[" spaces expr=expr spaces "]" { either(.expr, Nothing()) }
+ | "[" ~ spaces expr=expr spaces "]" { either(.expr, Nothing()) }
group:
- | "(" spaces expr=expr spaces ")" { .expr }
+ | "(" ~ spaces expr=expr spaces ")" { .expr }
choice:
- | try=expr spaces "|" spaces else=expr { either(.try, .else) }
+ | try=expr spaces "|" ~ spaces else=expr { either(.try, .else) }
sequence:
| head=expr spaces tail=expr { chain(.head, .tail) }
repeat:
| expr=expr spaces "+" { Repeat(.expr) }
| expr=expr spaces "*" { either(Repeat(.expr), Nothing()) }
capture:
- | name=identifier spaces "=" spaces expr=(reference | group) { Capture(.name, .expr) }
+ | name=identifier spaces "=" ~ spaces expr=(reference | group) { Capture(.name, .expr) }
reference:
| name=identifier { Reference(.name) }
reject:
- | "!" spaces expr=expr { Not(.expr) }
+ | "!" ~ spaces expr=expr { Not(.expr) }
require:
- | "&" spaces expr=expr { And(.expr) }
+ | "&" ~ spaces expr=expr { And(.expr) }
+commit:
+ | "~" ~ spaces expr=expr { require(.expr) }
expr:
- | expr=(choice | sequence | repeat | delimited | capture | reference | group | optional | reject | require | terminal) { .expr }
+ | expr=(choice | require | sequence | repeat | delimited | capture | reference | group | optional | reject | commit | terminal) { .expr }
rule:
| "|" spaces expr=expr spaces action=("{" :: "}") { Rule(.expr, Action(.action[1:-1])) }
@@ -54,7 +56,7 @@ comment:
blank:
| spaces end_line { Discard() }
define:
- | name=identifier ":" spaces end_line rules=rules { (.name, .rules) }
+ | name=identifier ":" ~ spaces end_line rules=rules { (.name, .rules) }
rules:
| " " spaces try=rule spaces end_line else=rules { either(.try, .else) }
| " " spaces rule=rule spaces end_line { .rule }
diff --git a/bootpeg/pika/act.py b/bootpeg/pika/act.py
index 54c94c8..620c80f 100644
--- a/bootpeg/pika/act.py
+++ b/bootpeg/pika/act.py
@@ -1,7 +1,7 @@
"""
Pika bottom-up Peg parser extension to transform parsed source
"""
-from typing import TypeVar, Any, Dict, Tuple, Mapping
+from typing import TypeVar, Any, Dict, Tuple, Mapping, Union, NamedTuple
import re
from .peg import Clause, D, Match, MemoTable, MemoKey, Literal, nested_str, Reference
@@ -49,7 +49,7 @@ class Capture(Clause[D]):
__slots__ = ("name", "sub_clauses", "_hash")
- def __init__(self, name, sub_clause: Clause[D]):
+ def __init__(self, name: str, sub_clause: Clause[D]):
self.name = name
self.sub_clauses = (sub_clause,)
self._hash = None
@@ -192,6 +192,105 @@ class Action:
return f"{self.__class__.__name__}({self.literal!r})"
+class Commit(Clause[D]):
+ """
+ The commitment to a clause, requiring a match of the sub_clause
+
+ This clause always matches, even if the sub_clause does not.
+ As a result, it "cuts" away alternatives of *not* matching the sub_clause.
+
+ Since Pika matches spuriously and can accumulate several failures,
+ a ``Cut`` does not raise an error during parsing.
+ Any :py:meth:`~.failed` match should be reported after parsing.
+ """
+
+ __slots__ = ("sub_clauses", "_hash")
+
+ def __init__(self, sub_clause: Clause[D]):
+ self.sub_clauses = (sub_clause,)
+ self._hash = None
+
+ @property
+ def maybe_zero(self):
+ return True
+
+ # The difference between a successful and failed match
+ # is that we do/don't have a parent match.
+ # A match length may be 0 in either case, if the parent
+ # matched 0 length or not at all.
+ def match(self, source: D, at: int, memo: MemoTable):
+ # While `Commit` handles cases in which the child is not matched,
+ # Pika never tries to match `Commit` without the child matching.
+ # An "empty" match is created by the memo as needed.
+ parent_match = memo[MemoKey(at, self.sub_clauses[0])]
+ return Match(parent_match.length, (parent_match,), at, self)
+
+ @classmethod
+ def failed(cls, match: Match) -> bool:
+ """Check whether the given ``match`` only succeeded due to the ``Cut``."""
+ assert isinstance(match.clause, cls), f"a {cls.__name__} match is required"
+ return not match.sub_matches and not match.clause.sub_clauses[0].maybe_zero
+
+ def __eq__(self, other):
+ return isinstance(other, Commit) and self.sub_clauses == other.sub_clauses
+
+ @cache_hash
+ def __hash__(self):
+ return hash(self.sub_clauses)
+
+ def __repr__(self):
+ return f"{self.__class__.__name__}({self.sub_clauses[0]!r})"
+
+ def __str__(self):
+ return f"~{self.sub_clauses[0]}"
+
+
+class CommitFailure(NamedTuple):
+ """Information on a single failed :py:class:`~.Commit` match"""
+
+ position: int
+ commit: Commit
+
+
+class NamedFailure(NamedTuple):
+ """Information on all failures of a :py:class:`~.Reference` match"""
+
+ name: str
+ failures: Tuple[CommitFailure]
+
+
+def leaves(failure):
+ if isinstance(failure, CommitFailure):
+ yield failure
+ elif isinstance(failure, NamedFailure):
+ for child in failure.failures:
+ yield from leaves(child)
+ else:
+ raise NotImplementedError
+
+
+class CapturedParseFailure(Exception):
+ """Parsing captured match failures"""
+
+ def __init__(self, *failures: Union[NamedFailure, CommitFailure]):
+ self.failures = failures
+ leave_failures = sorted(
+ {leave for failure in failures for leave in leaves(failure)},
+ key=lambda failure: failure.position,
+ )
+ leave_reports = (
+ f"{str(failure.commit.sub_clauses[0])!r}@{failure.position}"
+ for failure in leave_failures
+ )
+ super().__init__(f'failed expected parse of {", ".join(leave_reports)}')
+
+ @property
+ def positions(self):
+ return {
+ leave.position for failure in self.failures for leave in leaves(failure)
+ }
+
+
class TransformFailure(Exception):
def __init__(self, clause, matches, captures, exc: Exception):
super().__init__(f"failed to transform {clause}: {exc}")
@@ -202,25 +301,48 @@ class TransformFailure(Exception):
def transform(head: Match, memo: MemoTable, namespace: Mapping[str, Any]):
- return postorder_transform(head, memo.source, namespace)
+ matches, captures, failures = postorder_transform(head, memo.source, namespace)
+ if not failures:
+ return matches, captures
+ else:
+ raise CapturedParseFailure(*failures)
# TODO: Use trampoline/coroutines for infinite depth
def postorder_transform(
match: Match, source: D, namespace: Mapping[str, Any]
-) -> Tuple[Any, Dict[str, Any]]:
- matches, captures = (), {}
+) -> Tuple[Tuple, Dict[str, Any], Tuple]:
+ matches: Tuple = ()
+ captures: Dict[str, Any] = {}
+ failures: Tuple = ()
for sub_match in match.sub_matches:
- sub_matches, sub_captures = postorder_transform(sub_match, source, namespace)
+ sub_matches, sub_captures, sub_failures = postorder_transform(
+ sub_match, source, namespace
+ )
matches += sub_matches
captures.update(sub_captures)
+ failures += sub_failures
position, clause = match.position, match.clause
- if isinstance(clause, Capture):
+ if isinstance(clause, Commit):
+ if Commit.failed(match):
+ failures = (*failures, CommitFailure(position, clause))
+ elif isinstance(clause, Reference):
+ new_failures = tuple(
+ failure for failure in failures if not isinstance(failure, NamedFailure)
+ )
+ if new_failures:
+ failures = (
+ NamedFailure(clause.target, new_failures),
+ *(failure for failure in failures if isinstance(failure, NamedFailure)),
+ )
+ if failures:
+ return (), {}, failures
+ elif isinstance(clause, Capture):
assert len(matches) <= 1, "Captured rule must provide no more than one value"
captures[Action.mangle + clause.name] = (
matches[0] if matches else source[position : position + match.length]
)
- return (), captures
+ return (), captures, failures
elif isinstance(clause, Rule):
matches = matches if matches else source[position : position + match.length]
try:
@@ -229,5 +351,5 @@ def postorder_transform(
raise
except Exception as exc:
raise TransformFailure(clause, matches, captures, exc)
- return (result,) if not isinstance(result, Discard) else (), {}
- return matches, captures
+ return (result,) if not isinstance(result, Discard) else (), {}, failures
+ return matches, captures, failures
diff --git a/bootpeg/pika/boot.bpeg b/bootpeg/pika/boot.bpeg
index 1696a92..4396b7f 100644
--- a/bootpeg/pika/boot.bpeg
+++ b/bootpeg/pika/boot.bpeg
@@ -38,8 +38,10 @@ reject:
| "!" spaces expr=expr { Not(.expr) }
require:
| "&" spaces expr=expr { And(.expr) }
+commit:
+ | "~" spaces expr=expr { require(.expr) }
expr:
- | expr=(choice | sequence | repeat | delimited | capture | reference | group | optional | reject | require | range | literal | anything | nothing) { .expr }
+ | expr=(choice | commit | sequence | repeat | delimited | capture | reference | group | optional | reject | require | range | literal | anything | nothing) { .expr }
rule:
| "|" spaces expr=expr spaces "{" body=(((!"}") .)+) "}" { Rule(.expr, Action(.body)) }
diff --git a/bootpeg/pika/boot.py b/bootpeg/pika/boot.py
index 2a09b3b..defc556 100644
--- a/bootpeg/pika/boot.py
+++ b/bootpeg/pika/boot.py
@@ -22,9 +22,11 @@ from .front import (
Rule,
Action,
Discard,
+ Commit,
transform,
chain,
either,
+ require,
Range,
Delimited,
unescape,
@@ -126,6 +128,8 @@ namespace = {
Rule,
Action,
Discard,
+ Commit,
+ require,
Range,
Delimited,
unescape,
@@ -326,20 +330,21 @@ def bootpeg() -> Parser:
if __name__ == "__main__":
parser = bootpeg()
+ print("Generation:", -1, "(min)")
+ display(parser)
for iteration in range(2):
with open(boot_path) as boot_peg:
- print("Generation:", iteration)
- display(parser)
parser = range_parse(
boot_peg.read(),
parser,
)
+ print("Generation:", iteration, "(boot)")
+ display(parser)
for iteration in range(2, 4):
with open(full_path) as base_peg:
- print("Generation:", iteration)
- display(min_parser)
parser = range_parse(
base_peg.read(),
parser,
)
- display(parser)
+ print("Generation:", iteration, "(bpeg)")
+ display(parser)
diff --git a/bootpeg/pika/front.py b/bootpeg/pika/front.py
index b6edefc..e2de01e 100644
--- a/bootpeg/pika/front.py
+++ b/bootpeg/pika/front.py
@@ -19,7 +19,16 @@ from .peg import (
Terminal,
D,
)
-from .act import Debug, Capture, Rule, transform, Action, Discard
+from .act import (
+ Debug,
+ Capture,
+ Rule,
+ transform,
+ Action,
+ Discard,
+ Commit,
+ CapturedParseFailure,
+)
from ..utility import cache_hash
__all__ = [
@@ -40,6 +49,8 @@ __all__ = [
"Rule",
"Action",
"Discard",
+ "Commit",
+ "CapturedParseFailure",
"transform",
# helpers
"chain",
@@ -50,7 +61,7 @@ __all__ = [
]
-def chain(left, right) -> Sequence:
+def chain(left: Clause[D], right: Clause[D]) -> Sequence[D]:
"""Chain two clauses efficiently"""
if isinstance(left, Sequence):
if isinstance(right, Sequence):
@@ -61,7 +72,7 @@ def chain(left, right) -> Sequence:
return Sequence(left, right)
-def either(left, right) -> Choice:
+def either(left: Clause[D], right: Clause[D]) -> Choice[D]:
"""Choose between two clauses efficiently"""
if isinstance(left, Choice):
if isinstance(right, Choice):
@@ -72,6 +83,19 @@ def either(left, right) -> Choice:
return Choice(left, right)
+def require(target: Clause[D]) -> Clause[D]:
+ """Commit to clauses efficiently"""
+ # It is tempting to try and remove `maybe_zero` clauses here.
+ # However, we cannot actually do that: There is no full grammar here, just clauses
+ # – but at least Reference needs the grammar to derive its `maybe_zero`.
+ if isinstance(target, Commit):
+ return target
+ elif isinstance(target, Sequence):
+ return Sequence(*(require(clause) for clause in target.sub_clauses))
+ else:
+ return Commit(target)
+
+
class Range(Terminal[D]):
"""
A terminal matching anything between two bounds inclusively
diff --git a/docs/source/grammar_bpeg.rst b/docs/source/grammar_bpeg.rst
index 02eea0f..383a02b 100644
--- a/docs/source/grammar_bpeg.rst
+++ b/docs/source/grammar_bpeg.rst
@@ -77,6 +77,20 @@ any: ``e*``
Match ``e`` zero or several times. Equivalent to ``[ e+ ]``.
+commit: ``~ e``
+
+ Match ``e`` or fail. Always succeeds, may be zero width.
+
+ Failure to match ``e`` records the failure but proceeds "as if" ``e`` matched.
+ Useful for accurate failure reports.
+ ::
+
+ # fail on empty and mismatched parentheses
+ '(' ~ expr ')' | expr
+
+ Binds tighter than sequences and less tight than choices:
+ ``~e1 e2 | e3`` is equivalent to ``(~e1 ~e2) | e3``.
+
capture: ``name=e``
Capture the result of matching ``e`` with a given ``name`` for use in a rule action.
|
maxfischer2781/bootpeg
|
621e6ed1bae500cd9d255f47985db6c4c12eeffd
|
diff --git a/tests/test_grammars/test_bpeg.py b/tests/test_grammars/test_bpeg.py
index ab99117..d2a97bf 100644
--- a/tests/test_grammars/test_bpeg.py
+++ b/tests/test_grammars/test_bpeg.py
@@ -14,6 +14,7 @@ from bootpeg.pika.front import (
Reference,
Range,
Delimited,
+ CapturedParseFailure,
)
@@ -43,3 +44,16 @@ def test_roundtrip(clause):
"parse_test"
]
assert parsed_rule.sub_clauses[0] == clause
+
+
+commit_failures = (("top:\n | ~\n", {9}),)
+
+
[email protected]("source, positions", commit_failures)
+def test_commit(source, positions):
+ try:
+ bpeg.parse(source)
+ except CapturedParseFailure as cpf:
+ assert cpf.positions == positions
+ else:
+ assert not positions, "Expected parse failures, found none"
|
Provide rule commitment
Top-down PEG parsers commonly provide a "no backup" operator ([PEP 617 ``~``](https://www.python.org/dev/peps/pep-0617/#id9)/[pyparsing ``-``](https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html#operators)) that causes a failure if a follow-up rule does not match. A common example are matching parentheses: an opening parenthesis requires a closing parenthesis:
```
# PEP 617
group: "(" - expr - ")"
```
This "commit to rule" operator simplifies error detection/reporting.
Since Pika matches spuriously, it cannot directly commit to a rule and raise an error. Instead, reporting must be delayed until the outer rule has been matched.
|
0.0
|
621e6ed1bae500cd9d255f47985db6c4c12eeffd
|
[
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause0]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause1]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause2]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause3]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause4]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause5]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause6]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause7]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause8]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause9]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause10]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause11]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause12]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause13]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause14]",
"tests/test_grammars/test_bpeg.py::test_roundtrip[clause15]",
"tests/test_grammars/test_bpeg.py::test_commit[top:\\n"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-27 18:06:57+00:00
|
mit
| 3,832 |
|
maxfischer2781__cms_perf-6
|
diff --git a/cms_perf/cli.py b/cms_perf/cli.py
index 5f504eb..3dc73e6 100644
--- a/cms_perf/cli.py
+++ b/cms_perf/cli.py
@@ -1,6 +1,7 @@
import argparse
from . import xrd_load
+from . import net_load
from . import __version__ as lib_version
@@ -68,6 +69,27 @@ CLI_PAG = CLI.add_subparsers(
title="pag plugins", description="Sensor to use for the pag measurement",
)
+# pag System Plugins
+CLI_PAG_NUMSOCK = CLI_PAG.add_parser(
+ "pag=num_sockets", help="Total sockets across all processes",
+)
+CLI_PAG_NUMSOCK.add_argument(
+ "--max-sockets",
+ default=1000,
+ help="Maximum total sockets considered 100%%",
+ type=int,
+)
+CLI_PAG_NUMSOCK.add_argument(
+ "--socket-kind",
+ help="Which sockets to count",
+ choices=list(net_load.ConnectionKind.__members__),
+ default="tcp",
+)
+CLI_PAG_NUMSOCK.set_defaults(
+ __make_pag__=lambda args: net_load.prepare_num_sockets(
+ net_load.ConnectionKind.__getitem__(args.socket_kind), args.max_sockets
+ )
+)
# pag XRootD Plugins
CLI_PAG_XIOWAIT = CLI_PAG.add_parser(
diff --git a/cms_perf/net_load.py b/cms_perf/net_load.py
new file mode 100644
index 0000000..ebf8003
--- /dev/null
+++ b/cms_perf/net_load.py
@@ -0,0 +1,28 @@
+"""
+Sensor for network load
+"""
+import enum
+
+import psutil
+
+
+class ConnectionKind(enum.Enum):
+ inet = enum.auto()
+ inet4 = enum.auto()
+ inet6 = enum.auto()
+ tcp = enum.auto()
+ tcp4 = enum.auto()
+ tcp6 = enum.auto()
+ udp = enum.auto()
+ udp4 = enum.auto()
+ udp6 = enum.auto()
+ unix = enum.auto()
+ all = enum.auto()
+
+
+def prepare_num_sockets(kind: ConnectionKind, max_sockets):
+ return lambda: 100.0 * num_sockets(kind) / max_sockets
+
+
+def num_sockets(kind: ConnectionKind) -> float:
+ return len(psutil.net_connections(kind=kind.name))
diff --git a/cms_perf/xrd_load.py b/cms_perf/xrd_load.py
index 0c4813f..46c4b18 100644
--- a/cms_perf/xrd_load.py
+++ b/cms_perf/xrd_load.py
@@ -13,17 +13,17 @@ def rescan(interval):
def prepare_iowait(interval: float):
tracker = XrootdTracker(rescan_interval=rescan(interval))
- return tracker.io_wait
+ return lambda: 100.0 * tracker.io_wait()
def prepare_numfds(interval: float, max_core_fds: float):
tracker = XrootdTracker(rescan_interval=rescan(interval))
- return lambda: tracker.num_fds() / max_core_fds / psutil.cpu_count()
+ return lambda: 100.0 * tracker.num_fds() / max_core_fds / psutil.cpu_count()
def prepare_threads(interval: float, max_core_threads: float):
tracker = XrootdTracker(rescan_interval=rescan(interval))
- return lambda: tracker.num_threads() / max_core_threads / psutil.cpu_count()
+ return lambda: 100.0 * tracker.num_threads() / max_core_threads / psutil.cpu_count()
def is_alive(proc: psutil.Process) -> bool:
|
maxfischer2781/cms_perf
|
f1ee7a28ea9d6af3a96965763c656fc4b8aa46ce
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index a9e4617..ace0296 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -37,7 +37,7 @@ def test_run_sched(executable: List[str]):
assert total == readings[0]
-PAG_PLUGINS = ["xrootd.io_wait", "xrootd.num_fds", "xrootd.num_threads"]
+PAG_PLUGINS = ["num_sockets", "xrootd.io_wait", "xrootd.num_fds", "xrootd.num_threads"]
@mimicry.skipif_unsuported
|
Feature: Provide connection load sensor
Add a sensor for number of open connections. This is an indication for the number of requests the system must handle, and possibly if connections are stalling.
See [``psutil.net_connections``](https://psutil.readthedocs.io/en/latest/#psutil.net_connections) for a potential backend.
|
0.0
|
f1ee7a28ea9d6af3a96965763c656fc4b8aa46ce
|
[
"tests/test_cli.py::test_run_pag_plugin[num_sockets-executable0]",
"tests/test_cli.py::test_run_pag_plugin[num_sockets-executable1]"
] |
[
"tests/test_cli.py::test_run_normal[executable0]",
"tests/test_cli.py::test_run_normal[executable1]",
"tests/test_cli.py::test_run_sched[executable0]",
"tests/test_cli.py::test_run_sched[executable1]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.io_wait-executable0]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.io_wait-executable1]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.num_fds-executable0]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.num_fds-executable1]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.num_threads-executable0]",
"tests/test_cli.py::test_run_pag_plugin[xrootd.num_threads-executable1]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-22 12:01:56+00:00
|
mit
| 3,833 |
|
maxhumber__gif-17
|
diff --git a/examples/spiral.py b/examples/spiral.py
index 98f9431..ba5b5c3 100644
--- a/examples/spiral.py
+++ b/examples/spiral.py
@@ -10,7 +10,7 @@ N = 100
@gif.frame
def plot_spiral(i):
fig = plt.figure(figsize=(5, 3), dpi=100)
- ax = fig.gca(projection="3d")
+ ax = fig.add_subplot(projection="3d")
a, b = 0.5, 0.2
th = np.linspace(475, 500, N)
x = a * np.exp(b * th) * np.cos(th)
diff --git a/gif.py b/gif.py
index 570e4e1..efd90f1 100644
--- a/gif.py
+++ b/gif.py
@@ -60,12 +60,31 @@ def frame(plot: Callable[..., Plot]) -> Callable[..., Frame]: # type: ignore[va
return inner
+def _optimize_frames(frames: List[Frame]):
+ import numpy as np
+ joined_img = PI.fromarray(np.vstack(frames))
+ joined_img = joined_img.quantize(colors=256 - 1, dither=0)
+ palette = b'\xff\x00\xff' + joined_img.palette.getdata()[1]
+ joined_img_arr = np.array(joined_img)
+ joined_img_arr += 1
+ arrays = np.vsplit(joined_img_arr, len(frames))
+
+ prev_array = arrays[0]
+ for array in arrays[1:]:
+ mask = array == prev_array
+ prev_array = array.copy()
+ array[mask] = 0
+ frames_out = [PI.fromarray(array) for array in arrays]
+ return frames_out, palette
+
+
def save(
frames: List[Frame], # type: ignore[valid-type]
path: str,
duration: Milliseconds = 100,
*,
overlapping: bool = True,
+ optimize: bool = False,
) -> None:
"""Save prepared frames to .gif file
@@ -78,7 +97,15 @@ def save(
"""
if not path.endswith(".gif"):
- raise ValueError("must end with .gif")
+ raise ValueError(f"'{path}' must end with .gif")
+
+ kwargs = {}
+ if optimize:
+ frames, palette = _optimize_frames(frames)
+ kwargs = {
+ "palette": palette,
+ "transparency": 0,
+ }
frames[0].save( # type: ignore
path,
@@ -88,4 +115,5 @@ def save(
duration=duration,
disposal=0 if overlapping else 2,
loop=0,
+ **kwargs
)
|
maxhumber/gif
|
d41ef3ac837fed1bc9f4b8c217c16ee07cbd64b3
|
diff --git a/tests/test_gif.py b/tests/test_gif.py
index 87f0ebe..5d260a7 100644
--- a/tests/test_gif.py
+++ b/tests/test_gif.py
@@ -1,3 +1,4 @@
+import os
import pytest
from matplotlib import pyplot as plt
from PIL import Image
@@ -22,30 +23,35 @@ def plot(x, y):
plt.scatter(x, y)
[email protected](scope="session")
-def default_file(tmpdir_factory):
+def make_gif(tmpdir_factory, filename, dpi=None, **kwargs):
+ if dpi is not None:
+ gif.options.matplotlib["dpi"] = 300
frames = [plot([0, 5], [0, 5]), plot([0, 10], [0, 10])]
- path = str(tmpdir_factory.mktemp("matplotlib").join("default.gif"))
- gif.save(frames, path)
+ if dpi is not None:
+ gif.options.reset()
+ path = str(tmpdir_factory.mktemp("matplotlib").join(filename))
+ gif.save(frames, path, **kwargs)
return path
[email protected](scope="session")
+def default_file(tmpdir_factory):
+ return make_gif(tmpdir_factory, "default.gif")
+
+
[email protected](scope="session")
+def optimized_file(tmpdir_factory):
+ return make_gif(tmpdir_factory, "optimized.gif", optimize=True)
+
+
@pytest.fixture(scope="session")
def hd_file(tmpdir_factory):
- gif.options.matplotlib["dpi"] = 300
- frames = [plot([0, 5], [0, 5]), plot([0, 10], [0, 10])]
- gif.options.reset()
- path = str(tmpdir_factory.mktemp("matplotlib").join("hd.gif"))
- gif.save(frames, path)
- return path
+ return make_gif(tmpdir_factory, "hd.gif", dpi=300)
@pytest.fixture(scope="session")
def long_file(tmpdir_factory):
- frames = [plot([0, 5], [0, 5]), plot([0, 10], [0, 10])]
- path = str(tmpdir_factory.mktemp("matplotlib").join("long.gif"))
- gif.save(frames, path, duration=2500)
- return path
+ return make_gif(tmpdir_factory, "long.gif", duration=2500)
def test_frame():
@@ -59,6 +65,12 @@ def test_default_save(default_file):
assert milliseconds(img) == 200
+def test_optimization(default_file, optimized_file):
+ default_size = os.stat(default_file).st_size
+ optimized_size = os.stat(optimized_file).st_size
+ assert optimized_size < default_size * 0.9
+
+
def test_dpi_save(hd_file):
img = Image.open(hd_file)
assert img.format == "GIF"
|
Size optimization idea
Hi! I have an idea about optimizing gif size:
```python
from PIL import Image
from pathlib import Path
import numpy as np
# read list of pngs
paths = sorted(Path('.').glob('out*.png'))
# open pngs as numpy arrays
images = [np.array(Image.open(path)) for path in paths]
# stack the arrays into a single image
mega_img = Image.fromarray(np.hstack(images))
# reduce number of colors to 255, allowing for 0 to be transparent
mega_img = mega_img.quantize(colors=256 - 1, dither=0)
# append transparent color to the palette
palette = b'\xff\x00\xff' + mega_img.palette.getdata()[1]
# split arrays back
arrays = np.hsplit(np.array(mega_img), len(paths))
for array in arrays:
# account for transparent color
array += 1
prev_array = arrays[0]
for array in arrays[1:]:
mask = array == prev_array
prev_array = array.copy()
# set unchanged pixels to transparent color
array[mask] = 0
path = 'out.gif'
duration_ms = 200
images = [Image.fromarray(array) for array in arrays]
images[0].save( # type: ignore
path,
save_all=True,
append_images=images[1:],
palette=palette,
optimize=True,
duration=duration_ms,
disposal=0,
loop=0,
transparency=0,
version='GIF89a',
)
```
With this code my image sequence produced 176KiB gif instead of 3400KiB gif. The downside is that it is reasonably slower and uses at least 2x memory. Is there a place for this optimization technique in this library?
|
0.0
|
d41ef3ac837fed1bc9f4b8c217c16ee07cbd64b3
|
[
"tests/test_gif.py::test_optimization"
] |
[
"tests/test_gif.py::test_frame",
"tests/test_gif.py::test_default_save",
"tests/test_gif.py::test_dpi_save",
"tests/test_gif.py::test_long_save"
] |
{
"failed_lite_validators": [
"has_media",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-27 20:08:01+00:00
|
mit
| 3,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.