buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1]
class BaseReshapingTests(BaseExtensionTests): # Check that we have a view, not a copy result[0] = result[1] assert data[0] == data[1] def test_transpose(self, data): df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"]) result = df.T expected ...
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
class TestReshaping(BaseJSON, base.BaseReshapingTests): # this matches otherwise return super().test_unstack(data, index) @pytest.mark.xfail(reason="Inconsistent sizes.") def test_transpose(self, data): super().test_transpose(data) class TestGetitem(BaseJSON, base.BaseGetitemTests): ...
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): # Fails creating expected super().test_merge_on_extension_array_duplicates(data) @skip_nested def test_transpose(self, data): super().test_transpose(data) class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_...
class SchemaBase(BaseModel): not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore items: Optional[Any] = None properties: Optional[Dict[str, Any]] = None additionalProperties: Optional[Union[bool, Any]] = None description: Optional[str] = None format: Optional[str] = None d...
class SchemaBase(BaseModel): not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore items: Optional[Any] = None properties: Optional[Dict[str, Any]] = None additionalProperties: Optional[Union[Dict[str, Any], bool]] = None description: Optional[str] = None format: Optional[str] =...
class Schema(SchemaBase): not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore items: Optional[SchemaBase] = None properties: Optional[Dict[str, SchemaBase]] = None additionalProperties: Optional[Union[bool, SchemaBase]] = None class Example(BaseModel):
class Schema(SchemaBase): not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore items: Optional[SchemaBase] = None properties: Optional[Dict[str, SchemaBase]] = None additionalProperties: Optional[Union[SchemaBase, bool]] = None class Example(BaseModel):
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...
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") DHFILE = data_file("dh512.pem") BYTES_DHFILE = os.fsencode(DHFILE)
WRONGCERT = data_file("XXXnonexisting.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") NULLBYTECERT = data_file("nullbytecert.pem") DHFILE = data_file("dh512.pem") BYTES_DHFILE = os.fsencode(DHFILE)
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 support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") subject...
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # Slightly fake real-world example cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', 'subject': ((('commonName', 'linuxfrz.org'),),),
def fail(cert, hostname): fail(cert, 'foo.a.com') fail(cert, 'bar.foo.com') # NULL bytes are bad, CVE-2013-4073 cert = {'subject': ((('commonName', 'null.python.org\x00example.org'),),)} ok(cert, 'null.python.org\x00example.org') # or raise an error...
from PIL import Image "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", ], ) def test_crashes(test_file):
from PIL import Image "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", "Tests/images/crash-754d9c7ec485ffb76a90eeaab191ef69a2a3a3cd.sgi", "Tests/images/crash-465703f71a0f0094873a3e0e82c9f...
def Ghostscript(tile, size, fp, scale=1): import tempfile, os, subprocess outfile = tempfile.mktemp() infile = tempfile.mktemp() with open(infile, 'wb') as f: fp.seek(offset)
def Ghostscript(tile, size, fp, scale=1): import tempfile, os, subprocess out_fd, outfile = tempfile.mkstemp() os.close(out_fd) in_fd, infile = tempfile.mkstemp() os.close(in_fd) with open(infile, 'wb') as f: fp.seek(offset)
class Image: self.readonly = 0 def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format ...
class Image: self.readonly = 0 def _dump(self, file=None, format=None): import tempfile, os if not file: f, file = tempfile.mkstemp(format or '') os.close(f) self.load() if not format or format == "PPM": self.im.save_ppm(file)...
class IptcImageFile(ImageFile.ImageFile): self.fp.seek(offset) # Copy image data to temporary file outfile = tempfile.mktemp() o = open(outfile, "wb") if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header
class IptcImageFile(ImageFile.ImageFile): self.fp.seek(offset) # Copy image data to temporary file o_fd, outfile = tempfile.mkstemp(text=False) o = os.fdopen(o_fd) if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header
class JpegImageFile(ImageFile.ImageFile): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file)) try: self.im = Image.core.open_ppm(file) finally: ...
class JpegImageFile(ImageFile.ImageFile): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): os.system("djpeg '%s' >'%s'" % (self.filename, path)) else:...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu (\d+)\s+local=[^\d]*(.*?)\s+dest=[^\d]*(.*?)\/([\d]*)\s+bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [^\d]+\s+local=([0-9a-f...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu" r" (\d+)\s+local=[^\d]*(.*?)\s{0,40}dest=[^\d]*(.*?)\/([\d]*)\s{0,40}bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, user=user_ref, tenant=tenant_ref, ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, expires=auth_token_data['expires'], user=user_re...
# License for the specific language governing permissions and limitations # under the License. import uuid import default_fixtures from keystone import exception from keystone import identity from keystone import service
# License for the specific language governing permissions and limitations # under the License. import time import uuid import default_fixtures from keystone import config from keystone import exception from keystone import identity from keystone import service
from keystone.openstack.common import timeutils def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
from keystone.openstack.common import timeutils CONF = config.CONF def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict)
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict) class TokenExpirationTest(test.TestCase): def setUp(self): super(TokenExpirationTest, self).setUp() self.identity_api = kvs_identity.Identity() ...
part 3</font></u> cli_bool_option( {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='), ['--check-certificate=true']) def test_ohdave_rsa_encrypt(self): N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3af...
part 3</font></u> cli_bool_option( {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='), ['--check-certificate=true']) self.assertEqual( cli_bool_option( {}, '--check-certificate', 'nocheckcertificat...
def cli_option(params, command_option, param): def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None): param = params.get(param) assert isinstance(param, bool) if separator: return [command_option + separator + (true_value if param else false_valu...
def cli_option(params, command_option, param): def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None): param = params.get(param) if param is None: return [] assert isinstance(param, bool) if separator: return [command_option + separato...
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') self.assertEqual(unified_strdate('1968-12-10'), '19681210') def test_find_xpath_attr(self): testxml = '''<root>
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') self.assertEqual(unified_strdate('1968-12-10'), '19681210') self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0...
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] info_dict = { 'id': player_info['VID'], 'title': player_info['VTI'], 'description': player_info.get('VDE'), 'upload_date': uni...
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = player_info.get('VDA', '').split(' ')[0] info_dict = ...
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return str(name).replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_save_doesnt_close(self): with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file: file.write(b'1')
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
class Warnings(object): "loaded. (Shape: {shape})") W021 = ("Unexpected hash collision in PhraseMatcher. Matches may be " "incorrect. Modify PhraseMatcher._terminal_hash to fix.") @add_codes
class Warnings(object): "loaded. (Shape: {shape})") W021 = ("Unexpected hash collision in PhraseMatcher. Matches may be " "incorrect. Modify PhraseMatcher._terminal_hash to fix.") W022 = ("Training a new part-of-speech tagger using a model with no " "lemmatization rules or da...
dependency tree to find the noun phrase they are referring to – for example: $9.4 million --> Net income. Compatible with: spaCy v2.0.0+ Last tested with: v2.1.0 """ from __future__ import unicode_literals, print_function
dependency tree to find the noun phrase they are referring to – for example: $9.4 million --> Net income. Compatible with: spaCy v2.0.0+ Last tested with: v2.2.1 """ from __future__ import unicode_literals, print_function
def main(model="en_core_web_sm"): def filter_spans(spans): # Filter a sequence of spans so they don't contain overlaps get_sort_key = lambda span: (span.end - span.start, span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set() for span in sorted_...
def main(model="en_core_web_sm"): def filter_spans(spans): # Filter a sequence of spans so they don't contain overlaps # For spaCy 2.1.4+: this function is available as spacy.util.filter_spans() get_sort_key = lambda span: (span.end - span.start, -span.start) sorted_spans = sorted(spans, key=get_sort_k...
def test_filter_spans(doc): assert len(filtered[1]) == 5 assert filtered[0].start == 1 and filtered[0].end == 4 assert filtered[1].start == 5 and filtered[1].end == 10
def test_filter_spans(doc): assert len(filtered[1]) == 5 assert filtered[0].start == 1 and filtered[0].end == 4 assert filtered[1].start == 5 and filtered[1].end == 10 # Test filtering overlaps with earlier preference for identical length spans = [doc[1:4], doc[2:5], doc[5:10], doc[7:9], doc[1:4]] ...
def filter_spans(spans): spans (iterable): The spans to filter. RETURNS (list): The filtered spans. """ get_sort_key = lambda span: (span.end - span.start, span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set()
def filter_spans(spans): spans (iterable): The spans to filter. RETURNS (list): The filtered spans. """ get_sort_key = lambda span: (span.end - span.start, -span.start) sorted_spans = sorted(spans, key=get_sort_key, reverse=True) result = [] seen_tokens = set()
class Function(object): # (since the outputs of fetches are never returned). # This requires us to wrap fetches in `identity` ops. self.fetches = [tf.identity(x) for x in self.fetches] self.session_kwargs = session_kwargs if session_kwargs: raise ValueError('Some keys...
class Function(object): # (since the outputs of fetches are never returned). # This requires us to wrap fetches in `identity` ops. self.fetches = [tf.identity(x) for x in self.fetches] # self.session_kwargs is used for _legacy_call self.session_kwargs = session_kwargs.copy() ...
class Function(object): callable_opts.fetch.append(x.name) # Handle updates. callable_opts.target.append(self.updates_op.name) # Create callable. callable_fn = session._make_callable_from_options(callable_opts) # Cache parameters corresponding to the generated callabl...
class Function(object): callable_opts.fetch.append(x.name) # Handle updates. callable_opts.target.append(self.updates_op.name) # Handle run_options. if self.run_options: callable_opts.run_options.CopyFrom(self.run_options) # Create callable. callab...
class Function(object): feed_symbols, symbol_vals, session) fetched = self._callable_fn(*array_vals) return fetched[:len(self.outputs)] def _legacy_call(self, inputs):
class Function(object): feed_symbols, symbol_vals, session) if self.run_metadata: fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata) else: fetched = self._callabl...
class Function(object): 'supported with sparse inputs.') return self._legacy_call(inputs) return self._call(inputs) else: if py_any(is_tensor(x) for x in inputs):
class Function(object): 'supported with sparse inputs.') return self._legacy_call(inputs) # callable generated by Session._make_callable_from_options accepts # `run_metadata` keyword argument since TF 1.10 if (self.run_metadata and ...
class TestBackend(object): assert output == [21.] assert K.get_session().run(fetches=[x, y]) == [30., 40.] @pytest.mark.skipif(K.backend() != 'tensorflow', reason='Uses the `string` type for a tensor.') def test_function_tf_string_input(self):
class TestBackend(object): assert output == [21.] assert K.get_session().run(fetches=[x, y]) == [30., 40.] @pytest.mark.skipif(K.backend() != 'tensorflow', reason='Uses the `options` and `run_metadata` arguments.') def test_function_tf_run_options_with_run_metadata(self)...
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.utils.http import urlquote from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': urlquote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
from __future__ import unicode_literals import unittest from django.core.exceptions import ImproperlyConfigured
from __future__ import unicode_literals import sys import unittest from django.core.exceptions import ImproperlyConfigured
try: except ImportError: # Python < 3.5 HTTPStatus = None class HandlerTests(SimpleTestCase):
try: except ImportError: # Python < 3.5 HTTPStatus = None PY37 = sys.version_info >= (3, 7, 0) class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
def get_user_roles(self, context, user_id, tenant_id=None): not implementing them in hopes that the idea will die off. """ if tenant_id is None: raise exception.NotImplemented(message='User roles not supported: ' 'tenant ID required...
def get_user_roles(self, context, user_id, tenant_id=None): not implementing them in hopes that the idea will die off. """ self.assert_admin(context) if tenant_id is None: raise exception.NotImplemented(message='User roles not supported: ' ...
def test_service_crud_requires_auth(self): expected_status=401) self.assertValidErrorResponse(r) class XmlTestCase(RestfulTestCase, CoreApiTests): xmlns = 'http://docs.openstack.org/identity/api/v2.0'
def test_service_crud_requires_auth(self): expected_status=401) self.assertValidErrorResponse(r) def test_user_role_list_requires_auth(self): """User role list should 401 without an X-Auth-Token (bug 1006815).""" # values here don't matter because we should 40...
_simple_palette = re.compile(b'^\xff+\x00\xff*$') # -------------------------------------------------------------------- # Support classes. Suitable for PNG and related formats like MNG etc.
_simple_palette = re.compile(b'^\xff+\x00\xff*$') # Maximum decompressed size for a iTXt or zTXt chunk. # Eliminates decompression bombs where compressed chunks can expand 1000x MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK # Set the maximum total text chunk size. MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK def _safe_zlib_decompre...
def __init__(self, fp): self.im_tile = None self.im_palette = None def chunk_iCCP(self, pos, length): # ICC profile
def __init__(self, fp): self.im_tile = None self.im_palette = None self.text_memory = 0 def check_text_memory(self, chunklen): self.text_memory += chunklen if self.text_memory > MAX_TEXT_MEMORY: raise ValueError("Too much memory used in text chunks: %s>MAX_TEXT_...
def chunk_iCCP(self, pos, length): raise SyntaxError("Unknown compression method %s in iCCP chunk" % comp_method) try: icc_profile = zlib.decompress(s[i+2:]) except zlib.error: icc_profile = None # FIXME self.im_info["icc_profile...
def chunk_iCCP(self, pos, length): raise SyntaxError("Unknown compression method %s in iCCP chunk" % comp_method) try: icc_profile = _safe_zlib_decompress(s[i+2:]) except zlib.error: icc_profile = None # FIXME self.im_info["icc_p...
def chunk_tEXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v return s def chunk_zTXt(self, pos, length):
def chunk_tEXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v self.check_text_memory(len(v)) return s def chunk_zTXt(self, pos, length):
def chunk_zTXt(self, pos, length): raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method) try: v = zlib.decompress(v[1:]) except zlib.error: v = b""
def chunk_zTXt(self, pos, length): raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method) try: v = _safe_zlib_decompress(v[1:]) except zlib.error: v = b""
def chunk_zTXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v return s def chunk_iTXt(self, pos, length):
def chunk_zTXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v self.check_text_memory(len(v)) return s def chunk_iTXt(self, pos, length):
def chunk_iTXt(self, pos, length): if cf != 0: if cm == 0: try: v = zlib.decompress(v) except zlib.error: return s else:
def chunk_iTXt(self, pos, length): if cf != 0: if cm == 0: try: v = _safe_zlib_decompress(v) except zlib.error: return s else:
def chunk_iTXt(self, pos, length): return s self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk) return s
def chunk_iTXt(self, pos, length): return s self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk) self.check_text_memory(len(v)) return s
def test_bad_itxt(self): im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + zlib.compress(b"egg")[:1]) + TAIL) self.assertEqual(im.info, {}) im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' + zlib.compress(b"egg")) + T...
def test_bad_itxt(self): im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + zlib.compress(b"egg")[:1]) + TAIL) self.assertEqual(im.info, {'spam':''}) im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' + zlib.compress(b"e...
from oic.oauth2.message import ErrorResponse from oic.oauth2.message import Message from oic.oauth2.message import MessageFactory from oic.oauth2.util import get_or_post from oic.oic.message import SCOPE2CLAIMS from oic.oic.message import AccessTokenResponse
from oic.oauth2.message import ErrorResponse from oic.oauth2.message import Message from oic.oauth2.message import MessageFactory from oic.oauth2.message import WrongSigningAlgorithm from oic.oauth2.util import get_or_post from oic.oic.message import SCOPE2CLAIMS from oic.oic.message import AccessTokenResponse
def sign_enc_algs(self, typ): return resp def _verify_id_token( self, id_token, nonce="", acr_values=None, auth_time=0, max_age=0 ): """ Verify IdToken.
def sign_enc_algs(self, typ): return resp def _verify_id_token( self, id_token, nonce="", acr_values=None, auth_time=0, max_age=0, response_type="", ): """ Verify IdToken.
def _verify_id_token( if _now > id_token["exp"]: raise OtherError("Passed best before date") if ( self.id_token_max_age and _now > int(id_token["iat"]) + self.id_token_max_age
def _verify_id_token( if _now > id_token["exp"]: raise OtherError("Passed best before date") if response_type != ["code"] and id_token.jws_header["alg"] == "none": raise WrongSigningAlgorithm( "none is not allowed outside Authorization Flow." ) ...
def verify_id_token(self, id_token, authn_req): except KeyError: pass for param in ["acr_values", "max_age"]: try: kwa[param] = authn_req[param] except KeyError:
def verify_id_token(self, id_token, authn_req): except KeyError: pass for param in ["acr_values", "max_age", "response_type"]: try: kwa[param] = authn_req[param] except KeyError:
import warnings from typing import Dict from typing import Optional from oic import rndstr from oic.exception import AuthzError
import warnings from typing import Dict from typing import Optional from typing import Tuple from typing import Union from oic import rndstr from oic.exception import AuthzError
from oic.oic.message import BackChannelLogoutRequest from oic.oic.message import Claims from oic.oic.message import ClaimsRequest from oic.utils import http_util from oic.utils.sanitize import sanitize from oic.utils.sdb import DictSessionBackend
from oic.oic.message import BackChannelLogoutRequest from oic.oic.message import Claims from oic.oic.message import ClaimsRequest from oic.oic.message import IdToken from oic.utils import http_util from oic.utils.sanitize import sanitize from oic.utils.sdb import DictSessionBackend
def begin(self, scope="", response_type="", use_nonce=False, path="", **kwargs): if self.debug: _log_info("Redirecting to: %s" % location) return sid, location def _parse_authz(self, query="", **kwargs):
def begin(self, scope="", response_type="", use_nonce=False, path="", **kwargs): if self.debug: _log_info("Redirecting to: %s" % location) self.authz_req[areq["state"]] = areq return sid, location def _parse_authz(self, query="", **kwargs):
def _parse_authz(self, query="", **kwargs): self.redirect_uris = [self.sdb[_state]["redirect_uris"]] return aresp, _state def parse_authz(self, query="", **kwargs): """ Parse authorization response from server.
def _parse_authz(self, query="", **kwargs): self.redirect_uris = [self.sdb[_state]["redirect_uris"]] return aresp, _state def parse_authz( self, query="", **kwargs ) -> Union[ http_util.BadRequest, Tuple[ Optional[AuthorizationResponse], Optional[...
def parse_authz(self, query="", **kwargs): ["id_token"] ["id_token", "token"] ["token"] :return: A AccessTokenResponse instance """ _log_info = logger.info logger.debug("- authorization -") if not query: return http_util.BadRequest("Missing q...
def parse_authz(self, query="", **kwargs): ["id_token"] ["id_token", "token"] ["token"] """ _log_info = logger.info logger.debug("- authorization -") # FIXME: This shouldn't be here... We should rather raise a sepcific Client error # That would simplify t...
def parse_authz(self, query="", **kwargs): except KeyError: pass return aresp, atr, idt elif "token" in self.consumer_config["response_type"]: # implicit flow _log_info("Expect Access Token Response") atr = self.parse_response( ...
def parse_authz(self, query="", **kwargs): except KeyError: pass elif "token" in self.consumer_config["response_type"]: # implicit flow _log_info("Expect Access Token Response") aresp = None _state = None atr = self.parse_resp...
def parse_authz(self, query="", **kwargs): if isinstance(atr, ErrorResponse): raise TokenError(atr.get("error"), atr) idt = None return None, atr, idt else: # only id_token aresp, _state = self._parse_authz(query, **kwargs)
def parse_authz(self, query="", **kwargs): if isinstance(atr, ErrorResponse): raise TokenError(atr.get("error"), atr) idt = atr.get("id_token") else: # only id_token aresp, _state = self._parse_authz(query, **kwargs)
def parse_authz(self, query="", **kwargs): session_update(self.sso_db, _state, "smid", idt["sid"]) except KeyError: pass return None, None, idt def complete(self, state): """
def parse_authz(self, query="", **kwargs): session_update(self.sso_db, _state, "smid", idt["sid"]) except KeyError: pass # Null the aresp as only id_token should be returned aresp = atr = None # Verify the IdToken if it was present...
def verify_id_token(instance, check_hash=False, **kwargs): if check_hash: _alg = idt.jws_header["alg"] # What if _alg == 'none' hfunc = "HS" + _alg[-3:] if "access_token" in instance: if "at_hash" not in idt: raise MissingRequiredAttribute("Missing at_h...
def verify_id_token(instance, check_hash=False, **kwargs): if check_hash: _alg = idt.jws_header["alg"] if _alg != "none": hfunc = "HS" + _alg[-3:] else: # This is allowed only for `code` and it needs to be checked by a Client hfunc = None if "acc...
def verify(self, **kwargs): else: if (_iat + _storage_time) < (_now - _skew): raise IATError("Issued too long ago") return True
def verify(self, **kwargs): else: if (_iat + _storage_time) < (_now - _skew): raise IATError("Issued too long ago") if _now < (_iat - _skew): raise IATError("Issued in the future") if _exp < _iat: raise EXPError("Invalid expiration tim...
from jwkest.jwk import SYMKey from oic.oauth2.message import MissingSigningKey from oic.oic import DEF_SIGN_ALG from oic.oic import Server from oic.oic import response_types_to_grant_types from oic.oic.consumer import IGNORE from oic.oic.consumer import Consumer from oic.oic.consumer import clean_response from oic.oic...
from jwkest.jwk import SYMKey from oic.oauth2.message import MissingSigningKey from oic.oauth2.message import WrongSigningAlgorithm from oic.oic import DEF_SIGN_ALG from oic.oic import Server from oic.oic import response_types_to_grant_types from oic.oic.consumer import IGNORE from oic.oic.consumer import Consumer fro...
def setup_consumer(self, session_db_factory): self.consumer.userinfo_endpoint = "https://example.com/userinfo" # type: ignore self.consumer.client_secret = "hemlig" self.consumer.secret_type = "basic" def test_backup_keys(self): keys = self.consumer.__dict__.keys()
def setup_consumer(self, session_db_factory): self.consumer.userinfo_endpoint = "https://example.com/userinfo" # type: ignore self.consumer.client_secret = "hemlig" self.consumer.secret_type = "basic" self.consumer.provider_info = ProviderConfigurationResponse( issuer="https...
def test_parse_authz(self): self.consumer._backup(_state) part = self.consumer.parse_authz(query=result.headers["location"]) atr = part[0] assert part[1] is None assert part[2] is None
def test_parse_authz(self): self.consumer._backup(_state) part = self.consumer.parse_authz(query=result.headers["location"]) assert isinstance(part, tuple) atr = part[0] assert part[1] is None assert part[2] is None
def test_parse_authz_implicit(self): ) part = self.consumer.parse_authz(query=result.headers["location"]) assert part[0] is None atr = part[1] assert part[2] is None
def test_parse_authz_implicit(self): ) part = self.consumer.parse_authz(query=result.headers["location"]) assert isinstance(part, tuple) assert part[0] is None atr = part[1] assert part[2] is None
def test_complete_auth_token(self): parsed = urlparse(result.headers["location"]) part = self.consumer.parse_authz(query=parsed.query) auth = part[0] acc = part[1] assert part[2] is None
def test_complete_auth_token(self): parsed = urlparse(result.headers["location"]) part = self.consumer.parse_authz(query=parsed.query) assert isinstance(part, tuple) auth = part[0] acc = part[1] assert part[2] is None
def test_complete_auth_token_idtoken(self): _state = "state0" self.consumer.consumer_config["response_type"] = ["id_token", "token"] self.consumer.registration_response = RegistrationResponse( id_token_signed_response_alg="RS256" ) self.consumer.provider_info = Provid...
def test_complete_auth_token_idtoken(self): _state = "state0" self.consumer.consumer_config["response_type"] = ["id_token", "token"] self.consumer.registration_response = RegistrationResponse( id_token_signed_response_alg="HS256" ) self.consumer.authz_req = {} # Stor...
def test_complete_auth_token_idtoken(self): location = ( "https://example.com/cb?state=state0&access_token=token&token_type=bearer&" "scope=openid&id_token={}".format( token.to_jwt(key=KC_RSA.keys(), algorithm="RS256") ) ) with responses.Reques...
def test_complete_auth_token_idtoken(self): location = ( "https://example.com/cb?state=state0&access_token=token&token_type=bearer&" "scope=openid&id_token={}".format( token.to_jwt(key=[SYMKey(key="hemlig")], algorithm="HS256") ) ) with respons...
def test_complete_auth_token_idtoken(self): parsed = urlparse(result.headers["location"]) with freeze_time("2019-08-09 11:00:00"): part = self.consumer.parse_authz( query=parsed.query, algs=self.consumer.sign_enc_algs("id_token") ) auth = part[0] ...
def test_complete_auth_token_idtoken(self): parsed = urlparse(result.headers["location"]) with freeze_time("2019-08-09 11:00:00"): part = self.consumer.parse_authz(query=parsed.query, algs={"sign": "HS256"}) assert isinstance(part, tuple) auth = part[0] atr = part[1]...
def test_get_session_management_id(self): self.consumer.sdb[_state] = {"redirect_uris": ["https://example.org/cb"]} resp = AuthorizationResponse(id_token=_signed_jwt, state=_state) self.consumer.consumer_config["response_type"] = ["id_token"] self.consumer.parse_authz(resp.to_urlencoded(...
def test_get_session_management_id(self): self.consumer.sdb[_state] = {"redirect_uris": ["https://example.org/cb"]} resp = AuthorizationResponse(id_token=_signed_jwt, state=_state) self.consumer.consumer_config["response_type"] = ["id_token"] self.consumer.authz_req[_state] = AccessToken...
def test_logout_with_sub(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) aresp = self.consumer.parse_authz(resp.message) assert self.consumer.sdb[sid]["issuer"] == self.provider.baseurl # Si...
def test_logout_with_sub(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) part = self.consumer.parse_authz(resp.message) assert isinstance(part, tuple) aresp = part[0] assert aresp ...
def test_logout_without_sub(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) aresp = self.consumer.parse_authz(resp.message) assert self.consumer.sdb[sid]["issuer"] == self.provider.baseurl #...
def test_logout_without_sub(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) part = self.consumer.parse_authz(resp.message) assert isinstance(part, tuple) aresp = part[0] assert aresp ...
def test_sso_db_dict(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) aresp = _consumer.parse_authz(resp.message) assert _consumer.sdb[sid]["issuer"] == self.provider.baseurl # Simulate an ac...
def test_sso_db_dict(self): "openid", "code", path="https://example.com" ) resp = self.provider.authorization_endpoint(request=request_location) part = _consumer.parse_authz(resp.message) assert isinstance(part, tuple) aresp = part[0] assert aresp ass...
from urllib.parse import urlencode import pytest from jwkest import BadSignature from jwkest.jwk import SYMKey from jwkest.jws import left_hash
from urllib.parse import urlencode import pytest from freezegun import freeze_time from jwkest import BadSignature from jwkest.jwk import SYMKey from jwkest.jws import left_hash
from oic.oic.message import BackChannelLogoutRequest from oic.oic.message import CHashError from oic.oic.message import Claims from oic.oic.message import FrontChannelLogoutRequest from oic.oic.message import IdToken from oic.oic.message import LogoutToken from oic.oic.message import OpenIDSchema
from oic.oic.message import BackChannelLogoutRequest from oic.oic.message import CHashError from oic.oic.message import Claims from oic.oic.message import EXPError from oic.oic.message import FrontChannelLogoutRequest from oic.oic.message import IATError from oic.oic.message import IdToken from oic.oic.message import L...
def test_token_type(self): at.verify() def test_id_token(): _now = time_util.utc_time_sans_frac()
def test_token_type(self): at.verify() class TestIdToken(object): """Unittests for IdToken class.""" @freeze_time("2020-01-01 11:00:00") def test_verify_iat_in_future(self): now = time_util.utc_time_sans_frac() idt = IdToken( **{ "sub": "553df2bcf9...
from oic.oic.message import IdToken from oic.oic.message import Message from oic.oic.message import OpenIDSchema from oic.oic.message import RefreshAccessTokenRequest from oic.oic.message import RegistrationRequest from oic.oic.message import RegistrationResponse
from oic.oic.message import IdToken from oic.oic.message import Message from oic.oic.message import OpenIDSchema from oic.oic.message import ProviderConfigurationResponse from oic.oic.message import RefreshAccessTokenRequest from oic.oic.message import RegistrationRequest from oic.oic.message import RegistrationRespons...
def create_provider(self, session_db_factory): self.cons.keyjar.import_jwks( self.provider.keyjar.export_jwks(), self.cons.issuer ) self.cons2 = Consumer( {}, CONSUMER_CONFIG.copy(), CLIENT_CONFIG_2, server_info=SERVER_INFO
def create_provider(self, session_db_factory): self.cons.keyjar.import_jwks( self.provider.keyjar.export_jwks(), self.cons.issuer ) self.cons.provider_info = ProviderConfigurationResponse( issuer=SERVER_INFO["issuer"] ) self.cons2 = Consumer( ...
def test_authenticated(self): part = self.cons.parse_authz(query=resp.message) aresp = part[0] assert part[1] is None assert part[2] is None
def test_authenticated(self): part = self.cons.parse_authz(query=resp.message) assert isinstance(part, tuple) aresp = part[0] assert part[1] is None assert part[2] is None
def test_authenticated_hybrid(self): part = self.cons.parse_authz(resp.message) aresp = part[0] assert part[1] is None assert part[2] is not None assert isinstance(aresp, AuthorizationResponse) assert _eq(aresp.keys(), ["scope", "state", "id_token", "client_id", "code"...
def test_authenticated_hybrid(self): part = self.cons.parse_authz(resp.message) assert isinstance(part, tuple) aresp = part[0] assert part[1] is None id_token = part[2] assert isinstance(aresp, AuthorizationResponse) assert _eq(aresp.keys(), ["scope", "state", ...
def test_authenticated_hybrid(self): self.cons.grant[_state].keys(), ["code", "id_token", "tokens", "exp_in", "grant_expiration_time", "seed"], ) id_token = part[2] assert isinstance(id_token, IdToken) assert _eq( id_token.keys(),
def test_authenticated_hybrid(self): self.cons.grant[_state].keys(), ["code", "id_token", "tokens", "exp_in", "grant_expiration_time", "seed"], ) assert isinstance(id_token, IdToken) assert _eq( id_token.keys(),
class Language(object): kwargs = component_cfg.get(name, {}) kwargs.setdefault("batch_size", batch_size) if not hasattr(pipe, "pipe"): docs = _pipe(pipe, docs, kwargs) else: docs = pipe.pipe(docs, **kwargs) for doc, gold in zip(docs...
class Language(object): kwargs = component_cfg.get(name, {}) kwargs.setdefault("batch_size", batch_size) if not hasattr(pipe, "pipe"): docs = _pipe(docs, pipe, kwargs) else: docs = pipe.pipe(docs, **kwargs) for doc, gold in zip(docs...
def test_language_evaluate(nlp): nlp.evaluate([text, gold]) def vector_modification_pipe(doc): doc.vector += 1 return doc
def test_language_evaluate(nlp): nlp.evaluate([text, gold]) def test_evaluate_no_pipe(nlp): """Test that docs are processed correctly within Language.pipe if the component doesn't expose a .pipe method.""" def pipe(doc): return doc text = "hello world" annots = {"cats": {"POSITIV...
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: