buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def test_light_source_shading_default(): assert_array_almost_equal(rgb, expect, decimal=2) # Numpy 1.9.1 fixed a bug in masked arrays which resulted in # additional elements being masked when calculating the gradient thus # the output is different with earlier numpy versions.
def test_light_source_shading_default(): assert_array_almost_equal(rgb, expect, decimal=2) def test_light_source_shading_empty_mask(): y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] z0 = 10 * np.cos(x**2 + y**2) z1 = np.ma.array(z0) cmap = plt.cm.copper ls = mcolors.LightSource(315, 45) rgb0 =...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.generic import ABCSeries from pandas.core.accessor import PandasDelegate, delegate_names from pandas.core.algorithms import take_1d from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.base import NoNewAttributesMixin...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.generic import ABCSeries from pandas.core.accessor import PandasDelegate, delegate_names from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.base import NoNewAttributesMixin, PandasObject from pandas.core.indexes.dat...
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): result = np.asarray(result) # blow up if we operate on categories if self.orig is not None: result = take_1d(result, self.orig.cat.codes) index = self.orig.index else: index = self...
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): result = np.asarray(result) if self.orig is not None: index = self.orig.index else: index = self._parent.index
class CombinedDatetimelikeProperties( orig = data if is_categorical_dtype(data) else None if orig is not None: data = Series(orig.values.categories, name=orig.name, copy=False) if is_datetime64_dtype(data.dtype): return DatetimeProperties(data, orig)
class CombinedDatetimelikeProperties( orig = data if is_categorical_dtype(data) else None if orig is not None: data = Series( orig.array, name=orig.name, copy=False, dtype=orig.values.categories.dtype, ) if...
class TestSeriesDatetimeValues: expected = Series([2017, 2017, 2018, 2018], name="foo") tm.assert_series_equal(result, expected) def test_dt_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 s = Series(date_range("20130101", periods=5, freq="D"))
class TestSeriesDatetimeValues: expected = Series([2017, 2017, 2018, 2018], name="foo") tm.assert_series_equal(result, expected) def test_dt_tz_localize_categorical(self, tz_aware_fixture): # GH 27952 tz = tz_aware_fixture datetimes = pd.Series( ["2019-01-01", "2...
from blib2to3 import pygram, pytree from blib2to3.pgen2 import driver, token from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError __version__ = "19.3b0"
from blib2to3 import pygram, pytree from blib2to3.pgen2 import driver, token from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError from blib2to3.pgen2.tokenize import TokenizerConfig __version__ = "19.3b0"
class Feature(Enum): NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { TargetVersion.PY27: set(), TargetVersion.PY33: {Feature.UNICODE_LITERALS}, TargetVersion.PY34: {Feature.UNICODE_LITERALS}, TargetVers...
class Feature(Enum): NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 # The following two feature-flags are mutually exclusive, and exactly one should be # set for every version of python. ASYNC_IS_VALID_IDENTIFIER = 6 ASYNC_IS_RESERVED_KEYWORD = 7 VERSION_TO_FE...
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, }, TargetVersion.PY38: { Feature.UNICODE_LITERALS,
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_IS_RESERVED_KEYWORD, }, TargetVersion.PY38: { Feature.UNICODE_LITERALS,
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, }, }
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = { Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_IS_RESERVED_KEYWORD, }, }
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: return tiow.read(), encoding, newline def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: # No target_version specified, so try all grammars. return [ pygram.pytho...
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]: return tiow.read(), encoding, newline @dataclass(frozen=True) class ParserConfig: grammar: Grammar tokenizer_config: TokenizerConfig = TokenizerConfig() def get_parser_configs(target_versions: Set[TargetVersion]) -> List[ParserCo...
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) - if src_txt[-1:] != "\n": src_txt += "\n" for grammar in get_grammars(set(target_versions)): drv = driver.Driver(grammar, pytree.convert) try: result = drv.parse_string(src_txt, True) ...
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) - if src_txt[-1:] != "\n": src_txt += "\n" for parser_config in get_parser_configs(set(target_versions)): drv = driver.Driver( parser_config.grammar, pytree.convert, tokenizer_conf...
from . import grammar, parse, token, tokenize, pgen class Driver(object): def __init__(self, grammar, convert=None, logger=None): self.grammar = grammar if logger is None: logger = logging.getLogger(__name__) self.logger = logger self.convert = convert def parse_to...
from . import grammar, parse, token, tokenize, pgen class Driver(object): def __init__( self, grammar, convert=None, logger=None, tokenizer_config=tokenize.TokenizerConfig(), ): self.grammar = grammar if logger is None: logger = logging.getLo...
class Driver(object): def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug) def parse_stream(self, stream, debug=False):
class Driver(object): def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config) return self.parse_tokens(tokens, debug) def parse_stream(self, stream, debug=False):
class Driver(object): def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" tokens = tokenize.generate_tokens(io.StringIO(text).readline) return self.parse_tokens(tokens, debug) def _partially_consume_prefix(self, prefix, column):
class Driver(object): def parse_string(self, text, debug=False): """Parse a string and return the syntax tree.""" tokens = tokenize.generate_tokens( io.StringIO(text).readline, config=self.tokenizer_config, ) return self.parse_tokens(tokens, debug) def _...
__credits__ = \ import re from codecs import BOM_UTF8, lookup from blib2to3.pgen2.token import * from . import token
__credits__ = \ import re from codecs import BOM_UTF8, lookup from attr import dataclass from blib2to3.pgen2.token import * from . import token
single_quoted = ( tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass
single_quoted = ( tabsize = 8 @dataclass(frozen=True) class TokenizerConfig: async_is_reserved_keyword: bool = False class TokenError(Exception): pass class StopTokenizing(Exception): pass
def untokenize(iterable): ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the
def untokenize(iterable): ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline, config: TokenizerConfig = TokenizerConfig()): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the
def generate_tokens(readline): contline = None indents = [0] # 'stashed' and 'async_*' are used for async/await parsing stashed = None async_def = False
def generate_tokens(readline): contline = None indents = [0] # If we know we're parsing 3.7+, we can unconditionally parse `async` and # `await` as keywords. async_is_reserved_keyword = config.async_is_reserved_keyword # 'stashed' and 'async_*' are used for async/await parsing stashed = Non...
def generate_tokens(readline): yield (STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_def: yield (ASYNC if token == 'async'...
def generate_tokens(readline): yield (STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_is_reserved_keyword or async_def: yie...
async def func(): self.async_inc, arange(8), batch_size=3 ) ] # output
async def func(): self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i)) # output
async def func(): self.async_inc, arange(8), batch_size=3 ) ]
async def func(): self.async_inc, arange(8), batch_size=3 ) ] def awaited_generator_value(n): return (await awaitable for awaitable in awaitable_list) def make_arange(n): return (i * 2 for i in range(n) if await wrap(i))
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, mode) @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: source, expected = read_data("python37") actual = fs(source) self.asse...
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, mode) @patch("black.dump_to_file", dump_to_stderr) def test_async_as_identifier(self) -> None: source_path = (THIS_DIR / "data" / "async_as_identifier.py").resolve() ...
class BlackTestCase(unittest.TestCase): if major > 3 or (major == 3 and minor >= 7): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff(self) -> None:
class BlackTestCase(unittest.TestCase): if major > 3 or (major == 3 and minor >= 7): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) # ensure black can parse this when the target is 3.7 self.invokeBlack([str(source_path), "--targe...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, ...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename, errors='surrogate_or_strict'), to_native(tar.name))) b_dest_filepath = os.path.abspath(os.pa...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_require_one_of_collections_requirements_with_both(): cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace.collection', '-r', 'requirements.yml'])
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename))) tar_file = os.path.join(temp_dir, to_bytes('%s...
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.mark.parametrize('script, branch_name', [ ('git push', 'master'), ('git push origin', 'master')])
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.fixture def output_bitbucket(): return '''Total 0 (delta 0), reused 0 (delta 0) remote: remote: Create pull request for feature/set-upstream: remote: https://bitbucket.org/set-upstream remote: To git@bitb...
def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
def test_match(output, script, branch_name): assert match(Command(script, output)) def test_match_bitbucket(output_bitbucket): assert not match(Command('git push origin', output_bitbucket)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'set-upstream' in command.output) def _get_upstream_option_index(command_parts):
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'git push --set-upstream' in command.output) def _get_upstream_option_index(command_parts):
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, user=user_ref, tenant=tenant_ref, ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, expires=auth_token_data['expires'], user=user_re...
class ImagesPipeline(FilesPipeline): background = Image.new('RGBA', image.size, (255, 255, 255)) background.paste(image, image) image = background.convert('RGB') elif image.mode != 'RGB': image = image.convert('RGB')
class ImagesPipeline(FilesPipeline): background = Image.new('RGBA', image.size, (255, 255, 255)) background.paste(image, image) image = background.convert('RGB') elif image.mode == 'P': image = image.convert("RGBA") background = Image.new('RGBA', image...
class ImagesPipelineTestCase(unittest.TestCase): self.assertEquals(converted.mode, 'RGB') self.assertEquals(converted.getcolors(), [(10000, (205, 230, 255))]) class DeprecatedImagesPipeline(ImagesPipeline): def file_key(self, url):
class ImagesPipelineTestCase(unittest.TestCase): self.assertEquals(converted.mode, 'RGB') self.assertEquals(converted.getcolors(), [(10000, (205, 230, 255))]) # transparency case with palette: P and PNG COLOUR = (0, 127, 255, 50) im = _create_image('PNG', 'RGBA', SIZE, COLOUR) ...
class WorkerProcess(multiprocessing.Process): # set to /dev/null self._new_stdin = os.devnull def run(self): ''' Called when the process is started. Pushes the result onto the
class WorkerProcess(multiprocessing.Process): # set to /dev/null self._new_stdin = os.devnull # NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files # clear var to ensure we only delete files for this child self._lo...
class WorkerProcess(multiprocessing.Process): except: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) display.debug("WORKER PROCESS EXITING")
class WorkerProcess(multiprocessing.Process): except: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) finally: self._clean_up() display.debug(...
class WorkerProcess(multiprocessing.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
class WorkerProcess(multiprocessing.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue()) def _clean_up(self): # NOTE: see note in init about forks # ensure we cleanup all temp files for this worker self._l...
class DataLoader: ''' def __init__(self): self._basedir = '.' self._FILE_CACHE = dict() self._tempfiles = set() # initialize the vault stuff with an empty password
class DataLoader: ''' def __init__(self): self._basedir = '.' # NOTE: not effective with forks as the main copy does not get updated. # avoids rereading files self._FILE_CACHE = dict() # NOTE: not thread safe, also issues with forks not returning data to main proc ...
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp() f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP) f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): for f in self._tempfiles: try: self.cleanup_tmp_file(f)
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): """ Removes all temporary files that DataLoader has created NOTE: not thread safe, forks also need special handling see __init__ for details. """ for f in self._tempfiles: ...
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext) os.close(fd) cmd = self._editor_shell_command(tmp_path)
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP) os.close(fd) cmd = self._editor_shell_command(tmp_path)
from youtube_dl.utils import ( parse_iso8601, strip_jsonp, uppercase_escape, )
from youtube_dl.utils import ( parse_iso8601, strip_jsonp, uppercase_escape, limit_length, )
class TestUtil(unittest.TestCase): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐') if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐') def test_limit_length(self): self.assertEqual(limit_length(None, 12), None) self.assertEqual(limit_length('foo', 12), 'foo') self.assertT...
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, )
from ..utils import ( compat_urllib_parse, compat_urllib_request, urlencode_postdata, ExtractorError, limit_length, )
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'url': 'https://www.facebook.com/video.php?v=10204634152394104', 'only_matching': True,
class FacebookIE(InfoExtractor): 'duration': 38, 'title': 'Did you know Kei Nishikori is the first Asian man to ever reach a Grand Slam fin...', } }, { 'note': 'Video without discernible title', 'url': 'https://www.facebook.com/video.php?v=274175099429670', 'i...
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) if len(video_title) > 80 + 3: ...
class FacebookIE(InfoExtractor): video_title = self._html_search_regex( r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(.*?)</span>', webpage, 'alternative title', default=None) video_title = limit_length(video_title, 8...
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output
except AttributeError: if ret: raise subprocess.CalledProcessError(ret, p.args, output=output) return output def limit_length(s, length): """ Add ellipses to overly long strings """ if s is None: return None ELLIPSES = '...' if len(s) > length: return s[:len...
RETURN = """ - values from the environment variables. type: list """ import os from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase):
RETURN = """ - values from the environment variables. type: list """ from ansible.plugins.lookup import LookupBase from ansible.utils import py3compat class LookupModule(LookupBase):
class LookupModule(LookupBase): ret = [] for term in terms: var = term.split()[0] ret.append(os.getenv(var, '')) return ret
class LookupModule(LookupBase): ret = [] for term in terms: var = term.split()[0] ret.append(py3compat.environ.get(var, '')) return ret
from pandas.core.internals.construction import ( sanitize_index, to_arrays, ) from pandas.core.series import Series from pandas.io.formats import console, format as fmt
from pandas.core.internals.construction import ( sanitize_index, to_arrays, ) from pandas.core.ops.missing import dispatch_fill_zeros from pandas.core.series import Series from pandas.io.formats import console, format as fmt
class DataFrame(NDFrame): # iterate over columns return ops.dispatch_to_series(this, other, _arith_op) else: result = _arith_op(this.values, other.values) return self._constructor( result, index=new_index, columns=new_columns, copy=False ...
class DataFrame(NDFrame): # iterate over columns return ops.dispatch_to_series(this, other, _arith_op) else: with np.errstate(all="ignore"): result = _arith_op(this.values, other.values) result = dispatch_fill_zeros(func, this.values, other.values,...
class TestNumericArithmeticUnsorted: tm.assert_index_equal(index + index, 2 * index) tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty
class TestNumericArithmeticUnsorted: tm.assert_index_equal(index + index, 2 * index) tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty def test_fill_value_inf_masking(): # GH #27464 make sure we mask 0/1 with Inf and not NaN df = pd.DataFrame({"A": [0, 1,...
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() ...
def _connect(self): def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and has appropriate file permissions. This should be done before storing any sensitive data in it. """ # Prepare a file fd = os.open( self.file...
def _create_database(self, last_upgrade_to_run): finally: conn.close() # Set the file permissions os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR) def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
def _create_database(self, last_upgrade_to_run): finally: conn.close() def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """
import os import platform import shutil import tempfile import pytest
import os import platform import shutil import stat import tempfile import pytest
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.home = tempfile.mkdtemp() yield for cleanup_method in [lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.home)]: try: cleanup_method exce...
def setUp(self, request): os.unlink(self.db_path) except OSError: pass self.test_home = tempfile.mkdtemp() yield for cleanup_method in [ lambda: os.unlink(self.db_path), lambda: shutil.rmtree(self.test_home) ]: try: ...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.home}): return SqliteAccountInfo( file_nam...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.environ', env or {'HOME': self.test_home}): return SqliteAccountInfo( fil...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, } ) actual_path = os.path.abspath(ac...
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): def test_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, } ) actual_path = os.path....
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._make_sq...
def test_uses_xdg_config_home(self, apiver): def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.test_home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._ma...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, ...
def test_account_info_env_var_overrides_xdg_config_home(self): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.test_home, 'USERPROFILE': self.test_home, XDG_CONFIG_HOME_ENV_V...
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...
def namespace_facts(facts): ''' return all facts inside 'ansible_facts' w/o an ansible_ prefix ''' deprefixed = {} for k in facts: if k in ('ansible_local',): # exceptions to 'deprefixing' deprefixed[k] = module_response_deepcopy(facts[k]) else: deprefixed...
def namespace_facts(facts): ''' return all facts inside 'ansible_facts' w/o an ansible_ prefix ''' deprefixed = {} for k in facts: if k.startswith('ansible_') and k not in ('ansible_local',): deprefixed[k[8:]] = module_response_deepcopy(facts[k]) else: deprefixed[k] =...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1', 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', ]) for path in sys.argv[1:] or sys.stdin.read().splitli...
def main(): 'test/integration/targets/win_module_utils/library/legacy_only_new_way_win_line_ending.ps1', 'test/integration/targets/win_module_utils/library/legacy_only_old_way_win_line_ending.ps1', 'test/utils/shippable/timing.py', 'test/integration/targets/gathering_facts/library/bogus_...
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
def load_data(path='imdb.npz', path, origin=origin_folder + 'imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path, allow_pickle=True) as f: x_train, labels_train = f['x_train'], f['y_train'] x_test, labels_test = f['x_test'], f['y_test']
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,