buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def _validate_path(self, url): ).format(matched=match.group(), **locals()) raise InvalidURL(msg) def putheader(self, header, *values): """Send a request header line to the server.
def _validate_path(self, url): ).format(matched=match.group(), **locals()) raise InvalidURL(msg) def _validate_host(self, host): """Validate a host so it doesn't contain control characters.""" # Prevent CVE-2019-18348. match = _contains_disallowed_url_pchar_re.search...
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_domain_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_encoding(self): """ It should be possible to override the default encoding
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_host_validation(self): class UnsafeHTTPConnection(client.HTTPConnection): def _validate_host(self, url): pass conn = UnsafeHTTPConnecti...
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = "//localhost:7777/test{}/".format(char)
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = "//localhost:7777/test{}/".format(char)
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\...
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he...
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() def test_read_0_9(self): # "0.9" response accepted (but not "simple responses" without # a status line)
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_host_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) scheme...
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read() % allSubstitutions rawFrom = email.utils.parseaddr(mailFrom)[1] ...
def sendEmail(sydent, templateName, mailTo, substitutions): allSubstitutions[k+"_forhtml"] = cgi.escape(v.decode('utf8')) allSubstitutions[k+"_forurl"] = urllib.quote(v) mailString = open(mailTemplateFile).read().decode('utf8') % allSubstitutions parsedFrom = email.utils.parsead...
def sendEmail(sydent, templateName, mailTo, substitutions): smtp = smtplib.SMTP(mailServer, mailPort, myHostname) if mailUsername != '': smtp.login(mailUsername, mailPassword) smtp.sendmail(rawFrom, rawTo, mailString.encode('utf-8')) smtp.quit() ...
def sendEmail(sydent, templateName, mailTo, substitutions): smtp = smtplib.SMTP(mailServer, mailPort, myHostname) if mailUsername != '': smtp.login(mailUsername, mailPassword) # We're using the parsing above to do basic validation, but instead of # fa...
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, (self.host, self.port) = self._get_hostport(host, port) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_connection = socket.create_connection
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, (self.host, self.port) = self._get_hostport(host, port) self._validate_host(self.host) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_c...
def _validate_path(self, url): raise InvalidURL(f"URL can't contain control characters. {url!r} " f"(found at least {match.group()!r})") def putheader(self, header, *values): """Send a request header line to the server.
def _validate_path(self, url): raise InvalidURL(f"URL can't contain control characters. {url!r} " f"(found at least {match.group()!r})") def _validate_host(self, host): """Validate a host so it doesn't contain control characters.""" # Prevent CVE-2019-18348....
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_domain_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_encoding(self): """ It should be possible to override the default encoding
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_host_validation(self): class UnsafeHTTPConnection(client.HTTPConnection): def _validate_host(self, url): pass conn = UnsafeHTTPConnecti...
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = f"//localhost:7777/test{char}/"
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = f"//localhost:7777/test{char}/"
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\...
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he...
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() def test_read_0_9(self): # "0.9" response accepted (but not "simple responses" without # a status line)
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_host_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) scheme...
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...
from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
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, str): 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, str): exception_repr = message context = { 'request_path': quote(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...
import unittest from django.core.exceptions import ImproperlyConfigured
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 do_setup(): scripts=['airflow/bin/airflow'], install_requires=[ 'alembic>=0.8.3, <0.9', 'bleach==2.1.2', 'configparser>=3.5.0, <3.6.0', 'croniter>=0.3.17, <0.4', 'dill>=0.2.2, <0.3',
def do_setup(): scripts=['airflow/bin/airflow'], install_requires=[ 'alembic>=0.8.3, <0.9', 'bleach~=2.1.3', 'configparser>=3.5.0, <3.6.0', 'croniter>=0.3.17, <0.4', 'dill>=0.2.2, <0.3',
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN RSA PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256)
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN RSA PUBLIC KEY-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError):...
class Response(object_ref): """ if isinstance(url, Link): url = url.url url = self.urljoin(url) return Request(url, callback, method=method,
class Response(object_ref): """ if isinstance(url, Link): url = url.url elif url is None: raise ValueError("url can't be None") url = self.urljoin(url) return Request(url, callback, method=method,
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_whitespace_url(self): self._assert_followed_url('foo ', 'http://example.com/foo%20')
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_None_url(self): r = self.response_class("http://example.com") self.assertRaises(ValueError, r.follow, None) d...
def delete(self, req, image_id): % locals()) raise webob.exc.HTTPForbidden(explanation=msg) status = 'deleted' if image['location']: if CONF.delayed_delete: status = 'pending_delete' self.store_api.schedule_delayed_delete_from_...
def delete(self, req, image_id): % locals()) raise webob.exc.HTTPForbidden(explanation=msg) if image['location'] and CONF.delayed_delete: status = 'pending_delete' else: status = 'deleted' try: self.db_api.image_update(req.con...
def test_permissions(self): self.assertEqual(201, response.status_code) image_id = json.loads(response.text)['id'] # TENANT1 should see the image in their list path = self._url('/v2/images') response = requests.get(path, headers=self._headers())
def test_permissions(self): self.assertEqual(201, response.status_code) image_id = json.loads(response.text)['id'] # Upload some image data path = self._url('/v2/images/%s/file' % image_id) headers = self._headers({'Content-Type': 'application/octet-stream'}) response = ...
def test_permissions(self): response = requests.delete(path, headers=headers) self.assertEqual(404, response.status_code) self.stop_servers() def test_tag_lifecycle(self):
def test_permissions(self): response = requests.delete(path, headers=headers) self.assertEqual(404, response.status_code) # Image data should still be present after the failed delete path = self._url('/v2/images/%s/file' % image_id) response = requests.get(path, headers=self._he...
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
from pandas.core.dtypes.common import ( ensure_platform_int, is_bool, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype, is_dtype_equal,
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass return Index(values, **attributes) def _update_inplace(self, result, **kwargs):
class Index(IndexOpsMixin, PandasObject): return self._constructor(values, **attributes) except (TypeError, ValueError): pass # Remove tz so Index will try non-DatetimeIndex inference attributes.pop("tz", None) return Index(values, **attributes) ...
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical(target): tgt_values = np.asarray(target) elif self.is_all_dates and target.is_all_dates: # GH 30399 tgt_va...
class Index(IndexOpsMixin, PandasObject): if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) if is_categorical_dtype(target.dtype): tgt_values = np.asarray(target) else: tgt_values = target._get_engine_target()
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc from pan...
import numpy as np from pandas._libs import NaT, iNaT, join as libjoin, lib from pandas._libs.tslibs import timezones from pandas._typing import DtypeObj, Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, cache_readonly, doc...
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extensi...
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin from pandas.core.base import IndexOpsMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index from pandas.core.i...
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True # ------------------------------------------------------------------------ # Abstract data attributes
class DatetimeIndexOpsMixin(ExtensionIndex): def is_all_dates(self) -> bool: return True def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ raise AbstractMethodError(self) # -------------------------...
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] # -------------------------------------------------------------------- __add__ = make_wrapped_arith_op("__add__")
class DatetimeIndexOpsMixin(ExtensionIndex): # try to find the dates return (lhs_mask & rhs_mask).nonzero()[0] @Appender(Index.get_indexer_non_unique.__doc__) def get_indexer_non_unique(self, target): target = ensure_index(target) pself, ptarget = self._maybe_promote(tar...
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_intege...
import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts from pandas._libs.tslibs import fields, parsing, timezones from pandas._typing import DtypeObj, Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( _NS_DTYPE, ...
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") # -------------------------------------------------------------------- # Rendering Methods
class DatetimeIndex(DatetimeTimedeltaMixin): return Timestamp(value).asm8 raise ValueError("Passed item and index have different timezone") def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if no...
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import Label from pandas.util._decorators import Appender, cache_readonly from pa...
from pandas._libs.lib import no_default from pandas._libs.tslibs import frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string from pandas._libs.tslibs.period import Period from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender, cache_readonl...
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.arrays.period import ( PeriodArray,
from pandas.core.dtypes.common import ( is_scalar, pandas_dtype, ) from pandas.core.dtypes.dtypes import PeriodDtype from pandas.core.arrays.period import ( PeriodArray,
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) # ------------------------------------------------------------------------ # Rendering Methods
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # raise when input doesn't have freq raise raise_on_incompatible(self, None) def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ if not isinstance(...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if isinstance(target, PeriodIndex): if target.freq != self.freq: no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_m...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if not self._is_comparable_dtype(target.dtype): no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_matches, no_matches target = ...
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ return is_timedelta64_dtype(dtype...
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc")
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc") dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZ...
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2 def test_loc_datetimelike_mismatched_dtypes(): # GH#32650 dont mix and match datetime/timedelta/period dtypes df = pd.DataFrame( n...
class EmptyLineTracker: lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) before -= self.previous_after self.previous_after = after self.previous_line = current_line return before, after
class EmptyLineTracker: lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) before = ( # Black should not insert empty lines at the beginning # of the file 0 if self.previous_line is None else ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) def test_tab_comment_indentation(self) -> None: contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n" contents_spc = "if 1:\n if 2:\n ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_beginning_backslash(self) -> None: source, expected = read_data("beginning_backslash") actu...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(i...
class ModelAdmin(BaseModelAdmin): ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(...
class ModelAdmin(BaseModelAdmin): else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == 'POST': if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has...
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
from selenium.common.exceptions import NoSuchElementException from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class SeleniumTests(AdminSeleniumTestCase):
class TestInlinePermissions(TestCase): ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestReadOnlyChangeViewInlinePermissions(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('testing', password='password', is_staff=True) cls.user.user...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_delete_inlines(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + r...
class SeleniumTests(AdminSeleniumTestCase): self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_add_inline_link_absent_for_view_only_parent_model(self): user = User.objects.create_user('testing', password='password', is_st...
class ArticleAdmin9(admin.ModelAdmin): site9 = admin.AdminSite(name='admin9') site9.register(Article, ArticleAdmin9) class ArticleAdmin10(admin.ModelAdmin): def has_change_permission(self, request, obj=None): return False site10 = admin.AdminSite(name='admin10') site10.register(Article, ArticleAdmin10)
class ArticleAdmin9(admin.ModelAdmin): site9 = admin.AdminSite(name='admin9') site9.register(Article, ArticleAdmin9)
class AdminViewPermissionsTest(TestCase): self.assertEqual(post.status_code, 403) self.client.get(reverse('admin:logout')) # view user should be able to view the article but not change any of them # (the POST can be sent, but no modification occurs) self.client.force_login(self....
class AdminViewPermissionsTest(TestCase): self.assertEqual(post.status_code, 403) self.client.get(reverse('admin:logout')) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.a...
class AdminViewPermissionsTest(TestCase): self.assertContains(response, '<label>Extra form field:</label>') self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>') post = self.client.post(article_change_url, change_dict) self.assertEq...
class AdminViewPermissionsTest(TestCase): self.assertContains(response, '<label>Extra form field:</label>') self.assertContains(response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>') post = self.client.post(article_change_url, change_dict) self.assertEq...
class AdminViewPermissionsTest(TestCase): response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {'name': 'changed'}) self.assertRedirects(response, self.index_url) sel...
class AdminViewPermissionsTest(TestCase): response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {'name': 'changed'}) self.assertEqual(response.status_code, 403) self.a...
class AdminViewPermissionsTest(TestCase): self.assertEqual(response.context['title'], 'View article') self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>') def test_change_view_post_without_object_change_permission(self): """A POST re...
class AdminViewPermissionsTest(TestCase): self.assertEqual(response.context['title'], 'View article') self.assertContains(response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>') def test_change_view_save_as_new(self): """ 'Save as new' should raise...
class AdminInlineTests(TestCase): self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_simple_inline_permissions(self): """ Changes aren't allowed without change permissions for the inline object. """ ...
class AdminInlineTests(TestCase): self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_explicit_autofield_inline(self): "A model with an explicit autofield primary key can be saved as inlines. Regression for #8093" #...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), path('test_admin/admin9/', admin.site9.urls), path('test_admin/admin10/', admin.site10.urls), path('test_...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: path('test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), path('test_admin/admin9/', admin.site9.urls), path('test_admin/has_permission_admin/', custom_has_permission_...
class ChangelistTests(AuthViewsTestCase): data['password'] = 'shouldnotchange' change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,)) response = self.client.post(change_url, data) self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist')) u.re...
class ChangelistTests(AuthViewsTestCase): data['password'] = 'shouldnotchange' change_url = reverse('auth_test_admin:auth_user_change', args=(u.pk,)) response = self.client.post(change_url, data) self.assertEqual(response.status_code, 403) u.refresh_from_db() self.assertE...
See documentation in docs/topics/downloader-middleware.rst """ from w3lib.http import basic_auth_header from scrapy import signals class HttpAuthMiddleware(object):
See documentation in docs/topics/downloader-middleware.rst """ import warnings from w3lib.http import basic_auth_header from scrapy import signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.url import url_is_from_any_domain class HttpAu...
def spider_opened(self, spider): pwd = getattr(spider, 'http_pass', '') if usr or pwd: self.auth = basic_auth_header(usr, pwd) def process_request(self, request, spider): auth = getattr(self, 'auth', None) if auth and b'Authorization' not in request.headers: ...
def spider_opened(self, spider): pwd = getattr(spider, 'http_pass', '') if usr or pwd: self.auth = basic_auth_header(usr, pwd) if not hasattr(spider, 'http_auth_domain'): warnings.warn('Using HttpAuthMiddleware without http_auth_domain is deprecated and can cause ...
import unittest from scrapy.http import Request from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware from scrapy.spiders import Spider class TestSpider(Spider): http_user = 'foo' http_pass = 'bar' class HttpAuthMiddlewareTest(unittest.TestCase):
import unittest from w3lib.http import basic_auth_header from scrapy.http import Request from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware from scrapy.spiders import Spider class TestSpiderLegacy(Spider): http_user = 'foo' http_pass = 'bar' class TestSpider(Spider): http_user = 'foo...
def setUp(self): def tearDown(self): del self.mw def test_auth(self): req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None self.assertEqual(req.headers['Authorization'], b'Basic Zm9vOmJhcg==') def test_auth_already_set(self): ...
def setUp(self): def tearDown(self): del self.mw def test_no_auth(self): req = Request('http://example-noauth.com/') assert self.mw.process_request(req, self.spider) is None self.assertNotIn('Authorization', req.headers) def test_auth_domain(self): req = Request('ht...
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmax), min(vmin, vmax, oldmin), ignore=True) sel...
def _make_getset_interval(method_name, lim_name, attr_name): setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax), ignore=True) else: setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax), ignore=True) sel...
def test_bar_errbar_zorder(): assert capline.zorder > bar.zorder for barlinecol in barlinecols: assert barlinecol.zorder > bar.zorder
def test_bar_errbar_zorder(): assert capline.zorder > bar.zorder for barlinecol in barlinecols: assert barlinecol.zorder > bar.zorder def test_set_ticks_inverted(): fig, ax = plt.subplots() ax.invert_xaxis() ax.set_xticks([.3, .7]) assert ax.get_xlim() == (1, 0)
from pandas._libs.tslibs import ( timezones, tzconversion, ) from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
from pandas._libs.tslibs import ( timezones, tzconversion, ) import pandas._libs.tslibs.frequencies as libfrequencies from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import (
default 'raise' "You must pass a freq argument as current index has none." ) freq = get_period_alias(freq) return PeriodArray._from_datetime64(self._data, freq, tz=self.tz)
default 'raise' "You must pass a freq argument as current index has none." ) res = get_period_alias(freq) # https://github.com/pandas-dev/pandas/issues/33358 if res is None: base, stride = libfrequencies._base_and_stride(freq) ...
import dateutil.tz from dateutil.tz import tzlocal import pytest
import warnings import dateutil.tz from dateutil.tz import tzlocal import pytest
class TestToPeriod: with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): date_range("01-Jan-2012", periods=8, freq="EOM") def test_period_dt64_round_trip(self): dti = date_range("1/1/2000", "1/7/2002", freq="B") pi = dti.to_period()
class TestToPeriod: with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): date_range("01-Jan-2012", periods=8, freq="EOM") def test_to_period_infer(self): # https://github.com/pandas-dev/pandas/issues/33358 rng = date_range( start="2019-12-22 06:40:00+00:00", ...
install_requires = [ "docker >= 3.4.1, < 3.5", "mypy_extensions >= 0.3.0, < 0.4", "python-dateutil >= 2.7.3, < 3.0", "requests >= 2.19.1, < 3.0", "toml >= 0.9.4, < 1.0", "typing >= 3.6.4, < 4.0", "typing_extensions >= 3.6.4, < 4.0",
install_requires = [ "docker >= 3.4.1, < 3.5", "mypy_extensions >= 0.3.0, < 0.4", "python-dateutil >= 2.7.3, < 3.0", "requests >= 2.20, < 3.0", "toml >= 0.9.4, < 1.0", "typing >= 3.6.4, < 4.0", "typing_extensions >= 3.6.4, < 4.0",
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] + to_append else: to_concat = [self, to_append] return concat(
class Series(base.IndexOpsMixin, generic.NDFrame): from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] to_concat.extend(to_append) else: to_concat = [self, to_append] return concat(
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_combine_scalar(self): # GH 21248 # Note - combine() with another Series is tested elsewhere because
class TestSeriesCombine: with pytest.raises(ValueError, match=msg): pd.concat([s1, s2], verify_integrity=True) def test_append_tuples(self): # GH 28410 s = pd.Series([1, 2, 3]) list_input = [s, s] tuple_input = (s, s) expected = s.append(list_input) ...
from ellipticcurve.utils.compatibility import * from ellipticcurve.privateKey import PrivateKey from ellipticcurve.publicKey import PublicKey from ellipticcurve.signature import Signature from ellipticcurve.utils.file import File from ellipticcurve.ecdsa import Ecdsa
from .utils.compatibility import * from .privateKey import PrivateKey from .publicKey import PublicKey from .signature import Signature from .utils.file import File from .ecdsa import Ecdsa
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s inv = Math.inv(s, curve.N) u1 = Math.multiply(curve.G, n=(numberMessage * inv) % curve.N, N=curve.N, A=curve.A, P=curve.P) u2 = Math.multiply(publicKey...
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s if not 1 <= r <= curve.N - 1: return False if not 1 <= s <= curve.N - 1: return False inv = Math.inv(s, curve.N) u1 = M...
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). ...