buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def json_body_tests_json_body_post(
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
else:
raise ApiResponseError(response=response) | def json_body_tests_json_body_post(
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
else:
raise ApiResponseError(response=response)
def test_defaults_tests_test_defaults_post(
*,
client: Client,
json_body: Dict[Any, Any],
string_prop: Optional[str] = "th... |
from dataclasses import asdict
from datetime import date, datetime
from typing import Any, Dict, List, Optional, Union, cast
import httpx | import datetime
from dataclasses import asdict, field
from typing import Any, Dict, List, Optional, Union, cast
import httpx |
async def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime],
) -> Union[
List[AModel], HTTPValidationError,
]: |
async def get_user_list(
*, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime],
) -> Union[
List[AModel], HTTPValidationError,
]: |
async def get_user_list(
json_an_enum_value.append(an_enum_value_item)
if isinstance(some_date, date):
json_some_date = some_date.isoformat()
else: | async def get_user_list(
json_an_enum_value.append(an_enum_value_item)
if isinstance(some_date, datetime.date):
json_some_date = some_date.isoformat()
else: |
async def json_body_tests_json_body_post(
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
else:
raise ApiResponseError(response=response) | async def json_body_tests_json_body_post(
return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json()))
else:
raise ApiResponseError(response=response)
async def test_defaults_tests_test_defaults_post(
*,
client: Client,
json_body: Dict[Any, Any],
string_prop: Optiona... |
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any, Dict, List, Optional, Union, cast
from .an_enum import AnEnum | from __future__ import annotations
import datetime
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union, cast
from .an_enum import AnEnum |
class AModel:
""" A Model for testing all the ways custom objects can be used """
an_enum_value: AnEnum
a_camel_date_time: Union[datetime, date]
a_date: date
nested_list_of_enums: Optional[List[List[DifferentEnum]]] = field(
default_factory=lambda: cast(Optional[List[List[DifferentEnum]]],... | class AModel:
""" A Model for testing all the ways custom objects can be used """
an_enum_value: AnEnum
some_dict: Dict[Any, Any]
a_camel_date_time: Union[datetime.datetime, datetime.date]
a_date: datetime.date
nested_list_of_enums: Optional[List[List[DifferentEnum]]] = field(
default_... |
def to_dict(self) -> Dict[str, Any]:
nested_list_of_enums.append(nested_list_of_enums_item)
some_dict = self.some_dict
return {
"an_enum_value": an_enum_value,
"aCamelDateTime": a_camel_date_time,
"a_date": a_date,
"nested_list_of_enums"... | def to_dict(self) -> Dict[str, Any]:
nested_list_of_enums.append(nested_list_of_enums_item)
return {
"an_enum_value": an_enum_value,
"some_dict": some_dict,
"aCamelDateTime": a_camel_date_time,
"a_date": a_date,
"nested_list_of_enums"... |
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]:
nested_list_of_enums.append(nested_list_of_enums_item)
some_dict = d.get("some_dict")
return AModel(
an_enum_value=an_enum_value,
a_camel_date_time=a_camel_date_time,
a_date=a_... | def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]:
nested_list_of_enums.append(nested_list_of_enums_item)
return AModel(
an_enum_value=an_enum_value,
some_dict=some_dict,
a_camel_date_time=a_camel_date_time,
a_date=a_date,
... |
def __init__(self, *, openapi: GeneratorData) -> None:
self.package_name: str = self.package_name_override or self.project_name.replace("-", "_")
self.package_dir: Path = self.project_dir / self.package_name
self.package_description: str = f"A client library for accessing {self.openapi.title}"
... | def __init__(self, *, openapi: GeneratorData) -> None:
self.package_name: str = self.package_name_override or self.project_name.replace("-", "_")
self.package_dir: Path = self.project_dir / self.package_name
self.package_description: str = utils.remove_string_escapes(
f"A client lib... |
class PropertyError(ParseError):
""" Error raised when there's a problem creating a Property """
header = "Problem creating a Property: " | class PropertyError(ParseError):
""" Error raised when there's a problem creating a Property """
header = "Problem creating a Property: "
class ValidationError(Exception):
pass |
from pydantic import ValidationError
from .. import schema as oai
from .errors import GeneratorError, ParseError, PropertyError
from .properties import EnumProperty, Property, property_from_data
from .reference import Reference | from pydantic import ValidationError
from .. import schema as oai
from .. import utils
from .errors import GeneratorError, ParseError, PropertyError
from .properties import EnumProperty, Property, property_from_data
from .reference import Reference |
def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union
endpoint = Endpoint(
path=path,
method=method,
description=data.description,
name=data.operationId,
requires_security=bool(data.security),
tag=tag, | def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union
endpoint = Endpoint(
path=path,
method=method,
description=utils.remove_string_escapes(data.description) if data.description else "",
name=data.operationId,
requires_secur... |
from __future__ import annotations
from dataclasses import InitVar, dataclass, field
from typing import Any, ClassVar, Dict, Generic, List, Optional, Set, TypeVar, Union
from .. import schema as oai
from .. import utils
from .errors import PropertyError
from .reference import Reference
| from __future__ import annotations
from dataclasses import InitVar, dataclass, field
from datetime import date, datetime
from typing import Any, ClassVar, Dict, Generic, List, Optional, Set, TypeVar, Union
from .. import schema as oai
from .. import utils
from .errors import PropertyError, ValidationError
from .refer... |
class Property:
templates/property_templates and must contain two macros: construct and transform. Construct will be used to
build this property from JSON data (a response from an API). Transform will be used to convert this property
to JSON data (when sending a request to the API).
... | class Property:
templates/property_templates and must contain two macros: construct and transform. Construct will be used to
build this property from JSON data (a response from an API). Transform will be used to convert this property
to JSON data (when sending a request to the API).
... |
class Property:
def __post_init__(self) -> None:
self.python_name = utils.snake_case(self.name)
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self._type_string
... | class Property:
def __post_init__(self) -> None:
self.python_name = utils.snake_case(self.name)
if self.default is not None:
self.default = self._validate_default(default=self.default)
def _validate_default(self, default: Any) -> Any:
""" Check that the default value is val... |
class StringProperty(Property):
_type_string: ClassVar[str] = "str"
def __post_init__(self) -> None:
super().__post_init__()
if self.default is not None:
self.default = f'"{self.default}"'
@dataclass | class StringProperty(Property):
_type_string: ClassVar[str] = "str"
def _validate_default(self, default: Any) -> str:
return f'"{utils.remove_string_escapes(default)}"'
@dataclass |
class DateTimeProperty(Property):
A property of type datetime.datetime
"""
_type_string: ClassVar[str] = "datetime"
template: ClassVar[str] = "datetime_property.pyi"
def get_imports(self, *, prefix: str) -> Set[str]: | class DateTimeProperty(Property):
A property of type datetime.datetime
"""
_type_string: ClassVar[str] = "datetime.datetime"
template: ClassVar[str] = "datetime_property.pyi"
def get_imports(self, *, prefix: str) -> Set[str]: |
def get_imports(self, *, prefix: str) -> Set[str]:
prefix: A prefix to put before any relative (local) module names.
"""
imports = super().get_imports(prefix=prefix)
imports.update({"from datetime import datetime", "from typing import cast"})
return imports
@dataclass
class... | def get_imports(self, *, prefix: str) -> Set[str]:
prefix: A prefix to put before any relative (local) module names.
"""
imports = super().get_imports(prefix=prefix)
imports.update({"import datetime", "from typing import cast"})
return imports
def _validate_default(self,... |
def get_imports(self, *, prefix: str) -> Set[str]:
prefix: A prefix to put before any relative (local) module names.
"""
imports = super().get_imports(prefix=prefix)
imports.update({"from datetime import date", "from typing import cast"})
return imports
@dataclass
class Fil... | def get_imports(self, *, prefix: str) -> Set[str]:
prefix: A prefix to put before any relative (local) module names.
"""
imports = super().get_imports(prefix=prefix)
imports.update({"import datetime", "from typing import cast"})
return imports
def _validate_default(self,... |
class FloatProperty(Property):
default: Optional[float] = None
_type_string: ClassVar[str] = "float"
@dataclass
class IntProperty(Property): | class FloatProperty(Property):
default: Optional[float] = None
_type_string: ClassVar[str] = "float"
def _validate_default(self, default: Any) -> float:
try:
return float(default)
except (TypeError, ValueError) as e:
raise ValidationError() from e
@dataclass
class ... |
class IntProperty(Property):
default: Optional[int] = None
_type_string: ClassVar[str] = "int"
@dataclass
class BooleanProperty(Property): | class IntProperty(Property):
default: Optional[int] = None
_type_string: ClassVar[str] = "int"
def _validate_default(self, default: Any) -> int:
try:
return int(default)
except (TypeError, ValueError) as e:
raise ValidationError() from e
@dataclass
class BooleanPro... |
class BooleanProperty(Property):
_type_string: ClassVar[str] = "bool"
InnerProp = TypeVar("InnerProp", bound=Property)
| class BooleanProperty(Property):
_type_string: ClassVar[str] = "bool"
def _validate_default(self, default: Any) -> bool:
# no try/except needed as anything that comes from the initial load from json/yaml will be boolable
return bool(default)
InnerProp = TypeVar("InnerProp", bound=Property)
|
class ListProperty(Property, Generic[InnerProp]):
inner_property: InnerProp
template: ClassVar[str] = "list_property.pyi"
def __post_init__(self) -> None:
super().__post_init__()
if self.default is not None:
self.default = f"field(default_factory=lambda: cast({self.get_type_stri... | class ListProperty(Property, Generic[InnerProp]):
inner_property: InnerProp
template: ClassVar[str] = "list_property.pyi"
def get_type_string(self, no_optional: bool = False) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.require... |
def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import cast")
return imports
@dataclass
class UnionProperty(Property): | def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import cast")
return imports
def _validate_default(self, default: Any) -> str:
if not isinstance(default, list):
raise ValidationError()
default = list(map(self.inner_property._validate_defa... |
class UnionProperty(Property):
inner_properties: List[Property]
template: ClassVar[str] = "union_property.pyi"
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
inner_types = [p.get_type_string() for p in self.inne... | class UnionProperty(Property):
inner_properties: List[Property]
template: ClassVar[str] = "union_property.pyi"
def get_type_string(self, no_optional: bool = False) -> str:
""" Get a string representation of type that should be used when declaring this property """
inner_types = [p.get_type_... |
def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import Union")
return imports
_existing_enums: Dict[str, EnumProperty] = {}
| def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import Union")
return imports
def _validate_default(self, default: Any) -> Any:
for property in self.inner_properties:
try:
val = property._validate_default(default)
retur... |
class EnumProperty(Property):
template: ClassVar[str] = "enum_property.pyi"
def __post_init__(self, title: str) -> None: # type: ignore
super().__post_init__()
reference = Reference.from_ref(title)
dedup_counter = 0
while reference.class_name in _existing_enums: | class EnumProperty(Property):
template: ClassVar[str] = "enum_property.pyi"
def __post_init__(self, title: str) -> None: # type: ignore
reference = Reference.from_ref(title)
dedup_counter = 0
while reference.class_name in _existing_enums: |
def __post_init__(self, title: str) -> None: # type: ignore
reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}")
self.reference = reference
inverse_values = {v: k for k, v in self.values.items()}
if self.default is not None:
self.default = f"{self.re... | def __post_init__(self, title: str) -> None: # type: ignore
reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}")
self.reference = reference
super().__post_init__()
_existing_enums[self.reference.class_name] = self
@staticmethod |
def get_enum(name: str) -> Optional[EnumProperty]:
""" Get all the EnumProperties that have been registered keyed by class name """
return _existing_enums.get(name)
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """... | def get_enum(name: str) -> Optional[EnumProperty]:
""" Get all the EnumProperties that have been registered keyed by class name """
return _existing_enums.get(name)
def get_type_string(self, no_optional: bool = False) -> str:
""" Get a string representation of type that should be used when ... |
def values_from_list(values: List[str]) -> Dict[str, str]:
key = f"VALUE_{i}"
if key in output:
raise ValueError(f"Duplicate key {key} in Enum")
output[key] = value
return output
@dataclass
class RefProperty(Property): | def values_from_list(values: List[str]) -> Dict[str, str]:
key = f"VALUE_{i}"
if key in output:
raise ValueError(f"Duplicate key {key} in Enum")
sanitized_key = utils.fix_keywords(utils.sanitize(key))
output[sanitized_key] = utils.remove_string_escapes... |
def template(self) -> str: # type: ignore
return "enum_property.pyi"
return "ref_property.pyi"
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self.reference.clas... | def template(self) -> str: # type: ignore
return "enum_property.pyi"
return "ref_property.pyi"
def get_type_string(self, no_optional: bool = False) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required or no_option... |
def get_imports(self, *, prefix: str) -> Set[str]:
)
return imports
@dataclass
class DictProperty(Property):
""" Property that is a general Dict """
_type_string: ClassVar[str] = "Dict[Any, Any]"
def __post_init__(self) -> None:
super().__post_init__()
if self.default is ... | def get_imports(self, *, prefix: str) -> Set[str]:
)
return imports
def _validate_default(self, default: Any) -> Any:
enum = EnumProperty.get_enum(self.reference.class_name)
if enum:
return enum._validate_default(default)
else:
raise ValidationError
... |
def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import cast")
return imports
def _string_based_property(
name: str, required: bool, data: oai.Schema | def get_imports(self, *, prefix: str) -> Set[str]:
imports.add("from typing import cast")
return imports
def _validate_default(self, default: Any) -> str:
if isinstance(default, dict):
return repr(default)
raise ValidationError
def _string_based_property(
name:... |
def _string_based_property(
return StringProperty(name=name, default=data.default, required=required, pattern=data.pattern)
def property_from_data(
name: str, required: bool, data: Union[oai.Reference, oai.Schema]
) -> Union[Property, PropertyError]:
""" Generate a Property from the OpenAPI dictionary... | def _string_based_property(
return StringProperty(name=name, default=data.default, required=required, pattern=data.pattern)
def _property_from_data(
name: str, required: bool, data: Union[oai.Reference, oai.Schema]
) -> Union[Property, PropertyError]:
""" Generate a Property from the OpenAPI dictionar... |
def property_from_data(
elif data.type == "object":
return DictProperty(name=name, required=required, default=data.default)
return PropertyError(data=data, detail=f"unknown type {data.type}") | def property_from_data(
elif data.type == "object":
return DictProperty(name=name, required=required, default=data.default)
return PropertyError(data=data, detail=f"unknown type {data.type}")
def property_from_data(
name: str, required: bool, data: Union[oai.Reference, oai.Schema]
) -> Union[Prope... |
import re
import stringcase
def _sanitize(value: str) -> str:
return re.sub(r"[^\w _-]+", "", value)
def group_title(value: str) -> str:
value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip())
value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) ... | import re
from keyword import iskeyword
import stringcase
def sanitize(value: str) -> str:
return re.sub(r"[^\w _\-]+", "", value)
def fix_keywords(value: str) -> str:
if iskeyword(value):
return f"{value}_"
return value
def group_title(value: str) -> str:
value = re.sub(r"([A-Z]{2,})([A-... |
from pydantic.error_wrappers import ErrorWrapper
import openapi_python_client.schema as oai
from openapi_python_client import GeneratorError
from openapi_python_client.parser.errors import ParseError
MODULE_NAME = "openapi_python_client.parser.openapi" | from pydantic.error_wrappers import ErrorWrapper
import openapi_python_client.schema as oai
from openapi_python_client import GeneratorError, utils
from openapi_python_client.parser.errors import ParseError
MODULE_NAME = "openapi_python_client.parser.openapi" |
def test_from_data(self, mocker):
responses=mocker.MagicMock(),
)
endpoint = Endpoint.from_data(data=data, path=path, method=method, tag="default")
assert endpoint == _add_body.return_value | def test_from_data(self, mocker):
responses=mocker.MagicMock(),
)
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=data.description)
endpoint = Endpoint.from_data(data=data, path=path, method=method, tag="default")
assert endpoint == _add_body... |
import pytest
import openapi_python_client.schema as oai
from openapi_python_client.parser.errors import PropertyError
MODULE_NAME = "openapi_python_client.parser.properties"
class TestProperty:
def test_get_type_string(self):
from openapi_python_client.parser.properties import Property
| from datetime import date, datetime
import pytest
import openapi_python_client.schema as oai
from openapi_python_client.parser.errors import PropertyError, ValidationError
from openapi_python_client.parser.reference import Reference
MODULE_NAME = "openapi_python_client.parser.properties"
class TestProperty:
de... |
def test_get_imports(self, mocker):
p.required = False
assert p.get_imports(prefix="") == {"from typing import Optional"}
class TestStringProperty:
def test___post_init__(self):
from openapi_python_client.parser.properties import StringProperty
sp = StringProperty(name="test", req... | def test_get_imports(self, mocker):
p.required = False
assert p.get_imports(prefix="") == {"from typing import Optional"}
def test__validate_default(self):
from openapi_python_client.parser.properties import Property
# should be okay if default isn't specified
p = Property(... |
def test_get_type_string(self):
p.required = False
assert p.get_type_string() == "Optional[str]"
class TestDateTimeProperty:
def test_get_imports(self, mocker): | def test_get_type_string(self):
p.required = False
assert p.get_type_string() == "Optional[str]"
def test__validate_default(self):
from openapi_python_client.parser.properties import StringProperty
p = StringProperty(name="a name", required=True, default="the default value")
... |
def test_get_imports(self, mocker):
mocker.patch("openapi_python_client.utils.snake_case")
p = DateTimeProperty(name=name, required=True, default=None)
assert p.get_imports(prefix="") == {
"from datetime import datetime",
"from typing import cast",
}
p.re... | def test_get_imports(self, mocker):
mocker.patch("openapi_python_client.utils.snake_case")
p = DateTimeProperty(name=name, required=True, default=None)
assert p.get_imports(prefix="") == {
"import datetime",
"from typing import cast",
}
p.required = False... |
def test_get_imports(self, mocker):
mocker.patch("openapi_python_client.utils.snake_case")
p = DateProperty(name=name, required=True, default=None)
assert p.get_imports(prefix="") == {
"from datetime import date",
"from typing import cast",
}
p.required =... | def test_get_imports(self, mocker):
mocker.patch("openapi_python_client.utils.snake_case")
p = DateProperty(name=name, required=True, default=None)
assert p.get_imports(prefix="") == {
"import datetime",
"from typing import cast",
}
p.required = False
... |
def test_get_imports(self, mocker):
"from dataclasses import astuple",
}
class TestListProperty:
def test_get_type_string(self, mocker): | def test_get_imports(self, mocker):
"from dataclasses import astuple",
}
def test__validate_default(self):
from openapi_python_client.parser.properties import FileProperty
# should be okay if default isn't specified
p = FileProperty(name="a name", required=True, default... |
def test_get_type_imports(self, mocker):
"from dataclasses import field",
}
class TestUnionProperty:
def test_get_type_string(self, mocker): | def test_get_type_imports(self, mocker):
"from dataclasses import field",
}
def test__validate_default(self, mocker):
from openapi_python_client.parser.properties import ListProperty
inner_property = mocker.MagicMock()
inner_type_string = mocker.MagicMock()
inne... |
def test_get_type_imports(self, mocker):
"from typing import Optional",
}
class TestEnumProperty:
def test___post_init__(self, mocker): | def test_get_type_imports(self, mocker):
"from typing import Optional",
}
def test__validate_default(self, mocker):
from openapi_python_client.parser.properties import UnionProperty
inner_property_1 = mocker.MagicMock()
inner_property_1.get_type_string.return_value = "i... |
def test_get_enum(self):
assert properties.EnumProperty.get_enum("test") == "an enum"
properties._existing_enums = {}
class TestRefProperty:
def test_template(self, mocker): | def test_get_enum(self):
assert properties.EnumProperty.get_enum("test") == "an enum"
properties._existing_enums = {}
def test__validate_default(self, mocker):
fake_reference = mocker.MagicMock(class_name="MyTestEnum", module_name="my_test_enum")
mocker.patch(f"{MODULE_NAME}.Referen... |
def test_get_imports(self, mocker):
"from typing import Optional",
}
class TestDictProperty:
def test___post_init__(self):
from openapi_python_client.parser.properties import DictProperty
p = DictProperty(name="blah", required=True, default={})
assert p.default == "fie... | def test_get_imports(self, mocker):
"from typing import Optional",
}
def test__validate_default(self, mocker):
from openapi_python_client.parser.properties import RefProperty
with pytest.raises(ValidationError):
p = RefProperty(name="a name", required=True, default=... |
def test_get_imports(self, mocker):
"from dataclasses import field",
}
class TestPropertyFromData:
def test_property_from_data_enum(self, mocker): | def test_get_imports(self, mocker):
"from dataclasses import field",
}
def test__validate_default(self):
from openapi_python_client.parser.properties import DictProperty
p = DictProperty(name="a name", required=True, default={"key": "value"})
with pytest.raises(Validat... |
def test_property_from_data_enum(self, mocker):
required = mocker.MagicMock()
data = mocker.MagicMock(title=None)
EnumProperty = mocker.patch(f"{MODULE_NAME}.EnumProperty")
from openapi_python_client.parser.properties import property_from_data
| def test_property_from_data_enum(self, mocker):
required = mocker.MagicMock()
data = mocker.MagicMock(title=None)
EnumProperty = mocker.patch(f"{MODULE_NAME}.EnumProperty")
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name)
from openapi_python_c... |
def test_property_from_data_ref(self, mocker):
data = oai.Reference.construct(ref=mocker.MagicMock())
from_ref = mocker.patch(f"{MODULE_NAME}.Reference.from_ref")
RefProperty = mocker.patch(f"{MODULE_NAME}.RefProperty")
from openapi_python_client.parser.properties import property_from_d... | def test_property_from_data_ref(self, mocker):
data = oai.Reference.construct(ref=mocker.MagicMock())
from_ref = mocker.patch(f"{MODULE_NAME}.Reference.from_ref")
RefProperty = mocker.patch(f"{MODULE_NAME}.RefProperty")
mocker.patch("openapi_python_client.utils.remove_string_escapes", re... |
def test_property_from_data_string(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema.construct(type="string")
from openapi_python_client.parser.properties import property_from_data
p = property_from_data(name=name, required=required, data=d... | def test_property_from_data_string(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema.construct(type="string")
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name)
from openapi_python_client.parser.properties ... |
def test_property_from_data_simple_types(self, mocker, openapi_type, python_type
required = mocker.MagicMock()
data = oai.Schema.construct(type=openapi_type)
clazz = mocker.patch(f"{MODULE_NAME}.{python_type}")
from openapi_python_client.parser.properties import property_from_data
| def test_property_from_data_simple_types(self, mocker, openapi_type, python_type
required = mocker.MagicMock()
data = oai.Schema.construct(type=openapi_type)
clazz = mocker.patch(f"{MODULE_NAME}.{python_type}")
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_valu... |
def test_property_from_data_array(self, mocker):
data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},)
ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty")
FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty")
from openapi_python_client.parser.propert... | def test_property_from_data_array(self, mocker):
data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},)
ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty")
FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty")
mocker.patch("openapi_python_client.utils.... |
def test_property_from_data_array_invalid_items(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(type="array", items={},)
from openapi_python_client.parser.properties import property_from_data
| def test_property_from_data_array_invalid_items(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(type="array", items={},)
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name)
from openapi_python_client.parse... |
def test_property_from_data_union(self, mocker):
UnionProperty = mocker.patch(f"{MODULE_NAME}.UnionProperty")
FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty")
IntProperty = mocker.patch(f"{MODULE_NAME}.IntProperty")
from openapi_python_client.parser.properties import propert... | def test_property_from_data_union(self, mocker):
UnionProperty = mocker.patch(f"{MODULE_NAME}.UnionProperty")
FloatProperty = mocker.patch(f"{MODULE_NAME}.FloatProperty")
IntProperty = mocker.patch(f"{MODULE_NAME}.IntProperty")
mocker.patch("openapi_python_client.utils.remove_string_esca... |
def test_property_from_data_union_bad_type(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(anyOf=[{}])
from openapi_python_client.parser.properties import property_from_data
| def test_property_from_data_union_bad_type(self, mocker):
name = mocker.MagicMock()
required = mocker.MagicMock()
data = oai.Schema(anyOf=[{}])
mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name)
from openapi_python_client.parser.properties impor... |
def test_property_from_data_no_valid_props_in_data(self):
data=data, detail="Schemas must either have one of enum, anyOf, or type defined."
)
class TestStringBasedProperty:
def test__string_based_property_no_format(self, mocker): | def test_property_from_data_no_valid_props_in_data(self):
data=data, detail="Schemas must either have one of enum, anyOf, or type defined."
)
def test_property_from_data_validation_error(self, mocker):
from openapi_python_client.parser.errors import PropertyError
from openapi_py... |
def test_snake_case_from_camel():
def test_kebab_case():
assert utils.kebab_case("keep_alive") == "keep-alive" | def test_snake_case_from_camel():
def test_kebab_case():
assert utils.kebab_case("keep_alive") == "keep-alive"
def test__sanitize():
assert utils.sanitize("something*~with lots_- of weird things}=") == "somethingwith lots_- of weird things"
def test_no_string_escapes():
assert utils.remove_string_escap... |
class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
return multi_join_idx, lidx, ridx
jl = list(overlap)[0]
| class Index(IndexOpsMixin, PandasObject):
multi_join_idx = multi_join_idx.remove_unused_levels()
if return_indexers:
return multi_join_idx, lidx, ridx
else:
return multi_join_idx
jl = list(overlap)[0]
|
def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=False)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.... | def test_join_multi_wrong_order():
midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])
midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"])
join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True)
exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp)
tm.a... |
class BracketTracker:
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_variable: int = 0
_lambda_arguments: int = 0
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with brack... | class BracketTracker:
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_depths: List[int] = Factory(list)
_lambda_argument_depths: List[int] = Factory(list)
def mark(self, leaf: Leaf) ->... |
class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_variable += 1
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for... | class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_depths.append(self.depth)
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_i... |
class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_arguments += 1
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_la... | class BracketTracker:
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_argument_depths.append(self.depth)
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
def test_report_verbose(self) -> None:
report = black.Report(verbose=True)
out_lines = [] | class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, line_length=ll)
@patch("black.dump_to_file", dump_to_stderr)
def test_bracket_match(self) -> None:
source, expected = read_data("bracketmatch")
actual = fs(source)... |
def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connection | def __init__(self, host, port=None, strict=None,
(self.host, self.port) = self._get_hostport(host, port)
self._validate_host(self.host)
# This is stored as an instance variable to allow unittests
# to replace with a suitable mock
self._create_connection = socket.create_connect... |
def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def putheader(self, header, *values):
"""Send a request header line to the server.
| def _validate_path(self, url):
).format(matched=match.group(), url=url)
raise InvalidURL(msg)
def _validate_host(self, host):
"""Validate a host so it doesn't contain control characters."""
# Prevent CVE-2019-18348.
match = _contains_disallowed_url_pchar_re.search(ho... |
def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-38216). | def test_proxy_tunnel_without_status_line(self):
with self.assertRaisesRegexp(socket.error, "Invalid response"):
conn._tunnel()
def test_putrequest_override_domain_validation(self):
"""
It should be possible to override the default validation
behavior in putrequest (bpo-... |
def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
class OfflineTest(TestCase):
def test_responses(self): | def _validate_path(self, url):
conn.sock = FakeSocket('')
conn.putrequest('GET', '/\x00')
def test_putrequest_override_host_validation(self):
class UnsafeHTTPConnection(httplib.HTTPConnection):
def _validate_host(self, url):
pass
conn = UnsafeHTTPConnect... |
def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char | def test_unsupported_algorithm(self):
)
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_control_char_rejected(self):
for char_no in range(0, 0x21) + range(0x7f, 0x100):
char = chr(char_no)
schemeless_url = "//localhost:7777/test%s/" % char |
def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\... | def test_url_with_control_char_rejected(self):
self.unfakehttp()
@unittest.skipUnless(ssl, "ssl module required")
def test_url_path_with_newline_header_injection_rejected(self):
self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he... |
def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(
InvalidURL, r"... | def test_url_with_newline_header_injection_rejected(self):
# calls urllib.parse.quote() on the URL which makes all of the
# above attempts at injection within the url _path_ safe.
InvalidURL = httplib.InvalidURL
with self.assertRaisesRegexp(InvalidURL,
... |
class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if disable:
self.iterable = iterable
self.disable = disable
self.pos = self._get_free_pos(self)
self._instances.remove(self)
... | class tqdm(Comparable):
if disable is None and hasattr(file, "isatty") and not file.isatty():
disable = True
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... |
class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if total is None and iterable is not None:
try:
total = len(iterable)
except (TypeError, AttributeError):
total = None
... | class tqdm(Comparable):
else TqdmKeyError("Unknown argument(s): " + str(kwargs)))
# Preprocess the arguments
if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \
dynamic_ncols: # pragma: no cover
if dynamic_ncols: |
def test_threading():
# TODO: test interleaved output #445
@with_setup(pretest, posttest)
def test_autonotebook():
"""Test autonotebook fallback""" | def test_threading():
# TODO: test interleaved output #445
@with_setup(pretest, posttest)
def test_bool():
"""Test boolean cast"""
def internal(our_file, disable):
with tqdm(total=10, file=our_file, disable=disable) as t:
assert t
with tqdm(total=0, file=our_file, disable=disab... |
class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)} | class TestSortedCorrectedCommandsSequence(object):
settings)
assert set(seq) == {CorrectedCommand('ls', priority=100),
CorrectedCommand('ls', side_effect, 300)}
class TestCorrectedCommand(object):
def test_equality(self):
assert CorrectedCommand('ls', None,... |
from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
CorrectedCommand = namedtuple('CorrectedCommand', ('script', 'side_effect', 'priority'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
... | from .logs import debug
Command = namedtuple('Command', ('script', 'stdout', 'stderr'))
Rule = namedtuple('Rule', ('name', 'match', 'get_new_command',
'enabled_by_default', 'side_effect',
'priority', 'requires_output'))
class CorrectedCommand(object):
def __i... |
class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command.script != first.script or \
command.side_effect != first.side_effect:
return [first, command]
return [first]
def _remove_duplicates... | class SortedCorrectedCommandsSequence(object):
return []
for command in self._commands:
if command != first:
return [first, command]
return [first]
def _remove_duplicates(self, corrected_commands):
"""Removes low-priority duplicates."""
comma... |
class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# os.makedirs applies the global umask, so we reset it,
# for consistency with file_permissions_mode behavior.
old_uma... | class FileSystemStorage(Storage):
directory = os.path.dirname(full_path)
try:
if self.directory_permissions_mode is not None:
# Set the umask because os.makedirs() doesn't apply the "mode"
# argument to intermediate-level directories.
old_umask... |
class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save("the_directory/the_file", ContentFile("data"))
dir_mo... | class FileStoragePermissions(unittest.TestCase):
@override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
def test_file_upload_directory_permissions(self):
self.storage = FileSystemStorage(self.storage_dir)
name = self.storage.save('the_directory/subdir/the_file', ContentFile('data'))
... |
import sys
import tempfile
import unittest
from io import StringIO
from unittest import mock
from django.conf import settings | import sys
import tempfile
import unittest
from io import StringIO
from pathlib import Path
from unittest import mock
from django.conf import settings |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
file_mod... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_permissions(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().st_mode & 0o777
... |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_default_permissions(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_default_permissions(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().st_mode ... |
class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_subclass_of_static_storage(self):
call_command('collectstatic', **self.command_params)
test_file = os.path.join(settings.STATIC_ROOT, "test.txt")
test_dir = os.path.join(settings.STATIC_ROOT, "subdir")
... | class TestStaticFilePermissions(CollectionTestCase):
)
def test_collect_static_files_subclass_of_static_storage(self):
call_command('collectstatic', **self.command_params)
static_root = Path(settings.STATIC_ROOT)
test_file = static_root / 'test.txt'
file_mode = test_file.stat().s... |
def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output_path, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) | def get_write_function(output):
stderr.write(s)
elif isinstance(output, (pycompat.PathLike, str)):
def write(s):
with open(output, 'a') as output_file:
output_file.write(s)
else:
assert isinstance(output, utils.WritableStream) |
import abc
from python_toolbox import caching
from python_toolbox import sys_tools
import pysnooper
| import abc
from python_toolbox import caching
from python_toolbox import sys_tools
from python_toolbox import temp_file_tools
import pysnooper
|
def test_method_and_prefix():
),
prefix='ZZZ'
) | def test_method_and_prefix():
),
prefix='ZZZ'
)
def test_file_output():
with temp_file_tools.create_temp_folder(prefix='pysnooper') as folder:
path = folder / 'foo.log'
@pysnooper.snoop(str(path))
def my_function(foo):
x = 7
y = 8
ret... |
def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP):
encryption_cipher = ... | def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
## ECB mode
mode = self.module.MODE_ECB
encryption_cipher = self.module.new(a2b_hex(self.key), mode)
ciphertext = encryption_cipher.enc... |
class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError):
continue
return new_data, True
return data, False | class Parser:
for date_unit in date_units:
try:
new_data = to_datetime(new_data, errors="raise", unit=date_unit)
except (ValueError, OverflowError, TypeError):
continue
return new_data, True
return data, False |
DataFrame\\.index values are different \\(100\\.0 %\\)
# GH 31615
result = pd.DataFrame([[nulls_fixture]]).to_json()
assert result == '{"0":{"0":null}}' | DataFrame\\.index values are different \\(100\\.0 %\\)
# GH 31615
result = pd.DataFrame([[nulls_fixture]]).to_json()
assert result == '{"0":{"0":null}}'
def test_readjson_bool_series(self):
# GH31464
result = read_json("[true, true, false]", typ="series")
expected = ... |
import logging
import salt.utils.files
import salt.utils.path
import salt.payload
from salt.ext import six | import logging
import salt.utils.files
import salt.utils.path
import salt.utils.verify
import salt.payload
from salt.ext import six |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not salt.utils.verify.clean_path(opts['token_dir'], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
log = logging.getLogger(__name__)
| import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
import salt.ext.six
log = logging.getLogger(__name__)
|
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ''
for part in path.split(os.path.sep)[1:]:
if base != '':
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
... | def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(
yaml_contents,
default_flow_style=False,
)
if not os.... |
def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_: | def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['file_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.p... | def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
root = __opts__['file_roots'][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_p... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created' | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config('master')
self.conf_dir... |
class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.minion.test_blackout',
'integration.minion.test_executor',
'i... | class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.master.test_clear_funcs',
'integration.minion.test_blackout',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.