buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation import Removed...
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation...
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery)
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_unionagg_tolerance(self): ...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 2-compatible code, so don't try Python 3 grammar. return [ pygram.python_grammar_no_prin...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 3-compatible code, so don't try Python 2 grammar return [ pygram.python_grammar_no_print...
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_unicode_literals(self) -> None: source, expected = read_data("python2_unicode_literals")
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_print_function(self) -> None: source, expected = read_data("python2_print_function") ...
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 lookatme.exceptions import IgnoredByContrib def render_code(token, body, stack, loop): lang = token["lang"] or "" if lang != "calendar":
from lookatme.exceptions import IgnoredByContrib def user_warnings(): """No warnings exist for this extension. Anything you want to warn the user about, such as security risks in processing untrusted markdown, should go here. """ return [] def render_code(token, body, stack, loop): lang = to...
is_flag=True, default=False, ) @click.option( "-e", "--exts",
is_flag=True, default=False, ) @click.option( "-s", "--safe", help="Do not load any new extensions specified in the source markdown. " "Extensions specified via env var or -e are still loaded", is_flag=True, default=False, ) @click.option( "--no-ext-warn", help="Load new ext...
nargs=-1, ) def main(debug, log_path, theme, code_style, dump_styles, input_files, live_reload, extensions, single_slide): """lookatme - An interactive, terminal-based markdown presentation tool. """ if debug: lookatme.config.LOG = lookatme.log.create_log(log_path)
nargs=-1, ) def main(debug, log_path, theme, code_style, dump_styles, input_files, live_reload, extensions, single_slide, safe, no_ext_warn, ignore_ext_failure): """lookatme - An interactive, terminal-based markdown presentation tool. See https://lookatme.readthedocs.io/en/v{{VERSION}...
def main(debug, log_path, theme, code_style, dump_styles, live_reload=live_reload, single_slide=single_slide, preload_extensions=preload_exts, ) if dump_styles:
def main(debug, log_path, theme, code_style, dump_styles, live_reload=live_reload, single_slide=single_slide, preload_extensions=preload_exts, safe=safe, no_ext_warn=no_ext_warn, ignore_ext_failure=ignore_ext_failure, ) if dump_styles:
import contextlib from lookatme.exceptions import IgnoredByContrib from . import terminal from . import file_loader CONTRIB_MODULES = [ terminal, file_loader, ] def load_contribs(contrib_names): """Load all contrib modules specified by ``contrib_names``. These should all be namespaced packages und...
import contextlib import lookatme.ascii_art from lookatme.exceptions import IgnoredByContrib import lookatme.prompt from . import terminal from . import file_loader CONTRIB_MODULES = [] def validate_extension_mod(ext_name, ext_mod): """Validate the extension, returns an array of warnings associated with the ...
from lookatme.exceptions import IgnoredByContrib class YamlRender: loads = lambda data: yaml.safe_load(data) dumps = lambda data: yaml.safe_dump(data)
from lookatme.exceptions import IgnoredByContrib def user_warnings(): """Provide warnings to the user that loading this extension may cause shell commands specified in the markdown to be run. """ return [ "Code-blocks with a language starting with 'file' may cause shell", " commands f...
import lookatme.config class YamlRender: loads = lambda data: yaml.safe_load(data) dumps = lambda data: yaml.safe_dump(data)
import lookatme.config def user_warnings(): """Provide warnings to the user that loading this extension may cause shell commands specified in the markdown to be run. """ return [ "Code-blocks with a language starting with 'terminal' will cause shell", " commands from the source markdo...
import lookatme.config import lookatme.contrib from lookatme.parser import Parser import lookatme.themes import lookatme.tui from lookatme.utils import dict_deep_update
import lookatme.config import lookatme.contrib from lookatme.parser import Parser import lookatme.prompt import lookatme.themes import lookatme.tui from lookatme.utils import dict_deep_update
class Presentation(object): """Defines a presentation """ def __init__(self, input_stream, theme, style_override=None, live_reload=False, single_slide=False, preload_extensions=None): """Creates a new Presentation :param stream input_stream: An input stream from which to re...
class Presentation(object): """Defines a presentation """ def __init__(self, input_stream, theme, style_override=None, live_reload=False, single_slide=False, preload_extensions=None, safe=False, no_ext_warn=False, ignore_ext_failure=False): """Creates a new Presenta...
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.live_reload = live_reload self.tui = None self.single_slide = single_slide self.theme_mod = __import__("lookatme.themes." + theme, fromlist=[theme])
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.live_reload = live_reload self.tui = None self.single_slide = single_slide self.safe = safe self.no_ext_warn = no_ext_warn self.ignore_ext_failure = ignore_ext_failure self.initia...
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.reload_thread.start() self.reload(data=input_stream.read()) def reload_watcher(self): """Watch for changes to the input filename, automatically reloading
def __init__(self, input_stream, theme, style_override=None, live_reload=False, self.reload_thread.start() self.reload(data=input_stream.read()) self.initial_load_complete = True def reload_watcher(self): """Watch for changes to the input filename, automatically reloading
def reload(self, data=None): parser = Parser(single_slide=self.single_slide) self.meta, self.slides = parser.parse(data) all_exts = set(self.preload_extensions) all_exts |= set(self.meta.get("extensions", [])) lookatme.contrib.load_contribs(all_exts) self.styles = looka...
def reload(self, data=None): parser = Parser(single_slide=self.single_slide) self.meta, self.slides = parser.parse(data) # only load extensions once! Live editing does not support # auto-extension reloading if not self.initial_load_complete: safe_exts = set(self.prel...
def reload(self, data=None): self.styles["style"] = self.style_override lookatme.config.STYLE = self.styles def run(self, start_slide=0): """Run the presentation!
def reload(self, data=None): self.styles["style"] = self.style_override lookatme.config.STYLE = self.styles self.initial_load_complete = True def warn_exts(self, exts): """Warn about source-provided extensions that are to-be-loaded """ if len(exts) == 0 or self....
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(weights, 'weights')
optional. if bin_range is not None: bin_range = self.convert_xunits(bin_range) if not cbook.is_scalar_or_string(bins): bins = self.convert_xunits(bins) # We need to do to 'weights' what was done to 'x' if weights is not None: w = cbook._reshape_2D(we...
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize('data, expected_number_of_hists', [([], 1), ([[]], 1),
def test_hist_datetime_datasets(): ax.hist(data, stacked=False) @pytest.mark.parametrize("bins_preprocess", [mpl.dates.date2num, lambda bins: bins, lambda bins: np.asarray(bins).astype('datetime64')], ids=['date2...
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat(frames, axis=1, join="outer", verify_integrity=True) return res.reindex(self.index, copy=False) else: ...
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat( frames, axis=1, join="outer", verify_integrity=True, sort=sort ) return res.reindex(self.i...
def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected)
def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected) @pytest.mark.parametrize("sort_kw", [True, False, None]) def test_suppress_future_warning_with_sort_kw(sort_kw): a = DataFrame({"col1": [1, 2]}, index=["c", "a"]) b = DataFrame({"col2": [4, 5]}, index=["b", "a"...
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) def test_uppercase_escape(self): self.assertEqual(uppercase_escape('aä'), 'aä') self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc') d = json.loads(stripped) self.assertEqual(d, {'STATUS': 'OK'}) def test_uppercase_escape(self): ...
from ..utils import ( unified_strdate, parse_duration, qualities, url_basename, )
from ..utils import ( unified_strdate, parse_duration, qualities, strip_jsonp, url_basename, )
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=lambda j: re.sub(r'parseMetadata\((.*?)\);\n//.*$', r'\1', j) ) token_page = self._download_webpage( ...
class NPOIE(InfoExtractor): 'http://e.omroep.nl/metadata/aflevering/%s' % video_id, video_id, # We have to remove the javascript callback transform_source=strip_jsonp, ) token_page = self._download_webpage( 'http://ida.omroep.nl/npoplayer/i.js'...
def parse_age_limit(s): def strip_jsonp(code): return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code) def js_to_json(code):
def parse_age_limit(s): def strip_jsonp(code): return re.sub( r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code) def js_to_json(code):
def verify_signature(pubkey_path, message, signature): try: return pubkey.verify(digest, signature) except RSA.RSAError as exc: if exc.args[0] == "bad signature": return False raise else: verifier = PKCS1_v1_5.new(pubkey) return ver...
def verify_signature(pubkey_path, message, signature): try: return pubkey.verify(digest, signature) except RSA.RSAError as exc: log.debug("Signature verification failed: %s", exc.args[0]) return False else: verifier = PKCS1_v1_5.new(pubkey) return ...
class AsyncAuth: clear_signature = payload["sig"] payload = salt.payload.loads(clear_signed_data) auth["aes"] = self.verify_master(payload, master_pub="token" in sign_in_payload) if not auth["aes"]: log.critical( "The Salt Master server's public key did not a...
class AsyncAuth: clear_signature = payload["sig"] payload = salt.payload.loads(clear_signed_data) if "pub_key" in payload: auth["aes"] = self.verify_master( payload, master_pub="token" in sign_in_payload ) if not auth["aes"]: l...
import salt.crypt import salt.master import salt.utils.files def test_get_rsa_pub_key_bad_key(tmp_path): """
import salt.crypt import salt.master import salt.utils.files PRIV_KEY = """ -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAoAsMPt+4kuIG6vKyw9r3+OuZrVBee/2vDdVetW+Js5dTlgrJ aghWWn3doGmKlEjqh7E4UTa+t2Jd6w8RSLnyHNJ/HpVhMG0M07MF6FMfILtDrrt8 ZX7eDVt8sx5gCEpYI+XG8Y07Ga9i3Hiczt+fu6HYwu96HggmG2pqkOrn3iGfqBvV YVFJzSZYe7e4c1Pe...
def test_cryptical_dumps_invalid_nonce(): assert isinstance(ret, bytes) with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"): assert master_crypt.loads(ret, nonce="abcde")
def test_cryptical_dumps_invalid_nonce(): assert isinstance(ret, bytes) with pytest.raises(salt.crypt.SaltClientError, match="Nonce verification error"): assert master_crypt.loads(ret, nonce="abcde") def test_verify_signature(tmpdir): tmpdir.join("foo.pem").write(PRIV_KEY.strip()) tmpdir.join(...
async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop): pki_dir.join("minion", "minion_master.pub").read() == pki_dir.join("master", "master.pub").read() )
async def test_req_chan_auth_v2_with_master_signing(pki_dir, io_loop): pki_dir.join("minion", "minion_master.pub").read() == pki_dir.join("master", "master.pub").read() ) async def test_req_chan_auth_v2_new_minion_with_master_pub(pki_dir, io_loop): pki_dir.join("master", "minions", "minion")....
class Request(object_ref): s = safe_url_string(url, self.encoding) self._url = escape_ajax(s) if ':' not in self._url: raise ValueError('Missing scheme in request url: %s' % self._url) url = property(_get_url, obsolete_setter(_set_url, 'url'))
class Request(object_ref): s = safe_url_string(url, self.encoding) self._url = escape_ajax(s) if ('://' not in self._url) and (not self._url.startswith('data:')): raise ValueError('Missing scheme in request url: %s' % self._url) url = property(_get_url, obsolete_setter(_set_url...
class RequestTest(unittest.TestCase): def test_url_no_scheme(self): self.assertRaises(ValueError, self.request_class, 'foo') def test_headers(self): # Different ways of setting headers attribute
class RequestTest(unittest.TestCase): def test_url_no_scheme(self): self.assertRaises(ValueError, self.request_class, 'foo') self.assertRaises(ValueError, self.request_class, '/foo/') self.assertRaises(ValueError, self.request_class, '/foo:bar') def test_headers(self): # Differ...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlpar...
def parse_uri(self, uri): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) LOG.error(_("Invalid store URI: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri)
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) LOG.error(reason) raise exception.BadStor...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials in Swift URI.")) LOG.error(reason) raise exception.BadStoreUri() user, key = cred_parts
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri LOG.error(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") LOG.error(reason) raise exception.BadStoreUri()
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def get(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg = ...
def add(self, image_id, image_file, image_size): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location.")) msg = (_("Failed to add ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) ...
def delete(self, location): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() raise exception.NotFound(_("Swift could not find image at " ...
def set_acls(self, location, public=False, read_tenants=[], except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_store_uri() msg = _("Swift could not find image at URI.") raise exception.N...
def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame": if values is None: cols = [columns] if index is None else [index, columns] append = index is None
def _convert_by(by): @Substitution("\ndata : DataFrame") @Appender(_shared_docs["pivot"], indents=1) def pivot(data: "DataFrame", index=None, columns=None, values=None) -> "DataFrame": if columns is None: raise TypeError("pivot() missing 1 required argument: 'columns'") if values is None: cols ...
class TestPivotTable: expected = DataFrame(data=data, index=index, columns=columns, dtype="object") tm.assert_frame_equal(result, expected) @pytest.mark.xfail( reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966" )
class TestPivotTable: expected = DataFrame(data=data, index=index, columns=columns, dtype="object") tm.assert_frame_equal(result, expected) def test_pivot_columns_none_raise_error(self): # GH 30924 df = pd.DataFrame( {"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [...
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(...
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host patterns
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host pa...
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is included in Python 3.9.5...
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # validate_ipv6_address uses django.utils.ipv6, which # is tested in much greater detail in its own testcase (validate_ipv6_address, 'fe80::1', None),
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv4_address, '000.000.000.000', ValidationError), (validate_ipv4_address, '016.016.016.0...
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '12', None), (validate_comma_separated_integer_list, '1,2', None),
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv46_address, '000.000.000.000', ValidationError), (validate_ipv46_address, '016.016.016.016',...
def read_conllx(input_data, use_morphology=False, n=0): continue try: id_ = int(id_) - 1 head = (int(head) - 1) if head != "0" else id_ dep = "ROOT" if dep == "root" else dep tag = pos if tag == "_" else ...
def read_conllx(input_data, use_morphology=False, n=0): continue try: id_ = int(id_) - 1 head = (int(head) - 1) if head not in ["0", "_"] else id_ dep = "ROOT" if dep == "root" else dep tag = pos if tag =...
from tests.utils import Command @pytest.fixture def did_not_match(target, did_you_forget=True): error = ("error: pathspec '{}' did not match any " "file(s) known to git.".format(target)) if did_you_forget: error = ("{}\nDid you forget to 'git add'?'".format(error)) return error @pyt...
from tests.utils import Command @pytest.fixture def stderr(target): return ("error: pathspec '{}' did not match any " 'file(s) known to git.'.format(target)) @pytest.mark.parametrize('script, target', [ ('git submodule update unknown', 'unknown'), ('git commit unknown', 'unknown')]) def test...
from thefuck.specific.git import git_support @git_support def match(command): return ('did not match any file(s) known to git.' in command.stderr and "Did you forget to 'git add'?" in command.stderr) @git_support def get_new_command(command): missing_file = re.findall( r"error: pathsp...
from thefuck.specific.git import git_support @git_support def match(command): return 'did not match any file(s) known to git.' in command.stderr @git_support def get_new_command(command): missing_file = re.findall( r"error: pathspec '([^']*)' " r'did not match any file\(s\) known to git.', co...
class _AxesBase(martist.Artist): left, right = sorted([left, right], reverse=bool(reverse)) self._viewLim.intervalx = (left, right) if auto is not None: self._autoscaleXon = bool(auto)
class _AxesBase(martist.Artist): left, right = sorted([left, right], reverse=bool(reverse)) self._viewLim.intervalx = (left, right) # Mark viewlims as no longer stale without triggering an autoscale. for ax in self._shared_x_axes.get_siblings(self): ax._stale_viewlim_x = Fal...
class _AxesBase(martist.Artist): bottom, top = sorted([bottom, top], reverse=bool(reverse)) self._viewLim.intervaly = (bottom, top) if auto is not None: self._autoscaleYon = bool(auto)
class _AxesBase(martist.Artist): bottom, top = sorted([bottom, top], reverse=bool(reverse)) self._viewLim.intervaly = (bottom, top) # Mark viewlims as no longer stale without triggering an autoscale. for ax in self._shared_y_axes.get_siblings(self): ax._stale_viewlim_y = Fal...
def test_ytickcolor_is_not_markercolor(): assert tick.tick1line.get_markeredgecolor() != 'white' @check_figures_equal(extensions=["png"]) def test_polar_interpolation_steps_variable_r(fig_test, fig_ref): l, = fig_test.add_subplot(projection="polar").plot([0, np.pi/2], [1, 2])
def test_ytickcolor_is_not_markercolor(): assert tick.tick1line.get_markeredgecolor() != 'white' @pytest.mark.parametrize('auto', (True, False, None)) def test_unautoscaley(auto): fig, ax = plt.subplots() x = np.arange(100) y = np.linspace(-.1, .1, 100) ax.scatter(x, y) post_auto = ax.get...
def _connect_tls_proxy(self, hostname, conn): self.ca_cert_dir, self.ca_cert_data, ) # If no cert was provided, use only the default options for server # certificate validation
def _connect_tls_proxy(self, hostname, conn): self.ca_cert_dir, self.ca_cert_data, ) # By default urllib3's SSLContext disables `check_hostname` and uses # a custom check. For proxies we're good with relying on the default # verification. ssl_context.check...
def no_san_server(tmp_path_factory): yield cfg @pytest.fixture def ip_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs")
def no_san_server(tmp_path_factory): yield cfg @pytest.fixture def no_localhost_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # non localhost common name server_cert = ca.issue_cert(u"example.com") with run_server_in_thread("https", "localhost",...
def test_basic_ipv6_proxy(self): r = http.request("GET", "%s/" % self.https_url) assert r.status == 200
def test_basic_ipv6_proxy(self): r = http.request("GET", "%s/" % self.https_url) assert r.status == 200 class TestHTTPSProxyVerification: @onlyPy3 def test_https_proxy_hostname_verification(self, no_localhost_san_server): bad_server = no_localhost_san_server bad_proxy_...
def run(self): 'cookiecutter>=1.6.0', 'diff-match-patch>=20181111', 'intervaltree>=3.0.2', 'ipython>=7.6.0,<8.0.0', 'jedi>=0.17.2,<0.19.0', 'jellyfish>=0.7', 'jsonschema>=3.2.0',
def run(self): 'cookiecutter>=1.6.0', 'diff-match-patch>=20181111', 'intervaltree>=3.0.2', 'ipython>=7.31.1,<8.0.0', 'jedi>=0.17.2,<0.19.0', 'jellyfish>=0.7', 'jsonschema>=3.2.0',
# None for pynsist install for now # (check way to add dist.info/egg.info from packages without wheels available) INTERVALTREE_REQVER = None if is_pynsist() else '>=3.0.2' IPYTHON_REQVER = ">=7.6.0;<8.0.0" JEDI_REQVER = '>=0.17.2;<0.19.0' JELLYFISH_REQVER = '>=0.7' JSONSCHEMA_REQVER = '>=3.2.0'
# None for pynsist install for now # (check way to add dist.info/egg.info from packages without wheels available) INTERVALTREE_REQVER = None if is_pynsist() else '>=3.0.2' IPYTHON_REQVER = ">=7.31.1;<8.0.0" JEDI_REQVER = '>=0.17.2;<0.19.0' JELLYFISH_REQVER = '>=0.7' JSONSCHEMA_REQVER = '>=3.2.0'
class FileBasedCache(BaseCache): self._delete(fname) def _createdir(self): os.makedirs(self._dir, 0o700, exist_ok=True) def _key_to_file(self, key, version=None): """
class FileBasedCache(BaseCache): self._delete(fname) def _createdir(self): # Set the umask because os.makedirs() doesn't apply the "mode" argument # to intermediate-level directories. old_umask = os.umask(0o077) try: os.makedirs(self._dir, 0o700, exist_ok=Tru...
import os import pickle import re import shutil import tempfile import threading import time import unittest from unittest import mock from django.conf import settings from django.core import management, signals
import os import pickle import re import shutil import sys import tempfile import threading import time import unittest from pathlib import Path from unittest import mock, skipIf from django.conf import settings from django.core import management, signals
class FileBasedCacheTests(BaseCacheTests, TestCase): # Returns the default instead of erroring. self.assertEqual(cache.get('foo', 'baz'), 'baz') def test_get_does_not_ignore_non_filenotfound_exceptions(self): with mock.patch('builtins.open', side_effect=OSError): with self.asser...
class FileBasedCacheTests(BaseCacheTests, TestCase): # Returns the default instead of erroring. self.assertEqual(cache.get('foo', 'baz'), 'baz') @skipIf( sys.platform == 'win32', 'Windows only partially supports umasks and chmod.', ) def test_cache_dir_permissions(self): ...
else: def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, http_cookies.BaseCookie): try: c = SimpleCookie() c.load(cookie) except http_cookies.CookieError: # Invalid cookie return {} else: c = cookie...
else: def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} if six.PY2: cookie = force_str(cookie) for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: ...
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_str, force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_httponly_after_load(self): """ Test that we can use httponly attribute on cookies that we load
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_python_cookies(self): """ Test cases copied from Python's Lib/test/test_http_cookies.py """ self.assertEqual(parse_cookie('chips=ahoy; ...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, parse_cookie, ) from django.test import RequestFactory, SimpleTestCase, override_settings from d...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, ) from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client ...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid@key=true'), {}) def test_httpr...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_abs...
setup( name="waitress", version="1.4.0", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
setup( name="waitress", version="1.4.1", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
ServerNotImplemented, find_double_newline, ) class ParsingError(Exception):
ServerNotImplemented, find_double_newline, ) from .rfc7230 import HEADER_FIELD class ParsingError(Exception):
class ParsingError(Exception): class TransferEncodingNotImplemented(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
class ParsingError(Exception): class TransferEncodingNotImplemented(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
def parse_header(self, header_plus): headers = self.headers for line in lines: index = line.find(b":") if index > 0: key = line[:index] if key != key.strip(): raise ParsingError("Invalid whitespace after field-name") ...
def parse_header(self, header_plus): headers = self.headers for line in lines: header = HEADER_FIELD.match(line) if not header: raise ParsingError("Invalid header") key, value = header.group('name', 'value') if b"_" in key: ...
def get_header_lines(header): r = [] lines = header.split(b"\r\n") for line in lines: if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line))
def get_header_lines(header): r = [] lines = header.split(b"\r\n") for line in lines: if not line: continue if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line))
def test_parse_header_invalid_whitespace(self): try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Invalid whitespace after field-name", e.args[0]) else: # pragma: nocover self.assertTrue(False) class Test_split_uri(unittest.TestCa...
def test_parse_header_invalid_whitespace(self): try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Invalid header", e.args[0]) else: # pragma: nocover self.assertTrue(False) def test_parse_header_invalid_whitespace_vtab(self): ...
import stat import time logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
import stat import time from .rfc7230 import OBS_TEXT, VCHAR logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
def group(s): long_day_reg = group(join(long_days, "|")) daymap = {} for i in range(7): daymap[short_days[i]] = i daymap[long_days[i]] = i
def group(s): long_day_reg = group(join(long_days, "|")) daymap = {} for i in range(7): daymap[short_days[i]] = i daymap[long_days[i]] = i
def group(s): ] monmap = {} for i in range(12): monmap[months[i]] = i + 1
def group(s): ] monmap = {} for i in range(12): monmap[months[i]] = i + 1
def group(s): def unpack_rfc822(m): g = m.group return ( int(g(4)), # year monmap[g(3)], # month
def group(s): def unpack_rfc822(m): g = m.group return ( int(g(4)), # year monmap[g(3)], # month
def unpack_rfc822(m): def unpack_rfc850(m): g = m.group yr = g(4) if len(yr) == 2: yr = "19" + yr return ( int(yr), # year monmap[g(3)], # month
def unpack_rfc822(m): def unpack_rfc850(m): g = m.group yr = g(4) if len(yr) == 2: yr = "19" + yr return ( int(yr), # year monmap[g(3)], # month
def unpack_rfc850(m): def build_http_date(when): year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day,
def unpack_rfc850(m): def build_http_date(when): year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day,
def build_http_date(when): def parse_http_date(d): d = d.lower() m = rfc850_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc850(m))) else: m = rfc822_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc822(m)...
def build_http_date(when): def parse_http_date(d): d = d.lower() m = rfc850_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc850(m))) else: m = rfc822_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc822(...
def test_rules_names_list(): def test_update_settings(): settings = Settings({'key': 'val'}) new_settings = settings.update(key='new-val') assert new_settings.key == 'new-val' assert settings.key == 'val'
def test_rules_names_list(): def test_update_settings(): settings = Settings({'key': 'val'}) new_settings = settings.update(key='new-val', unset='unset-value') assert new_settings.key == 'val' assert new_settings.unset == 'unset-value' assert settings.key == 'val'
from tests.utils import Command @pytest.mark.parametrize('override, old, new', [ ({'key': 'val'}, {}, {'key': 'val'}), ({'key': 'new-val'}, {'key': 'val'}, {'key': 'new-val'})]) def test_wrap_settings(override, old, new): fn = lambda _, settings: settings assert wrap_settings(override)(fn)(None, Settin...
from tests.utils import Command @pytest.mark.parametrize('override, old, new', [ ({'key': 'val'}, {}, {'key': 'val'}), ({'key': 'new-val'}, {'key': 'val'}, {'key': 'val'}), ({'key': 'new-val', 'unset': 'unset'}, {'key': 'val'}, {'key': 'val', 'unset': 'unset'})]) def test_wrap_settings(override, old, new):...
class Settings(dict): return self.get(item) def update(self, **kwargs): """Returns new settings with new values from `kwargs`.""" conf = dict(self) conf.update(kwargs) return Settings(conf)
class Settings(dict): return self.get(item) def update(self, **kwargs): """ Returns new settings with values from `kwargs` for unset settings. """ conf = dict(kwargs) conf.update(self) return Settings(conf)
class Grouping: self._group_index = CategoricalIndex( Categorical.from_codes( codes=codes, categories=categories, ordered=self.grouper.ordered ) ) # we are done
class Grouping: self._group_index = CategoricalIndex( Categorical.from_codes( codes=codes, categories=categories, ordered=self.grouper.ordered ), name=self.name, ) # we are done
def test_preserve_categories(): # ordered=True df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)}) index = CategoricalIndex(categories, categories, ordered=True) tm.assert_index_equal( df.groupby("A", sort=True, observed=False).first().index, index )
def test_preserve_categories(): # ordered=True df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)}) index = CategoricalIndex(categories, categories, ordered=True, name="A") tm.assert_index_equal( df.groupby("A", sort=True, observed=False).first().index, index ...
def test_preserve_categories(): # ordered=False df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)}) sort_index = CategoricalIndex(categories, categories, ordered=False) nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False) tm.assert_index_equal( ...
def test_preserve_categories(): # ordered=False df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)}) sort_index = CategoricalIndex(categories, categories, ordered=False, name="A") nosort_index = CategoricalIndex(list("bac"), list("bac"), ordered=False, name="A") tm.a...
def test_groupby_categorical_axis_1(code): result = df.groupby(cat, axis=1).mean() expected = df.T.groupby(cat, axis=0).mean().T assert_frame_equal(result, expected)
def test_groupby_categorical_axis_1(code): result = df.groupby(cat, axis=1).mean() expected = df.T.groupby(cat, axis=0).mean().T assert_frame_equal(result, expected) def test_groupby_cat_preserves_structure(observed): # GH 28787 df = DataFrame([("Bob", 1), ("Greg", 2)], columns=["Name", "Item"]) ...
def test_pdf_append_to_bytesio(): f = io.BytesIO(f.getvalue()) im.save(f, format="PDF", append=True) assert len(f.getvalue()) > initial_size
def test_pdf_append_to_bytesio(): f = io.BytesIO(f.getvalue()) im.save(f, format="PDF", append=True) assert len(f.getvalue()) > initial_size @pytest.mark.timeout(1) def test_redos(): malicious = b" trailer<<>>" + b"\n" * 3456 # This particular exception isn't relevant here. # The important th...
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...
def test_parser_feed(): # Assert assert p.image.size == (640, 480)
def test_parser_feed(): # Assert assert p.image.size == (640, 480) @pytest.mark.parametrize( "test_file", [ "Tests/images/crash-4fb027452e6988530aa5dabee76eecacb3b79f8a.j2k", "Tests/images/crash-7d4c83eb92150fb8f1653a697703ae06ae7c4998.j2k", "Tests/images/crash-ccca68ff40171fd...
def get_domain(value): token, value = get_dot_atom(value) except errors.HeaderParseError: token, value = get_atom(value) if leader is not None: token[:0] = [leader] domain.append(token)
def get_domain(value): token, value = get_dot_atom(value) except errors.HeaderParseError: token, value = get_atom(value) if value and value[0] == '@': raise errors.HeaderParseError('Invalid Domain') if leader is not None: token[:0] = [leader] domain.append(token)
def getaddrspec(self): aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain() def getdomain(self): """Get the complete domain name from an address."""
def getaddrspec(self): aslist.append('@') self.pos += 1 self.gotonext() domain = self.getdomain() if not domain: # Invalid domain, return an empty address instead of returning a # local part to denote failed parsing. return EMPTYSTRING ...
def getdomain(self): elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] in self.atomends: break else:
def getdomain(self): elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] == '@': # bpo-34155: Don't parse domains with two `@` like # `a@malicious.org@important.com`. return E...
def test_get_addr_spec_dot_atom(self): self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com') # get_obs_route def test_get_obs_route_simple(self):
def test_get_addr_spec_dot_atom(self): self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, 'star.a.star@example.com') def test_get_addr_spec_multiple_domains(self): with self.assertRaises(errors.HeaderParseError): parser.get_addr_spec('star@a....
def test_parseaddr_empty(self): self.assertEqual(utils.parseaddr('<>'), ('', '')) self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') def test_noquote_dump(self): self.assertEqual( utils.formataddr(('A Silly Person', 'person@dom.ain')),
def test_parseaddr_empty(self): self.assertEqual(utils.parseaddr('<>'), ('', '')) self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') def test_parseaddr_multiple_domains(self): self.assertEqual( utils.parseaddr('a@b@c'), ('', '') ) self.asse...
class _Alpha: raise ValueError def __gt__(self, other): return not self.__lt__(other) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __ge__(self, other): return self.__gt__(other) or self.__eq__(other) class _Numeric:
class _Alpha: raise ValueError def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other) class _Numeric: