buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Operation(BaseModel): operationId: Optional[str] = None parameters: Optional[List[Union[Parameter, Reference]]] = None requestBody: Optional[Union[RequestBody, Reference]] = None responses: Union[Responses, Dict[Union[str], Response]] # Workaround OpenAPI recursive reference callbacks: Opt...
class Operation(BaseModel): operationId: Optional[str] = None parameters: Optional[List[Union[Parameter, Reference]]] = None requestBody: Optional[Union[RequestBody, Reference]] = None responses: Union[Responses, Dict[str, Response]] # Workaround OpenAPI recursive reference callbacks: Optional[D...
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "templates/utf8.html", "test.crt", "test.key",
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "static_foo.txt", "templates/utf8.html", "test.crt", "test.key",
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) @wsgi_safe class StaticDefaultFilenameTest(WebTestCase):
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) def test_path_traversal_protection(self): with ExpectLog(gen_log, ".*not in root static directory"): response = self.get_and_head('/static/../static_foo.txt') ...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ root = os.path.abspath(root) # os.path.abspath strips a trailing / # it needs to be temporarily added back for requests to root/ if not (absolute_path + os.path.sep).startswith(root): raise HT...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ # os.path.abspath strips a trailing /. # We must add it back to `root` so that we only match files # in a directory named `root` instead of files starting with # that prefix. root = os.path.abspat...
import pytest import warnings from mock import Mock, patch from thefuck.utils import default_settings, \ memoize, get_closest, get_all_executables, replace_argument, \ get_all_matched_commands, is_app, for_app, cache, \
import pytest import warnings from mock import Mock, call, patch from thefuck.utils import default_settings, \ memoize, get_closest, get_all_executables, replace_argument, \ get_all_matched_commands, is_app, for_app, cache, \
def test_get_all_executables(): assert 'fuck' not in all_callables @pytest.mark.parametrize('args, result', [ (('apt-get instol vim', 'instol', 'install'), 'apt-get install vim'), (('git brnch', 'brnch', 'branch'), 'git branch')])
def test_get_all_executables(): assert 'fuck' not in all_callables @pytest.fixture def os_environ_pathsep(monkeypatch, path, pathsep): env = {'PATH': path} monkeypatch.setattr('os.environ', env) monkeypatch.setattr('os.pathsep', pathsep) return env @pytest.mark.usefixtures('no_memoize', 'os_envi...
def get_all_executables(): tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(':') for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) and...
def get_all_executables(): tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(os.pathsep) for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) ...
import grp import os import re import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import grp import os import re import platform import pty import pwd import select import shutil import socket import subprocess import time from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
class Index(IndexOpsMixin, PandasObject): if is_categorical(target): tgt_values = np.asarray(target) elif self.is_all_dates: tgt_values = target.asi8 else: tgt_values = target._ndarray_values
class Index(IndexOpsMixin, PandasObject): if is_categorical(target): tgt_values = np.asarray(target) elif self.is_all_dates and target.is_all_dates: # GH 30399 tgt_values = target.asi8 else: tgt_values = target._ndarray_values
def test_drop_not_lexsorted(): tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi) with tm.assert_produces_warning(PerformanceWarning): tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a"))
def test_drop_not_lexsorted(): tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi) with tm.assert_produces_warning(PerformanceWarning): tm.assert_index_equal(lexsorted_mi.drop("a"), not_lexsorted_mi.drop("a")) def test_drop_with_non_unique_datetime_index_and_invalid_keys(): # GH 30399 # def...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: # An authentication backend may reject inactive users. Check # if the...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise self.get_invalid_login_error() else: self.confirm_l...
from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.models import User from django.test import TestCase class AdminAuthenticationFormTests(TestCase): @classmethod def setUpTestData(cls):
from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.models import User from django.test import TestCase, override_settings # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings(AUTHENTICATION_BACKENDS=['django.c...
class UserCreationFormTest(ReloadFormsMixin, TestDataMixin, TestCase): self.assertTrue(form.is_valid()) class AuthenticationFormTest(TestDataMixin, TestCase): def test_invalid_username(self):
class UserCreationFormTest(ReloadFormsMixin, TestDataMixin, TestCase): self.assertTrue(form.is_valid()) # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBack...
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])]) def test_login_failed(self): signal_calls = []
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])]) # Use an authentication backend that rejects inactive users. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.aut...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. The input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), tf.uint8) <tf.Ten...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. Every component of the input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), ...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... Note: There is currently a bug in `fixed_length` that can result in data loss: >>> # truncated to length of type as it matches fixed_leng...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... If the input value is larger than `fixed_length`, it is truncated: >>> x=''.join([chr(1), chr(2), chr(3), chr(4)]) >>> tf.io.decode_raw...
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
HOST = test_support.HOST CERTFILE = None SVN_PYTHON_ORG_ROOT_CERT = None NULLBYTECERT = None def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_DER_to_PEM(self): with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: pem = f.read()
def test_parse_cert(self): ('DNS', 'projects.forum.nokia.com')) ) def test_parse_cert_CVE_2013_4238(self): p = ssl._ssl._test_decode_cert(NULLBYTECERT) if test_support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") su...
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
def test_default_ciphers(self): def test_main(verbose=False): global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT, NULLBYTECERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") if (not os.path.exists(CERTFILE) or not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or not os.path.exists(NOKIACERT)): ...
def test_main(verbose=False): "https_svn_python_org_root.pem") NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nokia.pem") NULLBYTECERT = os.path.join(os.path.dirname(__file__) or os.curdir, "nullbytecert.pem") if (not o...
class Line: bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 if leaf.parent and leaf.parent.type == syms.arglist: commas += 1 break
class Line: bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 if leaf.parent and leaf.parent.type in { syms.arglist, syms.typedargslist, }: ...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports, but be careful not to add one after # any comments. ...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports and standalone function arguments, but # be careful not to add ...
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_expression(self) -> None: source, expected = read_data("expression")
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_function_trailing_comma(self) -> None: source, expected = read_data("function_trailing_comma") ...
import warnings from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) from django.core.exceptions import TooManyFieldsSent
import warnings from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, quote, quote_plus, scheme_chars, unquote, unquote_plus, urlencode as original_urlencode, uses_params, ) from django.c...
def is_safe_url(url, host=None, allowed_hosts=None, require_https=False): _is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https)) def _is_safe_url(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlpars...
def is_safe_url(url, host=None, allowed_hosts=None, require_https=False): _is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https)) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', ) for good_url in good_urls: with ignore_warnings(category=RemovedInDjango21Warning):
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: with ignore_warnings(category=RemovedInDjango21Warning):
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
from jose.constants import ALGORITHMS from jose.exceptions import JWKError from jose.utils import base64url_decode from jose.utils import constant_time_string_compare # PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class # Instead it has a class named RsaKey, which serves the same purpose.
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return sig == self.sign(msg) class RSAKey(Key):
def sign(self, msg): return hmac.new(self.prepared_key, msg, self.hash_alg).digest() def verify(self, msg, sig): return constant_time_string_compare(sig, self.sign(msg)) class RSAKey(Key):
import base64 def calculate_at_hash(access_token, hash_alg):
import base64 import hmac def calculate_at_hash(access_token, hash_alg):
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds
def timedelta_total_seconds(delta): delta (timedelta): A timedelta to convert to seconds. """ return delta.days * 24 * 60 * 60 + delta.seconds def constant_time_string_compare(a, b): """Helper for comparing string in constant time, independent of the python version being used. Args: ...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or start_line.method in ("HEAD", "GET")): return connection_header == "keep-alive...
class HTTP1Connection(httputil.HTTPConnection): return connection_header != "close" elif ("Content-Length" in headers or headers.get("Transfer-Encoding", "").lower() == "chunked" or getattr(start_line, 'method', None) in ("HEAD", "GET")): # start_line may be a...
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
TEST_MODULES = [ 'tornado.test.curl_httpclient_test', 'tornado.test.escape_test', 'tornado.test.gen_test', 'tornado.test.http1connection_test', 'tornado.test.httpclient_test', 'tornado.test.httpserver_test', 'tornado.test.httputil_test',
import hmac import time import uuid from tornado.concurrent import TracebackFuture, return_future from tornado import gen from tornado import httpclient from tornado import escape
import hmac import time import uuid from tornado.concurrent import TracebackFuture, return_future, chain_future from tornado import gen from tornado import httpclient from tornado import escape
class FacebookGraphMixin(OAuth2Mixin): future.set_exception(AuthError('Facebook auth error: %s' % str(response))) return args = escape.parse_qs_bytes(escape.native_str(response.body)) session = { "access_token": args["access_token"][-1], "expires": args.g...
class FacebookGraphMixin(OAuth2Mixin): future.set_exception(AuthError('Facebook auth error: %s' % str(response))) return args = urlparse.parse_qs(escape.native_str(response.body)) session = { "access_token": args["access_token"][-1], "expires": args.get("...
class FacebookGraphMixin(OAuth2Mixin): Added the ability to override ``self._FACEBOOK_BASE_URL``. """ url = self._FACEBOOK_BASE_URL + path return self.oauth2_request(url, callback, access_token, post_args, **args) def _oauth_signature(consumer_toke...
class FacebookGraphMixin(OAuth2Mixin): Added the ability to override ``self._FACEBOOK_BASE_URL``. """ url = self._FACEBOOK_BASE_URL + path # Thanks to the _auth_return_future decorator, our "callback" # argument is a Future, which we cannot pass as a callback to # oaut...
from __future__ import absolute_import, division, print_function, with_statement from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin from tornado.concurrent import Future from tornado.escape import json_decode from tornado import gen
from __future__ import absolute_import, division, print_function, with_statement from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin from tornado.concurrent import Future from tornado.escape import json_decode from tornado import gen
class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin): assert res.done() class TwitterClientHandler(RequestHandler, TwitterMixin): def initialize(self, test): self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')
class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin): assert res.done() class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin): def initialize(self, test): self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize') self._OAUTH_ACCESS_TOKEN_URL = test.get_ur...
class AuthTest(AsyncHTTPTestCase): dict(version='1.0a')), ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)), ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)), ('/twitter/client/login_gen_engine', TwitterClientLoginG...
class AuthTest(AsyncHTTPTestCase): dict(version='1.0a')), ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)), ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)), ('/twitter/client/login', TwitterClientLoginHandler, ...
class AuthTest(AsyncHTTPTestCase): ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler), ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler), ('/twitter/server/access_token', TwitterServerAccessTokenHandler), (r'/twitter/api/users...
class AuthTest(AsyncHTTPTestCase): ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler), ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler), ('/facebook/server/access_token', FacebookServerAccessTokenHandler), ('/facebook/server/...
class AuthTest(AsyncHTTPTestCase): self.assertEqual(response.code, 302) self.assertTrue('/oauth2/server/authorize?' in response.headers['Location']) def base_twitter_redirect(self, url): # Same as test_oauth10a_redirect response = self.fetch(url, follow_redirects=False)
class AuthTest(AsyncHTTPTestCase): self.assertEqual(response.code, 302) self.assertTrue('/oauth2/server/authorize?' in response.headers['Location']) def test_facebook_login(self): response = self.fetch('/facebook/client/login', follow_redirects=False) self.assertEqual(response.code,...
setup( python_requires="~=3.6", install_requires=[ "urwid>=1.1.1", "pygments>=1.0", "jedi>=0.18,<1" ], test_requires=[
setup( python_requires="~=3.6", install_requires=[ "urwid>=1.1.1", "pygments>=2.7.4", "jedi>=0.18,<1" ], test_requires=[
class FrameApply: from pandas import Series if not should_reduce: EMPTY_SERIES = Series([]) try: r = self.f(EMPTY_SERIES, *self.args, **self.kwds) except Exception: pass else: should_reduce = not isinstance...
class FrameApply: from pandas import Series if not should_reduce: try: r = self.f(Series([])) except Exception: pass else: should_reduce = not isinstance(r, Series) if should_reduce: if len(self.agg...
class TestDataFrameApply: # Ensure that x.append hasn't been called assert x == [] def test_apply_deprecate_reduce(self): empty_frame = DataFrame()
class TestDataFrameApply: # Ensure that x.append hasn't been called assert x == [] @pytest.mark.parametrize("func", ["sum", "prod", "any", "all"]) def test_apply_funcs_over_empty(self, func): # GH 28213 df = DataFrame(columns=["a", "b", "c"]) result = df.apply(getattr(n...
from openapi_python_client.cli import app if __name__ == "__main__": from .fastapi_app import generate_openapi_json generate_openapi_json() runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
from openapi_python_client.cli import app if __name__ == "__main__": runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{openapi.title.replace(' ', '-').low...
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).low...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): module_path = api_dir / f"{tag}.py" ...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): tag = utils.snake_case(tag) ...
import stringcase def snake_case(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return stringcase.snakecase(value) def pascal_case(value...
import stringcase def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value) def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = mocker.MagicMock(autospec=str) tag_2 = mocker.MagicMock(autospec=str) collection_1 = mocker.MagicMock() ...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = "a_tag" tag_2 = "another_tag" collection_1 = mocker.MagicMock() collection_2 = mocker.MagicMock() ...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return en...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_spinal_case(): assert utils.spinal_case("keep_alive") == "keep-alive"
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_kebab_case(): assert utils.kebab_case("keep_alive") == "keep-alive"
def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) result = libops.vec_binop(x, y, op) else: # let null fall thru assert lib.is_scalar(y)
def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) result = libops.vec_binop(x.ravel(), y.ravel(), op) else: # let null fall thru assert lib.is_s...
def na_logical_op(x: np.ndarray, y, op): f"and scalar of type [{typ}]" ) return result def logical_op(
def na_logical_op(x: np.ndarray, y, op): f"and scalar of type [{typ}]" ) return result.reshape(x.shape) def logical_op(
Various other classes in this module support this usage: from __future__ import division, absolute_import __metaclass__ = type from zope.interface import implementer from twisted.python.compat import networkString
Various other classes in this module support this usage: from __future__ import division, absolute_import __metaclass__ = type import re from zope.interface import implementer from twisted.python.compat import networkString
class HTTPClientParser(HTTPParser): @implementer(IClientRequest) class Request: """
class HTTPClientParser(HTTPParser): _VALID_METHOD = re.compile( br"\A[%s]+\Z" % ( bytes().join( ( b"!", b"#", b"$", b"%", b"&", b"'", b"*", b"+", b"-", b".", b"^", b"_", b"`", b"|", b"~", b"\x30-\x39", b"\x41-\x5a", ...
class Request: connection, defaults to C{False}. @type persistent: L{bool} """ self.method = method self.uri = uri self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent
class Request: connection, defaults to C{False}. @type persistent: L{bool} """ self.method = _ensureValidMethod(method) self.uri = _ensureValidURI(uri) self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent
class Request: # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append(b' '.join([self.method, self.uri, b'HTTP/1.1\r\n'])) if not self.persistent: requestLines...
class Request: # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append( b' '.join( [ _ensureValidMethod(self.method), _ensur...
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse from twisted.web.http_headers import Headers from twisted.logger import Logger class PartialDownloadError(error.Error): """
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse from twisted.web.http_headers import Headers from twisted.logger import Logger from twisted.web._newclient import _ensureValidURI, _ensureValidMethod class PartialDownloadError(error.Error): """
class HTTPPageGetter(http.HTTPClient): _completelyDone = True _specialHeaders = set((b'host', b'user-agent', b'cookie', b'content-length')) def connectionMade(self): method = getattr(self.factory, 'method', b'GET') self.sendCommand(method, self.factory.path) if self.factory.scheme...
class HTTPPageGetter(http.HTTPClient): _completelyDone = True _specialHeaders = set( (b'host', b'user-agent', b'cookie', b'content-length'), ) def connectionMade(self): method = _ensureValidMethod(getattr(self.factory, 'method', b'GET')) self.sendCommand(method, _ensureValidUR...
class HTTPClientFactory(protocol.ClientFactory): # just in case a broken http/1.1 decides to keep connection alive self.headers.setdefault(b"connection", b"close") self.postdata = postdata self.method = method self.setURL(url)
class HTTPClientFactory(protocol.ClientFactory): # just in case a broken http/1.1 decides to keep connection alive self.headers.setdefault(b"connection", b"close") self.postdata = postdata self.method = _ensureValidMethod(method) self.setURL(url)
class HTTPClientFactory(protocol.ClientFactory): return "<%s: %s>" % (self.__class__.__name__, self.url) def setURL(self, url): self.url = url uri = URI.fromBytes(url) if uri.scheme and uri.host:
class HTTPClientFactory(protocol.ClientFactory): return "<%s: %s>" % (self.__class__.__name__, self.url) def setURL(self, url): _ensureValidURI(url.strip()) self.url = url uri = URI.fromBytes(url) if uri.scheme and uri.host:
def _makeGetterFactory(url, factoryFactory, contextFactory=None, @return: The factory created by C{factoryFactory} """ uri = URI.fromBytes(url) factory = factoryFactory(url, *args, **kwargs) if uri.scheme == b'https': from twisted.internet import ssl
def _makeGetterFactory(url, factoryFactory, contextFactory=None, @return: The factory created by C{factoryFactory} """ uri = URI.fromBytes(_ensureValidURI(url.strip())) factory = factoryFactory(url, *args, **kwargs) if uri.scheme == b'https': from twisted.internet import ssl
class _AgentBase(object): Issue a new request, given the endpoint and the path sent as part of the request. """ # Create minimal headers, if necessary: if headers is None: headers = Headers()
class _AgentBase(object): Issue a new request, given the endpoint and the path sent as part of the request. """ method = _ensureValidMethod(method) # Create minimal headers, if necessary: if headers is None: headers = Headers()
class Agent(_AgentBase): @see: L{twisted.web.iweb.IAgent.request} """ parsedURI = URI.fromBytes(uri) try: endpoint = self._getEndpoint(parsedURI)
class Agent(_AgentBase): @see: L{twisted.web.iweb.IAgent.request} """ uri = _ensureValidURI(uri.strip()) parsedURI = URI.fromBytes(uri) try: endpoint = self._getEndpoint(parsedURI)
class ProxyAgent(_AgentBase): """ Issue a new request via the configured proxy. """ # Cache *all* connections under the same key, since we are only # connecting to a single destination, the proxy: key = ("http-proxy", self._proxyEndpoint)
class ProxyAgent(_AgentBase): """ Issue a new request via the configured proxy. """ uri = _ensureValidURI(uri.strip()) # Cache *all* connections under the same key, since we are only # connecting to a single destination, the proxy: key = ("http-proxy", self._prox...
from io import BytesIO from zope.interface.verify import verifyObject from twisted.trial.unittest import TestCase from twisted.web import client, error, http_headers from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed from twisted.web._newclient import ResponseNeverReceived, ResponseFailed
from io import BytesIO from zope.interface.verify import verifyObject from twisted.trial.unittest import TestCase, SynchronousTestCase from twisted.web import client, error, http_headers from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed from twisted.web._newclient import ResponseNeverReceiv...
from twisted.internet.endpoints import HostnameEndpoint from twisted.test.proto_helpers import AccumulatingProtocol from twisted.test.iosim import IOPump, FakeTransport from twisted.test.test_sslverify import certificatesForAuthorityAndServer from twisted.web.error import SchemeNotSupported from twisted.logger import g...
from twisted.internet.endpoints import HostnameEndpoint from twisted.test.proto_helpers import AccumulatingProtocol from twisted.test.iosim import IOPump, FakeTransport from twisted.test.test_sslverify import certificatesForAuthorityAndServer from twisted.web.test.injectionhelpers import ( MethodInjectionTestsMixin...
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin, """ Tests for the new HTTP client API provided by L{Agent}. """ def makeAgent(self): """ @return: a new L{twisted.web.client.Agent} instance
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin, """ Tests for the new HTTP client API provided by L{Agent}. """ def makeAgent(self): """ @return: a new L{twisted.web.client.Agent} instance
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin, class AgentHTTPSTests(TestCase, FakeReactorAndConnectMixin, IntegrationTestingMixin): """
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin, class AgentMethodInjectionTests( FakeReactorAndConnectMixin, MethodInjectionTestsMixin, SynchronousTestCase, ): """ Test L{client.Agent} against HTTP method injections. """ def attemptRequestWithMalicious...
class HostnameCachingHTTPSPolicyTests(TestCase): self.assertEquals(5, len(policy._cache)) self.assertIn(hostn, policy._cache)
class HostnameCachingHTTPSPolicyTests(TestCase): self.assertEquals(5, len(policy._cache)) self.assertIn(hostn, policy._cache) class RequestMethodInjectionTests( MethodInjectionTestsMixin, SynchronousTestCase, ): """ Test L{client.Request} against HTTP method injections. "...
Tests for the old L{twisted.web.client} APIs, C{getPage} and friends. from __future__ import division, absolute_import import os from errno import ENOSPC
Tests for the old L{twisted.web.client} APIs, C{getPage} and friends. from __future__ import division, absolute_import import io import os from errno import ENOSPC
from twisted.trial import unittest, util from twisted.web import server, client, error, resource from twisted.web.static import Data from twisted.web.util import Redirect from twisted.internet import reactor, defer, interfaces from twisted.python.filepath import FilePath from twisted.protocols.policies import WrappingF...
from twisted.trial import unittest, util from twisted.web import server, client, error, resource from twisted.web.static import Data from twisted.web.util import Redirect from twisted.internet import address, reactor, defer, interfaces from twisted.internet.protocol import ClientFactory from twisted.python.filepath imp...
from twisted import test from twisted.logger import (globalLogPublisher, FilteringLogObserver, LogLevelFilterPredicate, LogLevel, Logger) serverPEM = FilePath(test.__file__).sibling('server.pem') serverPEMPath = serverPEM.asBytesMode().path
from twisted import test from twisted.logger import (globalLogPublisher, FilteringLogObserver, LogLevelFilterPredicate, LogLevel, Logger) from twisted.web.test.injectionhelpers import ( MethodInjectionTestsMixin, URIInjectionTestsMixin, ) serverPEM = FilePath(test.__file__).sibli...
class DeprecationTests(unittest.TestCase): L{client.HTTPDownloader} is deprecated. """ self._testDeprecatedClass("HTTPDownloader")
class DeprecationTests(unittest.TestCase): L{client.HTTPDownloader} is deprecated. """ self._testDeprecatedClass("HTTPDownloader") class GetPageMethodInjectionTests( MethodInjectionTestsMixin, unittest.SynchronousTestCase, ): """ Test L{client.getPage} against HTTP met...
import re from io import BytesIO from waitress.compat import ( tostr, urlparse, unquote_bytes_to_wsgi, ) from waitress.buffers import OverflowableBuffer from waitress.receiver import ( FixedStreamReceiver, ChunkedReceiver, ) from waitress.utilities import ( find_double_newline, RequestEn...
import re from io import BytesIO from waitress.buffers import OverflowableBuffer from waitress.compat import tostr, unquote_bytes_to_wsgi, urlparse from waitress.receiver import ChunkedReceiver, FixedStreamReceiver from waitress.utilities import ( BadRequest, RequestEntityTooLarge, RequestHeaderFieldsTooLa...
def received(self, data): # Header finished. header_plus = s[:index] consumed = len(data) - (len(s) - index) # Remove preceeding blank lines. header_plus = header_plus.lstrip() if not header_plus: self.em...
def received(self, data): # Header finished. header_plus = s[:index] consumed = len(data) - (len(s) - index) # Remove preceeding blank lines. This is suggested by # https://tools.ietf.org/html/rfc7230#section-3.5 to support ...
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 1 :] ...
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\r\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 2 :] ...
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\n") for line in lines: if line.startswith((b" ", b"\t")): if not r: # https://corte.si/posts/code/pathod/pythonservers/index.html
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ 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)) if ...
"""Data Chunk Receiver """ from waitress.utilities import find_double_newline from waitress.utilities import BadRequest class FixedStreamReceiver(object):
"""Data Chunk Receiver """ from waitress.utilities import BadRequest, find_double_newline class FixedStreamReceiver(object):
def __len__(self): def received(self, data): "See IStreamConsumer" rm = self.remain if rm < 1: self.completed = True # Avoid any chance of spinning return 0 datalen = len(data) if rm <= datalen: self.buf.append(data[:rm]) self....
def __len__(self): def received(self, data): "See IStreamConsumer" rm = self.remain if rm < 1: self.completed = True # Avoid any chance of spinning return 0 datalen = len(data) if rm <= datalen: self.buf.append(data[:rm]) se...
def getbuf(self): class ChunkedReceiver(object): chunk_remainder = 0 control_line = b"" all_chunks_received = False trailer = b""
def getbuf(self): class ChunkedReceiver(object): chunk_remainder = 0 validate_chunk_end = False control_line = b"" all_chunks_received = False trailer = b""
def __len__(self): def received(self, s): # Returns the number of bytes consumed. if self.completed: return 0 orig_size = len(s) while s: rm = self.chunk_remainder if rm > 0: # Receive the remainder of a chunk. to_w...
def __len__(self): def received(self, s): # Returns the number of bytes consumed. if self.completed: return 0 orig_size = len(s) while s: rm = self.chunk_remainder if rm > 0: # Receive the remainder of a chunk. t...
def received(self, s): else: # Control line finished. line = s[:pos] s = s[pos + 1 :] self.control_line = b"" line = line.strip() if line: # Begin a new chunk. ...
def received(self, s): else: # Control line finished. line = s[:pos] s = s[pos + 2 :] self.control_line = b"" line = line.strip() if line: # Begin a new chunk....
def received(self, s): except ValueError: # garbage in input self.error = BadRequest("garbage in chunked encoding input") sz = 0 if sz > 0: # Start a new chunk. ...
def received(self, s): except ValueError: # garbage in input self.error = BadRequest("garbage in chunked encoding input") sz = 0 if sz > 0: # Start a new chunk. ...
def received(self, s): else: # Receive the trailer. trailer = self.trailer + s if trailer.startswith(b"\r\n"): # No trailer. self.completed = True return orig_size - (len(trailer) - 2) ...
def received(self, s): else: # Receive the trailer. trailer = self.trailer + s if trailer.startswith(b"\r\n"): # No trailer. self.completed = True return orig_size - (len(trailer) - 2) ...
def received(self, s): # Finished the trailer. self.completed = True self.trailer = trailer[:pos] return orig_size - (len(trailer) - pos) return orig_size def getfile(self):
def received(self, s): # Finished the trailer. self.completed = True self.trailer = trailer[:pos] return orig_size - (len(trailer) - pos) return orig_size def getfile(self):
def test_del_channel(self): def test_received(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.server.tasks, [inst]) self.assertTrue(inst.requests)
def test_del_channel(self): def test_received(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.server.tasks, [inst]) self.assertTrue(inst.requests)
def test_received_preq_not_completed(self): inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.requests, ()) self.assertEqual(inst.server.tasks, [])
def test_received_preq_not_completed(self): inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.requests, ()) self.assertEqual(inst.server.tasks, [])
def test_received_preq_completed_empty(self): inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
def test_received_preq_completed_empty(self): inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
def test_received_preq_error(self): inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
def test_received_preq_error(self): inst.request = preq preq.completed = True preq.error = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, None) self.assertEqual(len(inst.server.tasks), 1) self.assertTrue(inst.requests)
def test_received_preq_completed_connection_close(self): preq.completed = True preq.empty = True preq.connection_close = True inst.received(b"GET / HTTP/1.1\n\n" + b"a" * 50000) self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, []) def test_rec...
def test_received_preq_completed_connection_close(self): preq.completed = True preq.empty = True preq.connection_close = True inst.received(b"GET / HTTP/1.1\r\n\r\n" + b"a" * 50000) self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, []) def test...
def test_received_headers_finished_expect_continue_false(self): preq.completed = False preq.empty = False preq.retval = 1 inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(inst.outbuf...
def test_received_headers_finished_expect_continue_false(self): preq.completed = False preq.empty = False preq.retval = 1 inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(inst.ou...
def test_received_headers_finished_expect_continue_true(self): preq.headers_finished = True preq.completed = False preq.empty = False inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual...
def test_received_headers_finished_expect_continue_true(self): preq.headers_finished = True preq.completed = False preq.empty = False inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertE...
def test_received_headers_finished_expect_continue_true_sent_true(self): preq.completed = False preq.empty = False inst.sent_continue = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.asse...
def test_received_headers_finished_expect_continue_true_sent_true(self): preq.completed = False preq.empty = False inst.sent_continue = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self....
def _read_echo(self, fp): return line, headers, echo.parse_response(body) def test_date_and_server(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def _read_echo(self, fp): return line, headers, echo.parse_response(body) def test_date_and_server(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_date_and_server(self): def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\n" " Host: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_date_and_server(self): def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\r\n Host: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_bad_host_header(self): self.assertTrue(headers.get("date")) def test_send_with_body(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n" to_send += "hello" to_send = tobytes(to_send) self.connect()
def test_bad_host_header(self): self.assertTrue(headers.get("date")) def test_send_with_body(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n" to_send += "hello" to_send = tobytes(to_send) self.connect()
def test_send_with_body(self): self.assertEqual(echo.body, b"hello") def test_send_empty_body(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)
def test_send_with_body(self): self.assertEqual(echo.body, b"hello") def test_send_empty_body(self): to_send = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send)