buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Index(IndexOpsMixin, PandasObject): left_indexer = self.get_indexer(target, "pad", limit=limit) right_indexer = self.get_indexer(target, "backfill", limit=limit) target = np.asarray(target) left_distances = abs(self.values[left_indexer] - target) right_distances = abs(self...
class Index(IndexOpsMixin, PandasObject): left_indexer = self.get_indexer(target, "pad", limit=limit) right_indexer = self.get_indexer(target, "backfill", limit=limit) left_distances = np.abs(self[left_indexer] - target) right_distances = np.abs(self[right_indexer] - target) op...
class TestDataFrameIndexing: actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) tm.assert_frame_equal(expected, actual) def test_reindex_frame_add_nat(self): rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s") df = DataFrame({"A": np.random.rand...
class TestDataFrameIndexing: actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) tm.assert_frame_equal(expected, actual) def test_reindex_nearest_tz(self, tz_aware_fixture): # GH26683 tz = tz_aware_fixture idx = pd.date_range("2019-01-01", periods=...
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 ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' become_unprivileged = self._is_become_unprivileged() remote_tmp = self.get_shell_option('remote_tmp', default='~/.ansible/tmp') # deal with tmpdir creation basefil...
class ActionBase(with_metaclass(ABCMeta, object)): Create and return a temporary path on a remote box. ''' # Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host. # As such, we want to avoid using remote_user for paths as remote...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Authentication or permission failure. ' 'In some cases, you may have been able to authentic...
class ActionBase(with_metaclass(ABCMeta, object)): elif u'No space left on device' in result['stderr']: output = result['stderr'] else: output = ('Failed to create temporary directory.' 'In some cases, you may have been able to authentica...
import random import re import time import ansible.constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
import random import re import time from ansible.errors import AnsibleError from ansible.module_utils.six import text_type from ansible.module_utils.six.moves import shlex_quote
class ShellBase(AnsiblePlugin): except KeyError: pass def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in kwargs.items()])
class ShellBase(AnsiblePlugin): except KeyError: pass @staticmethod def _generate_temp_dir_name(): return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48)) def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48)) # When system is specified we have to create this in a directory where # other user...
class ShellBase(AnsiblePlugin): def mkdtemp(self, basefile=None, system=False, mode=0o700, tmpdir=None): if not basefile: basefile = self.__class__._generate_temp_dir_name() # When system is specified we have to create this in a directory where # other users can read and access...
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): # passed in tmpdir if it is valid or the first one from the setting if not. if system: if tmpdir: tmpdir = tmpdir.rstrip('/') if tmpdir in self.get_option('system_tmpdirs'): basetmpdir = tmpdir
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT) ...
class ShellBase(AnsiblePlugin): basetmp = self.join_path(basetmpdir, basefile) # use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT) cmd += '%s mkdir %s' ...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored basefile = self._escape(self._unquote(basefile)) basetmpdir = tmpdir if tmpdir else self.ge...
class ShellModule(ShellBase): def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): # Windows does not have an equivalent for the system temp files, so # the param is ignored if not basefile: basefile = self.__class__._generate_temp_dir_name() basefile =...
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.deprecation import RemovedInDjango40Warning from django.utils.html import conditional_escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils....
from itertools import cycle as itertools_cycle, groupby from django.conf import settings from django.utils import timezone from django.utils.deprecation import RemovedInDjango40Warning from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from djang...
class CycleNode(Node): class DebugNode(Node): def render(self, context): from pprint import pformat output = [pformat(val) for val in context] output.append('\n\n') output.append(pformat(sys.modules)) return ''.join(output)
class CycleNode(Node): class DebugNode(Node): def render(self, context): if not settings.DEBUG: return '' from pprint import pformat output = [escape(pformat(val)) for val in context] output.append('\n\n') output.append(escape(pformat(sys.modules))) retu...
import sys from django.contrib.auth.models import Group from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
import sys from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [gro...
class TemplateTests(SimpleTestCase): with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: return ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import FrozenList import pandas.core.missing as missing
import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.frozen import ...
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = getattr(series, "_values", series) if isinstance(s, (ExtensionArray, Index)) and is_...
class Index(IndexOpsMixin, PandasObject): # if we have something that is Index-like, then # use this, e.g. DatetimeIndex # Things like `Series._get_value` (via .at) pass the EA directly here. s = extract_array(series, extract_numpy=True) if isinstance(s, ExtensionArray): ...
def test_groupby_agg_ea_method(monkeypatch): s = pd.Series(DecimalArray(data)) result = s.groupby(np.array([0, 0, 0, 1, 1])).agg(lambda x: x.values.my_sum()) tm.assert_series_equal(result, expected, check_names=False)
def test_groupby_agg_ea_method(monkeypatch): s = pd.Series(DecimalArray(data)) result = s.groupby(np.array([0, 0, 0, 1, 1])).agg(lambda x: x.values.my_sum()) tm.assert_series_equal(result, expected, check_names=False) def test_indexing_no_materialize(monkeypatch): # See https://github.com/pandas-dev/p...
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_integer, is_list_like, is_scalar, is_timedelta64_dtype,
from pandas.core.dtypes.common import ( is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_extension_array_dtype, is_integer, is_integer_dtype, is_list_like, is_scalar, is_timedelta64_dtype,
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.")
def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) # To support cut(IntegerArray), we convert to object dtype with NaN # Will properly support in the future. # https://github.com/pandas-dev/pandas/pull/31290 if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype): ...
def test_value_counts_na(): tm.assert_series_equal(result, expected) # TODO(jreback) - these need testing / are broken # shift
def test_value_counts_na(): tm.assert_series_equal(result, expected) @pytest.mark.parametrize("bins", [3, [0, 5, 15]]) @pytest.mark.parametrize("right", [True, False]) @pytest.mark.parametrize("include_lowest", [True, False]) def test_cut(bins, right, include_lowest): a = np.random.randint(0, 10, size=50).ast...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'g...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterab...
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI-delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): @cache_readonly def _engine(self): # To avoid a reference cycle, pass a weakref of self to _engine_type. period = weakref.ref(self) return self._engine_type(period, len(self)) @doc(Index.__contains__)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): @cache_readonly def _engine(self): # To avoid a reference cycle, pass a weakref of self._values to _engine_type. period = weakref.ref(self._values) return self._engine_type(period, len(self)) @doc(Index.__contains__)
def test_get_level_values_na(): result = index.get_level_values(0) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected)
def test_get_level_values_na(): result = index.get_level_values(0) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected) def test_get_level_values_when_periods(): # GH33131. See also discussion in GH32669. # This test can probably be removed when PeriodIndex._engine is remo...
class S3CopyToTable(rdbms.CopyToTable): if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = %s and table_name = %s limit 1") else: query = ("select 1 as table_exists " ...
class S3CopyToTable(rdbms.CopyToTable): if '.' in self.table: query = ("select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and table_name = lower(%s) limit 1") else: query = ("select 1 as table_ex...
class TestS3CopyToTable(unittest.TestCase): # Check the SQL query in `S3CopyToTable.does_table_exist`. mock_cursor.execute.assert_called_with("select 1 as table_exists " "from pg_table_def " "where tablename = ...
class TestS3CopyToTable(unittest.TestCase): # Check the SQL query in `S3CopyToTable.does_table_exist`. mock_cursor.execute.assert_called_with("select 1 as table_exists " "from pg_table_def " "where tablename = ...
class TestS3CopyToTable(unittest.TestCase): mock_cursor.execute.assert_any_call( "select 1 as table_exists " "from pg_table_def " "where tablename = %s limit 1", (task.table,), )
class TestS3CopyToTable(unittest.TestCase): mock_cursor.execute.assert_any_call( "select 1 as table_exists " "from pg_table_def " "where tablename = lower(%s) limit 1", (task.table,), )
class TestS3CopyToSchemaTable(unittest.TestCase): mock_cursor.execute.assert_called_with( "select 1 as table_exists " "from information_schema.tables " "where table_schema = %s and " "table_name = %s limit 1", tuple(task.table.split('.')), )
class TestS3CopyToSchemaTable(unittest.TestCase): mock_cursor.execute.assert_called_with( "select 1 as table_exists " "from information_schema.tables " "where table_schema = lower(%s) and " "table_name = lower(%s) limit 1", tuple(task.table.split('.'))...
def test_register(self): # Test registering a viewer that is not a class ImageShow.register("not a class") def test_show(self): class TestViewer: methodCalled = False
def test_register(self): # Test registering a viewer that is not a class ImageShow.register("not a class") # Restore original state ImageShow._viewers.pop() def test_show(self): class TestViewer: methodCalled = False
def show(self, image, title=None, **options): self.assertTrue(ImageShow.show(im)) self.assertTrue(viewer.methodCalled) def test_viewer(self): viewer = ImageShow.Viewer()
def show(self, image, title=None, **options): self.assertTrue(ImageShow.show(im)) self.assertTrue(viewer.methodCalled) # Restore original state ImageShow._viewers.pop(0) def test_viewer(self): viewer = ImageShow.Viewer()
def test_viewer(self): self.assertRaises(NotImplementedError, viewer.get_command, None) if __name__ == '__main__': unittest.main()
def test_viewer(self): self.assertRaises(NotImplementedError, viewer.get_command, None) def test_viewers(self): for viewer in ImageShow._viewers: viewer.get_command('test.jpg') if __name__ == '__main__': unittest.main()
from PIL import Image import os import sys if sys.version_info.major >= 3: from shlex import quote
from PIL import Image import os import sys import subprocess import tempfile if sys.version_info.major >= 3: from shlex import quote
def get_command(self, file, **options): quote(file)) return command register(MacViewer) else:
def get_command(self, file, **options): quote(file)) return command def show_file(self, file, **options): """Display given file""" f, path = tempfile.mkstemp() f.write(file) f.close() ...
class UnixViewer(Viewer): format = "PNG" options = {'compress_level': 1} def show_file(self, file, **options): command, executable = self.get_command_ex(file, **options) command = "(%s %s; rm -f %s)&" % (command, quote(file), ...
class UnixViewer(Viewer): format = "PNG" options = {'compress_level': 1} def get_command(self, file, **options): command = self.get_command_ex(file, **options)[0] return "(%s %s; rm -f %s)&" % (command, quote(file), quote(file)) def show_file(self, file, **optio...
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.mark.parametrize('script, branch_name', [ ('git push', 'master'), ('git push origin', 'master')])
To push the current branch and set the remote as upstream, use '''.format(branch_name, branch_name) @pytest.fixture def output_bitbucket(): return '''Total 0 (delta 0), reused 0 (delta 0) remote: remote: Create pull request for feature/set-upstream: remote: https://bitbucket.org/set-upstream remote: To git@bitb...
def test_match(output, script, branch_name): assert match(Command(script, output)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
def test_match(output, script, branch_name): assert match(Command(script, output)) def test_match_bitbucket(output_bitbucket): assert not match(Command('git push origin', output_bitbucket)) @pytest.mark.parametrize('script, branch_name', [ ('git push master', None), ('ls', 'master')])
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'set-upstream' in command.output) def _get_upstream_option_index(command_parts):
from thefuck.specific.git import git_support @git_support def match(command): return ('push' in command.script_parts and 'git push --set-upstream' in command.output) def _get_upstream_option_index(command_parts):
def __init__(self, password): def load(self, stream): '''read vault steam and return python object''' return yaml.load(self.vault.decrypt(stream)) def dump(self, data, stream=None): '''encrypt data and print stdout or write to stream'''
def __init__(self, password): def load(self, stream): '''read vault steam and return python object''' return yaml.safe_load(self.vault.decrypt(stream)) def dump(self, data, stream=None): '''encrypt data and print stdout or write to stream'''
import os from tempfile import mkstemp from testfixtures import ShouldRaise from ansible.errors import AnsibleError here = os.path.dirname(os.path.abspath(__file__))
import os from tempfile import mkstemp from ansible.errors import AnsibleError from testfixtures import ShouldRaise from yaml.constructor import ConstructorError here = os.path.dirname(os.path.abspath(__file__))
def test_cannot(self): with ShouldRaise(AnsibleError('Decryption failed')): vault.load(open(fpath).read()) class TestVaultDump(object): def _getTargetClass(self):
def test_cannot(self): with ShouldRaise(AnsibleError('Decryption failed')): vault.load(open(fpath).read()) def test_not_pwned(self): fpath = os.path.join(here, 'file', 'pwned.txt') vault = self._makeOne('password') with ShouldRaise(ConstructorError): vault.lo...
def run_tests(self): setup( name='ansible-vault', version='1.0.4', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/jptomo/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_package...
def run_tests(self): setup( name='ansible-vault', version='1.0.5', author='Tomohiro NAKAMURA', author_email='quickness.net@gmail.com', url='https://github.com/tomoh1r/ansible-vault', description='R/W an ansible-vault yaml file', long_description=_read('README.rst'), packages=find_packag...
class Session(BaseConfigDict): """ for name, value in request_headers.items(): value = value.decode('utf8') if name == 'User-Agent' and value.startswith('HTTPie/'): continue
class Session(BaseConfigDict): """ for name, value in request_headers.items(): if value is None: continue # Ignore explicitely unset headers value = value.decode('utf8') if name == 'User-Agent' and value.startswith('HTTPie/'): conti...
import os import shutil import sys import pytest
import os import shutil import sys from tempfile import gettempdir import pytest
class TestSession(SessionTestBase): r2 = http('--session=test', httpbin.url + '/headers', env=self.env()) assert HTTP_OK in r2 assert r2.json['headers']['User-Agent'] == 'custom'
class TestSession(SessionTestBase): r2 = http('--session=test', httpbin.url + '/headers', env=self.env()) assert HTTP_OK in r2 assert r2.json['headers']['User-Agent'] == 'custom' def test_download_in_session(self, httpbin): # https://github.com/jkbrzt/httpie/issues/412 self....
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...
class Poll(models.Model): class Question(models.Model): poll = models.ForeignKey(Poll, models.CASCADE)
class Poll(models.Model): class Question(models.Model): text = models.CharField(max_length=40) poll = models.ForeignKey(Poll, models.CASCADE)
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.assertEqual(response.status_code, 302) self.assertRedirects(respo...
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.assertEqual(RowLevelC...
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: url(r'^test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), url(r'^test_admin/admin9/', admin.site9.urls), url(r'^test_admin/admin10/', admin.site10.urls), url(r'^t...
urlpatterns = [ # All admin views accept `extra_context` to allow adding it like this: url(r'^test_admin/admin8/', (admin.site.get_urls(), 'admin', 'admin-extra-context'), {'extra_context': {}}), url(r'^test_admin/admin9/', admin.site9.urls), url(r'^test_admin/has_permission_admin/', custom_has_permissi...
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...
from collections import namedtuple import re from ..exceptions import LocationParseError url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
from collections import namedtuple import re from ..exceptions import LocationParseError from ..packages.six.moves.urllib.parse import quote url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None auth = None
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 url = _contains_disallowed_url_pchar_re.sub(lambda match: quote(match.group()), url) scheme = None auth = None
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') @pytest.mark.parametrize('url, expected_url', [ ( 'http://localhost/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:', Url('http', host='localhost', port=None, path='/%20HTTP/1.1%0D...
import warnings import zlib from functools import wraps from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse from zope.interface import implementer
import warnings import zlib from functools import wraps from typing import Iterable from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse from zope.interface import implementer
def _handleResponse(self, response): return response @implementer(IAgent) class RedirectAgent: """
def _handleResponse(self, response): return response _canonicalHeaderName = Headers()._canonicalNameCaps _defaultSensitiveHeaders = frozenset( [ b"Authorization", b"Cookie", b"Cookie2", b"Proxy-Authorization", b"WWW-Authenticate", ] ) @implementer(IAgent) clas...
class RedirectAgent: @param redirectLimit: The maximum number of times the agent is allowed to follow redirects before failing with a L{error.InfiniteRedirection}. @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected for I{GET} and I{HEAD} methods.
class RedirectAgent: @param redirectLimit: The maximum number of times the agent is allowed to follow redirects before failing with a L{error.InfiniteRedirection}. @param sensitiveHeaderNames: An iterable of C{bytes} enumerating the names of headers that must not be transmitted when redirecting...
class RedirectAgent: ] _seeOtherResponses = [http.SEE_OTHER] def __init__(self, agent, redirectLimit=20): self._agent = agent self._redirectLimit = redirectLimit def request(self, method, uri, headers=None, bodyProducer=None): """
class RedirectAgent: ] _seeOtherResponses = [http.SEE_OTHER] def __init__( self, agent: IAgent, redirectLimit: int = 20, sensitiveHeaderNames: Iterable[bytes] = (), ): self._agent = agent self._redirectLimit = redirectLimit sensitive = {_canonical...
def _handleRedirect(self, response, method, uri, headers, redirectCount): ) raise ResponseFailed([Failure(err)], response) location = self._resolveLocation(uri, locationHeaders[0]) deferred = self._agent.request(method, location, headers) def _chainResponse(newResponse):
def _handleRedirect(self, response, method, uri, headers, redirectCount): ) raise ResponseFailed([Failure(err)], response) location = self._resolveLocation(uri, locationHeaders[0]) if headers: parsedURI = URI.fromBytes(uri) parsedLocation = URI.fromBytes(l...
class IAgent(Interface): obtained by combining a number of (hypothetical) implementations:: baseAgent = Agent(reactor) redirect = BrowserLikeRedirectAgent(baseAgent, limit=10) authenticate = AuthenticateAgent( redirect, [diskStore.credentials, GtkAuthInterface()]) cookie...
class IAgent(Interface): obtained by combining a number of (hypothetical) implementations:: baseAgent = Agent(reactor) decode = ContentDecoderAgent(baseAgent, [(b"gzip", GzipDecoder())]) cookie = CookieAgent(decode, diskStore.cookie) authenticate = AuthenticateAgent( coo...
import zlib from http.cookiejar import CookieJar from io import BytesIO from unittest import skipIf from zope.interface.declarations import implementer from zope.interface.verify import verifyObject
import zlib from http.cookiejar import CookieJar from io import BytesIO from typing import TYPE_CHECKING, List, Optional, Tuple from unittest import SkipTest, skipIf from zope.interface.declarations import implementer from zope.interface.verify import verifyObject
URIInjectionTestsMixin, ) try: from twisted.internet import ssl as _ssl except ImportError:
URIInjectionTestsMixin, ) # Creatively lie to mypy about the nature of inheritance, since dealing with # expectations of a mixin class is basically impossible (don't use mixins). if TYPE_CHECKING: testMixinClass = TestCase runtimeTestCase = object else: testMixinClass = object runtimeTestCase = Tes...
class StubHTTPProtocol(Protocol): request method is appended to this list. """ def __init__(self): self.requests = [] self.state = "QUIESCENT" def request(self, request):
class StubHTTPProtocol(Protocol): request method is appended to this list. """ def __init__(self) -> None: self.requests: List[Tuple[Request, Deferred[IResponse]]] = [] self.state = "QUIESCENT" def request(self, request):
def getConnection(this, key, ep): self.assertEqual(agent._pool.connected, True) class _RedirectAgentTestsMixin: """ Test cases mixin for L{RedirectAgentTests} and L{BrowserLikeRedirectAgentTests}. """ def test_noRedirect(self): """ L{client.RedirectAgent} behaves like L{cl...
def getConnection(this, key, ep): self.assertEqual(agent._pool.connected, True) SENSITIVE_HEADERS = [ b"authorization", b"cookie", b"cookie2", b"proxy-authorization", b"www-authenticate", ] class _RedirectAgentTestsMixin(testMixinClass): """ Test cases mixin for L{RedirectAgentTe...
def test_noRedirect(self): self.assertIdentical(response, result) self.assertIdentical(result.previousResponse, None) def _testRedirectDefault(self, code): """ When getting a redirect, L{client.RedirectAgent} follows the URL specified in the L{Location} header field and make...
def test_noRedirect(self): self.assertIdentical(response, result) self.assertIdentical(result.previousResponse, None) def _testRedirectDefault( self, code: int, crossScheme: bool = False, crossDomain: bool = False, crossPort: bool = False, requestHead...
def _testRedirectDefault(self, code): self.assertEqual(b"/bar", req2.uri) host, port = self.reactor.tcpClients.pop()[:2] self.assertEqual(EXAMPLE_COM_IP, host) self.assertEqual(expectedPort, port) def test_redirect301(self): """
def _testRedirectDefault(self, code): self.assertEqual(b"/bar", req2.uri) host, port = self.reactor.tcpClients.pop()[:2] self.assertEqual(EXAMPLE_NET_IP if crossDomain else EXAMPLE_COM_IP, host) self.assertEqual(targetPort, port) return req2 def test_redirect301(self): ...
def test_redirect301(self): """ self._testRedirectDefault(301) def test_redirect302(self): """ L{client.RedirectAgent} follows redirects on status code 302.
def test_redirect301(self): """ self._testRedirectDefault(301) def test_redirect301Scheme(self): """ L{client.RedirectAgent} follows cross-scheme redirects. """ self._testRedirectDefault( 301, crossScheme=True, ) def test_redirect...
def test_redirect308(self): """ self._testRedirectDefault(308) def _testRedirectToGet(self, code, method): """ L{client.RedirectAgent} changes the method to I{GET} when getting
def test_redirect308(self): """ self._testRedirectDefault(308) def _sensitiveHeadersTest( self, expectedHostHeader: bytes = b"example.com", **crossKwargs: bool ) -> None: """ L{client.RedirectAgent} scrubs sensitive headers when redirecting between differing orig...
def test_responseHistory(self): class RedirectAgentTests( TestCase, FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin ): """ Tests for L{client.RedirectAgent}.
def test_responseHistory(self): class RedirectAgentTests( FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin, runtimeTestCase, ): """ Tests for L{client.RedirectAgent}.
def makeAgent(self): """ @return: a new L{twisted.web.client.RedirectAgent} """ return client.RedirectAgent(self.buildAgentForWrapperTest(self.reactor)) def setUp(self): self.reactor = self.createReactor()
def makeAgent(self): """ @return: a new L{twisted.web.client.RedirectAgent} """ return client.RedirectAgent( self.buildAgentForWrapperTest(self.reactor), sensitiveHeaderNames=[b"X-Custom-sensitive"], ) def setUp(self): self.reactor = self.crea...
def test_302OnPost(self): class BrowserLikeRedirectAgentTests( TestCase, FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin ): """ Tests for L{client.BrowserLikeRedirectAgent}.
def test_302OnPost(self): class BrowserLikeRedirectAgentTests( FakeReactorAndConnectMixin, _RedirectAgentTestsMixin, AgentTestsMixin, runtimeTestCase, ): """ Tests for L{client.BrowserLikeRedirectAgent}.
def makeAgent(self): @return: a new L{twisted.web.client.BrowserLikeRedirectAgent} """ return client.BrowserLikeRedirectAgent( self.buildAgentForWrapperTest(self.reactor) ) def setUp(self):
def makeAgent(self): @return: a new L{twisted.web.client.BrowserLikeRedirectAgent} """ return client.BrowserLikeRedirectAgent( self.buildAgentForWrapperTest(self.reactor), sensitiveHeaderNames=[b"x-Custom-sensitive"], ) def setUp(self):
def handle_write(self): if self.will_close: self.handle_close() def _flush_exception(self, flush): if flush: try: return (flush(), False) except OSError: if self.adj.log_socket_errors: self.logger.exception("Soc...
def handle_write(self): if self.will_close: self.handle_close() def _flush_exception(self, flush, do_close=True): if flush: try: return (flush(do_close=do_close), False) except OSError: if self.adj.log_socket_errors: ...
def received(self, data): return True def _flush_some_if_lockable(self): # Since our task may be appending to the outbuf, we try to acquire # the lock, but we don't block if we can't. if self.outbuf_lock.acquire(False): try: self._flush_some() ...
def received(self, data): return True def _flush_some_if_lockable(self, do_close=True): # Since our task may be appending to the outbuf, we try to acquire # the lock, but we don't block if we can't. if self.outbuf_lock.acquire(False): try: self._flush_s...
def _flush_some(self): while outbuflen > 0: chunk = outbuf.get(self.sendbuf_len) num_sent = self.send(chunk) if num_sent: outbuf.skip(num_sent, True)
def _flush_some(self): while outbuflen > 0: chunk = outbuf.get(self.sendbuf_len) num_sent = self.send(chunk, do_close=do_close) if num_sent: outbuf.skip(num_sent, True)
def write_soon(self, data): self.total_outbufs_len += num_bytes if self.total_outbufs_len >= self.adj.send_bytes: (flushed, exception) = self._flush_exception(self._flush_some) if ( exception
def write_soon(self, data): self.total_outbufs_len += num_bytes if self.total_outbufs_len >= self.adj.send_bytes: (flushed, exception) = self._flush_exception( self._flush_some, do_close=False ) if ( ...
def _flush_outbufs_below_high_watermark(self): if self.total_outbufs_len > self.adj.outbuf_high_watermark: with self.outbuf_lock: (_, exception) = self._flush_exception(self._flush_some) if exception: # An exception happened while flushing, wake ...
def _flush_outbufs_below_high_watermark(self): if self.total_outbufs_len > self.adj.outbuf_high_watermark: with self.outbuf_lock: (_, exception) = self._flush_exception(self._flush_some, do_close=False) if exception: # An exception happened while...
def accept(self): else: return conn, addr def send(self, data): try: result = self.socket.send(data) return result
def accept(self): else: return conn, addr def send(self, data, do_close=True): try: result = self.socket.send(data) return result
def send(self, data): if why.args[0] == EWOULDBLOCK: return 0 elif why.args[0] in _DISCONNECTED: self.handle_close() return 0 else: raise
def send(self, data): if why.args[0] == EWOULDBLOCK: return 0 elif why.args[0] in _DISCONNECTED: if do_close: self.handle_close() return 0 else: raise
def test_handle_write_no_notify_after_flush(self): inst.total_outbufs_len = len(inst.outbufs[0]) inst.adj.send_bytes = 1 inst.adj.outbuf_high_watermark = 2 sock.send = lambda x: False inst.will_close = False inst.last_activity = 0 result = inst.handle_write()
def test_handle_write_no_notify_after_flush(self): inst.total_outbufs_len = len(inst.outbufs[0]) inst.adj.send_bytes = 1 inst.adj.outbuf_high_watermark = 2 sock.send = lambda x, do_close=True: False inst.will_close = False inst.last_activity = 0 result = inst.hand...
def get(self, numbytes): buf = DummyHugeOutbuffer() inst.outbufs = [buf] inst.send = lambda *arg: 0 result = inst._flush_some() # we are testing that _flush_some doesn't raise an OverflowError # when one of its outbufs has a __len__ that returns gt sys.maxint
def get(self, numbytes): buf = DummyHugeOutbuffer() inst.outbufs = [buf] inst.send = lambda *arg, do_close: 0 result = inst._flush_some() # we are testing that _flush_some doesn't raise an OverflowError # when one of its outbufs has a __len__ that returns gt sys.maxint
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError, HTTPRequest from tornado.log import gen_log, app_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.test.util import unittest, skipBefore35, exec_test from tornado.w...
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError, HTTPRequest from tornado.log import gen_log, app_log from tornado.template import DictLoader from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.test.util import unittest...
class CoroutineOnMessageHandler(TestWebSocketHandler): self.write_message(message) class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.coroutine def ws_connect(self, path, **kwargs):
class CoroutineOnMessageHandler(TestWebSocketHandler): self.write_message(message) class RenderMessageHandler(TestWebSocketHandler): def on_message(self, message): self.write_message(self.render_string('message.html', message=message)) class WebSocketBaseTestCase(AsyncHTTPTestCase): @gen.cor...
class WebSocketTest(WebSocketBaseTestCase): dict(close_future=self.close_future)), ('/coroutine', CoroutineOnMessageHandler, dict(close_future=self.close_future)), ]) def test_http_request(self): # WS server, HTTP client.
class WebSocketTest(WebSocketBaseTestCase): dict(close_future=self.close_future)), ('/coroutine', CoroutineOnMessageHandler, dict(close_future=self.close_future)), ('/render', RenderMessageHandler, dict(close_future=self.close_future)), ], template_...
class WebSocketTest(WebSocketBaseTestCase): self.assertEqual(response, u'hello \u00e9') yield self.close(ws) @gen_test def test_error_in_on_message(self): ws = yield self.ws_connect('/error_in_on_message')
class WebSocketTest(WebSocketBaseTestCase): self.assertEqual(response, u'hello \u00e9') yield self.close(ws) @gen_test def test_render_message(self): ws = yield self.ws_connect('/render') ws.write_message('hello') response = yield ws.read_message() self.assertEqu...
class RequestHandler(object): self._log() self._finished = True self.on_finish() # Break up a reference cycle between this handler and the # _ui_module closures to allow for faster GC on CPython. self.ui = None
class RequestHandler(object): self._log() self._finished = True self.on_finish() self._break_cycles() def _break_cycles(self): # Break up a reference cycle between this handler and the # _ui_module closures to allow for faster GC on CPython. self.ui = None
class WebSocketHandler(tornado.web.RequestHandler): if not self._on_close_called: self._on_close_called = True self.on_close() def send_error(self, *args, **kwargs): if self.stream is None:
class WebSocketHandler(tornado.web.RequestHandler): if not self._on_close_called: self._on_close_called = True self.on_close() self._break_cycles() def _break_cycles(self): # WebSocketHandlers call finish() early, but we don't want to # break up reference...
def register_cli_int(*args, **kw): register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False)
def register_cli_int(*args, **kw): register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') register_int('max_param_size', default=64) # we allow tokens to be a bit larger to accomidate PKI register_int('max_token_size', default=8192) #ssl options register_bool('e...
class ValidationError(Error): title = 'Bad Request' class Unauthorized(Error): """The request you have made requires authentication.""" code = 401
class ValidationError(Error): title = 'Bad Request' class ValidationSizeError(Error): """Request attribute %(attribute)s must be less than or equal to %(size)i. The server could not comply with the request because the attribute size is invalid (too large). The client is assumed to be in error. ...
from keystone import catalog from keystone.common import cms from keystone.common import logging from keystone.common import wsgi from keystone import exception from keystone import identity
from keystone import catalog from keystone.common import cms from keystone.common import logging from keystone.common import utils from keystone.common import wsgi from keystone import exception from keystone import identity
LOG = logging.getLogger(__name__) class AdminRouter(wsgi.ComposingRouter):
LOG = logging.getLogger(__name__) MAX_PARAM_SIZE = config.CONF.max_param_size MAX_TOKEN_SIZE = config.CONF.max_token_size class AdminRouter(wsgi.ComposingRouter):