buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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 RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', ...
} def reset_format_cache(): """Clear any cached formats.
} FORMAT_SETTINGS = frozenset([ 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'FIRST_DAY_OF_WEEK', 'MONTH_DAY_FORMAT', 'TIME_FORMAT', 'DATE_FORMAT', 'DATETIME_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'YEAR_MONTH_FORMAT', 'DATE_INPUT_FORMATS...
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language()
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if format_type not in FORMAT_SETTINGS: return format_type if use_l10n or (use_l10n is None and settings.USE_L10N): if lang...
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) class MiscTests(SimpleTestCase):
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) def test_format_arbitrary_settings(self): self.assertEqual(get_format('DEBUG'), 'DEBUG') class MiscTests(SimpleTestCase):
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None try: new_deps = self._run_get_new_deps() if new_deps is None: status = RUNNING else: ...
class TaskProcess(AbstractTaskProcess): self.task.trigger_event(Event.START, self.task) t0 = time.time() status = None new_deps = self._run_get_new_deps() if new_deps is None: status = DONE self.task.trigger_event( ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def test_success_handler(self): saved_tasks = [] @EmptyTask.event_handler(Event.SUCCESS) def save_task(task): print("Saving task...") sav...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(saved_tasks, [t]) def _run_empty_task(self, fail): successes = [] failures = [] exceptions = [] @EmptyTask.event_handler(Event.SUCCESS) def success(task): ...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def test_processing_time_handler(self): @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): self.result = task, processing_...
class TestEventCallbacks(unittest.TestCase): build([t], local_scheduler=True) self.assertEqual(dummies[0], "foo") def _run_processing_time_handler(self, fail): result = [] @EmptyTask.event_handler(Event.PROCESSING_TIME) def save_task(task, processing_time): resu...
from tests.utils import Command Command(script='open foo.org'), Command(script='open foo.net'), Command(script='open foo.se'), Command(script='open foo.io')]) def test_match(command): assert match(command, None)
from tests.utils import Command Command(script='open foo.org'), Command(script='open foo.net'), Command(script='open foo.se'), Command(script='open foo.io'), Command(script='xdg-open foo.com'), Command(script='gnome-open foo.com'), Command(script='kde-open foo.com')]) def test_match(command)...
def test_match(command): (Command('open foo.org'), 'open http://foo.org'), (Command('open foo.net'), 'open http://foo.net'), (Command('open foo.se'), 'open http://foo.se'), (Command('open foo.io'), 'open http://foo.io')]) def test_get_new_command(command, new_command): assert get_new_command(command...
def test_match(command): (Command('open foo.org'), 'open http://foo.org'), (Command('open foo.net'), 'open http://foo.net'), (Command('open foo.se'), 'open http://foo.se'), (Command('open foo.io'), 'open http://foo.io'), (Command('xdg-open foo.io'), 'xdg-open http://foo.io'), (Command('gnome-ope...
def match(command, settings): def get_new_command(command, settings): return 'open http://' + command.script[5:]
def match(command, settings): def get_new_command(command, settings): return command.script.replace('open ', 'open http://')
Make api awesomeness """ from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import inspect import os import salt.client import salt.client.ssh.client import salt.config import salt.exceptions # Import Salt libs
Make api awesomeness """ from __future__ import absolute_import, print_function, unicode_literals import copy # Import Python libs import inspect import logging import os import salt.auth import salt.client import salt.client.ssh.client import salt.config import salt.daemons.masterapi import salt.exceptions # Impor...
import salt.log # pylint: disable=W0611 import salt.runner import salt.syspaths import salt.utils.args import salt.wheel # Import third party libs from salt.ext import six class NetapiClient(object): """
import salt.log # pylint: disable=W0611 import salt.runner import salt.syspaths import salt.utils.args import salt.utils.minions import salt.wheel from salt.defaults import DEFAULT_TARGET_DELIM # Import third party libs from salt.ext import six log = logging.getLogger(__name__) class NetapiClient(object): """
class NetapiClient(object): def __init__(self, opts): self.opts = opts def _is_master_running(self): """
class NetapiClient(object): def __init__(self, opts): self.opts = opts self.loadauth = salt.auth.LoadAuth(opts) self.key = salt.daemons.masterapi.access_keys(self.opts) minopts = copy.deepcopy(self.opts) minopts["enable_ssh_minions"] = True self.ckminions = salt.util...
class NetapiClient(object): ipc_file = "workers.ipc" return os.path.exists(os.path.join(self.opts["sock_dir"], ipc_file)) def run(self, low): """ Execute the specified function in the specified client by passing the
class NetapiClient(object): ipc_file = "workers.ipc" return os.path.exists(os.path.join(self.opts["sock_dir"], ipc_file)) def _prep_auth_info(self, clear_load): sensitive_load_keys = [] key = None if "token" in clear_load: auth_type = "token" err_...
class NetapiClient(object): "Raw shell option not allowed." ) l_fun = getattr(self, low["client"]) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get("args", ()), **f_call.get("kwargs", {}))
class NetapiClient(object): "Raw shell option not allowed." ) if low["client"] == "ssh": self._authorize_ssh(low) l_fun = getattr(self, low["client"]) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get("args", ()), **f_call...
# encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import logging import os import time
# encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import time
import pytest import salt.config import salt.netapi import salt.utils.files from salt.exceptions import EauthAuthenticationError from tests.support.case import SSHCase from tests.support.helpers import ( SaveRequestsPostHandler, Webserver,
import pytest import salt.config import salt.netapi import salt.utils.files import salt.utils.platform import salt.utils.pycrypto from salt.exceptions import EauthAuthenticationError from tests.support.case import ModuleCase, SSHCase from tests.support.helpers import ( SaveRequestsPostHandler, Webserver,
class NetapiSSHClientTest(SSHCase): """ opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) self.netapi = salt.netapi.NetapiClient(opts) self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "key_test") self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR)...
class NetapiSSHClientTest(SSHCase): """ opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) self.netapi = salt.netapi.NetapiClient(opts) self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "key_test") self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR) ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "fun": "xx", "eauth": "xx", "ssh_priv": "aaa|id>{} #".format(path), } ret = self.netapi.run(low) self.assertFalse(os...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "ssh_priv": "aaa|id>{} #".format(path), "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password":...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", } ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "fun": "test.ping", "eauth": "auto", ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_options": ["|id>{} #".f...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_port": "hhhhh|id>{} #"....
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_remote_port_forwards": "hhhhh|id>{} #, lol"...
def register_cli_int(*args, **kw): register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False)
def register_cli_int(*args, **kw): register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') register_int('max_param_size', default=64) # we allow tokens to be a bit larger to accomidate PKI register_int('max_token_size', default=8192) #ssl options register_bool('e...
class ValidationError(Error): title = 'Bad Request' class Unauthorized(Error): """The request you have made requires authentication.""" code = 401
class ValidationError(Error): title = 'Bad Request' class ValidationSizeError(Error): """Request attribute %(attribute)s must be less than or equal to %(size)i. The server could not comply with the request because the attribute size is invalid (too large). The client is assumed to be in error. ...
from keystone import catalog from keystone.common import cms from keystone.common import logging from keystone.common import wsgi from keystone import exception from keystone import identity
from keystone import catalog from keystone.common import cms from keystone.common import logging from keystone.common import utils from keystone.common import wsgi from keystone import exception from keystone import identity
LOG = logging.getLogger(__name__) class AdminRouter(wsgi.ComposingRouter):
LOG = logging.getLogger(__name__) MAX_PARAM_SIZE = config.CONF.max_param_size MAX_TOKEN_SIZE = config.CONF.max_token_size class AdminRouter(wsgi.ComposingRouter):
def authenticate(self, context, auth=None): if 'passwordCredentials' in auth: user_id = auth['passwordCredentials'].get('userId', None) username = auth['passwordCredentials'].get('username', '') password = auth['passwordCredentials'].get('password', '') tenant_na...
def authenticate(self, context, auth=None): if 'passwordCredentials' in auth: user_id = auth['passwordCredentials'].get('userId', None) if user_id and len(user_id) > MAX_PARAM_SIZE: raise exception.ValidationSizeError(attribute='userId', ...
def authenticate(self, context, auth=None): # more compat tenant_id = auth.get('tenantId', None) if tenant_name: try: tenant_ref = self.identity_api.get_tenant_by_name(
def authenticate(self, context, auth=None): # more compat tenant_id = auth.get('tenantId', None) if tenant_id and len(tenant_id) > MAX_PARAM_SIZE: raise exception.ValidationSizeError(attribute='tenantId', size=MAX_P...
def authenticate(self, context, auth=None): catalog_ref = {} elif 'token' in auth: old_token = auth['token'].get('id', None) tenant_name = auth.get('tenantName') try: old_token_ref = self.token_api.get_token(context=context,
def authenticate(self, context, auth=None): catalog_ref = {} elif 'token' in auth: old_token = auth['token'].get('id', None) if len(old_token) > MAX_TOKEN_SIZE: raise exception.ValidationSizeError(attribute='token', ...
import default_fixtures from keystone import config from keystone import service from keystone import test from keystone.identity.backends import kvs as kvs_identity
import default_fixtures from keystone import config from keystone import exception from keystone import service from keystone import test from keystone.identity.backends import kvs as kvs_identity
CONF = config.CONF class TokenExpirationTest(test.TestCase): def setUp(self): super(TokenExpirationTest, self).setUp()
CONF = config.CONF def _build_user_auth(token=None, user_id=None, username=None, password=None, tenant_id=None, tenant_name=None): """Build auth dictionary. It will create an auth dictionary based on all the arguments that it receives. """ auth_json = {} if token is not N...
def _maintain_token_expiration(self): def test_maintain_uuid_token_expiration(self): self.opt_in_group('signing', token_format='UUID') self._maintain_token_expiration()
def _maintain_token_expiration(self): def test_maintain_uuid_token_expiration(self): self.opt_in_group('signing', token_format='UUID') self._maintain_token_expiration() class AuthTest(test.TestCase): def setUp(self): super(AuthTest, self).setUp() CONF.identity.driver = 'keysto...
class _ScalarAccessIndexer(_NDFrameIndexerBase): if not isinstance(key, tuple): key = _tuplify(self.ndim, key) if len(key) != self.ndim: raise ValueError("Not enough indexers for scalar access (setting)!") key = list(self._convert_key(key, is_setter=True)) self....
class _ScalarAccessIndexer(_NDFrameIndexerBase): if not isinstance(key, tuple): key = _tuplify(self.ndim, key) key = list(self._convert_key(key, is_setter=True)) if len(key) != self.ndim: raise ValueError("Not enough indexers for scalar access (setting)!") self....
class _AtIndexer(_ScalarAccessIndexer): Require they keys to be the same type as the index. (so we don't fallback) """ # allow arbitrary setting if is_setter: return list(key)
class _AtIndexer(_ScalarAccessIndexer): Require they keys to be the same type as the index. (so we don't fallback) """ # GH 26989 # For series, unpacking key needs to result in the label. # This is already the case for len(key) == 1; e.g. (1,) if self.ndim == 1 an...
def test_iat_series_with_period_index(): expected = ser[index[0]] result = ser.iat[0] assert expected == result
def test_iat_series_with_period_index(): expected = ser[index[0]] result = ser.iat[0] assert expected == result def test_at_with_tuple_index_get(): # GH 26989 # DataFrame.at getter works with Index of tuples df = DataFrame({"a": [1, 2]}, index=[(1, 2), (3, 4)]) assert df.index.nlevels == 1...
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin from pandas.core.arrays.datetimelike import ( DatetimeLikeArrayMixin, _ensure_datetimelik...
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core import algorithms from pandas.core.accessor import PandasDelegate from pandas.core.arrays import ( DatetimeArray, ExtensionArray, ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import (...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] taken = ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) # keep freq in PeriodArray/Index, reset otherwise ...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): if isinstance(maybe_slice, slice): return self[maybe_slice] return ExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) _can_hold_na = True _na_value = NaT
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) freq = self.freq if is_period_dtype(self) else None return self._shallow_copy(sel...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) def repeat(self, repeats, axis=None): nv.validate_repeat(tuple(), dict(axis=axis)) result = type(self._data)(self.asi8.repeat(repeats), dtype=self.dtype) return sel...
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq # -------------------------------------------------------------------- # Set Operation Methods
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): self._data._freq = freq def _shallow_copy(self, values=None, **kwargs): if values is None: values = self._data if isinstance(values, type(self)): values = values._data attributes = self._get_a...
class TestDatetimeIndex: with pytest.raises(ValueError, match=msg): dt_cls([pd.NaT, pd.Timestamp("2011-01-01").value], freq="D") def test_categorical_preserves_tz(self): # GH#18664 retain tz when going DTI-->Categorical-->DTI # TODO: parametrize over DatetimeIndex/DatetimeArray
class TestDatetimeIndex: with pytest.raises(ValueError, match=msg): dt_cls([pd.NaT, pd.Timestamp("2011-01-01").value], freq="D") # TODO: better place for tests shared by DTI/TDI? @pytest.mark.parametrize( "index", [ pd.date_range("2016-01-01", periods=5, tz="US/P...
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' self._filled = True self._marker_function() def __bool__(self):
class MarkerStyle: self._snap_threshold = None self._joinstyle = 'round' self._capstyle = 'butt' # Initial guess: Assume the marker is filled unless the fillstyle is # set to 'none'. The marker function will override this for unfilled # markers. self._filled = sel...
from matplotlib.testing.decorators import check_figures_equal import pytest def test_markers_valid(): marker_style = markers.MarkerStyle() mrk_array = np.array([[-0.5, 0],
from matplotlib.testing.decorators import check_figures_equal import pytest def test_marker_fillstyle(): marker_style = markers.MarkerStyle(marker='o', fillstyle='none') assert marker_style.get_fillstyle() == 'none' assert not marker_style.is_filled() def test_markers_valid(): marker_style = markers...
import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name from pandas.core.indexes.extension import ExtensionIndex, inherit_names import pandas.core.missing as missing _index_doc_kwargs = dict(ibase._index_doc_kwargs) _index_doc_kwargs.update(dict(targe...
import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name from pandas.core.indexes.extension import ExtensionIndex, inherit_names import pandas.core.missing as missing from pandas.core.ops import get_op_result_name _index_doc_kwargs = dict(ibase._index_...
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): return res return CategoricalIndex(res, name=self.name) CategoricalIndex._add_numeric_methods_add_sub_disabled() CategoricalIndex._add_numeric_methods_disabled()
class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): return res return CategoricalIndex(res, name=self.name) def _wrap_joined_index( self, joined: np.ndarray, other: "CategoricalIndex" ) -> "CategoricalIndex": name = get_op_result_name(self, other) return...
def test_merge_datetime_upcast_dtype(): } ) tm.assert_frame_equal(result, expected)
def test_merge_datetime_upcast_dtype(): } ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("n_categories", [5, 128]) def test_categorical_non_unique_monotonic(n_categories): # GH 28189 # With n_categories as 5, we test the int8 case is hit in libjoin, # with n_categories ...
import re import shlex import pkgutil import xml.etree.ElementTree as ET from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text
import re import shlex import pkgutil import xml.etree.ElementTree as ET import ntpath from ansible.errors import AnsibleError from ansible.module_utils._text import to_bytes, to_text
class ShellModule(ShellBase): return "" def join_path(self, *args): parts = [] for arg in args: arg = self._unquote(arg).replace('/', '\\') parts.extend([a for a in arg.split('\\') if a]) path = '\\'.join(parts) if path.startswith('~'): re...
class ShellModule(ShellBase): return "" def join_path(self, *args): # use normpath() to remove doubled slashed and convert forward to backslashes parts = [ntpath.normpath(self._unquote(arg)) for arg in args] # Becuase ntpath.join treats any component that begins with a backslash as...
from ansible.plugins.shell.powershell import _parse_clixml def test_parse_clixml_empty():
from ansible.plugins.shell.powershell import _parse_clixml, ShellModule def test_parse_clixml_empty():
def test_parse_clixml_multiple_streams(): expected = b"hi info" actual = _parse_clixml(multiple_stream, stream="Info") assert actual == expected
def test_parse_clixml_multiple_streams(): expected = b"hi info" actual = _parse_clixml(multiple_stream, stream="Info") assert actual == expected def test_join_path_unc(): pwsh = ShellModule() unc_path_parts = ['\\\\host\\share\\dir1\\\\dir2\\', '\\dir3/dir4', 'dir5', 'dir6\\'] expected = '\\\\...
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray): if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
class TimedeltaIndex( "represent unambiguous timedelta values durations." ) if isinstance(data, TimedeltaArray) and freq is None: if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq)
class TestTimedeltaIndex: # GH#23789 TimedeltaArray(tdi, freq="D") def test_dt64_data_invalid(self): # GH#23539 # passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64]
class TestTimedeltaIndex: # GH#23789 TimedeltaArray(tdi, freq="D") with pytest.raises(ValueError, match=msg): TimedeltaIndex(tdi._data, freq="D") with pytest.raises(ValueError, match=msg): TimedeltaArray(tdi._data, freq="D") def test_dt64_data_inval...
def Ghostscript(tile, size, fp, scale=1): status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(outfile) finally: try: os.unlink(outfile)
def Ghostscript(tile, size, fp, scale=1): status = gs.wait() if status: raise IOError("gs failed (status %d)" % status) im = Image.open(outfile) im.load() finally: try: os.unlink(outfile)
def Ghostscript(tile, size, fp, scale=1): except OSError: pass return im class PSFile(object):
def Ghostscript(tile, size, fp, scale=1): except OSError: pass return im.im.copy() class PSFile(object):
def _wedge(): return Image()._new(core.wedge("L")) def new(mode, size, color=0): """
def _wedge(): return Image()._new(core.wedge("L")) def _check_size(size): """ Common check to enforce type and sanity check on size tuples :param size: Should be a 2 tuple of (width, height) :returns: True, or raises a ValueError """ if not isinstance(size, tuple): raise ValueErr...
def new(mode, size, color=0): :returns: An :py:class:`~PIL.Image.Image` object. """ if color is None: # don't initialize return Image()._new(core.new(mode, size))
def new(mode, size, color=0): :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) if color is None: # don't initialize return Image()._new(core.new(mode, size))
def frombytes(mode, size, data, decoder_name="raw", *args): :returns: An :py:class:`~PIL.Image.Image` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombytes(mode, size, data, decoder_name="raw", *args): :returns: An :py:class:`~PIL.Image.Image` object. """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombuffer(mode, size, data, decoder_name="raw", *args): .. versionadded:: 1.1.4 """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def frombuffer(mode, size, data, decoder_name="raw", *args): .. versionadded:: 1.1.4 """ _check_size(size) # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0]
def load(self): if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES: try: if hasattr(Image.core, "map"): # use built-in mapper self.map = Image.core.map(self.filename) self.map.seek(o) ...
def load(self): if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES: try: if hasattr(Image.core, "map"): # use built-in mapper WIN32 only self.map = Image.core.map(self.filename) self.map...
def load(self): o.close() try: try: # fast self.im = Image.core.open_ppm(outfile) except: # slightly slower im = Image.open(outfile) im.load() self.im = im.im finally: ...
def load(self): o.close() try: _im = Image.open(outfile) _im.load() self.im = _im.im finally: try: os.unlink(outfile)
def load_djpeg(self): raise ValueError("Invalid Filename") try: self.im = Image.core.open_ppm(path) finally: try: os.unlink(path)
def load_djpeg(self): raise ValueError("Invalid Filename") try: _im = Image.open(path) _im.load() self.im = _im.im finally: try: os.unlink(path)
def _open(self): self.fp.tell(), (rawmode, 0, 1))] # ALTERNATIVE: load via builtin debug function # self.im = Image.core.open_ppm(self.filename) # self.mode = self.im.mode # self.size = self.im.size # # ----------------------------------------...
def _open(self): self.fp.tell(), (rawmode, 0, 1))] # # --------------------------------------------------------------------
def test_truncated_file(self): self.assertRaises(ValueError, lambda: Image.open(path)) if __name__ == '__main__': unittest.main()
def test_truncated_file(self): self.assertRaises(ValueError, lambda: Image.open(path)) def test_neg_ppm(self): # Storage.c accepted negative values for xsize, ysize. the # internal open_ppm function didn't check for sanity but it # has been removed. The default opener doesn't acce...
def test_effect_spread(self): im3 = Image.open('Tests/images/effect_spread.png') self.assert_image_similar(im2, im3, 110) if __name__ == '__main__': unittest.main()
def test_effect_spread(self): im3 = Image.open('Tests/images/effect_spread.png') self.assert_image_similar(im2, im3, 110) def test_check_size(self): # Checking that the _check_size function throws value errors when we want it to. with self.assertRaises(ValueError): Imag...
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not ax.holds_integer(): raise ValueError( "At based indexing on an non-integer " ...
class _AtIndexer(_ScalarAccessIndexer): "can only have integer indexers" ) else: if is_integer(i) and not (ax.holds_integer() or ax.is_floating()): raise ValueError( "At based indexing on an non-integer "...
class TestFloat64Index(Numeric): ) def test_lookups_datetimelike_values(self, vals): # If we have datetime64 or timedelta64 values, make sure they are # wrappped correctly ser = pd.Series(vals, index=range(3, 6)) ser.index = ser.index.astype("float64")
class TestFloat64Index(Numeric): ) def test_lookups_datetimelike_values(self, vals): # If we have datetime64 or timedelta64 values, make sure they are # wrappped correctly GH#31163 ser = pd.Series(vals, index=range(3, 6)) ser.index = ser.index.astype("float64")
class TestFloat64Index(Numeric): result = ser.at[4.0] assert isinstance(result, type(expected)) and result == expected # Note: ser.at[4] raises ValueError; TODO: should we make this match loc? result = ser.iloc[1] assert isinstance(result, type(expected)) and result == expected
class TestFloat64Index(Numeric): result = ser.at[4.0] assert isinstance(result, type(expected)) and result == expected # GH#31329 .at[4] should cast to 4.0, matching .loc behavior result = ser.at[4] assert isinstance(result, type(expected)) and result == expected result...
class SchemaBase(BaseModel): not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore items: Optional[Any] = None properties: Optional[Dict[str, Any]] = None additionalProperties: Optional[Union[bool, Any]] = None description: Optional[str] = None format: Optional[str] = None d...
class SchemaBase(BaseModel): not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore items: Optional[Any] = None properties: Optional[Dict[str, Any]] = None additionalProperties: Optional[Union[Dict[str, Any], bool]] = None description: Optional[str] = None format: Optional[str] =...
class Schema(SchemaBase): not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore items: Optional[SchemaBase] = None properties: Optional[Dict[str, SchemaBase]] = None additionalProperties: Optional[Union[bool, SchemaBase]] = None class Example(BaseModel):
class Schema(SchemaBase): not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore items: Optional[SchemaBase] = None properties: Optional[Dict[str, SchemaBase]] = None additionalProperties: Optional[Union[SchemaBase, bool]] = None class Example(BaseModel):