buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode() except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_brok...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exceptio...
import datetime import unittest from unittest import mock from urllib.parse import quote_plus
import datetime import sys import unittest from unittest import mock from urllib.parse import quote_plus
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, smart_bytes, smart_text, uri_to_iri, ) from django.utils.functional import Simp...
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_text, uri_to_iri, ) from django.ut...
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested ...
class LinuxHardware(Hardware): # The fields for ARM CPUs do not always include 'vendor_id' or 'model name', # and sometimes includes both 'processor' and 'Processor'. # Always use 'processor' count for ARM systems if collected_facts.get('ansible_architecture', '').startswith(('armv', 'a...
class LinuxHardware(Hardware): # The fields for ARM CPUs do not always include 'vendor_id' or 'model name', # and sometimes includes both 'processor' and 'Processor'. # The fields for Power CPUs include 'processor' and 'cpu'. # Always use 'processor' count for ARM and Power systems ...
CPU_INFO_TEST_SCENARIOS = [ '7', 'POWER7 (architected), altivec supported' ], 'processor_cores': 1, 'processor_count': 16, 'processor_threads_per_core': 1, 'processor_vcpus': 16 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '7', 'POWER7 (architected), altivec supported' ], 'processor_cores': 1, 'processor_count': 8, 'processor_threads_per_core': 1, 'processor_vcpus': 8 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '23', 'POWER8 (architected), altivec supported', ], 'processor_cores': 1, 'processor_count': 48, 'processor_threads_per_core': 1, 'processor_vcpus': 48 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '23', 'POWER8 (architected), altivec supported', ], 'processor_cores': 1, 'processor_count': 24, 'processor_threads_per_core': 1, 'processor_vcpus': 24 }, }, {
def test_get_cpu_info_missing_arch(mocker): module = mocker.Mock() inst = linux.LinuxHardware(module) # ARM will report incorrect processor count if architecture is not available mocker.patch('os.path.exists', return_value=False) mocker.patch('os.access', return_value=True) for test in CPU_INFO...
def test_get_cpu_info_missing_arch(mocker): module = mocker.Mock() inst = linux.LinuxHardware(module) # ARM and Power will report incorrect processor count if architecture is not available mocker.patch('os.path.exists', return_value=False) mocker.patch('os.access', return_value=True) for test i...
Tests for L{twisted.web.twcgi}. """ import sys, os from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, resource from twisted...
Tests for L{twisted.web.twcgi}. """ import sys import os import json from io import BytesIO from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import cl...
print print "cgi output" ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
print print "cgi output" ''' HEADER_OUTPUT_CGI = '''\ import json import os print("") print("") vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")} print(json.dumps(vals)) ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
class CGITests(unittest.TestCase): return factory.deferred def test_duplicateHeaderCGI(self): """ If a CGI script emits two instances of the same header, both are sent in
class CGITests(unittest.TestCase): return factory.deferred def test_noProxyPassthrough(self): """ The CGI script is never called with the Proxy header passed through. """ cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI) portnum = self.startServer(cgiFilename) ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length'): envname = "HTTP_" + envname env[envname] = ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length', 'proxy'): envname = "HTTP_" + envname env[en...
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar() or not os.path.exists(job.jar()): logger.error("Can't find jar: %s, full path %s", job.jar(), os.path.abspath(job.jar()...
class HadoopJarJobRunner(luigi.contrib.hadoop.JobRunner): arglist.append('{}@{}'.format(username, host)) else: arglist = [] if not job.jar(): raise HadoopJarJobError("Jar not defined") if not os.path.exists(job.jar()): logger.error(...
class Templar: res = ansible_native_concat(rf) else: res = j2_concat(rf) if getattr(new_context, 'unsafe', False): res = wrap_var(res) except TypeError as te: if 'AnsibleUndefined' in to_native(te):
class Templar: res = ansible_native_concat(rf) else: res = j2_concat(rf) unsafe = getattr(new_context, 'unsafe', False) if unsafe: res = wrap_var(res) except TypeError as te: if 'Ansib...
class Templar: res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) return res except (UndefinedError, AnsibleUndefinedVariable) as e: if...
class Templar: res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) if unsafe: res = wrap_var(res) return res ...
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,...
def list_logical_volumes(vg): return [line.strip() for line in out.splitlines()] def remove_logical_volumes(*paths): """Remove one or more logical volume.""" if paths: lvremove = ('lvremove', '-f') + paths execute(*lvremove, attempts=3, run_as_root=True)
def list_logical_volumes(vg): return [line.strip() for line in out.splitlines()] def logical_volume_size(path): """Get logical volume size in bytes. :param path: logical volume path """ # TODO(p-draigbrady) POssibly replace with the more general # use of blockdev --getsize64 in future out...
class DataFrame(NDFrame): other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list) and not isinstance(other[0], DataFrame): other = DataFrame(...
class DataFrame(NDFrame): other = other._convert(datetime=True, timedelta=True) if not self.columns.equals(combined_columns): self = self.reindex(columns=combined_columns) elif isinstance(other, list): if not other: pass elif not is...
class TestDataFrameConcatCommon: ) tm.assert_frame_equal(results, expected) def test_append_series_dict(self): df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"])
class TestDataFrameConcatCommon: ) tm.assert_frame_equal(results, expected) def test_append_empty_list(self): # GH 28769 df = DataFrame() result = df.append([]) expected = df tm.assert_frame_equal(result, expected) assert result is not df df ...
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal,
class _AsOfMerge(_OrderedMerge): ) ) if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
class _AsOfMerge(_OrderedMerge): ) ) if is_datetimelike(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0):
import numpy as np import pytest import pytz
import datetime import numpy as np import pytest import pytz
class TestAsOfMerge: # ok, though has dupes merge_asof(trades, self.quotes, on="time", by="ticker") def test_tolerance(self): trades = self.trades quotes = self.quotes result = merge_asof( trades, quotes, on="time", by="ticker", tolerance=Timedelta("1day") ...
class TestAsOfMerge: # ok, though has dupes merge_asof(trades, self.quotes, on="time", by="ticker") @pytest.mark.parametrize( "tolerance", [ Timedelta("1day"), pytest.param( datetime.timedelta(days=1), marks=pytest.mark.xfail(r...
class TestAsOfMerge: ) expected["value_y"] = np.array([np.nan], dtype=object) assert_frame_equal(result, expected)
class TestAsOfMerge: ) expected["value_y"] = np.array([np.nan], dtype=object) assert_frame_equal(result, expected) def test_timedelta_tolerance_nearest(self): # GH 27642 left = pd.DataFrame( list(zip([0, 5, 10, 15, 20, 25], [0, 1, 2, 3, 4, 5])), colu...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1) self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0) self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1) def test_dfxp2srt(self): dfxp_data = '''<...
ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4') self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1) self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0) self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1) self.assertEqual(parse_dfxp_time_expr('00:00:0...
def parse_dfxp_time_expr(time_expr): if mobj: return float(mobj.group('time_offset')) mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:\.\d+)?)$', time_expr) if mobj: return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3)) def srt_subtitles_timecode(seconds):
def parse_dfxp_time_expr(time_expr): if mobj: return float(mobj.group('time_offset')) mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr) if mobj: return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.')) def srt_subtitles_timecod...
class CentralPlannerScheduler(Scheduler): for task in self._state.get_active_tasks(): self._state.fail_dead_worker_task(task, self._config, assistant_ids) if task.id not in necessary_tasks and self._state.prune(task, self._config): remove_tasks.append(task.id) s...
class CentralPlannerScheduler(Scheduler): for task in self._state.get_active_tasks(): self._state.fail_dead_worker_task(task, self._config, assistant_ids) removed = self._state.prune(task, self._config) if removed and task.id not in necessary_tasks: remove_ta...
class CentralPlannerTest(unittest.TestCase): self.sch.prune() self.assertFalse(list(self.sch.task_list('', ''))) def test_fail_job_from_dead_worker_with_live_assistant(self): self.setTime(0) self.sch.add_task(worker='X', task_id='A')
class CentralPlannerTest(unittest.TestCase): self.sch.prune() self.assertFalse(list(self.sch.task_list('', ''))) def test_re_enable_failed_task_assistant(self): self.setTime(0) self.sch.add_worker('X', [('assistant', True)]) self.sch.add_task(worker='X', task_id='A', status=...
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile: raise Impossible() obj = self.node.as_const(eval_ctx)
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile or eval_ctx.environment.sandboxed: raise Impossible() obj = self.node.as_const(eval_ctx)
""" import types import operator from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, PY2 #: maximum number of items a range may produce
""" import types import operator from collections import Mapping from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, text_type, PY2 from jinja2.utils import Markup has_format = False if hasattr(text_type, 'format'): from markupsafe import ...
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) import warnings # make sure we don't warn in python 2.6 about stuff we don't care about
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) #: unsafe attributes on coroutines UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code']) #: unsafe attributes on async generators UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame']) import warnings # make su...
) def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items.
) class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args...
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occour during the rendering so the caller has to ensure that all exceptions are catched. """ sa...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught. """ sand...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" # the double prefixes are to avoid double keyword argument # e...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. ...
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr)
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr) if has_format: # This really is not a public API apparenlty. try: from _string import formatter_fi...
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe, has_format from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
def disable_op(arg): pass else: assert False, 'expected runtime error'
def disable_op(arg): pass else: assert False, 'expected runtime error' @pytest.mark.sandbox @pytest.mark.skipif(not has_format, reason='No format support') class TestStringFormat(object): def test_basic_format_safety(self): env = SandboxedEnvironment() ...
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_...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote ...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse im...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not ...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): ...
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', params={'value': value}) def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid', params={'value': value}) else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is...
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',...
class ContractsManager(object): def eb_wrapper(failure): case = _create_testcase(method, 'errback') exc_info = failure.value, failure.type, failure.getTracebackObject() results.addError(case, exc_info) request.callback = cb_wrapper
class ContractsManager(object): def eb_wrapper(failure): case = _create_testcase(method, 'errback') exc_info = failure.type, failure.value, failure.getTracebackObject() results.addError(case, exc_info) request.callback = cb_wrapper
from unittest import TextTestResult from twisted.trial import unittest from scrapy.spiders import Spider from scrapy.http import Request from scrapy.item import Item, Field
from unittest import TextTestResult from twisted.python import failure from twisted.trial import unittest from scrapy.spidermiddlewares.httperror import HttpError from scrapy.spiders import Spider from scrapy.http import Request from scrapy.item import Item, Field
class ContractsManagerTest(unittest.TestCase): self.results) request.callback(response) self.should_fail()
class ContractsManagerTest(unittest.TestCase): self.results) request.callback(response) self.should_fail() def test_errback(self): spider = TestSpider() response = ResponseMock() try: raise HttpError(response, 'Ignoring non-200 response') ...
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path) ...
def write(data, path, saltenv="base", index=0): ) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_dir, dest, subdir=True): return "Invalid path" dest = os.path.join(__opts__["pillar_roots"][saltenv][index...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_cvr_2021_25282(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo", "path...
class WheelPillarRootsTest(TestCase, AdaptedConfigurationTestCaseMixin): assert os.path.exists(os.path.join(self.pillar_dir, "foo")) assert ret.find("Wrote data to file") != -1 def test_write_subdir(self): ret = self.wheel.cmd( "pillar_roots.write", kwarg={"data": "foo: bar", "p...
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
class core(task.Config): class _WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True, record_task_history=False) def create_remote_scheduler(self, url): return rpc.RemoteScheduler(url)
class SchedulerTest(unittest.TestCase): cps = luigi.scheduler.CentralPlannerScheduler() self.assertEqual({'a': 100, 'b': 200}, cps._resources) def test_load_recovers_tasks_index(self): cps = luigi.scheduler.CentralPlannerScheduler() cps.add_task(worker='A', task_id='1')
class SchedulerTest(unittest.TestCase): cps = luigi.scheduler.CentralPlannerScheduler() self.assertEqual({'a': 100, 'b': 200}, cps._resources) @with_config({'scheduler': {'record_task_history': 'True'}, 'task_history': {'db_connection': 'sqlite:////none/existing/path/hist.db'}}) ...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = ''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_dotted_attribute(self): # This avoids waiting for the socket timeout. self.test_simple1() def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = httplib.HTTPConnection(ADDR, PORT) conn.request('POST', '/RPC2 HTTP/...
from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel app = FastAPI(title="My Test API", description="An API for testing openapi-python-client",)
from pathlib import Path from typing import Any, Dict, List, Union from fastapi import APIRouter, Body, FastAPI, File, Header, Query, UploadFile from pydantic import BaseModel app = FastAPI(title="My Test API", description="An API for testing openapi-python-client",)
class AModel(BaseModel): an_enum_value: AnEnum nested_list_of_enums: List[List[DifferentEnum]] = [] some_dict: Dict[str, str] = {} aCamelDateTime: Union[datetime, date] a_date: date @test_router.get("/", response_model=List[AModel], operation_id="getUserList") def get_list(an_enum_value: List[AnE...
class AModel(BaseModel): an_enum_value: AnEnum nested_list_of_enums: List[List[DifferentEnum]] = [] some_dict: Dict[str, str] aCamelDateTime: Union[datetime, date] a_date: date @test_router.get("/", response_model=List[AModel], operation_id="getUserList") def get_list( an_enum_value: List[AnE...
def json_body(body: AModel): return app.include_router(test_router, prefix="/tests", tags=["tests"])
def json_body(body: AModel): return @test_router.post("/test_defaults") def test_defaults( string_prop: str = Query(default="the default string"), datetime_prop: datetime = Query(default=datetime(1010, 10, 10)), date_prop: date = Query(default=date(1010, 10, 10)), float_prop: float = Query(default...
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx
def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]:
def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]:
def get_user_list( json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, date): json_some_date = some_date.isoformat() else:
def get_user_list( json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() else:
def json_body_tests_json_body_post( return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
def json_body_tests_json_body_post( return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) def test_defaults_tests_test_defaults_post( *, client: Client, json_body: Dict[Any, Any], string_prop: Optional[str] = "th...
from dataclasses import asdict from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast import httpx
import datetime from dataclasses import asdict, field from typing import Any, Dict, List, Optional, Union, cast import httpx
async def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[date, datetime], ) -> Union[ List[AModel], HTTPValidationError, ]:
async def get_user_list( *, client: Client, an_enum_value: List[AnEnum], some_date: Union[datetime.date, datetime.datetime], ) -> Union[ List[AModel], HTTPValidationError, ]:
async def get_user_list( json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, date): json_some_date = some_date.isoformat() else:
async def get_user_list( json_an_enum_value.append(an_enum_value_item) if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() else:
async def json_body_tests_json_body_post( return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
async def json_body_tests_json_body_post( return HTTPValidationError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response) async def test_defaults_tests_test_defaults_post( *, client: Client, json_body: Dict[Any, Any], string_prop: Optiona...
from __future__ import annotations from dataclasses import dataclass, field from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, cast from .an_enum import AnEnum
from __future__ import annotations import datetime from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union, cast from .an_enum import AnEnum
class AModel: """ A Model for testing all the ways custom objects can be used """ an_enum_value: AnEnum a_camel_date_time: Union[datetime, date] a_date: date nested_list_of_enums: Optional[List[List[DifferentEnum]]] = field( default_factory=lambda: cast(Optional[List[List[DifferentEnum]]],...
class AModel: """ A Model for testing all the ways custom objects can be used """ an_enum_value: AnEnum some_dict: Dict[Any, Any] a_camel_date_time: Union[datetime.datetime, datetime.date] a_date: datetime.date nested_list_of_enums: Optional[List[List[DifferentEnum]]] = field( default_...
def to_dict(self) -> Dict[str, Any]: nested_list_of_enums.append(nested_list_of_enums_item) some_dict = self.some_dict return { "an_enum_value": an_enum_value, "aCamelDateTime": a_camel_date_time, "a_date": a_date, "nested_list_of_enums"...
def to_dict(self) -> Dict[str, Any]: nested_list_of_enums.append(nested_list_of_enums_item) return { "an_enum_value": an_enum_value, "some_dict": some_dict, "aCamelDateTime": a_camel_date_time, "a_date": a_date, "nested_list_of_enums"...
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]: nested_list_of_enums.append(nested_list_of_enums_item) some_dict = d.get("some_dict") return AModel( an_enum_value=an_enum_value, a_camel_date_time=a_camel_date_time, a_date=a_...
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]: nested_list_of_enums.append(nested_list_of_enums_item) return AModel( an_enum_value=an_enum_value, some_dict=some_dict, a_camel_date_time=a_camel_date_time, a_date=a_date, ...
def __init__(self, *, openapi: GeneratorData) -> None: self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = f"A client library for accessing {self.openapi.title}" ...
def __init__(self, *, openapi: GeneratorData) -> None: self.package_name: str = self.package_name_override or self.project_name.replace("-", "_") self.package_dir: Path = self.project_dir / self.package_name self.package_description: str = utils.remove_string_escapes( f"A client lib...
class PropertyError(ParseError): """ Error raised when there's a problem creating a Property """ header = "Problem creating a Property: "
class PropertyError(ParseError): """ Error raised when there's a problem creating a Property """ header = "Problem creating a Property: " class ValidationError(Exception): pass
from pydantic import ValidationError from .. import schema as oai from .errors import GeneratorError, ParseError, PropertyError from .properties import EnumProperty, Property, property_from_data from .reference import Reference
from pydantic import ValidationError from .. import schema as oai from .. import utils from .errors import GeneratorError, ParseError, PropertyError from .properties import EnumProperty, Property, property_from_data from .reference import Reference
def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union endpoint = Endpoint( path=path, method=method, description=data.description, name=data.operationId, requires_security=bool(data.security), tag=tag,
def from_data(*, data: oai.Operation, path: str, method: str, tag: str) -> Union endpoint = Endpoint( path=path, method=method, description=utils.remove_string_escapes(data.description) if data.description else "", name=data.operationId, requires_secur...
from __future__ import annotations from dataclasses import InitVar, dataclass, field from typing import Any, ClassVar, Dict, Generic, List, Optional, Set, TypeVar, Union from .. import schema as oai from .. import utils from .errors import PropertyError from .reference import Reference
from __future__ import annotations from dataclasses import InitVar, dataclass, field from datetime import date, datetime from typing import Any, ClassVar, Dict, Generic, List, Optional, Set, TypeVar, Union from .. import schema as oai from .. import utils from .errors import PropertyError, ValidationError from .refer...
class Property: templates/property_templates and must contain two macros: construct and transform. Construct will be used to build this property from JSON data (a response from an API). Transform will be used to convert this property to JSON data (when sending a request to the API). ...
class Property: templates/property_templates and must contain two macros: construct and transform. Construct will be used to build this property from JSON data (a response from an API). Transform will be used to convert this property to JSON data (when sending a request to the API). ...
class Property: def __post_init__(self) -> None: self.python_name = utils.snake_case(self.name) def get_type_string(self) -> str: """ Get a string representation of type that should be used when declaring this property """ if self.required: return self._type_string ...
class Property: def __post_init__(self) -> None: self.python_name = utils.snake_case(self.name) if self.default is not None: self.default = self._validate_default(default=self.default) def _validate_default(self, default: Any) -> Any: """ Check that the default value is val...
class StringProperty(Property): _type_string: ClassVar[str] = "str" def __post_init__(self) -> None: super().__post_init__() if self.default is not None: self.default = f'"{self.default}"' @dataclass
class StringProperty(Property): _type_string: ClassVar[str] = "str" def _validate_default(self, default: Any) -> str: return f'"{utils.remove_string_escapes(default)}"' @dataclass
class DateTimeProperty(Property): A property of type datetime.datetime """ _type_string: ClassVar[str] = "datetime" template: ClassVar[str] = "datetime_property.pyi" def get_imports(self, *, prefix: str) -> Set[str]:
class DateTimeProperty(Property): A property of type datetime.datetime """ _type_string: ClassVar[str] = "datetime.datetime" template: ClassVar[str] = "datetime_property.pyi" def get_imports(self, *, prefix: str) -> Set[str]:
def get_imports(self, *, prefix: str) -> Set[str]: prefix: A prefix to put before any relative (local) module names. """ imports = super().get_imports(prefix=prefix) imports.update({"from datetime import datetime", "from typing import cast"}) return imports @dataclass class...
def get_imports(self, *, prefix: str) -> Set[str]: prefix: A prefix to put before any relative (local) module names. """ imports = super().get_imports(prefix=prefix) imports.update({"import datetime", "from typing import cast"}) return imports def _validate_default(self,...
def get_imports(self, *, prefix: str) -> Set[str]: prefix: A prefix to put before any relative (local) module names. """ imports = super().get_imports(prefix=prefix) imports.update({"from datetime import date", "from typing import cast"}) return imports @dataclass class Fil...
def get_imports(self, *, prefix: str) -> Set[str]: prefix: A prefix to put before any relative (local) module names. """ imports = super().get_imports(prefix=prefix) imports.update({"import datetime", "from typing import cast"}) return imports def _validate_default(self,...
class FloatProperty(Property): default: Optional[float] = None _type_string: ClassVar[str] = "float" @dataclass class IntProperty(Property):
class FloatProperty(Property): default: Optional[float] = None _type_string: ClassVar[str] = "float" def _validate_default(self, default: Any) -> float: try: return float(default) except (TypeError, ValueError) as e: raise ValidationError() from e @dataclass class ...
class IntProperty(Property): default: Optional[int] = None _type_string: ClassVar[str] = "int" @dataclass class BooleanProperty(Property):
class IntProperty(Property): default: Optional[int] = None _type_string: ClassVar[str] = "int" def _validate_default(self, default: Any) -> int: try: return int(default) except (TypeError, ValueError) as e: raise ValidationError() from e @dataclass class BooleanPro...
class BooleanProperty(Property): _type_string: ClassVar[str] = "bool" InnerProp = TypeVar("InnerProp", bound=Property)
class BooleanProperty(Property): _type_string: ClassVar[str] = "bool" def _validate_default(self, default: Any) -> bool: # no try/except needed as anything that comes from the initial load from json/yaml will be boolable return bool(default) InnerProp = TypeVar("InnerProp", bound=Property)
class ListProperty(Property, Generic[InnerProp]): inner_property: InnerProp template: ClassVar[str] = "list_property.pyi" def __post_init__(self) -> None: super().__post_init__() if self.default is not None: self.default = f"field(default_factory=lambda: cast({self.get_type_stri...
class ListProperty(Property, Generic[InnerProp]): inner_property: InnerProp template: ClassVar[str] = "list_property.pyi" def get_type_string(self, no_optional: bool = False) -> str: """ Get a string representation of type that should be used when declaring this property """ if self.require...
def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import cast") return imports @dataclass class UnionProperty(Property):
def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import cast") return imports def _validate_default(self, default: Any) -> str: if not isinstance(default, list): raise ValidationError() default = list(map(self.inner_property._validate_defa...
class UnionProperty(Property): inner_properties: List[Property] template: ClassVar[str] = "union_property.pyi" def get_type_string(self) -> str: """ Get a string representation of type that should be used when declaring this property """ inner_types = [p.get_type_string() for p in self.inne...
class UnionProperty(Property): inner_properties: List[Property] template: ClassVar[str] = "union_property.pyi" def get_type_string(self, no_optional: bool = False) -> str: """ Get a string representation of type that should be used when declaring this property """ inner_types = [p.get_type_...
def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import Union") return imports _existing_enums: Dict[str, EnumProperty] = {}
def get_imports(self, *, prefix: str) -> Set[str]: imports.add("from typing import Union") return imports def _validate_default(self, default: Any) -> Any: for property in self.inner_properties: try: val = property._validate_default(default) retur...
class EnumProperty(Property): template: ClassVar[str] = "enum_property.pyi" def __post_init__(self, title: str) -> None: # type: ignore super().__post_init__() reference = Reference.from_ref(title) dedup_counter = 0 while reference.class_name in _existing_enums:
class EnumProperty(Property): template: ClassVar[str] = "enum_property.pyi" def __post_init__(self, title: str) -> None: # type: ignore reference = Reference.from_ref(title) dedup_counter = 0 while reference.class_name in _existing_enums:
def __post_init__(self, title: str) -> None: # type: ignore reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}") self.reference = reference inverse_values = {v: k for k, v in self.values.items()} if self.default is not None: self.default = f"{self.re...
def __post_init__(self, title: str) -> None: # type: ignore reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}") self.reference = reference super().__post_init__() _existing_enums[self.reference.class_name] = self @staticmethod
def get_enum(name: str) -> Optional[EnumProperty]: """ Get all the EnumProperties that have been registered keyed by class name """ return _existing_enums.get(name) def get_type_string(self) -> str: """ Get a string representation of type that should be used when declaring this property """...
def get_enum(name: str) -> Optional[EnumProperty]: """ Get all the EnumProperties that have been registered keyed by class name """ return _existing_enums.get(name) def get_type_string(self, no_optional: bool = False) -> str: """ Get a string representation of type that should be used when ...
def values_from_list(values: List[str]) -> Dict[str, str]: key = f"VALUE_{i}" if key in output: raise ValueError(f"Duplicate key {key} in Enum") output[key] = value return output @dataclass class RefProperty(Property):
def values_from_list(values: List[str]) -> Dict[str, str]: key = f"VALUE_{i}" if key in output: raise ValueError(f"Duplicate key {key} in Enum") sanitized_key = utils.fix_keywords(utils.sanitize(key)) output[sanitized_key] = utils.remove_string_escapes...