buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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 _LocIndexer(_LocationIndexer): return self._getbool_axis(key, axis=axis) elif is_list_like_indexer(key): # convert various list-like indexers # to a list of keys # we will use the *values* of the object # and NOT the index if its a PandasObject ...
class _LocIndexer(_LocationIndexer): return self._getbool_axis(key, axis=axis) elif is_list_like_indexer(key): # an iterable multi-selection if not (isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)):
class TestMultiIndexLoc: @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) def test_loc_multiindex_list_missing_label(self, key, pos): # GH 27148 - lists with missing labels do not raise: df = DataFrame( np.random.randn(3, 3), columns=[[2,...
class TestMultiIndexLoc: @pytest.mark.parametrize("key, pos", [([2, 4], [0, 1]), ([2], []), ([2, 3], [])]) def test_loc_multiindex_list_missing_label(self, key, pos): # GH 27148 - lists with missing labels _do_ raise df = DataFrame( np.random.randn(3, 3), columns=[[2, 2,...
class TestMultiIndexLoc: [ ([], []), # empty ok (["A"], slice(3)), (["A", "D"], slice(3)), (["D", "E"], []), # no values found - fine (["D"], []), # same, with single item list: GH 27148 (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), (pd.IndexSlice[:, ["fo...
class TestMultiIndexLoc: [ ([], []), # empty ok (["A"], slice(3)), (["A", "D"], []), # "D" isnt present -> raise (["D", "E"], []), # no values found -> raise (["D"], []), # same, with single item list: GH 27148 (pd.IndexSlice[:, ["foo"]], slice(2, None, 3)), ...
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): ) s = Series(np.arange(9, dtype="int64"), index=idx).sort_index() expected = s.iloc[pos] result = s.loc[indexer] tm.assert_series_equal(result, expected) def test_series_loc_getitem_fancy(multiindex_year_month_day_dataframe...
def test_loc_getitem_duplicates_multiindex_missing_indexers(indexer, pos): ) s = Series(np.arange(9, dtype="int64"), index=idx).sort_index() expected = s.iloc[pos] if expected.size == 0 and indexer != []: with pytest.raises(KeyError, match=str(indexer)): s.loc[indexer] else: ...
class TestMultiIndexSlicers: with pytest.raises(ValueError, match=msg): df.loc[(slice(None), np.array([True, False])), :] # ambiguous notation # this is interpreted as slicing on both axes (GH #16396) result = df.loc[slice(None), [1]] expected = df.iloc[:, []] ...
class TestMultiIndexSlicers: with pytest.raises(ValueError, match=msg): df.loc[(slice(None), np.array([True, False])), :] with pytest.raises(KeyError, match=r"\[1\] not in index"): # slice(None) is on the index, [1] is on the columns, but 1 is # not in the columns, ...
class TestSeriesGetitemListLike: result = ser[key] tm.assert_series_equal(result, expected) def test_getitem_generator(string_series): gen = (x > 0 for x in string_series)
class TestSeriesGetitemListLike: result = ser[key] tm.assert_series_equal(result, expected) @pytest.mark.parametrize("box", [list, np.array, pd.Index]) @pytest.mark.parametrize("dtype", [np.int64, np.float64, np.uint64]) def test_getitem_intlist_multiindex_numeric_level(self, dtype, box): ...
else: def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, http_cookies.BaseCookie): try: c = SimpleCookie() c.load(cookie) except http_cookies.CookieError: # Invalid cookie return {} else: c = cookie...
else: def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} if six.PY2: cookie = force_str(cookie) for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: ...
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_str, force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_httponly_after_load(self): """ Test that we can use httponly attribute on cookies that we load
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_python_cookies(self): """ Test cases copied from Python's Lib/test/test_http_cookies.py """ self.assertEqual(parse_cookie('chips=ahoy; ...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, parse_cookie, ) from django.test import RequestFactory, SimpleTestCase, override_settings from d...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, ) from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client ...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid@key=true'), {}) def test_httpr...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_abs...
class Axes(_AxesBase): if not np.iterable(xmax): xmax = [xmax] y, xmin, xmax = cbook.delete_masked_points(y, xmin, xmax) y = np.ravel(y) xmin = np.resize(xmin, y.shape) xmax = np.resize(xmax, y.shape) verts = [((thisxmin, thisy), (thisxmax, thisy)) ...
class Axes(_AxesBase): if not np.iterable(xmax): xmax = [xmax] # Create and combine masked_arrays from input y, xmin, xmax = cbook._combine_masks(y, xmin, xmax) y = np.ravel(y) xmin = np.ravel(xmin) xmax = np.ravel(xmax) masked_verts = np.ma.empty((l...
class Axes(_AxesBase): if not np.iterable(ymax): ymax = [ymax] x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax) x = np.ravel(x) ymin = np.resize(ymin, x.shape) ymax = np.resize(ymax, x.shape) verts = [((thisx, thisymin), (thisx, thisymax)) ...
class Axes(_AxesBase): if not np.iterable(ymax): ymax = [ymax] # Create and combine masked_arrays from input x, ymin, ymax = cbook._combine_masks(x, ymin, ymax) x = np.ravel(x) ymin = np.ravel(ymin) ymax = np.ravel(ymax) masked_verts = np.ma.empty((l...
def test_hlines(): ax5.set_ylim(0, 15) @image_comparison(['step_linestyle', 'step_linestyle'], remove_text=True) def test_step_linestyle(): x = y = np.arange(10)
def test_hlines(): ax5.set_ylim(0, 15) @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], np.ma.masked_equal([1, 2, 3, 4, 5], 4)]) @check_figures_equal(extensions=["png"]) def test_lines_with_colors(fig_test, fig_ref, data): test_colors = ['red', 'green', 'blue', 'purple...
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() except AssertionError as e: raise exception.Unauthorized(e.message)
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() # If the tenant is disabled don't allow them to authenticate if tenant_re...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) if tenant_ref: metadata_ref = self.identity_api.get_metadata( context=context...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) # If the tenant is disabled don't allow them to authenticate if tenant_ref and not tenant_ref.get('enabl...
def test_authenticate_no_username(self): self.get_client, user_ref) # FIXME(ja): this test should require the "keystone:admin" roled # (probably the role set via --keystone_admin_role flag) # FIXME(ja): add a test that admin endpoint is only se...
def test_authenticate_no_username(self): self.get_client, user_ref) def test_authenticate_disabled_tenant(self): from keystoneclient import exceptions as client_exceptions admin_client = self.get_client(admin=True) tenant = { ...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tuple cont...
class HttpRequest: def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tup...
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) class IsOverriddenTest(SimpleTestCase): def test_configure(self):
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequ...
class Rolling(_Rolling_and_Expanding): def _on(self): if self.on is None: return self.obj.index elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns: return Index(self.obj[self.on]) else:
class Rolling(_Rolling_and_Expanding): def _on(self): if self.on is None: if self.axis == 0: return self.obj.index elif self.axis == 1: return self.obj.columns elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns: ...
class TestRolling(Base): result = pd.Series(arr).rolling(2).mean() expected = pd.Series([np.nan, 2, np.nan, np.nan, 4]) tm.assert_series_equal(result, expected)
class TestRolling(Base): result = pd.Series(arr).rolling(2).mean() expected = pd.Series([np.nan, 2, np.nan, np.nan, 4]) tm.assert_series_equal(result, expected) def test_rolling_datetime(self, axis_frame, tz_naive_fixture): # GH-28192 tz = tz_naive_fixture df = pd.Da...
class Axes(_AxesBase): if not np.iterable(xmax): xmax = [xmax] y, xmin, xmax = cbook.delete_masked_points(y, xmin, xmax) y = np.ravel(y) xmin = np.resize(xmin, y.shape) xmax = np.resize(xmax, y.shape) verts = [((thisxmin, thisy), (thisxmax, thisy)) ...
class Axes(_AxesBase): if not np.iterable(xmax): xmax = [xmax] # Create and combine masked_arrays from input y, xmin, xmax = cbook._combine_masks(y, xmin, xmax) y = np.ravel(y) xmin = np.ravel(xmin) xmax = np.ravel(xmax) masked_verts = np.ma.empty((l...
class Axes(_AxesBase): if not np.iterable(ymax): ymax = [ymax] x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax) x = np.ravel(x) ymin = np.resize(ymin, x.shape) ymax = np.resize(ymax, x.shape) verts = [((thisx, thisymin), (thisx, thisymax)) ...
class Axes(_AxesBase): if not np.iterable(ymax): ymax = [ymax] # Create and combine masked_arrays from input x, ymin, ymax = cbook._combine_masks(x, ymin, ymax) x = np.ravel(x) ymin = np.ravel(ymin) ymax = np.ravel(ymax) masked_verts = np.ma.empty((l...
def test_hlines(): ax5.set_ylim(0, 15) @image_comparison(['step_linestyle', 'step_linestyle'], remove_text=True) def test_step_linestyle(): x = y = np.arange(10)
def test_hlines(): ax5.set_ylim(0, 15) @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5], np.ma.masked_equal([1, 2, 3, 4, 5], 4)]) @check_figures_equal(extensions=["png"]) def test_lines_with_colors(fig_test, fig_ref, data): test_colors = ['red', 'green', 'blue', 'purple...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s p=%(process)d u...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG loggin...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s p=%(process)d u...
logger = None if getattr(C, 'DEFAULT_LOG_PATH'): path = C.DEFAULT_LOG_PATH if path and (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK): # NOTE: level is kept at INFO to avoid security disclosures caused by certain libraries when using DEBUG loggin...
# the maximum length for a user id is 255 characters MAX_USERID_LENGTH = 255 class Membership:
# the maximum length for a user id is 255 characters MAX_USERID_LENGTH = 255 # The maximum length for a group id is 255 characters MAX_GROUPID_LENGTH = 255 MAX_GROUP_CATEGORYID_LENGTH = 255 MAX_GROUP_ROLEID_LENGTH = 255 class Membership:
from typing import Optional, Tuple, Type import synapse from synapse.api.errors import Codes, FederationDeniedError, SynapseError from synapse.api.room_versions import RoomVersions from synapse.api.urls import (
from typing import Optional, Tuple, Type import synapse from synapse.api.constants import MAX_GROUP_CATEGORYID_LENGTH, MAX_GROUP_ROLEID_LENGTH from synapse.api.errors import Codes, FederationDeniedError, SynapseError from synapse.api.room_versions import RoomVersions from synapse.api.urls import (
async def on_POST(self, origin, content, query, group_id, category_id, room_id): raise SynapseError(403, "requester_user_id doesn't match origin") if category_id == "": raise SynapseError(400, "category_id cannot be empty string") resp = await self.handler.update_group_summary_...
async def on_POST(self, origin, content, query, group_id, category_id, room_id): raise SynapseError(403, "requester_user_id doesn't match origin") if category_id == "": raise SynapseError( 400, "category_id cannot be empty string", Codes.INVALID_PARAM ) ...
async def on_POST(self, origin, content, query, group_id, category_id): if category_id == "": raise SynapseError(400, "category_id cannot be empty string") resp = await self.handler.upsert_group_category( group_id, requester_user_id, category_id, content )
async def on_POST(self, origin, content, query, group_id, category_id): if category_id == "": raise SynapseError(400, "category_id cannot be empty string") if len(category_id) > MAX_GROUP_CATEGORYID_LENGTH: raise SynapseError( 400, "category_id ma...
async def on_POST(self, origin, content, query, group_id, role_id): raise SynapseError(403, "requester_user_id doesn't match origin") if role_id == "": raise SynapseError(400, "role_id cannot be empty string") resp = await self.handler.update_group_role( group_id, r...
async def on_POST(self, origin, content, query, group_id, role_id): raise SynapseError(403, "requester_user_id doesn't match origin") if role_id == "": raise SynapseError( 400, "role_id cannot be empty string", Codes.INVALID_PARAM ) if len(role_id) >...
async def on_POST(self, origin, content, query, group_id, role_id, user_id): if role_id == "": raise SynapseError(400, "role_id cannot be empty string") resp = await self.handler.update_group_summary_user( group_id, requester_user_id,
async def on_POST(self, origin, content, query, group_id, role_id, user_id): if role_id == "": raise SynapseError(400, "role_id cannot be empty string") if len(role_id) > MAX_GROUP_ROLEID_LENGTH: raise SynapseError( 400, "role_id may not be longer...
import logging import random from typing import Tuple from signedjson.sign import sign_json from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.metrics.background_process_metrics import run_as_background_process from synapse.types import get_domain_from_id logger = log...
import logging import random from typing import TYPE_CHECKING, Optional, Tuple from signedjson.sign import sign_json from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.metrics.background_process_metrics import run_as_background_process from synapse.types import JsonDic...
class GroupAttestationSigning: """Creates and verifies group attestations.""" def __init__(self, hs): self.keyring = hs.get_keyring() self.clock = hs.get_clock() self.server_name = hs.hostname self.signing_key = hs.signing_key async def verify_attestation( self, att...
class GroupAttestationSigning: """Creates and verifies group attestations.""" def __init__(self, hs: "HomeServer"): self.keyring = hs.get_keyring() self.clock = hs.get_clock() self.server_name = hs.hostname self.signing_key = hs.signing_key async def verify_attestation( ...
async def verify_attestation( if valid_until_ms < now: raise SynapseError(400, "Attestation expired") await self.keyring.verify_json_for_server( server_name, attestation, now, "Group attestation" ) def create_attestation(self, group_id, user_id): """Create a...
async def verify_attestation( if valid_until_ms < now: raise SynapseError(400, "Attestation expired") assert server_name is not None await self.keyring.verify_json_for_server( server_name, attestation, now, "Group attestation" ) def create_attestation(self, ...
def create_attestation(self, group_id, user_id): class GroupAttestionRenewer: """Responsible for sending and receiving attestation updates.""" def __init__(self, hs): self.clock = hs.get_clock() self.store = hs.get_datastore() self.assestations = hs.get_groups_attestation_signing()
def create_attestation(self, group_id, user_id): class GroupAttestionRenewer: """Responsible for sending and receiving attestation updates.""" def __init__(self, hs: "HomeServer"): self.clock = hs.get_clock() self.store = hs.get_datastore() self.assestations = hs.get_groups_attestation_...
def __init__(self, hs): self._start_renew_attestations, 30 * 60 * 1000 ) async def on_renew_attestation(self, group_id, user_id, content): """When a remote updates an attestation""" attestation = content["attestation"]
def __init__(self, hs): self._start_renew_attestations, 30 * 60 * 1000 ) async def on_renew_attestation( self, group_id: str, user_id: str, content: JsonDict ) -> JsonDict: """When a remote updates an attestation""" attestation = content["attestation"]
async def on_renew_attestation(self, group_id, user_id, content): return {} def _start_renew_attestations(self): return run_as_background_process("renew_attestations", self._renew_attestations) async def _renew_attestations(self): """Called periodically to check if we need to update a...
async def on_renew_attestation(self, group_id, user_id, content): return {} def _start_renew_attestations(self) -> None: return run_as_background_process("renew_attestations", self._renew_attestations) async def _renew_attestations(self) -> None: """Called periodically to check if we ...
async def _renew_attestations(self): now + UPDATE_ATTESTATION_TIME_MS ) async def _renew_attestation(group_user: Tuple[str, str]): group_id, user_id = group_user try: if not self.is_mine_id(group_id):
async def _renew_attestations(self): now + UPDATE_ATTESTATION_TIME_MS ) async def _renew_attestation(group_user: Tuple[str, str]) -> None: group_id, user_id = group_user try: if not self.is_mine_id(group_id):
# limitations under the License. import logging from synapse.api.errors import Codes, SynapseError from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN from synapse.types import GroupID, RoomID, UserID, get_domain_from_id from synapse.util.async_helpers import concurrently_execute logger = lo...
# limitations under the License. import logging from typing import TYPE_CHECKING, Optional from synapse.api.errors import Codes, SynapseError from synapse.handlers.groups_local import GroupsLocalHandler from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN from synapse.types import GroupID, Jso...
class GroupsServerWorkerHandler: def __init__(self, hs): self.hs = hs self.store = hs.get_datastore() self.room_list_handler = hs.get_room_list_handler()
class GroupsServerWorkerHandler: def __init__(self, hs: "HomeServer"): self.hs = hs self.store = hs.get_datastore() self.room_list_handler = hs.get_room_list_handler()
def __init__(self, hs): self.profile_handler = hs.get_profile_handler() async def check_group_is_ours( self, group_id, requester_user_id, and_exists=False, and_is_admin=None ): """Check that the group is ours, and optionally if it exists. If group does exist then return group. ...
def __init__(self, hs): self.profile_handler = hs.get_profile_handler() async def check_group_is_ours( self, group_id: str, requester_user_id: str, and_exists: bool = False, and_is_admin: Optional[str] = None, ) -> Optional[dict]: """Check that the group ...
async def check_group_is_ours( return group async def get_group_summary(self, group_id, requester_user_id): """Get the summary for a group as seen by requester_user_id. The group summary consists of the profile of the room, and a curated
async def check_group_is_ours( return group async def get_group_summary( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the summary for a group as seen by requester_user_id. The group summary consists of the profile of the room, and a curated
async def get_group_summary(self, group_id, requester_user_id): entry = await self.room_list_handler.generate_room_entry( room_id, len(joined_users), with_alias=False, allow_private=True ) entry = dict(entry) # so we don't change what's cached entry.pop("...
async def get_group_summary(self, group_id, requester_user_id): entry = await self.room_list_handler.generate_room_entry( room_id, len(joined_users), with_alias=False, allow_private=True ) if entry is None: continue entry = dict(entry) # s...
async def get_group_summary(self, group_id, requester_user_id): rooms.sort(key=lambda e: e.get("order", 0)) for entry in users: user_id = entry["user_id"] if not self.is_mine_id(requester_user_id): attestation = await self.store.get_remote_attestation(group_id,...
async def get_group_summary(self, group_id, requester_user_id): rooms.sort(key=lambda e: e.get("order", 0)) for user in users: user_id = user["user_id"] if not self.is_mine_id(requester_user_id): attestation = await self.store.get_remote_attestation(group_id, u...
async def get_group_summary(self, group_id, requester_user_id): "user": membership_info, } async def get_group_categories(self, group_id, requester_user_id): """Get all categories in a group (as seen by user)""" await self.check_group_is_ours(group_id, requester_user_id, and_exi...
async def get_group_summary(self, group_id, requester_user_id): "user": membership_info, } async def get_group_categories( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get all categories in a group (as seen by user)""" await self.check_group_is_ours(...
async def get_group_profile(self, group_id, requester_user_id): else: raise SynapseError(404, "Unknown group") async def get_users_in_group(self, group_id, requester_user_id): """Get the users in group as seen by requester_user_id. The ordering is arbitrary at the moment
async def get_group_profile(self, group_id, requester_user_id): else: raise SynapseError(404, "Unknown group") async def get_users_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the users in group as seen by requester_user_id. The orderi...
async def get_users_in_group(self, group_id, requester_user_id): return {"chunk": chunk, "total_user_count_estimate": len(user_results)} async def get_invited_users_in_group(self, group_id, requester_user_id): """Get the users that have been invited to a group as seen by requester_user_id. ...
async def get_users_in_group(self, group_id, requester_user_id): return {"chunk": chunk, "total_user_count_estimate": len(user_results)} async def get_invited_users_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the users that have been invited to a group a...
async def get_invited_users_in_group(self, group_id, requester_user_id): return {"chunk": user_profiles, "total_user_count_estimate": len(invited_users)} async def get_rooms_in_group(self, group_id, requester_user_id): """Get the rooms in group as seen by requester_user_id This returns ro...
async def get_invited_users_in_group(self, group_id, requester_user_id): return {"chunk": user_profiles, "total_user_count_estimate": len(invited_users)} async def get_rooms_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the rooms in group as seen by reques...
async def get_rooms_in_group(self, group_id, requester_user_id): class GroupsServerHandler(GroupsServerWorkerHandler): def __init__(self, hs): super().__init__(hs) # Ensure attestations get renewed hs.get_groups_attestation_renewer() async def update_group_summary_room( self,...
async def get_rooms_in_group(self, group_id, requester_user_id): class GroupsServerHandler(GroupsServerWorkerHandler): def __init__(self, hs: "HomeServer"): super().__init__(hs) # Ensure attestations get renewed hs.get_groups_attestation_renewer() async def update_group_summary_room(...
async def update_group_summary_room( return {} async def delete_group_summary_room( self, group_id, requester_user_id, room_id, category_id ): """Remove a room from the summary""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_ad...
async def update_group_summary_room( return {} async def delete_group_summary_room( self, group_id: str, requester_user_id: str, room_id: str, category_id: str ) -> JsonDict: """Remove a room from the summary""" await self.check_group_is_ours( group_id, requester_use...
async def delete_group_summary_room( return {} async def set_group_join_policy(self, group_id, requester_user_id, content): """Sets the group join policy. Currently supported policies are:
async def delete_group_summary_room( return {} async def set_group_join_policy( self, group_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: """Sets the group join policy. Currently supported policies are:
async def set_group_join_policy(self, group_id, requester_user_id, content): return {} async def update_group_category( self, group_id, requester_user_id, category_id, content ): """Add/Update a group category""" await self.check_group_is_ours( group_id, requester_us...
async def set_group_join_policy(self, group_id, requester_user_id, content): return {} async def update_group_category( self, group_id: str, requester_user_id: str, category_id: str, content: JsonDict ) -> JsonDict: """Add/Update a group category""" await self.check_group_is_our...