buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
from twisted.words.protocols.jabber import client, error, jid, xmlstream from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer from twisted.words.xish import utility IQ_AUTH_GET = '/iq[@type="get"]/query[@xmlns="jabber:iq:auth"]' IQ_AUTH_SET = '/iq[@type="set"]/query[@xmlns="jabber:iq:auth"]' NS_BI...
from twisted.words.protocols.jabber import client, error, jid, xmlstream from twisted.words.protocols.jabber.sasl import SASLInitiatingInitializer from twisted.words.xish import utility try: from twisted.internet import ssl except ImportError: ssl = None skipWhenNoSSL = "SSL not available" else: skipWh...
class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase): class XMPPAuthenticatorTests(unittest.TestCase): """ Test for both XMPPAuthenticator and XMPPClientFactory. """ def testBasic(self): """ Test basic operations.
class SessionInitializerTests(InitiatingInitializerHarness, unittest.TestCase): class BasicAuthenticatorTests(unittest.TestCase): """ Test for both BasicAuthenticator and basicClientFactory. """ def test_basic(self): """ Authenticator and stream are properly constructed by the factor...
class XMPPAuthenticatorTests(unittest.TestCase): self.assertIsInstance(bind, client.BindInitializer) self.assertIsInstance(session, client.SessionInitializer) self.assertFalse(tls.required) self.assertTrue(sasl.required) self.assertFalse(bind.required) self.assertFalse(s...
class XMPPAuthenticatorTests(unittest.TestCase): self.assertIsInstance(bind, client.BindInitializer) self.assertIsInstance(session, client.SessionInitializer) self.assertTrue(tls.required) self.assertTrue(sasl.required) self.assertTrue(bind.required) self.assertFalse(ses...
from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin from twisted.words.xish import domish from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls'
from twisted.words.test.test_xmlstream import GenericXmlStreamFactoryTestsMixin from twisted.words.xish import domish from twisted.words.protocols.jabber import error, ijabber, jid, xmlstream try: from twisted.internet import ssl except ImportError: ssl = None skipWhenNoSSL = "SSL not available" else: ...
class TLSInitiatingInitializerTests(unittest.TestCase): self.savedSSL = xmlstream.ssl self.authenticator = xmlstream.Authenticator() self.xmlstream = xmlstream.XmlStream(self.authenticator) self.xmlstream.send = self.output.append self.xmlstream.connectionMade()
class TLSInitiatingInitializerTests(unittest.TestCase): self.savedSSL = xmlstream.ssl self.authenticator = xmlstream.ConnectAuthenticator(u'example.com') self.xmlstream = xmlstream.XmlStream(self.authenticator) self.xmlstream.send = self.output.append self.xmlstream.connectionM...
class TLSInitiatingInitializerTests(unittest.TestCase): xmlstream.ssl = self.savedSSL def testWantedSupported(self): """ Test start when TLS is wanted and the SSL library available. """ self.xmlstream.transport = proto_helpers.StringTransport() self.xmlstream.transp...
class TLSInitiatingInitializerTests(unittest.TestCase): xmlstream.ssl = self.savedSSL def test_initRequired(self): """ Passing required sets the instance variable. """ self.init = xmlstream.TLSInitiatingInitializer(self.xmlstream, ...
class TLSInitiatingInitializerTests(unittest.TestCase): d = self.init.start() d.addCallback(self.assertEqual, xmlstream.Reset) starttls = self.output[0] self.assertEqual('starttls', starttls.name) self.assertEqual(NS_XMPP_TLS, starttls.uri) self.xmlstream.dataReceived("<...
class TLSInitiatingInitializerTests(unittest.TestCase): d = self.init.start() d.addCallback(self.assertEqual, xmlstream.Reset) self.assertEqual(2, len(self.output)) starttls = self.output[1] self.assertEqual('starttls', starttls.name) self.assertEqual(NS_XMPP_TLS, startt...
class TLSInitiatingInitializerTests(unittest.TestCase): return d if not xmlstream.ssl: testWantedSupported.skip = "SSL not available" def testWantedNotSupportedNotRequired(self): """ Test start when TLS is wanted and the SSL library available. """ xmlstream.ss...
class TLSInitiatingInitializerTests(unittest.TestCase): return d test_wantedSupported.skip = skipWhenNoSSL def test_certificateVerify(self): """ The server certificate will be verified. """ def fakeStartTLS(contextFactory): self.assertIsInstance(contextFa...
class TLSInitiatingInitializerTests(unittest.TestCase): self.init.wanted = False d = self.init.start() self.assertEqual([], self.output) self.assertFailure(d, xmlstream.TLSRequired) return d def testNotWantedNotRequired(self): """ Test start when TLS is no...
class TLSInitiatingInitializerTests(unittest.TestCase): self.init.wanted = False d = self.init.start() self.assertEqual(1, len(self.output)) self.assertFailure(d, xmlstream.TLSRequired) return d def test_notWantedNotRequired(self): """ No StartTLS is initi...
from openapi_python_client.cli import app if __name__ == "__main__": from .fastapi_app import generate_openapi_json generate_openapi_json() runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
from openapi_python_client.cli import app if __name__ == "__main__": runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{openapi.title.replace(' ', '-').low...
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).low...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): module_path = api_dir / f"{tag}.py" ...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): tag = utils.snake_case(tag) ...
import stringcase def snake_case(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return stringcase.snakecase(value) def pascal_case(value...
import stringcase def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value) def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = mocker.MagicMock(autospec=str) tag_2 = mocker.MagicMock(autospec=str) collection_1 = mocker.MagicMock() ...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = "a_tag" tag_2 = "another_tag" collection_1 = mocker.MagicMock() collection_2 = mocker.MagicMock() ...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return en...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_spinal_case(): assert utils.spinal_case("keep_alive") == "keep-alive"
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_kebab_case(): assert utils.kebab_case("keep_alive") == "keep-alive"
def __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...
class Series(base.IndexOpsMixin, generic.NDFrame): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") non_mapping = is_scalar(index) or ( is_list_like(index) and not is_dict_like(index) ) if non_mapping: return self._set_...
class Series(base.IndexOpsMixin, generic.NDFrame): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") if callable(index) or is_dict_like(index): return super().rename(index=index, **kwargs) else: return self._set_name(index, inpl...
class TestSeriesAlterAxes: expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) def test_set_axis_inplace_axes(self, axis_series): # GH14636 ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
class TestSeriesAlterAxes: expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) def test_rename_with_custom_indexer(self): # GH 27814 class MyIndexer: pass ix = MyIndexer() s = Series([1, 2, 3]).rename(ix) a...
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) values = self._ndarray t = np.result_type(value, values) if t != self._ndarray.dtype: values = values.astype(t, casting="safe") ...
class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): if not lib.is_scalar(value): value = np.asarray(value) value = np.asarray(value, dtype=self._ndarray.dtype) self._ndarray[key] = value def __len__(self) -> int: return len(self._ndarray)
def test_basic_binop(): result = x + x expected = PandasArray(np.array([2, 4, 6])) tm.assert_extension_array_equal(result, expected)
def test_basic_binop(): result = x + x expected = PandasArray(np.array([2, 4, 6])) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize("dtype", [None, object]) def test_setitem_object_typecode(dtype): arr = PandasArray(np.array(["a", "b", "c"], dtype=dtype)) arr[0] = "t" ...
class _MergeOperation: ) ] else: left_keys = [self.left.index.values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class _MergeOperation: ) ] else: left_keys = [self.left.index._values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected) def test_merge_index_column_tz(self): # GH 29864 index = pd.date_range("2019-10-01", freq="30min", periods=5, tz="UTC") left = pd.DataFrame([0.9, 0.8, 0.7,...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(params[11], {'k': [1, {}]}) class TraverseTests(unittest.TestCase): def test_underscore(self): from supervisor import xmlrpc self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None) def test_notfound(self): ...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(params[11], {'k': [1, {}]}) class TraverseTests(unittest.TestCase): def test_security_disallows_underscore_methods(self): from supervisor import xmlrpc class Root: pass class A: def _danger(self): ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): path = method.split('.') for name in path: if name.startswith('_'): # security (don't allow things that start with an underscore to # be ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): dotted_parts = method.split('.') # security (CVE-2017-11610, don't allow object traversal) if len(dotted_parts) != 2: raise RPCError(Faults.UNKNOWN_METHOD) ...
class Errors(object): E168 = ("Unknown field: {field}") E169 = ("Can't find module: {module}") E170 = ("Cannot apply transition {name}: invalid for the current state.") @add_codes
class Errors(object): E168 = ("Unknown field: {field}") E169 = ("Can't find module: {module}") E170 = ("Cannot apply transition {name}: invalid for the current state.") E171 = ("Matcher.add received invalid on_match callback argument: expected " "callable or None, but got: {arg_type}") @ad...
def test_matcher_schema_token_attributes(en_vocab, pattern, text): assert len(matcher) == 1 matches = matcher(doc) assert len(matches) == 1
def test_matcher_schema_token_attributes(en_vocab, pattern, text): assert len(matcher) == 1 matches = matcher(doc) assert len(matches) == 1 def test_matcher_valid_callback(en_vocab): """Test that on_match can only be None or callable.""" matcher = Matcher(en_vocab) with pytest.raises(ValueErro...
class LinuxHardware(Hardware): # The fields for ARM CPUs do not always include 'vendor_id' or 'model name', # and sometimes includes both 'processor' and 'Processor'. # Always use 'processor' count for ARM systems if collected_facts.get('ansible_architecture', '').startswith(('armv', 'a...
class LinuxHardware(Hardware): # The fields for ARM CPUs do not always include 'vendor_id' or 'model name', # and sometimes includes both 'processor' and 'Processor'. # The fields for Power CPUs include 'processor' and 'cpu'. # Always use 'processor' count for ARM and Power systems ...
CPU_INFO_TEST_SCENARIOS = [ '7', 'POWER7 (architected), altivec supported' ], 'processor_cores': 1, 'processor_count': 16, 'processor_threads_per_core': 1, 'processor_vcpus': 16 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '7', 'POWER7 (architected), altivec supported' ], 'processor_cores': 1, 'processor_count': 8, 'processor_threads_per_core': 1, 'processor_vcpus': 8 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '23', 'POWER8 (architected), altivec supported', ], 'processor_cores': 1, 'processor_count': 48, 'processor_threads_per_core': 1, 'processor_vcpus': 48 }, }, {
CPU_INFO_TEST_SCENARIOS = [ '23', 'POWER8 (architected), altivec supported', ], 'processor_cores': 1, 'processor_count': 24, 'processor_threads_per_core': 1, 'processor_vcpus': 24 }, }, {
def test_get_cpu_info_missing_arch(mocker): module = mocker.Mock() inst = linux.LinuxHardware(module) # ARM will report incorrect processor count if architecture is not available mocker.patch('os.path.exists', return_value=False) mocker.patch('os.access', return_value=True) for test in CPU_INFO...
def test_get_cpu_info_missing_arch(mocker): module = mocker.Mock() inst = linux.LinuxHardware(module) # ARM and Power will report incorrect processor count if architecture is not available mocker.patch('os.path.exists', return_value=False) mocker.patch('os.access', return_value=True) for test i...
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') ################################################################ if __name__ == '__main__':
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') def test_parameter_repr(self): from ctypes import ( c_bool, c_char, c_wchar, c_byte, c_ubyte, c_short, ...
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 core(task.Config): class WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler() def create_remote_scheduler(self, host, port): return rpc.RemoteScheduler(host=host, port=port)
class core(task.Config): class WorkerSchedulerFactory(object): def create_local_scheduler(self): return scheduler.CentralPlannerScheduler(prune_on_get_work=True) def create_remote_scheduler(self, host, port): return rpc.RemoteScheduler(host=host, port=port)
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled state might store datetime objects
class scheduler(Config): visualization_graph = parameter.Parameter(default="svg", config_path=dict(section='scheduler', name='visualization-graph')) prune_on_get_work = parameter.BoolParameter(default=False) def fix_time(x): # Backwards compatibility for a fix in Dec 2014. Prior to the fix, pickled stat...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active # seconds since epoch self.started = time.time() ...
class Worker(object): def __init__(self, worker_id, last_active=None): self.id = worker_id self.reference = None # reference to the worker in the real world. (Currently a dict containing just the host) self.last_active = last_active or time.time() # seconds since epoch self.started...
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for worker_id = kwargs['worker'] # Return remaining tasks that have no FAILED descendents self.update(worker_id, {'host': host})
class CentralPlannerScheduler(Scheduler): # TODO: remove tasks that can't be done, figure out if the worker has absolutely # nothing it can wait for if self._config.prune_on_get_work: self.prune() worker_id = kwargs['worker'] # Return remaining tasks that have no FA...
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...
class WorkerExternalTaskTest(unittest.TestCase): worker_disconnect_delay=3, disable_persist=3, disable_window=5, disable_fai...
class WorkerExternalTaskTest(unittest.TestCase): 'retry-external-tasks', False) is True original_get_work = self.scheduler.get_work def decorated_get_work(*args, **kwargs): ...
class WorkerExternalTaskTest(unittest.TestCase): 'retry-external-tasks', False) is True tempdir = tempfile.mkdtemp(prefix='luigi-test-') with patch('random.randint', return_value=0.1):
import stat import tarfile import zipfile class ArchiveException(Exception): """
import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """
class BaseArchive: return False return True def extract(self): raise NotImplementedError('subclasses of BaseArchive must provide an extract() method')
class BaseArchive: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) if not filename.startswith(target_path): raise SuspiciousOperation("Ar...
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) if member.isdir(): if filename and not os.path.exists(filename): os.makedirs(fil...
class TarArchive(BaseArchive): name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename and not os.path.exists(filename): os.make...
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] filename = os.path.join(to_path, name) dirname = os.path.dirname(filename) if dirname and not os.path.exists(dirname): ...
class ZipArchive(BaseArchive): info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) dirname = os.path.dirname(filename) ...
import sys import tempfile import unittest from django.utils.archive import Archive, extract TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives')
import sys import tempfile import unittest from django.core.exceptions import SuspiciousOperation from django.test import SimpleTestCase from django.utils.archive import Archive, extract TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives')
class TestGzipTar(ArchiveTester, unittest.TestCase): class TestBzip2Tar(ArchiveTester, unittest.TestCase): archive = 'foobar.tar.bz2'
class TestGzipTar(ArchiveTester, unittest.TestCase): class TestBzip2Tar(ArchiveTester, unittest.TestCase): archive = 'foobar.tar.bz2' class TestArchiveInvalid(SimpleTestCase): def test_extract_function_traversal(self): archives_dir = os.path.join(os.path.dirname(__file__), 'traversal_archives') ...
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
class RFPDupeFilter(BaseDupeFilter): self.logger = logging.getLogger(__name__) if path: self.file = open(os.path.join(path, 'requests.seen'), 'a+') self.file.seek(0) self.fingerprints.update(x.rstrip() for x in self.file) @classmethod
import hashlib import unittest from scrapy.dupefilters import RFPDupeFilter from scrapy.http import Request
import hashlib import tempfile import unittest import shutil from scrapy.dupefilters import RFPDupeFilter from scrapy.http import Request
class RFPDupeFilterTest(unittest.TestCase): dupefilter.close('finished') def test_request_fingerprint(self): """Test if customization of request_fingerprint method will change output of request_seen.
class RFPDupeFilterTest(unittest.TestCase): dupefilter.close('finished') def test_dupefilter_path(self): r1 = Request('http://scrapytest.org/1') r2 = Request('http://scrapytest.org/2') path = tempfile.mkdtemp() try: df = RFPDupeFilter(path) df.open(...
from tests.utils import Command @pytest.fixture def did_not_match(target, did_you_forget=True): error = ("error: pathspec '{}' did not match any " "file(s) known to git.".format(target)) if did_you_forget: error = ("{}\nDid you forget to 'git add'?'".format(error)) return error @pyt...
from tests.utils import Command @pytest.fixture def stderr(target): return ("error: pathspec '{}' did not match any " 'file(s) known to git.'.format(target)) @pytest.mark.parametrize('script, target', [ ('git submodule update unknown', 'unknown'), ('git commit unknown', 'unknown')]) def test...
from thefuck.specific.git import git_support @git_support def match(command): return ('did not match any file(s) known to git.' in command.stderr and "Did you forget to 'git add'?" in command.stderr) @git_support def get_new_command(command): missing_file = re.findall( r"error: pathsp...
from thefuck.specific.git import git_support @git_support def match(command): return 'did not match any file(s) known to git.' in command.stderr @git_support def get_new_command(command): missing_file = re.findall( r"error: pathspec '([^']*)' " r'did not match any file\(s\) known to git.', co...
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) self._build_input_shape = None # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] if self._layers: self._layers[0].batch_input_shape = batch_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] self._build_input_shape = input_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): config = [] for layer in self.layers: config.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) return copy.d...
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): layer_configs = [] for layer in self.layers: layer_configs.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) ...
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config) model.summary() json_str = model.to_json()
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.weights # Model should be built. model.summary()...
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config)
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() Sequential.from_config(config)
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 config = model.get_config() new_model = keras.models.Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 assert len(new_model.weights) == 4
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 ass...
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id, '--quantity', quantity] rc, stderr, stdout = self.module.run_command(args, check_rc=True) e...
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id] if quantity is not None: args.extend(['--quantity', to_native(quantity)]) ...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, 1 pool_ids[pool_id] = str(quantity) consumer_type = module.params["consumer_type"] consumer_name = module.param...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, None pool_ids[pool_id] = quantity consumer_type = module.params["consumer_type"] consumer_name = module.params[...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, (0, ...
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', ], {'check_rc': True}, (0, '', '')
from django.contrib.postgres.fields import JSONField from django.db.models.aggregates import Aggregate __all__ = [
from django.contrib.postgres.fields import JSONField from django.db.models import Value from django.db.models.aggregates import Aggregate __all__ = [
class JSONBAgg(Aggregate): class StringAgg(Aggregate): function = 'STRING_AGG' template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s')" def __init__(self, expression, delimiter, distinct=False, **extra): distinct = 'DISTINCT ' if distinct else '' super(StringAgg, self).__ini...
class JSONBAgg(Aggregate): class StringAgg(Aggregate): function = 'STRING_AGG' template = '%(function)s(%(distinct)s%(expressions)s)' def __init__(self, expression, delimiter, distinct=False, **extra): distinct = 'DISTINCT ' if distinct else '' delimiter_expr = Value(str(delimiter)) ...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi...
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, ) if sys.version_info < (3, 0):
from youtube_dl.utils import ( xpath_with_ns, parse_iso8601, strip_jsonp, uppercase_escape, ) if sys.version_info < (3, 0):
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): d = json.loads(stripped) self.assertEqual(d, [{"id": "532cb", "x": 3}]) def test_uppercase_escpae(self): self.assertEqual(uppercase_escape(u'aä'), u'aä') self.assertEqual(uppercase_escape(u'\\U0001d550'), u'𝕐') if __name__ == '__main__': unit...
# -*- coding: utf-8 -*- import calendar import contextlib import ctypes import datetime
# -*- coding: utf-8 -*- import calendar import codecs import contextlib import ctypes import datetime
class PagedList(object): def uppercase_escape(s): return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: m.group(0).decode('unicode-escape'), s) try: struct.pack(u'!I', 0)
class PagedList(object): def uppercase_escape(s): unicode_escape = codecs.getdecoder('unicode_escape') return re.sub( r'\\U[0-9a-fA-F]{8}', lambda m: unicode_escape(m.group(0))[0], s) try: struct.pack(u'!I', 0)
# the maximum length for a user id is 255 characters MAX_USERID_LENGTH = 255 class Membership:
# the maximum length for a user id is 255 characters MAX_USERID_LENGTH = 255 # The maximum length for a group id is 255 characters MAX_GROUPID_LENGTH = 255 MAX_GROUP_CATEGORYID_LENGTH = 255 MAX_GROUP_ROLEID_LENGTH = 255 class Membership:
from typing import Optional, Tuple, Type import synapse from synapse.api.errors import Codes, FederationDeniedError, SynapseError from synapse.api.room_versions import RoomVersions from synapse.api.urls import (
from typing import Optional, Tuple, Type import synapse from synapse.api.constants import MAX_GROUP_CATEGORYID_LENGTH, MAX_GROUP_ROLEID_LENGTH from synapse.api.errors import Codes, FederationDeniedError, SynapseError from synapse.api.room_versions import RoomVersions from synapse.api.urls import (
async def on_POST(self, origin, content, query, group_id, category_id, room_id): raise SynapseError(403, "requester_user_id doesn't match origin") if category_id == "": raise SynapseError(400, "category_id cannot be empty string") resp = await self.handler.update_group_summary_...
async def on_POST(self, origin, content, query, group_id, category_id, room_id): raise SynapseError(403, "requester_user_id doesn't match origin") if category_id == "": raise SynapseError( 400, "category_id cannot be empty string", Codes.INVALID_PARAM ) ...
async def on_POST(self, origin, content, query, group_id, category_id): if category_id == "": raise SynapseError(400, "category_id cannot be empty string") resp = await self.handler.upsert_group_category( group_id, requester_user_id, category_id, content )
async def on_POST(self, origin, content, query, group_id, category_id): if category_id == "": raise SynapseError(400, "category_id cannot be empty string") if len(category_id) > MAX_GROUP_CATEGORYID_LENGTH: raise SynapseError( 400, "category_id ma...
async def on_POST(self, origin, content, query, group_id, role_id): raise SynapseError(403, "requester_user_id doesn't match origin") if role_id == "": raise SynapseError(400, "role_id cannot be empty string") resp = await self.handler.update_group_role( group_id, r...
async def on_POST(self, origin, content, query, group_id, role_id): raise SynapseError(403, "requester_user_id doesn't match origin") if role_id == "": raise SynapseError( 400, "role_id cannot be empty string", Codes.INVALID_PARAM ) if len(role_id) >...
async def on_POST(self, origin, content, query, group_id, role_id, user_id): if role_id == "": raise SynapseError(400, "role_id cannot be empty string") resp = await self.handler.update_group_summary_user( group_id, requester_user_id,
async def on_POST(self, origin, content, query, group_id, role_id, user_id): if role_id == "": raise SynapseError(400, "role_id cannot be empty string") if len(role_id) > MAX_GROUP_ROLEID_LENGTH: raise SynapseError( 400, "role_id may not be longer...
import logging import random from typing import Tuple from signedjson.sign import sign_json from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.metrics.background_process_metrics import run_as_background_process from synapse.types import get_domain_from_id logger = log...
import logging import random from typing import TYPE_CHECKING, Optional, Tuple from signedjson.sign import sign_json from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError from synapse.metrics.background_process_metrics import run_as_background_process from synapse.types import JsonDic...
class GroupAttestationSigning: """Creates and verifies group attestations.""" def __init__(self, hs): self.keyring = hs.get_keyring() self.clock = hs.get_clock() self.server_name = hs.hostname self.signing_key = hs.signing_key async def verify_attestation( self, att...
class GroupAttestationSigning: """Creates and verifies group attestations.""" def __init__(self, hs: "HomeServer"): self.keyring = hs.get_keyring() self.clock = hs.get_clock() self.server_name = hs.hostname self.signing_key = hs.signing_key async def verify_attestation( ...
async def verify_attestation( if valid_until_ms < now: raise SynapseError(400, "Attestation expired") await self.keyring.verify_json_for_server( server_name, attestation, now, "Group attestation" ) def create_attestation(self, group_id, user_id): """Create a...
async def verify_attestation( if valid_until_ms < now: raise SynapseError(400, "Attestation expired") assert server_name is not None await self.keyring.verify_json_for_server( server_name, attestation, now, "Group attestation" ) def create_attestation(self, ...
def create_attestation(self, group_id, user_id): class GroupAttestionRenewer: """Responsible for sending and receiving attestation updates.""" def __init__(self, hs): self.clock = hs.get_clock() self.store = hs.get_datastore() self.assestations = hs.get_groups_attestation_signing()
def create_attestation(self, group_id, user_id): class GroupAttestionRenewer: """Responsible for sending and receiving attestation updates.""" def __init__(self, hs: "HomeServer"): self.clock = hs.get_clock() self.store = hs.get_datastore() self.assestations = hs.get_groups_attestation_...
def __init__(self, hs): self._start_renew_attestations, 30 * 60 * 1000 ) async def on_renew_attestation(self, group_id, user_id, content): """When a remote updates an attestation""" attestation = content["attestation"]
def __init__(self, hs): self._start_renew_attestations, 30 * 60 * 1000 ) async def on_renew_attestation( self, group_id: str, user_id: str, content: JsonDict ) -> JsonDict: """When a remote updates an attestation""" attestation = content["attestation"]
async def on_renew_attestation(self, group_id, user_id, content): return {} def _start_renew_attestations(self): return run_as_background_process("renew_attestations", self._renew_attestations) async def _renew_attestations(self): """Called periodically to check if we need to update a...
async def on_renew_attestation(self, group_id, user_id, content): return {} def _start_renew_attestations(self) -> None: return run_as_background_process("renew_attestations", self._renew_attestations) async def _renew_attestations(self) -> None: """Called periodically to check if we ...
async def _renew_attestations(self): now + UPDATE_ATTESTATION_TIME_MS ) async def _renew_attestation(group_user: Tuple[str, str]): group_id, user_id = group_user try: if not self.is_mine_id(group_id):
async def _renew_attestations(self): now + UPDATE_ATTESTATION_TIME_MS ) async def _renew_attestation(group_user: Tuple[str, str]) -> None: group_id, user_id = group_user try: if not self.is_mine_id(group_id):
# limitations under the License. import logging from synapse.api.errors import Codes, SynapseError from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN from synapse.types import GroupID, RoomID, UserID, get_domain_from_id from synapse.util.async_helpers import concurrently_execute logger = lo...
# limitations under the License. import logging from typing import TYPE_CHECKING, Optional from synapse.api.errors import Codes, SynapseError from synapse.handlers.groups_local import GroupsLocalHandler from synapse.handlers.profile import MAX_AVATAR_URL_LEN, MAX_DISPLAYNAME_LEN from synapse.types import GroupID, Jso...
class GroupsServerWorkerHandler: def __init__(self, hs): self.hs = hs self.store = hs.get_datastore() self.room_list_handler = hs.get_room_list_handler()
class GroupsServerWorkerHandler: def __init__(self, hs: "HomeServer"): self.hs = hs self.store = hs.get_datastore() self.room_list_handler = hs.get_room_list_handler()
def __init__(self, hs): self.profile_handler = hs.get_profile_handler() async def check_group_is_ours( self, group_id, requester_user_id, and_exists=False, and_is_admin=None ): """Check that the group is ours, and optionally if it exists. If group does exist then return group. ...
def __init__(self, hs): self.profile_handler = hs.get_profile_handler() async def check_group_is_ours( self, group_id: str, requester_user_id: str, and_exists: bool = False, and_is_admin: Optional[str] = None, ) -> Optional[dict]: """Check that the group ...
async def check_group_is_ours( return group async def get_group_summary(self, group_id, requester_user_id): """Get the summary for a group as seen by requester_user_id. The group summary consists of the profile of the room, and a curated
async def check_group_is_ours( return group async def get_group_summary( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the summary for a group as seen by requester_user_id. The group summary consists of the profile of the room, and a curated
async def get_group_summary(self, group_id, requester_user_id): entry = await self.room_list_handler.generate_room_entry( room_id, len(joined_users), with_alias=False, allow_private=True ) entry = dict(entry) # so we don't change what's cached entry.pop("...
async def get_group_summary(self, group_id, requester_user_id): entry = await self.room_list_handler.generate_room_entry( room_id, len(joined_users), with_alias=False, allow_private=True ) if entry is None: continue entry = dict(entry) # s...
async def get_group_summary(self, group_id, requester_user_id): rooms.sort(key=lambda e: e.get("order", 0)) for entry in users: user_id = entry["user_id"] if not self.is_mine_id(requester_user_id): attestation = await self.store.get_remote_attestation(group_id,...
async def get_group_summary(self, group_id, requester_user_id): rooms.sort(key=lambda e: e.get("order", 0)) for user in users: user_id = user["user_id"] if not self.is_mine_id(requester_user_id): attestation = await self.store.get_remote_attestation(group_id, u...
async def get_group_summary(self, group_id, requester_user_id): "user": membership_info, } async def get_group_categories(self, group_id, requester_user_id): """Get all categories in a group (as seen by user)""" await self.check_group_is_ours(group_id, requester_user_id, and_exi...
async def get_group_summary(self, group_id, requester_user_id): "user": membership_info, } async def get_group_categories( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get all categories in a group (as seen by user)""" await self.check_group_is_ours(...
async def get_group_profile(self, group_id, requester_user_id): else: raise SynapseError(404, "Unknown group") async def get_users_in_group(self, group_id, requester_user_id): """Get the users in group as seen by requester_user_id. The ordering is arbitrary at the moment
async def get_group_profile(self, group_id, requester_user_id): else: raise SynapseError(404, "Unknown group") async def get_users_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the users in group as seen by requester_user_id. The orderi...
async def get_users_in_group(self, group_id, requester_user_id): return {"chunk": chunk, "total_user_count_estimate": len(user_results)} async def get_invited_users_in_group(self, group_id, requester_user_id): """Get the users that have been invited to a group as seen by requester_user_id. ...
async def get_users_in_group(self, group_id, requester_user_id): return {"chunk": chunk, "total_user_count_estimate": len(user_results)} async def get_invited_users_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the users that have been invited to a group a...
async def get_invited_users_in_group(self, group_id, requester_user_id): return {"chunk": user_profiles, "total_user_count_estimate": len(invited_users)} async def get_rooms_in_group(self, group_id, requester_user_id): """Get the rooms in group as seen by requester_user_id This returns ro...
async def get_invited_users_in_group(self, group_id, requester_user_id): return {"chunk": user_profiles, "total_user_count_estimate": len(invited_users)} async def get_rooms_in_group( self, group_id: str, requester_user_id: str ) -> JsonDict: """Get the rooms in group as seen by reques...
async def get_rooms_in_group(self, group_id, requester_user_id): class GroupsServerHandler(GroupsServerWorkerHandler): def __init__(self, hs): super().__init__(hs) # Ensure attestations get renewed hs.get_groups_attestation_renewer() async def update_group_summary_room( self,...
async def get_rooms_in_group(self, group_id, requester_user_id): class GroupsServerHandler(GroupsServerWorkerHandler): def __init__(self, hs: "HomeServer"): super().__init__(hs) # Ensure attestations get renewed hs.get_groups_attestation_renewer() async def update_group_summary_room(...