buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestUtil(unittest.TestCase): self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz') if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz') self.assertEqual( url_basename(u'http...
def remove_start(s, start): def url_basename(url): m = re.match(r'(?:https?:|)//[^/]+/(?:[^/?#]+/)?([^/?#]+)/?(?:[?#]|$)', url) if not m: return u'' return m.group(1)
def remove_start(s, start): def url_basename(url): m = re.match(r'(?:https?:|)//[^/]+/(?:[^?#]+/)?([^/?#]+)/?(?:[?#]|$)', url) if not m: return u'' return m.group(1)
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:
from thefuck.rules.git_diff_staged import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [Command(script='git diff')]) def test_match(command): assert match(command, None)
from thefuck.rules.git_diff_staged import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='git diff foo'), Command(script='git diff')]) def test_match(command): assert match(command, None)
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('git diff'), 'git diff --staged')]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command('git diff'), 'git diff --staged'), (Command('git diff foo'), 'git diff --staged foo')]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
def match(command, settings): @utils.git_support def get_new_command(command, settings): return '{} --staged'.format(command.script)
def match(command, settings): @utils.git_support def get_new_command(command, settings): return command.script.replace(' diff', ' diff --staged')
def test_buffer_size(fig_test, fig_ref): ax = fig_ref.add_subplot() ax.set_yticks([0, 1]) ax.set_yticklabels(["€", ""])
def test_buffer_size(fig_test, fig_ref): ax = fig_ref.add_subplot() ax.set_yticks([0, 1]) ax.set_yticklabels(["€", ""]) def test_fontproperties_kwarg_precedence(): """Test that kwargs take precedence over fontproperties defaults.""" plt.figure() text1 = plt.xlabel("value", fontproperties='Time...
class Text(Artist): def update(self, kwargs): # docstring inherited # Update bbox last, as it depends on font properties. sentinel = object() # bbox can be None, so use another sentinel. bbox = kwargs.pop("bbox", sentinel) super().update(kwargs) if bbox is not senti...
class Text(Artist): def update(self, kwargs): # docstring inherited sentinel = object() # bbox can be None, so use another sentinel. # Update fontproperties first, as it has lowest priority. fontproperties = kwargs.pop("fontproperties", sentinel) if fontproperties is not se...
try: except AttributeError: pass _openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } #: The list of supported SSL/TLS cipher suites. DEFAULT_SSL_CIPHER_LI...
try: except AttributeError: pass _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict( (v, k) for k, v in _st...
class PyOpenSSLContext(object): @property def verify_mode(self): return self._ctx.get_verify_mode() @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify(value, _verify_callback) def set_default_verify_paths(self): self._ctx.set_default_verify_paths()
class PyOpenSSLContext(object): @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify( _stdlib_to_openssl_verify[value], _verify_callback ) def set_d...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locations(ca_ce...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locat...
class WrappedRequest(object): """ return self.request.meta.get('is_unverifiable', False) # python3 uses request.unverifiable @property def unverifiable(self): return self.is_unverifiable() def get_origin_req_host(self): return urlparse_cached(self.request).hostname ...
class WrappedRequest(object): """ return self.request.meta.get('is_unverifiable', False) def get_origin_req_host(self): return urlparse_cached(self.request).hostname # python3 uses attributes instead of methods @property def full_url(self): return self.get_full_url() ...
class WrappedRequestTest(TestCase): def test_get_full_url(self): self.assertEqual(self.wrapped.get_full_url(), self.request.url) def test_get_host(self): self.assertEqual(self.wrapped.get_host(), urlparse(self.request.url).netloc) def test_get_type(self): self.assertEqual(self.wra...
class WrappedRequestTest(TestCase): def test_get_full_url(self): self.assertEqual(self.wrapped.get_full_url(), self.request.url) self.assertEqual(self.wrapped.full_url, self.request.url) def test_get_host(self): self.assertEqual(self.wrapped.get_host(), urlparse(self.request.url).netlo...
class WrappedRequestTest(TestCase): def test_get_origin_req_host(self): self.assertEqual(self.wrapped.get_origin_req_host(), 'www.example.com') def test_has_header(self): self.assertTrue(self.wrapped.has_header('content-type'))
class WrappedRequestTest(TestCase): def test_get_origin_req_host(self): self.assertEqual(self.wrapped.get_origin_req_host(), 'www.example.com') self.assertEqual(self.wrapped.origin_req_host, 'www.example.com') def test_has_header(self): self.assertTrue(self.wrapped.has_header('content-...
class DataFrame(NDFrame): scalar """ if takeable: series = self._iget_item_cache(col) return com.maybe_box_datetimelike(series._values[index]) series = self._get_item_cache(col) engine = self.index._engine
class DataFrame(NDFrame): scalar """ if takeable: series = self._ixs(col, axis=1) return series._values[index] series = self._get_item_cache(col) engine = self.index._engine
""" test scalar indexing, including at and iat """ import numpy as np import pytest
""" test scalar indexing, including at and iat """ from datetime import datetime, timedelta import numpy as np import pytest
class TestScalar2: s = Series([1, 2]) result = s[np.array(0)] assert result == 1
class TestScalar2: s = Series([1, 2]) result = s[np.array(0)] assert result == 1 def test_iat_dont_wrap_object_datetimelike(): # GH#32809 .iat calls go through DataFrame._get_value, should not # call maybe_box_datetimelike dti = date_range("2016-01-01", periods=3) tdi = dti - ...
class BaseMemcachedTests(BaseCacheTests): Whilst other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, ':1:%s' % key) with self.assertRaisesMessage(InvalidCacheKey, msg): cache.set(key, 'value')
class BaseMemcachedTests(BaseCacheTests): Whilst other backends merely warn, memcached should raise for an invalid key. """ msg = expected_warning.replace(key, cache.make_key(key)) with self.assertRaisesMessage(InvalidCacheKey, msg): cache.set(key, 'value')
ReferenceError: conole is not defined @pytest.mark.parametrize('test', tests) def test_match(monkeypatch, test): monkeypatch.setenv('EDITOR', 'dummy_editor') assert match(Command(stderr=test[4]), None) @pytest.mark.parametrize('test', tests) def test_not_match(monkeypatch, test): if 'EDITOR' in os.envir...
ReferenceError: conole is not defined @pytest.mark.parametrize('test', tests) def test_match(mocker, monkeypatch, test): mocker.patch('os.path.isfile', return_value=True) monkeypatch.setenv('EDITOR', 'dummy_editor') assert match(Command(stderr=test[4]), None) @pytest.mark.parametrize('test', tests) def ...
def _search(stderr): def match(command, settings): return 'EDITOR' in os.environ and _search(command.stderr) def get_new_command(command, settings):
def _search(stderr): def match(command, settings): if 'EDITOR' not in os.environ: return False m = _search(command.stderr) return m and os.path.isfile(m.group('file')) def get_new_command(command, settings):
def match(command): def _parse_operations(help_text_lines): # The regex has to be a bytes-style regex since reading from a file # like stdin returns a bytes-style object and a string-style regex # wouldn't work. operation_regex = re.compile(b'^([a-z-]+) +', re.MULTILINE) return operation_regex.fin...
def match(command): def _parse_operations(help_text_lines): operation_regex = re.compile(r'^([a-z-]+) +', re.MULTILINE) return operation_regex.findall(help_text_lines)
def _get_operations(): proc = subprocess.Popen(["dnf", '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) lines = proc.stdout.read() return _parse_operations(lines)
def _get_operations(): proc = subprocess.Popen(["dnf", '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) lines = proc.stdout.read().decode("utf-8") return _parse_operations(lines)
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...
ssl = None import sys import tempfile from nturl2path import url2pathname, pathname2url from base64 import b64encode
ssl = None import sys import tempfile import warnings from nturl2path import url2pathname, pathname2url from base64 import b64encode
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc. # Everywhere else they work ok, but on those machines, sometimes
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") def test_local_file_open(self): # bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme class DummyURLopener(urllib.request.URLopener): ...
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name) or name == 'open_local_file': if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
LOGGING_CONFIG_DEFAULTS = dict( version=1, disable_existing_loggers=False, loggers={ "root": {"level": "INFO", "handlers": ["console"]}, "sanic.error": { "level": "INFO", "handlers": ["error_console"],
LOGGING_CONFIG_DEFAULTS = dict( version=1, disable_existing_loggers=False, loggers={ "sanic.root": {"level": "INFO", "handlers": ["console"]}, "sanic.error": { "level": "INFO", "handlers": ["error_console"],
def test_logging_defaults(): reset_logging() app = Sanic("test_logging") for fmt in [h.formatter for h in logging.getLogger('root').handlers]: assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic.error').handler...
def test_logging_defaults(): reset_logging() app = Sanic("test_logging") for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]: assert fmt._fmt == LOGGING_CONFIG_DEFAULTS['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic.error').h...
def test_logging_pass_customer_logconfig(): app = Sanic("test_logging", log_config=modified_config) for fmt in [h.formatter for h in logging.getLogger('root').handlers]: assert fmt._fmt == modified_config['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger('sanic...
def test_logging_pass_customer_logconfig(): app = Sanic("test_logging", log_config=modified_config) for fmt in [h.formatter for h in logging.getLogger('sanic.root').handlers]: assert fmt._fmt == modified_config['formatters']['generic']['format'] for fmt in [h.formatter for h in logging.getLogger(...
def test_logging_pass_customer_logconfig(): def test_log_connection_lost(app, debug, monkeypatch): """ Should not log Connection lost exception on non debug """ stream = StringIO() root = logging.getLogger('root') root.addHandler(logging.StreamHandler(stream)) monkeypatch.setattr(sanic.server, 'logg...
def test_logging_pass_customer_logconfig(): def test_log_connection_lost(app, debug, monkeypatch): """ Should not log Connection lost exception on non debug """ stream = StringIO() root = logging.getLogger('sanic.root') root.addHandler(logging.StreamHandler(stream)) monkeypatch.setattr(sanic.server,...
def test_log_connection_lost(app, debug, monkeypatch): assert 'Connection lost before response written @' in log else: assert 'Connection lost before response written @' not in log
def test_log_connection_lost(app, debug, monkeypatch): assert 'Connection lost before response written @' in log else: assert 'Connection lost before response written @' not in log def test_logging_modified_root_logger_config(): reset_logging() modified_config = LOGGING_CONFIG_DEFAULTS ...
from thefuck.types import Command @pytest.fixture def output(branch_name): return "fatal: A branch named '{}' already exists.".format(branch_name) @pytest.fixture
from thefuck.types import Command @pytest.fixture def output(src_branch_name): return "fatal: A branch named '{}' already exists.".format(src_branch_name) @pytest.fixture
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, branch_name', [ ('git branch foo', 'foo'), ('git checkout bar', 'bar')]) def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.pa...
def new_command(branch_name): 'git branch -D {0} && git checkout -b {0}', 'git checkout {0}']] @pytest.mark.parametrize('script, src_branch_name, branch_name', [ ('git branch foo', 'foo', 'foo'), ('git checkout bar', 'bar', 'bar'), ('git checkout -b "let\'s-push-this"', '"let\'s-push-this"', '"let...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and " already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '([^']*)' already exists.", com...
from thefuck.utils import eager @git_support def match(command): return ("fatal: A branch named '" in command.output and "' already exists." in command.output) @git_support @eager def get_new_command(command): branch_name = re.findall( r"fatal: A branch named '(.+)' already exists.", comma...
def _recast_datetimelike_result(result: DataFrame) -> DataFrame: result = result.copy() obj_cols = [ idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes[idx]) ] # See GH#26285
def _recast_datetimelike_result(result: DataFrame) -> DataFrame: result = result.copy() obj_cols = [ idx for idx in range(len(result.columns)) if is_object_dtype(result.dtypes.iloc[idx]) ] # See GH#26285
def test_apply_with_mixed_types(): result = g.apply(lambda x: x / x.sum()) tm.assert_frame_equal(result, expected)
def test_apply_with_mixed_types(): result = g.apply(lambda x: x / x.sum()) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "group_column_dtlike", [datetime.today(), datetime.today().date(), datetime.today().time()], ) def test_apply_datetime_issue(group_column_dtlike): # GH-2824...
class Axis(martist.Artist): the top for the y-axis; the "inverse" direction is increasing to the left for the x-axis and to the bottom for the y-axis. """ a, b = self.get_view_interval() if inverted: self.set_view_interval(max(a, b), min(a, b), ignore=True) el...
class Axis(martist.Artist): the top for the y-axis; the "inverse" direction is increasing to the left for the x-axis and to the bottom for the y-axis. """ # Currently, must be implemented in subclasses using set_xlim/set_ylim # rather than generically using set_view_interval, so ...
class XAxis(Axis): def get_minpos(self): return self.axes.dataLim.minposx def set_default_intervals(self): # docstring inherited xmin, xmax = 0., 1.
class XAxis(Axis): def get_minpos(self): return self.axes.dataLim.minposx def set_inverted(self, inverted): # docstring inherited a, b = self.get_view_interval() self.axes.set_xlim(sorted((a, b), reverse=inverted), auto=None) def set_default_intervals(self): # docst...
class YAxis(Axis): def get_minpos(self): return self.axes.dataLim.minposy def set_default_intervals(self): # docstring inherited ymin, ymax = 0., 1.
class YAxis(Axis): def get_minpos(self): return self.axes.dataLim.minposy def set_inverted(self, inverted): # docstring inherited a, b = self.get_view_interval() self.axes.set_ylim(sorted((a, b), reverse=inverted), auto=None) def set_default_intervals(self): # docst...
def test_inverted_cla(): ax.cla() ax.imshow(img) plt.autoscale() assert not(ax.xaxis_inverted()) assert ax.yaxis_inverted() # 5. two shared axes. Clearing the master axis should bring axes in shared # axes back to normal ax0 = plt.subplot(211) ax1 = plt.subplot(212, sharey=ax0) ...
def test_inverted_cla(): ax.cla() ax.imshow(img) plt.autoscale() assert not ax.xaxis_inverted() assert ax.yaxis_inverted() # 5. two shared axes. Inverting the master axis should invert the shared # axes; clearing the master axis should bring axes in shared # axes back to normal. ax0...
from pandas.core.dtypes.inference import is_array_like from pandas import compat from pandas.core import ops from pandas.core.arrays import PandasArray from pandas.core.construction import extract_array from pandas.core.indexers import check_array_indexer from pandas.core.missing import isna
from pandas.core.dtypes.inference import is_array_like from pandas import compat from pandas.core import ops from pandas.core.arrays import IntegerArray, PandasArray from pandas.core.arrays.integer import _IntegerDtype from pandas.core.construction import extract_array from pandas.core.indexers import check_array_inde...
class StringArray(PandasArray): if copy: return self.copy() return self return super().astype(dtype, copy) def _reduce(self, name, skipna=True, **kwargs):
class StringArray(PandasArray): if copy: return self.copy() return self elif isinstance(dtype, _IntegerDtype): arr = self._ndarray.copy() mask = self.isna() arr[mask] = 0 values = arr.astype(dtype.numpy_dtype) re...
def test_from_sequence_no_mutate(copy): tm.assert_numpy_array_equal(a, original) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.xfail(reason="Not implemented StringArray.sum") def test_reduce(skipna):
def test_from_sequence_no_mutate(copy): tm.assert_numpy_array_equal(a, original) def test_astype_int(): arr = pd.array(["1", pd.NA, "3"], dtype="string") result = arr.astype("Int64") expected = pd.array([1, pd.NA, 3], dtype="Int64") tm.assert_extension_array_equal(result, expected) @pytest.mark...
def get_meta_refresh(response): def response_status_message(status): """Return status code plus status text descriptive message >>> response_status_message(200) '200 OK' >>> response_status_message(404) '404 Not Found' """ return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(sta...
def get_meta_refresh(response): def response_status_message(status): """Return status code plus status text descriptive message """ return '%s %s' % (status, to_native_str(http.RESPONSES.get(int(status), "Unknown Status"))) def response_httprepr(response):
from six.moves.urllib.parse import urlparse from scrapy.http import Response, TextResponse, HtmlResponse from scrapy.utils.python import to_bytes from scrapy.utils.response import (response_httprepr, open_in_browser, get_meta_refresh, get_base_url) __doctests__ = ['scrapy.utils.respo...
from six.moves.urllib.parse import urlparse from scrapy.http import Response, TextResponse, HtmlResponse from scrapy.utils.python import to_bytes from scrapy.utils.response import (response_httprepr, open_in_browser, get_meta_refresh, get_base_url, response_status_message) __doctests...
class ResponseUtilsTest(unittest.TestCase): resp2 = HtmlResponse("http://www.example.com", body=b""" <html><body>blahablsdfsal&amp;</body></html>""") self.assertEqual(get_base_url(resp2), "http://www.example.com")
class ResponseUtilsTest(unittest.TestCase): resp2 = HtmlResponse("http://www.example.com", body=b""" <html><body>blahablsdfsal&amp;</body></html>""") self.assertEqual(get_base_url(resp2), "http://www.example.com") def test_response_status_message(self): self.assertEqual(response_sta...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> {% autoescape off %} <div id="browserTraceback"> <ul c...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);"> Switch to copy-and-paste view</a></span>{% endif %} </h2> <div id="browserTraceback"> <ul class="traceback"> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <tbody> {% for var in frame.vars|dictsort:0 %} <tr> <td>{{ var.0|force_escape }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> <tbody> {% for var in frame.vars|dictsort:0 %} <tr> <td>{{ var.0 }}</td> <td class="code"><pre>{{ var.1 }}</pre></td> </tr> ...
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> {% endfor %} </ul> </div> {% endautoescape %} <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin">
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> {% endfor %} </ul> </div> <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post"> {% if not is_email %} <div id="pastebinTraceback" class="pastebin">
In template {{ template_info.name }}, error at line {{ template_info.line }} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception: {% else %} During handli...
In template {{ template_info.name }}, error at line {{ template_info.line }} Traceback:{% for frame in frames %} {% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %} The above exception ({{ frame.exc_cause|force_escape }}) was the direct cause of the following exception: {% else %} ...
error (raise ... from ...) can't be silenced using NOQA. import sys from django.test import RequestFactory, TestCase from django.views.debug import ExceptionReporter
error (raise ... from ...) can't be silenced using NOQA. import sys from django.test import RequestFactory, TestCase from django.utils.safestring import mark_safe from django.views.debug import ExceptionReporter
class Py3ExceptionReporterTests(TestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError('Top level') except AttributeError as explicit: try: raise ValueError('Second exception') from explicit ...
class Py3ExceptionReporterTests(TestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError('<p>Second exception</p>') fr...
class Py3ExceptionReporterTests(TestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format("Top level"))) self.assertEqual(2, html.count(implicit_...
class Py3ExceptionReporterTests(TestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, h...
class DataFrame(NDFrame): for k1, k2 in zip(key, value.columns): self[k1] = value[k2] else: indexer = self.loc._get_listlike_indexer( key, axis=1, raise_missing=False )[1]
class DataFrame(NDFrame): for k1, k2 in zip(key, value.columns): self[k1] = value[k2] else: self.loc._ensure_listlike_indexer(key, axis=1) indexer = self.loc._get_listlike_indexer( key, axis=1, raise_missing=False ...
from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( is_integer, is_iterator, is_list_like,
from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( is_hashable, is_integer, is_iterator, is_list_like,
class _LocationIndexer(_NDFrameIndexerBase): """ Convert a potentially-label-based key into a positional indexer. """ if self.axis is not None: return self._convert_tuple(key, is_setter=True)
class _LocationIndexer(_NDFrameIndexerBase): """ Convert a potentially-label-based key into a positional indexer. """ if self.name == "loc": self._ensure_listlike_indexer(key) if self.axis is not None: return self._convert_tuple(key, is_setter=True)
class _LocationIndexer(_NDFrameIndexerBase): raise raise IndexingError(key) from e def __setitem__(self, key, value): if isinstance(key, tuple): key = tuple(com.apply_if_callable(x, self.obj) for x in key)
class _LocationIndexer(_NDFrameIndexerBase): raise raise IndexingError(key) from e def _ensure_listlike_indexer(self, key, axis=None): """ Ensure that a list-like of column labels are all present by adding them if they do not already exist. Parameters ...
class TestDataFrameIndexing: expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected) def test_setitem_multi_index(self): # GH7655, test that assigning to a sub-frame of a frame # with multi-index columns aligns both rows and columns
class TestDataFrameIndexing: expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "columns,box,expected", [ ( ["A", "B", "C", "D"], 7, pd.DataF...
class TestDataFrameIndexing: float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False) msg = ( r"\"None of \[Float64Index\(\[.*dtype='float64'\)\] are in the " r"\[columns\]\"" ) with pytest.raises(KeyError, match...
class TestDataFrameIndexing: float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False) # set ndarray arr = np.random.randn(len(float_frame)) float_frame["col9"] = arr
Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" assert is_scalar(result) and result == "Z" def test_loc_coercion(self): # 12411
Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" assert is_scalar(result) and result == "Z" @pytest.mark.parametrize( "index,box,expected", [ ( ([0, 2], ["A", "B", "C", "D"]), 7, pd.DataFrame( ...
def _isna_new(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _isna_ndarr...
def _isna_new(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj, old=False) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return ...
def _isna_old(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _isna_n...
def _isna_old(obj): elif isinstance(obj, type): return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)): return _isna_ndarraylike(obj, old=True) elif isinstance(obj, ABCDataFrame): return obj.isna() elif isinstance(obj, list): return _...
def _use_inf_as_na(key): globals()["_isna"] = _isna_new def _isna_ndarraylike(obj): values = getattr(obj, "_values", obj) dtype = values.dtype if is_extension_array_dtype(dtype): result = values.isna() elif is_string_dtype(dtype): result = _isna_string_dtype(values, dtype, old...
def _use_inf_as_na(key): globals()["_isna"] = _isna_new def _isna_ndarraylike(obj, old: bool = False): """ Return an array indicating which values of the input array are NaN / NA. Parameters ---------- obj: array-like The input array whose elements are to be checked. old: bool...
import pytest from pandas.core.dtypes.dtypes import CategoricalDtype from pandas import Categorical, Index, Series, isna import pandas._testing as tm
import pytest from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd from pandas import Categorical, DataFrame, Index, Series, isna import pandas._testing as tm
class TestCategoricalMissing: expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype) tm.assert_categorical_equal(result, expected) assert isna(cat[-1]) # didnt modify original inplace
class TestCategoricalMissing: expected = Categorical(["A", "B", "C", "B", "A"], dtype=cat.dtype) tm.assert_categorical_equal(result, expected) assert isna(cat[-1]) # didnt modify original inplace @pytest.mark.parametrize( "values, expected", [ ([1, 2, 3], np.arr...
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return state.get_pending_tasks() def is_trivial_worker(self, state): """
class Worker(object): return six.moves.filter(lambda task: task.status in [PENDING, RUNNING], self.tasks) else: return six.moves.filter(lambda task: self.id in task.workers, state.get_pending_tasks()) def is_trivial_worker(self, state): ""...
class SchedulerIoTest(unittest.TestCase): self.assertFalse(task_9.has_excessive_failures()) task_9.add_failure() self.assertTrue(task_9.has_excessive_failures())
class SchedulerIoTest(unittest.TestCase): self.assertFalse(task_9.has_excessive_failures()) task_9.add_failure() self.assertTrue(task_9.has_excessive_failures()) class SchedulerWorkerTest(unittest.TestCase): def get_pending_ids(self, worker, state): return {task.id for task in work...
class TestJSInterpreter(unittest.TestCase): }''') self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50]) if __name__ == '__main__': unittest.main()
class TestJSInterpreter(unittest.TestCase): }''') self.assertEqual(jsi.call_function('x'), [20, 20, 30, 40, 50]) def test_call(self): jsi = JSInterpreter(''' function x() { return 2; } function y(a) { return x() + a; } function z() { return y(3); } ''') ...
class JSInterpreter(object): return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v ...
class JSInterpreter(object): return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v ...
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines(['ls', 'rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestBash(object): assert 'TF_ALIAS=fuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING=utf-8' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias asser...
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_get_history(self, history_lines, shell): history_lines([': 1432613911:0;ls', ': 1432613916:0;rm']) assert list(shell.get_history()) == ['ls', 'rm']
class TestZsh(object): assert 'thefuck' in shell.app_alias('fuck') assert 'PYTHONIOENCODING' in shell.app_alias('fuck') def test_app_alias_variables_correctly_set(self, shell): alias = shell.app_alias('fuck') assert "alias fuck='TF_CMD=$(TF_ALIAS" in alias assert '$(TF_ALIAS...
from .generic import Generic class Bash(Generic): def app_alias(self, fuck): alias = "TF_ALIAS={0}" \ " alias {0}='PYTHONIOENCODING=utf-8" \ " TF_CMD=$(TF_SHELL_ALIASES=$(alias) thefuck $(fc -ln -1)) && " \ " eval $TF_CMD".format(fuck) if settings.al...
from .generic import Generic class Bash(Generic): def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n' ' env TF_ALIAS={0} PYTHONIOENCODING=utf-8'
class Fish(Generic): return ['cd', 'grep', 'ls', 'man', 'open'] def app_alias(self, fuck): # It is VERY important to have the variables declared WITHIN the alias return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): alias = "alias {0}='TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ ' TF_SHELL_ALIASES=$(alias)' \ " TF_CMD=$(thefuck $(fc -ln -1 | tail -n 1)) &&" \ " eval $TF_CMD"...
from .generic import Generic class Zsh(Generic): def app_alias(self, alias_name): # It is VERY important to have the variables declared WITHIN the alias alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \ " PYTHONIOENCODING=utf-8" \ " TF_SHELL_ALIASES=$(alias)" \ ...
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '>-not-set-<'))) print(self.script)
class CorrectedCommand(object): compatibility_call(self.side_effect, old_cmd, self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) print(self.script)
class BlockManager(PandasObject): if len(self.blocks) != len(other.blocks): return False # canonicalize block order, using a tuple combining the type # name and then mgr_locs because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by...
class BlockManager(PandasObject): if len(self.blocks) != len(other.blocks): return False # canonicalize block order, using a tuple combining the mgr_locs # then type name because there might be unconsolidated # blocks (say, Categorical) which can only be distinguished by ...
def test_make_block_no_pandas_array(): result = make_block(arr.to_numpy(), slice(len(arr)), dtype=arr.dtype) assert result.is_integer is True assert result.is_extension is False
def test_make_block_no_pandas_array(): result = make_block(arr.to_numpy(), slice(len(arr)), dtype=arr.dtype) assert result.is_integer is True assert result.is_extension is False def test_dataframe_not_equal(): # see GH28839 df1 = pd.DataFrame({"a": [1, 2], "b": ["s", "d"]}) df2 = pd.DataFrame(...
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared...
def resolve_redirects(self, resp, req, stream=False, timeout=None, except KeyError: pass extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._coo...
default 'raise' DatetimeIndex(['2018-03-01 09:00:00-05:00', '2018-03-02 09:00:00-05:00', '2018-03-03 09:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq='D') With the ``tz=None``, we can remove the time zone information ...
default 'raise' DatetimeIndex(['2018-03-01 09:00:00-05:00', '2018-03-02 09:00:00-05:00', '2018-03-03 09:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None) With the ``tz=None``, we can remove the time zone information ...
default 'raise' >>> tz_aware.tz_localize(None) DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', '2018-03-03 09:00:00'], dtype='datetime64[ns]', freq='D') Be careful with DST changes. When there is sequential data, pandas can infer...
default 'raise' >>> tz_aware.tz_localize(None) DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', '2018-03-03 09:00:00'], dtype='datetime64[ns]', freq=None) Be careful with DST changes. When there is sequential data, pandas can infe...
default 'raise' ) new_dates = new_dates.view(DT64NS_DTYPE) dtype = tz_to_dtype(tz) return self._simple_new(new_dates, dtype=dtype, freq=self.freq) # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timestamp meth...
default 'raise' ) new_dates = new_dates.view(DT64NS_DTYPE) dtype = tz_to_dtype(tz) freq = None if timezones.is_utc(tz) or (len(self) == 1 and not isna(new_dates[0])): # we can preserve freq # TODO: Also for fixed-offsets freq = self.freq ...
class TestDatetimeIndexTimezones: ) for i, ts in enumerate(index): assert ts == index[i]
class TestDatetimeIndexTimezones: ) for i, ts in enumerate(index): assert ts == index[i] def test_tz_localize_invalidates_freq(): # we only preserve freq in unambiguous cases # if localized to US/Eastern, this crosses a DST transition dti = date_range("2014-03-08 23:00", "2014...
class TestSeriesComparison: # datetime64tz dtype dti = dti.tz_localize("US/Central") ser = Series(dti).rename(names[1]) result = op(ser, dti) assert result.name == names[2]
class TestSeriesComparison: # datetime64tz dtype dti = dti.tz_localize("US/Central") dti._set_freq("infer") # freq not preserved by tz_localize ser = Series(dti).rename(names[1]) result = op(ser, dti) assert result.name == names[2]
from .helper import on_ci @pytest.mark.parametrize( "test_file", ["Tests/images/crash_1.tif", "Tests/images/crash_2.tif"] ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Metadata warning")
from .helper import on_ci @pytest.mark.parametrize( "test_file", [ "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Metadata warni...
'is_url', 'url_to_path', 'path_to_url', 'is_archive_file', 'unpack_vcs_link', 'unpack_file_url', 'is_vcs_url', 'is_file_url', 'unpack_http_url', 'unpack_url'] logger = logging.getLogger(__name__)
'is_url', 'url_to_path', 'path_to_url', 'is_archive_file', 'unpack_vcs_link', 'unpack_file_url', 'is_vcs_url', 'is_file_url', 'unpack_http_url', 'unpack_url', 'parse_content_disposition', 'sanitize_content_filename'] logger = logging.getLogger(__name__)
def unpack_url( write_delete_marker_file(location) def _download_http_url( link, # type: Link session, # type: PipSession
def unpack_url( write_delete_marker_file(location) def sanitize_content_filename(filename): # type: (str) -> str """ Sanitize the "filename" value from a Content-Disposition header. """ return os.path.basename(filename) def parse_content_disposition(content_disposition, default_filename)...
def _download_http_url( # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: type, params = cgi.parse_header(content_disposition) # We use ``or`` here because we don't want to use an "empty" v...
def _download_http_url( # Have a look at the Content-Disposition header for a better guess content_disposition = resp.headers.get('content-disposition') if content_disposition: filename = parse_content_disposition(content_disposition, filename) ext = splitext(filename)[1] if not ext: ...
import pip from pip._internal.download import ( CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache, unpack_file_url, unpack_http_url, url_to_path, ) from pip._internal.exceptions import HashMismatch
import pip from pip._internal.download import ( CI_ENVIRONMENT_VARIABLES, MultiDomainBasicAuth, PipSession, SafeFileCache, _download_http_url, parse_content_disposition, sanitize_content_filename, unpack_file_url, unpack_http_url, url_to_path, ) from pip._internal.exceptions import HashMismatch
def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file): rmtree(download_dir) @pytest.mark.parametrize("url,win_expected,non_win_expected", [ ('file:tmp', 'tmp', 'tmp'), ('file:c:/path/to/file', r'C:\path\to\file', 'c:/path/to/file'),
def test_unpack_http_url_bad_downloaded_checksum(mock_unpack_file): rmtree(download_dir) @pytest.mark.parametrize("filename, expected", [ ('dir/file', 'file'), ('../file', 'file'), ('../../file', 'file'), ('../', ''), ('../..', '..'), ('/', ''), ]) def test_sanitize_content_filename(fi...
except ImportError: # pragma: nocover from pydantic.fields import Field as ModelField # type: ignore async def serialize_response( *, field: ModelField = None,
except ImportError: # pragma: nocover from pydantic.fields import Field as ModelField # type: ignore def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclu...
async def serialize_response( ) -> Any: if field: errors = [] if exclude_unset and isinstance(response_content, BaseModel): if PYDANTIC_1: response_content = response_content.dict(exclude_unset=exclude_unset) else: response_content = response_c...
async def serialize_response( ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, by_alias=by_alias, exclude_unset=exclude_unset ) if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response...