buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class YoutubeDL(object): FORMAT_RE.format(numeric_field), r'%({0})s'.format(numeric_field), outtmpl) filename = expand_path(outtmpl % template_dict) # Temporary fix for #4787 # 'Treat' all problem characters by passing filename through...
class YoutubeDL(object): FORMAT_RE.format(numeric_field), r'%({0})s'.format(numeric_field), outtmpl) # expand_path translates '%%' into '%' and '$$' into '$' # correspondingly that is not what we want since we need to keep # '%%' intac...
class tqdm(object): return self.total if self.iterable is None else \ (self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.total) def __enter__(self): return self
class tqdm(object): return self.total if self.iterable is None else \ (self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else getattr(self, "total", None)) def __enter__(self): return self
from __future__ import division from tqdm import tqdm from tests_tqdm import with_setup, pretest, posttest, StringIO, closing from tests_tqdm import DiscreteTimer, cpu_timify from time import sleep from threading import Event from tqdm import TMonitor class FakeSleep(object):
from __future__ import division from tqdm import tqdm, TMonitor from tests_tqdm import with_setup, pretest, posttest, SkipTest, \ StringIO, closing from tests_tqdm import DiscreteTimer, cpu_timify from time import sleep from threading import Event class FakeSleep(object):
def make_create_fake_sleep_event(sleep): return create_fake_sleep_event @with_setup(pretest, posttest) def test_monitor_thread(): """Test dummy monitoring thread"""
def make_create_fake_sleep_event(sleep): return create_fake_sleep_event def incr(x): return x + 1 @with_setup(pretest, posttest) def test_monitor_thread(): """Test dummy monitoring thread"""
def test_monitoring_multi(): # Check that class var monitor is deleted if no instance left tqdm.monitor_interval = 10 assert tqdm.monitor is None
def test_monitoring_multi(): # Check that class var monitor is deleted if no instance left tqdm.monitor_interval = 10 assert tqdm.monitor is None @with_setup(pretest, posttest) def test_imap(): """Test multiprocessing.Pool""" try: from multiprocessing import Pool except ImportError: ...
def test_options(cli_runner, mocker): "bla", "--ca-bundle", "yay", "--no-render", "--login-cert", "puc", "--login-cert-key",
def test_options(cli_runner, mocker): "bla", "--ca-bundle", "yay", "--login-cert", "puc", "--login-cert-key",
def test_options(cli_runner, mocker): assert set(kwargs) == { "base_path", "ca_bundle", "render", "login_cert", "login_cert_key", "password",
def test_options(cli_runner, mocker): assert set(kwargs) == { "base_path", "ca_bundle", "login_cert", "login_cert_key", "password",
def test_options(cli_runner, mocker): assert kwargs["url"] == "https://foo" assert kwargs["username"] == "user" assert kwargs["verify"] is True assert kwargs["render"] is False @pytest.fixture
def test_options(cli_runner, mocker): assert kwargs["url"] == "https://foo" assert kwargs["username"] == "user" assert kwargs["verify"] is True @pytest.fixture
import itertools import pytest from vault_cli import client, exceptions, testing def test_get_client(mocker):
import pytest from vault_cli import client, exceptions def test_get_client(mocker):
def test_vault_client_base_render_template_path_not_found(vault, template): ({"a": {"value": "b"}}, {"value": "b"}), # Secret not a string ({"a": {"value": ["yay"]}}, {"value": ["yay"]}), # Secret is a template without variable expansion ({"a": {"value": "!template!b"}, "b": {"va...
def test_vault_client_base_render_template_path_not_found(vault, template): ({"a": {"value": "b"}}, {"value": "b"}), # Secret not a string ({"a": {"value": ["yay"]}}, {"value": ["yay"]}), ], ) def test_vault_client_base_get_secret(vault, vault_contents, expected):
def test_vault_client_base_get_secret(vault, vault_contents, expected): assert vault.get_secret("a") == expected def test_vault_client_base_get_secret_deprecation_warning(vault, caplog): vault.db = {"a": {"value": "!template!b"}} caplog.set_level("WARNING") vault.get_secret("a") assert "Templated...
def test_vault_client_base_get_secret(vault, vault_contents, expected): assert vault.get_secret("a") == expected def test_vault_client_base_get_secret_multiple_keys(vault): vault.db = {"rabbitmq/creds/role": {"username": "foo", "password": "bar"}} assert vault.get_secret("rabbitmq/creds/role") == {
def test_vault_client_base_get_secret_multiple_keys(vault): } def test_vault_client_base_get_secret_with_dict(vault): vault.db = { "credentials": {"value": {"username": "foo", "password": "bar"}}, "dsn": { "value": "!template!proto://{{ vault('credentials')['value']['username'] }}:...
def test_vault_client_base_get_secret_multiple_keys(vault): } def test_vault_client_base_get_secret_not_found(vault): vault.db = {} with pytest.raises(exceptions.VaultSecretNotFound): vault.get_secret("not-existing") def test_vault_client_base_get_secret_missing_key(vault):
def test_vault_client_base_get_secret_missing_key(vault): vault.get_secret("a", key="username") def test_vault_client_base_get_secret_template_error(vault, caplog): vault.db = {"a": {"key": "!template!{{"}} with pytest.raises(exceptions.VaultRenderTemplateError) as exc_info: vault.get_secret(...
def test_vault_client_base_get_secret_missing_key(vault): vault.get_secret("a", key="username") def test_vault_client_base_lookup_token(vault): assert vault.lookup_token() == {"data": {"expire_time": "2100-01-01T00:00:00"}}
def test_vault_client_base_get_secret_implicit_cache(vault): assert vault.get_secret("a") == {"value": "b"} class RaceConditionTestVaultClient(testing.TestVaultClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.counter = itertools.count() def _get_secret(...
def test_vault_client_base_get_secret_implicit_cache(vault): assert vault.get_secret("a") == {"value": "b"} def test_vault_client_base_get_secret_explicit_cache(vault): vault.db = {"a": {"value": "b"}} with vault:
def repr_octal(value: Optional[int]) -> Optional[str]: ) @click.option( "--render/--no-render", default=settings.DEFAULTS.render, help="Render templated values", ) @click.option( "--umask",
def repr_octal(value: Optional[int]) -> Optional[str]: ) @click.option( "--render/--no-render", default=False, help="Deprecated / unused", ) @click.option( "--umask",
def cli(ctx: click.Context, verbose: int, umask: int, **kwargs) -> None: (including VAULT_CLI_PASSWORD and VAULT_CLI_TOKEN). """ kwargs.pop("config_file") set_verbosity(verbose) set_umask(umask)
def cli(ctx: click.Context, verbose: int, umask: int, **kwargs) -> None: (including VAULT_CLI_PASSWORD and VAULT_CLI_TOKEN). """ kwargs.pop("render") kwargs.pop("config_file") set_verbosity(verbose) set_umask(umask)
import json import logging import pathlib from typing import Dict, Iterable, List, Optional, Set, Tuple, Type, Union, cast import hvac # type: ignore import jinja2
import json import logging import pathlib from typing import Dict, Iterable, List, Optional, Tuple, Type, cast import hvac # type: ignore import jinja2
logger = logging.getLogger(__name__) JSONRecursive = Union[types.JSONValue, utils.RecursiveValue] JSONDictRecursive = Dict[str, JSONRecursive] def get_client(**kwargs) -> "VaultClientBase": """
logger = logging.getLogger(__name__) def get_client(**kwargs) -> "VaultClientBase": """
def get_client(**kwargs) -> "VaultClientBase": Path to your config file, instead of the default ones safe_write : bool If set to True, will keep you from overwriting secrets without force=True render : bool If set to False, templated secrets will not be rendered Returns -------
def get_client(**kwargs) -> "VaultClientBase": Path to your config file, instead of the default ones safe_write : bool If set to True, will keep you from overwriting secrets without force=True Returns -------
def __init__( username: Optional[str] = settings.DEFAULTS.username, password: Optional[str] = settings.DEFAULTS.password, safe_write: bool = settings.DEFAULTS.safe_write, render: bool = settings.DEFAULTS.render, ): self.url = url self.verify: types.VerifyOrCABundle = ...
def __init__( username: Optional[str] = settings.DEFAULTS.username, password: Optional[str] = settings.DEFAULTS.password, safe_write: bool = settings.DEFAULTS.safe_write, ): self.url = url self.verify: types.VerifyOrCABundle = verify
def __init__( self.username = username self.password = password self.safe_write = safe_write self.render = render self.cache: Dict[str, types.JSONDict] = {} self.errors: List[str] = [] self._currently_fetching: Set[str] = set() @property def base_path(sel...
def __init__( self.username = username self.password = password self.safe_write = safe_write self.cache: Dict[str, types.JSONDict] = {} self.errors: List[str] = [] @property def base_path(self):
def _build_full_path(self, path: str) -> str: # path relative to base_path return self.base_path + path def _browse_recursive_secrets( self, path: str, render: bool = True ) -> Iterable[str]: """ Given a secret or folder path, return the path of all secrets ...
def _build_full_path(self, path: str) -> str: # path relative to base_path return self.base_path + path def _browse_recursive_secrets(self, path: str) -> Iterable[str]: """ Given a secret or folder path, return the path of all secrets under it (or the path itself)
def _browse_recursive_secrets( yield key_url continue for sub_path in self._browse_recursive_secrets(key_url, render=render): yield sub_path def get_all_secrets( self, *paths: str, render: bool = True, flat: bool = False ) -> JSONDictRecursiv...
def _browse_recursive_secrets( yield key_url continue for sub_path in self._browse_recursive_secrets(key_url): yield sub_path def get_all_secrets(self, *paths: str, flat: bool = False) -> types.JSONDict: """ Takes several paths, return th...
def get_all_secrets( ---------- *paths : str Paths to read recursively render : bool, optional Whether templated secrets should be rendered, by default True flat : bool, optional Whether to return flat structure with full path as keys or nested ...
def get_all_secrets( ---------- *paths : str Paths to read recursively flat : bool, optional Whether to return flat structure with full path as keys or nested structure that looks like a tree
def get_all_secrets( {"folder": {"subfolder": {"secret_key": "secret_value"}}} """ result: JSONDictRecursive = {} for path in paths: path_dict = self.get_secrets(path, render=render) if flat: result.update(path_dict) else:
def get_all_secrets( {"folder": {"subfolder": {"secret_key": "secret_value"}}} """ result: types.JSONDict = {} for path in paths: path_dict = self.get_secrets(path) if flat: result.update(path_dict) else:
def get_all_secrets( return result def get_secrets( self, path: str, render: bool = True, relative: bool = False ) -> Dict[str, JSONDictRecursive]: """ Takes a path, return all secrets below this path
def get_all_secrets( return result def get_secrets( self, path: str, relative: bool = False ) -> Dict[str, types.JSONDict]: """ Takes a path, return all secrets below this path
def get_secrets( ---------- path : str Path to read recursively render : bool, optional Whether templated secrets should be rendered, by default True relative: bool, optional When false (default), the keys of the returned dict are the paths of the secr...
def get_secrets( ---------- path : str Path to read recursively relative: bool, optional When false (default), the keys of the returned dict are the paths of the secrets When true, the keys are the relative paths of the secret to `path` (`""` if the secret is ...
def get_secrets( """ path = path.rstrip("/") try: secrets_paths = list( self._browse_recursive_secrets(path=path, render=render) ) except exceptions.VaultAPIException: # If we cannot list secrets, we can't browse them, but there's still...
def get_secrets( """ path = path.rstrip("/") try: secrets_paths = list(self._browse_recursive_secrets(path=path)) except exceptions.VaultAPIException: # If we cannot list secrets, we can't browse them, but there's still # a chance that the provided pat...
def get_secrets( key = subpath try: secret = self.get_secret(path=subpath, render=render) secret = cast(JSONDictRecursive, secret) result[key] = secret except ( exceptions.VaultAPIException, exceptio...
def get_secrets( key = subpath try: secret = self.get_secret(path=subpath) secret = cast(types.JSONDict, secret) result[key] = secret except exceptions.VaultAPIException as exc: for message in utils.extract_error_me...
def list_secrets(self, path: str) -> Iterable[str]: """ return self._list_secrets(path=self._build_full_path(path)) def get_secret( self, path: str, key: Optional[str] = None, render: bool = True ) -> Union[types.JSONValue, utils.RecursiveValue]: """ Retrieve the value o...
def list_secrets(self, path: str) -> Iterable[str]: """ return self._list_secrets(path=self._build_full_path(path)) def get_secret(self, path: str, key: Optional[str] = None) -> types.JSONValue: """ Retrieve the value of a single secret
def get_secret( key : str, optional If set, return only this key render : bool, optional Whether to render templated secret or not, by default True Returns ------- types.JSONValue Secret value """ full_path = self._build_full_...
def get_secret( key : str, optional If set, return only this key Returns ------- types.JSONValue Secret value """ full_path = self._build_full_path(path) assert self.cache is not None try: mapping = self.cache[full_pat...
def delete_secret(self, path: str, key: Optional[str] = None) -> None: else: # Delete only one attribute try: secret = self.get_secret(path, render=False) except exceptions.VaultSecretNotFound: # secret does not exist return
def delete_secret(self, path: str, key: Optional[str] = None) -> None: else: # Delete only one attribute try: secret = self.get_secret(path) except exceptions.VaultSecretNotFound: # secret does not exist return
def delete_secret(self, path: str, key: Optional[str] = None) -> None: def delete_all_secrets_iter(self, *paths: str) -> Iterable[str]: for path in paths: path = path.rstrip("/") secrets_paths = self._browse_recursive_secrets(path=path, render=False) for secret_path in se...
def delete_secret(self, path: str, key: Optional[str] = None) -> None: def delete_all_secrets_iter(self, *paths: str) -> Iterable[str]: for path in paths: path = path.rstrip("/") secrets_paths = self._browse_recursive_secrets(path=path) for secret_path in secrets_paths: ...
def copy_secrets_iter( delete_source: Optional[bool] = False, ) -> Iterable[Tuple[str, str]]: source_secrets = self.get_secrets(path=source, render=False) for old_path, secret in source_secrets.items(): new_path = dest + old_path[len(source) :]
def copy_secrets_iter( delete_source: Optional[bool] = False, ) -> Iterable[Tuple[str, str]]: source_secrets = self.get_secrets(path=source) for old_path, secret in source_secrets.items(): new_path = dest + old_path[len(source) :]
def copy_secrets( return iterator return list(iterator) template_prefix = "!template!" def _render_template_value(self, secret: types.JSONValue) -> types.JSONValue: if isinstance(secret, dict): return {k: self._render_template_value(v) for k, v in secret.items()} ...
def copy_secrets( return iterator return list(iterator) def render_template( self, template: str, search_path: pathlib.Path = pathlib.Path("."), ) -> str: """
def render_template( def vault(path): try: return self.get_secret(path, render=render) except exceptions.VaultException as exc: raise exceptions.VaultRenderTemplateError( "Error while rendering template"
def render_template( def vault(path): try: return self.get_secret(path) except exceptions.VaultException as exc: raise exceptions.VaultRenderTemplateError( "Error while rendering template"
def set_secret( force = self.get_force(force) try: existing_value = self.get_secret(path=path, render=False) assert isinstance(existing_value, dict) except exceptions.VaultSecretNotFound: pass
def set_secret( force = self.get_force(force) try: existing_value = self.get_secret(path=path) assert isinstance(existing_value, dict) except exceptions.VaultSecretNotFound: pass
def set_secret( path = path.rstrip("/") for parent in list(pathlib.PurePath(path).parents)[:-1]: try: self.get_secret(str(parent), render=False) except exceptions.VaultSecretNotFound: pass except exceptions.VaultForbidden:
def set_secret( path = path.rstrip("/") for parent in list(pathlib.PurePath(path).parents)[:-1]: try: self.get_secret(str(parent)) except exceptions.VaultSecretNotFound: pass except exceptions.VaultForbidden:
def set_secret( def set_secrets( self, secrets: Dict[str, JSONDictRecursive], force: Optional[bool] = None, update: Optional[bool] = None, ) -> None:
def set_secret( def set_secrets( self, secrets: Dict[str, types.JSONDict], force: Optional[bool] = None, update: Optional[bool] = None, ) -> None:
import re from typing import Dict, Mapping, NoReturn, Optional, Sequence from vault_cli import client, exceptions logger = logging.getLogger(__name__)
import re from typing import Dict, Mapping, NoReturn, Optional, Sequence from vault_cli import client, exceptions, types logger = logging.getLogger(__name__)
def _normalize(name: str) -> str: return envvar_name def _make_env_value(value: client.JSONRecursive) -> str: if isinstance(value, str): return value return json.dumps(value)
def _normalize(name: str) -> str: return envvar_name def _make_env_value(value: types.JSONValue) -> str: if isinstance(value, str): return value return json.dumps(value)
def exec_command( def get_envvars_for_secrets( secrets: Dict[str, client.JSONDictRecursive], path: str, prefix: str, omit_single_key: bool = False,
def exec_command( def get_envvars_for_secrets( secrets: Dict[str, types.JSONDict], path: str, prefix: str, omit_single_key: bool = False,
class DEFAULTS: verify = True ca_bundle = None safe_write = False render = True @staticmethod def _as_dict():
class DEFAULTS: verify = True ca_bundle = None safe_write = False @staticmethod def _as_dict():
def path_to_nested(dict_obj: Dict) -> Dict: return dict_obj class RecursiveValue: def __init__(self, name: str): self.name = name def __str__(self) -> str: return f'<recursive value "{self.name}">' def __getitem__(self, key: str) -> str: return str(self) def extract_error_m...
def path_to_nested(dict_obj: Dict) -> Dict: return dict_obj def extract_error_messages(exc: BaseException) -> Iterable[str]: while True: exc_str = str(exc).strip()
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if domain and ...
class HttpRequest(object): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() ...
class HostValidationTests(SimpleTestCase): self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], '137+141') self.assertEqual(downloaded['ext'], 'mp4') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'}) ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], '137+141') self.assertEqual(downloaded['ext'], 'mp4') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'}) yie ...
class YoutubeDL(object): else: filter_parts.append(string) def _parse_format_selection(tokens, endwith=[]): selectors = [] current_selector = None for type, string, start, _, _ in tokens:
class YoutubeDL(object): else: filter_parts.append(string) def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False): selectors = [] current_selector = None for type, string, start, _, _ in tokens:
class YoutubeDL(object): elif type in [tokenize.NAME, tokenize.NUMBER]: current_selector = FormatSelector(SINGLE, string, []) elif type == tokenize.OP: if string in endwith: break elif string == ')': ...
class YoutubeDL(object): elif type in [tokenize.NAME, tokenize.NUMBER]: current_selector = FormatSelector(SINGLE, string, []) elif type == tokenize.OP: if string == ')': if not inside_group: # ')'...
class YoutubeDL(object): elif string == '(': if current_selector: raise syntax_error('Unexpected "("', start) current_selector = FormatSelector(GROUP, _parse_format_selection(tokens, [')']), []) elif stri...
class YoutubeDL(object): elif string == '(': if current_selector: raise syntax_error('Unexpected "("', start) group = _parse_format_selection(tokens, inside_group=True) current_selector = FormatSelect...
def _isna_old(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): return obj._construct...
def _isna_old(obj): raise NotImplementedError("isna is not defined for MultiIndex") elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): re...
class TestSeriesAnalytics: ts.iloc[[0, 3, 5]] = np.nan tm.assert_series_equal(ts.count(level=1), right - 1) def test_dot(self): a = Series(np.random.randn(4), index=["p", "q", "r", "s"]) b = DataFrame(
class TestSeriesAnalytics: ts.iloc[[0, 3, 5]] = np.nan tm.assert_series_equal(ts.count(level=1), right - 1) # GH29478 with pd.option_context("use_inf_as_na", True): assert pd.Series([pd.Timestamp("1990/1/1")]).count() == 1 def test_dot(self): a = Series(np.rando...
def authenticate(self, context, credentials=None, context=context, user_id=creds_ref['user_id']) metadata_ref = self.identity_api.get_metadata( context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) catalog_ref...
def authenticate(self, context, credentials=None, context=context, user_id=creds_ref['user_id']) metadata_ref = self.identity_api.get_metadata( context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) # TODO(termie): optimi...
def authenticate(self, context, credentials=None, tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): optimize this call at some point and put it into the # the return for metadata # fill out th...
def authenticate(self, context, credentials=None, tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): make this a util function or something # TODO(termie): i don't think the ec2 middleware currently expects a ...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9'...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catast...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'g...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterab...
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI-delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], islist=True) DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEF...
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], islist=True) DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEF...
class Templar: loader=FileSystemLoader(self._basedir), ) self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) self.block_start = self.environment.block_start_string
class Templar: loader=FileSystemLoader(self._basedir), ) # the current rendering context under which the templar class is working self.cur_context = None self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e...
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(term...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran: from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var ...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran and not allow_unsafe: from ansible.vars.unsafe_proxy import UnsafeProxy,...
class Templar: else: ran = wrap_var(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: jvars = AnsibleJ2Vars(self, t.globals) new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class Templar: jvars = AnsibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
def get_domain(value): token, value = get_dot_atom(value) except errors.HeaderParseError: token, value = get_atom(value) if leader is not None: token[:0] = [leader] domain.append(token)
def get_domain(value): token, value = get_dot_atom(value) except errors.HeaderParseError: token, value = get_atom(value) if value and value[0] == '@': raise errors.HeaderParseError('Invalid Domain') if leader is not None: token[:0] = [leader] domain.append(token)
def getaddrspec(self): aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain() def getdomain(self): """Get the complete domain name from an address."""
def getaddrspec(self): aslist.append('@') self.pos += 1 self.gotonext() domain = self.getdomain() if not domain: # Invalid domain, return an empty address instead of returning a # local part to denote failed parsing. return EMPTYSTRING ...
def getdomain(self): elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] in self.atomends: break else:
def getdomain(self): elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] == '@': # bpo-34155: Don't parse domains with two `@` like # `a@malicious.org@important.com`. return E...
def test_get_addr_spec_dot_atom(self): self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com') # get_obs_route def test_get_obs_route_simple(self):
def test_get_addr_spec_dot_atom(self): self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com') def test_get_addr_spec_multiple_domains(self): with self.assertRaises(errors.HeaderParseError): parser.get_addr_spec('star@a....
def test_parseaddr_empty(self): self.assertEqual(utils.parseaddr('<>'), ('', '')) self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') def test_noquote_dump(self): self.assertEqual( utils.formataddr(('A Silly Person', 'person@dom.ain')),
def test_parseaddr_empty(self): self.assertEqual(utils.parseaddr('<>'), ('', '')) self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') def test_parseaddr_multiple_domains(self): self.assertEqual( utils.parseaddr('a@b@c'), ('', '') ) self.asse...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): if self._next_timeout <= current_time: callback_time_sec = self.callback_time / 1000.0 self._next_timeout += (math.floor((current...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): callback_time_sec = self.callback_time / 1000.0 if self._next_timeout <= current_time: # The period should be measured from the start...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds. This method returns the times at which each call would be made. """ calls = [] ...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds (negative values work to simulate clock adjustments during the call, or more or less equivalent...
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) class TestIOLoopConfiguration(unittest.TestCase): def run_python(self, *statements):
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) def test_clock_backwards(self): pc = PeriodicCallback(None, 10000) # Backwards jumps are ignored, potentially resulting in a # slightly slo...
class JSON(object): json_renderer_factory = JSON() # bw compat JSONP_VALID_CALLBACK = re.compile(r"^[a-zA-Z_$][0-9a-zA-Z_$]+$") class JSONP(JSON): """ `JSONP <http://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper
class JSON(object): json_renderer_factory = JSON() # bw compat JSONP_VALID_CALLBACK = re.compile(r"^[$a-z_][$0-9a-z_\.\[\]]+[^.]$", re.I) class JSONP(JSON): """ `JSONP <http://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper
class JSONP(JSON): raise HTTPBadRequest('Invalid JSONP callback function name.') ct = 'application/javascript' body = '%s(%s);' % (callback, val) response = request.response if response.content_type == response.default_cont...
class JSONP(JSON): raise HTTPBadRequest('Invalid JSONP callback function name.') ct = 'application/javascript' body = '/**/{0}({1});'.format(callback, val) response = request.response if response.content_type == response.de...
class TestJSONP(unittest.TestCase): request = testing.DummyRequest() request.GET['callback'] = 'callback' result = renderer({'a':'1'}, {'request':request}) self.assertEqual(result, 'callback({"a": "1"});') self.assertEqual(request.response.content_type, '...
class TestJSONP(unittest.TestCase): request = testing.DummyRequest() request.GET['callback'] = 'callback' result = renderer({'a':'1'}, {'request':request}) self.assertEqual(result, '/**/callback({"a": "1"});') self.assertEqual(request.response.content_type, ...
class KeyValueType(object): """A type used with `argparse`.""" def __init__(self, *separators): self.separators = separators def __call__(self, string): found = {} for sep in self.separators: regex = '[^\\\\]' + sep match = re.search(regex, string) ...
class KeyValueType(object): """A type used with `argparse`.""" def __init__(self, *separators): self.separators = separators self.escapes = ['\\\\' + sep for sep in separators] def __call__(self, string): found = {} found_escapes = [] for esc in self.escapes: ...
class TestItemParsing(BaseTest): }) self.assertIn('bar@baz', files) def test_valid_items(self): headers, data, files = cli.parse_items([
class TestItemParsing(BaseTest): }) self.assertIn('bar@baz', files) def test_escape_longsep(self): headers, data, files = cli.parse_items([ self.kv('bob\\:==foo'), ]) self.assertDictEqual(data, { 'bob:=': 'foo', }) def test_valid_item...
def _parse_octet(cls, octet_str): raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and #...
def _parse_octet(cls, octet_str): raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
def pickle_test(self, addr): y = pickle.loads(pickle.dumps(x, proto)) self.assertEqual(y, x) class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): self.assertInstancesEqual("000.000.000.000", "0.0.0.0") self.assertInstancesEqual("192.168.000.001",...
def pickle_test(self, addr): y = pickle.loads(pickle.dumps(x, proto)) self.assertEqual(y, x) class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): self.assertInstancesEqual("000.000.000.000", "0.0.0.0") self.assertInstancesEqual("192.168.000.001"...
def assertBadOctet(addr, octet): assertBadOctet("1.2.3.4::", "4::") assertBadOctet("1.a.2.3", "a") def test_octal_decimal_ambiguity(self): def assertBadOctet(addr, octet): msg = "Ambiguous (octal/decimal) value in %r not permitted in %r" with self.assertAddressError(...
def assertBadOctet(addr, octet): assertBadOctet("1.2.3.4::", "4::") assertBadOctet("1.a.2.3", "a") def test_octet_length(self): def assertBadOctet(addr, octet): msg = "At most 3 characters permitted in %r in %r"
class Categorical(ExtensionArray, PandasObject): code_values = code_values[null_mask | (code_values >= 0)] return algorithms.isin(self.codes, code_values) # The Series.cat accessor
class Categorical(ExtensionArray, PandasObject): code_values = code_values[null_mask | (code_values >= 0)] return algorithms.isin(self.codes, code_values) def replace(self, to_replace, value, inplace: bool = False): """ Replaces all instances of one value with another Param...
class CategoricalBlock(ExtensionBlock): ) return result # ----------------------------------------------------------------- # Constructor Helpers
class CategoricalBlock(ExtensionBlock): ) return result def replace( self, to_replace, value, inplace: bool = False, filter=None, regex: bool = False, convert: bool = True, ): inplace = validate_bool_kwarg(inplace, "inplace") ...
def test_isin_cats(): tm.assert_numpy_array_equal(expected, result) @pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])]) def test_isin_empty(empty): s = pd.Categorical(["a", "b"])
def test_isin_cats(): tm.assert_numpy_array_equal(expected, result) @pytest.mark.parametrize( "to_replace, value, result", [("b", "c", ["a", "c"]), ("c", "d", ["a", "b"]), ("b", None, ["a", None])], ) def test_replace(to_replace, value, result): # GH 26988 cat = pd.Categorical(["a", "b"]) expe...
class TestDataFrameReplace: expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "df, to_replace, exp", [
class TestDataFrameReplace: expected = DataFrame(expected) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "replace_dict, final_data", [({"a": 1, "b": 1}, [[3, 3], [2, 2]]), ({"a": 1, "b": 2}, [[3, 1], [2, 3]])], ) def test_categorical_replace_with_dict(sel...
class TestSeriesReplace: expected = pd.Series(numeric) tm.assert_series_equal(expected, result, check_dtype=False) def test_replace_with_no_overflowerror(self): # GH 25616 # casts to object without Exception from OverflowError
class TestSeriesReplace: expected = pd.Series(numeric) tm.assert_series_equal(expected, result, check_dtype=False) def test_replace_categorical_single(self): # GH 26988 dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") s = pd.Series(dti) c = s.astype("cat...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_bypass_environment_host_match(self): bypass = urllib.reques...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value for name, value in os.environ.items(): if name[-6:] == '_proxy': name = name.lower()
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the clie...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) def __add__(self, other): other = lib.item_from_zerodim(other) if isinstance(other, (ABCSeries, ABCDataFrame)): return NotImplemented # scalar others
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) def __add__(self, other): other = lib.item_from_zerodim(other) if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): return NotImplemented # scalar others
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) def __sub__(self, other): other = lib.item_from_zerodim(other) if isinstance(other, (ABCSeries, ABCDataFrame)): return NotImplemented # scalar others
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) def __sub__(self, other): other = lib.item_from_zerodim(other) if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): return NotImplemented # scalar others
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) return result def __rsub__(self, other): if is_datetime64_dtype(other) and is_timedelta64_dtype(self): # ndarray[datetime64] cannot be subtracted from self, so # we need to wrap in DatetimeArray...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) return result def __rsub__(self, other): if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self): # ndarray[datetime64] cannot be subtracted from self, so # we need to wrap in DatetimeA...
class TestDatetimeIndexArithmetic: # ------------------------------------------------------------- def test_sub_dti_dti(self): # previously performed setop (deprecated in 0.16.0), now changed to # return subtraction -> TimeDeltaIndex (GH ...)
class TestDatetimeIndexArithmetic: # ------------------------------------------------------------- def test_dta_add_sub_index(self, tz_naive_fixture): # Check that DatetimeArray defers to Index classes dti = date_range("20130101", periods=3, tz=tz_naive_fixture) dta = dti.array ...
def test_shift_months(years, months): tm.assert_index_equal(actual, expected) class SubDatetime(datetime): pass
def test_shift_months(years, months): tm.assert_index_equal(actual, expected) # FIXME: this belongs in scalar tests class SubDatetime(datetime): pass
class TestPeriodIndexArithmetic: with pytest.raises(TypeError): other - obj class TestPeriodSeriesArithmetic: def test_ops_series_timedelta(self):
class TestPeriodIndexArithmetic: with pytest.raises(TypeError): other - obj # --------------------------------------------------------------- # Unsorted def test_parr_add_sub_index(self): # Check that PeriodArray defers to Index on arithmetic ops pi = pd.period_range("2...
class TestTimedelta64ArithmeticUnsorted: tm.assert_index_equal(result1, result4) tm.assert_index_equal(result2, result3) class TestAddSubNaTMasking: # TODO: parametrize over boxes
class TestTimedelta64ArithmeticUnsorted: tm.assert_index_equal(result1, result4) tm.assert_index_equal(result2, result3) def test_tda_add_sub_index(self): # Check that TimedeltaArray defers to Index on arithmetic ops tdi = TimedeltaIndex(["1 days", pd.NaT, "2 days"]) tda = t...
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): new_index = self.index[loc] if is_scalar(loc): new_values = self._data.fast_xs(loc) # may need to box a datelike-scalar # # if we encounter an array-like and we only have 1 dim ...
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): new_index = self.index[loc] if is_scalar(loc): # In this case loc should be an integer if self.ndim == 1: # if we encounter an array-like and we only have 1 dim # that me...
class SingleBlockManager(BlockManager): fast path for getting a cross-section return a view of the data """ return self._block.values[loc] def concat(self, to_concat, new_axis) -> "SingleBlockManager": """
class SingleBlockManager(BlockManager): fast path for getting a cross-section return a view of the data """ raise NotImplementedError("Use series._values[loc] instead") def concat(self, to_concat, new_axis) -> "SingleBlockManager": """
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 2-compatible code, so don't try Python 3 grammar. return [ pygram.python_grammar_no_prin...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 3-compatible code, so don't try Python 2 grammar return [ pygram.python_grammar_no_print...
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_unicode_literals(self) -> None: source, expected = read_data("python2_unicode_literals")
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_print_function(self) -> None: source, expected = read_data("python2_print_function") ...
INTERNAL_RESULT_KEYS = ('add_host', 'add_group') LOCALHOST = ('127.0.0.1', 'localhost', '::1') MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script') MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw') RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo...
INTERNAL_RESULT_KEYS = ('add_host', 'add_group') LOCALHOST = ('127.0.0.1', 'localhost', '::1') MODULE_REQUIRE_ARGS = ('command', 'win_command', 'shell', 'win_shell', 'raw', 'script') MODULE_NO_JSON = ('command', 'win_command', 'shell', 'win_shell', 'raw') RESTRICTED_RESULT_KEYS = ('ansible_rsync_path', 'ansible_playboo...
from ansible.module_utils.common._collections_compat import MutableMapping, Muta from ansible.plugins.loader import connection_loader from ansible.utils.display import Display display = Display()
from ansible.module_utils.common._collections_compat import MutableMapping, Muta from ansible.plugins.loader import connection_loader from ansible.utils.display import Display display = Display()