buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def main(): level=dict(type='str', choices=['authNoPriv', 'authPriv']), integrity=dict(type='str', choices=['md5', 'sha']), privacy=dict(type='str', choices=['aes', 'des']), authkey=dict(type='str'), privkey=dict(type='str'), ), required_togeth...
def main(): level=dict(type='str', choices=['authNoPriv', 'authPriv']), integrity=dict(type='str', choices=['md5', 'sha']), privacy=dict(type='str', choices=['aes', 'des']), authkey=dict(type='str', no_log=True), privkey=dict(type='str', no_log=True), ...
def parse(validator_string, validators=None): validators = validators or val.DefaultValidators try: tree = ast.parse(validator_string, mode='eval') # evaluate with access to a limited global scope only
def parse(validator_string, validators=None): validators = validators or val.DefaultValidators if validator_string: for validator in validators.keys(): if validator_string.startswith(validator): break else: raise SyntaxError( 'Invalid sch...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing punctuation ...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_CHARS = '.,:;!' WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible strings used for b...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) @keep_lazy(six.text_type, SafeText)
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS) if middle != stripped: trail = middle[len(stripped):] + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail words = word_split_re.split(force_text(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word:
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.m...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and is_email_simple(m...
class TestUtilsHtml(SimpleTestCase): @html.html_safe class HtmlClass(object): pass
class TestUtilsHtml(SimpleTestCase): @html.html_safe class HtmlClass(object): pass def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ('a' + '.' * 1000000) + 'a', # trailing_punc...
def ct_lt_u32(val_a, val_b): return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31 def ct_gt_u32(val_a, val_b): """ Return 1 if val_a > val_b, 0 otherwise. Constant time.
def ct_lt_u32(val_a, val_b): return (val_a^((val_a^val_b)|(((val_a-val_b)&0xffffffff)^val_b)))>>31 def ct_gt_u32(val_a, val_b): """ Return 1 if val_a > val_b, 0 otherwise. Constant time.
def ct_gt_u32(val_a, val_b): """ return ct_lt_u32(val_b, val_a) def ct_le_u32(val_a, val_b): """ Return 1 if val_a <= val_b, 0 otherwise. Constant time.
def ct_gt_u32(val_a, val_b): """ return ct_lt_u32(val_b, val_a) def ct_le_u32(val_a, val_b): """ Return 1 if val_a <= val_b, 0 otherwise. Constant time.
def ct_le_u32(val_a, val_b): """ return 1 ^ ct_gt_u32(val_a, val_b) def ct_lsb_prop_u8(val): """Propagate LSB to all 8 bits of the returned byte. Constant time.""" val &= 0x01 val |= val << 1 val |= val << 2 val |= val << 4 return val def ct_isnonzero_u32(val): """ Returns 1 if...
def ct_le_u32(val_a, val_b): """ return 1 ^ ct_gt_u32(val_a, val_b) def ct_lsb_prop_u8(val): """Propagate LSB to all 8 bits of the returned int. Constant time.""" val &= 0x01 val |= val << 1 val |= val << 2 val |= val << 4 return val def ct_lsb_prop_u16(val): """Propagate LSB to ...
def ct_isnonzero_u32(val): val &= 0xffffffff return (val|(-val&0xffffffff)) >> 31 def ct_neq_u32(val_a, val_b): """ Return 1 if val_a != val_b, 0 otherwise. Constant time.
def ct_isnonzero_u32(val): val &= 0xffffffff return (val|(-val&0xffffffff)) >> 31 def ct_neq_u32(val_a, val_b): """ Return 1 if val_a != val_b, 0 otherwise. Constant time.
def parsePEMKey(s, private=False, public=False, passwordCallback=None, def _parseKeyHelper(key, private, public): if private: if not key.hasPrivateKey(): raise SyntaxError("Not a private key!") if public: return _createPublicKey(key) if private: if hasattr(key, "d"): ...
def parsePEMKey(s, private=False, public=False, passwordCallback=None, def _parseKeyHelper(key, private, public): if private and not key.hasPrivateKey(): raise SyntaxError("Not a private key!") if public: return _createPublicKey(key) if private: if cryptomath.m2cryptoLoaded: ...
from .rsakey import * from .python_rsakey import Python_RSAKey from .compat import compatAscii2Bytes #copied from M2Crypto.util.py, so when we load the local copy of m2 #we can still use it
from .rsakey import * from .python_rsakey import Python_RSAKey from .compat import compatAscii2Bytes import sys #copied from M2Crypto.util.py, so when we load the local copy of m2 #we can still use it
def _rawPrivateKeyOp(self, message): ciphertext = bytesToNumber(bytearray(string)) return ciphertext def _rawPublicKeyOp(self, ciphertext): data = numberToByteArray(ciphertext, numBytes(self.n)) string = m2.rsa_public_decrypt(self.rsa, bytes(data),
def _rawPrivateKeyOp(self, message): ciphertext = bytesToNumber(bytearray(string)) return ciphertext def _raw_private_key_op_bytes(self, message): return bytearray(m2.rsa_private_encrypt(self.rsa, bytes(message), m2.no_padd...
def _rawPublicKeyOp(self, ciphertext): message = bytesToNumber(bytearray(string)) return message def acceptsPassword(self): return True def write(self, password=None):
def _rawPublicKeyOp(self, ciphertext): message = bytesToNumber(bytearray(string)) return message def _raw_public_key_op_bytes(self, ciphertext): return bytearray(m2.rsa_public_decrypt(self.rsa, bytes(ciphertext), m2.no_paddi...
def f():pass key._hasPrivateKey = False else: raise SyntaxError() return key finally: m2.bio_free(bio)
def f():pass key._hasPrivateKey = False else: raise SyntaxError() if key._hasPrivateKey: if sys.version_info < (3, 0): b64_key = str(key.write()) else: ...
def parsePEM(s, passwordCallback=None): elif pemSniff(s, "EC PRIVATE KEY"): bytes = dePem(s, "EC PRIVATE KEY") return Python_Key._parse_ecc_ssleay(bytes) else: raise SyntaxError("Not a PEM private key file") @staticmethod def _parse_pkcs8(bytes): pars...
def parsePEM(s, passwordCallback=None): elif pemSniff(s, "EC PRIVATE KEY"): bytes = dePem(s, "EC PRIVATE KEY") return Python_Key._parse_ecc_ssleay(bytes) elif pemSniff(s, "PUBLIC KEY"): bytes = dePem(s, "PUBLIC KEY") return Python_Key._parse_public_key(byt...
from . import tlshashlib as hashlib from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \ InvalidSignature, UnknownRSAType class RSAKey(object):
from . import tlshashlib as hashlib from ..errors import MaskTooLongError, MessageTooLongError, EncodingError, \ InvalidSignature, UnknownRSAType from .constanttime import ct_isnonzero_u32, ct_neq_u32, ct_lsb_prop_u8, \ ct_lsb_prop_u16, ct_lt_u32 class RSAKey(object):
def __init__(self, n=0, e=0, key_type="rsa"): self.e = e # pylint: enable=invalid-name self.key_type = key_type raise NotImplementedError() def __len__(self):
def __init__(self, n=0, e=0, key_type="rsa"): self.e = e # pylint: enable=invalid-name self.key_type = key_type self._key_hash = None raise NotImplementedError() def __len__(self):
def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0): :type sLen: int :param sLen: length of salt""" EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen) m = bytesToNumber(EM) if m >= self.n: raise MessageTooLongError("Encode output too long") s = self....
def RSASSA_PSS_sign(self, mHash, hAlg, sLen=0): :type sLen: int :param sLen: length of salt""" EM = self.EMSA_PSS_encode(mHash, numBits(self.n) - 1, hAlg, sLen) try: ret = self._raw_private_key_op_bytes(EM) except ValueError: raise MessageTooLongError("Enc...
def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0): :type sLen: int :param sLen: Length of salt """ if len(bytearray(S)) != len(numberToByteArray(self.n)): raise InvalidSignature("Invalid signature") s = bytesToNumber(S) m = self._rawPublicKeyOp(s) EM...
def RSASSA_PSS_verify(self, mHash, S, hAlg, sLen=0): :type sLen: int :param sLen: Length of salt """ try: EM = self._raw_public_key_op_bytes(S) except ValueError: raise InvalidSignature("Invalid signature") result = self.EMSA_PSS_verify(mHash, EM, ...
def _raw_pkcs1_sign(self, bytes): if not self.hasPrivateKey(): raise AssertionError() paddedBytes = self._addPKCS1Padding(bytes, 1) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPrivateKeyOp(m) sigBytes = numberToBy...
def _raw_pkcs1_sign(self, bytes): if not self.hasPrivateKey(): raise AssertionError() paddedBytes = self._addPKCS1Padding(bytes, 1) return self._raw_private_key_op_bytes(paddedBytes) def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None): """Sign the passed-i...
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None): def _raw_pkcs1_verify(self, sigBytes, bytes): """Perform verification operation on raw PKCS#1 padded signature""" if len(sigBytes) != numBytes(self.n): return False paddedBytes = self._addPKCS1Padding(bytes, 1) ...
def sign(self, bytes, padding='pkcs1', hashAlg=None, saltLen=None): def _raw_pkcs1_verify(self, sigBytes, bytes): """Perform verification operation on raw PKCS#1 padded signature""" try: checkBytes = self._raw_public_key_op_bytes(sigBytes) except ValueError: return F...
def encrypt(self, bytes): :returns: A PKCS1 encryption of the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 2) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPublicKeyOp(m) encBytes = numberToByteArray(c...
def encrypt(self, bytes): :returns: A PKCS1 encryption of the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 2) return self._raw_public_key_op_bytes(paddedBytes) def _dec_prf(self, key, label, out_len): """PRF for deterministic implicit rejection in the RSA d...
def _rawPrivateKeyOp(self, message): def _rawPublicKeyOp(self, ciphertext): raise NotImplementedError() def acceptsPassword(self): """Return True if the write() method accepts a password for use in encrypting the private key.
def _rawPrivateKeyOp(self, message): def _rawPublicKeyOp(self, ciphertext): raise NotImplementedError() def _raw_private_key_op_bytes(self, message): n = self.n if len(message) != numBytes(n): raise ValueError("Message has incorrect length for the key size") m_int = ...
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \ ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \ ct_check_cbc_mac_and_pad, ct_compare_digest from hypothesis import given, example import hypothesis.strategies as st
from tlslite.utils.constanttime import ct_lt_u32, ct_gt_u32, ct_le_u32, \ ct_lsb_prop_u8, ct_isnonzero_u32, ct_neq_u32, ct_eq_u32, \ ct_check_cbc_mac_and_pad, ct_compare_digest, ct_lsb_prop_u16 from hypothesis import given, example import hypothesis.strategies as st
def test_ct_lsb_prop_u8(self, i): self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff)) self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00)) @given(i=st.integers(0,2**32 - 1)) @example(i=0) def test_ct_isnonzero_u32(self, i):
def test_ct_lsb_prop_u8(self, i): self.assertEqual(((i & 0x1) == 1), (ct_lsb_prop_u8(i) == 0xff)) self.assertEqual(((i & 0x1) == 0), (ct_lsb_prop_u8(i) == 0x00)) @given(i=st.integers(0, 2**16-1)) @example(i=0) @example(i=255) @example(i=2**16-1) def test_ct_lsb_prop_u16(self, i): ...
from tlslite.utils.python_rsakey import Python_RSAKey from tlslite.utils.cryptomath import * from tlslite.errors import * try: import mock from mock import call
from tlslite.utils.python_rsakey import Python_RSAKey from tlslite.utils.cryptomath import * from tlslite.errors import * from tlslite.utils.keyfactory import parsePEMKey from tlslite.utils.compat import a2b_hex, remove_whitespace try: import mock from mock import call
def test_addPKCS1Prefix(self): self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray( b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' + b' sha-1 hash of data '))
def test_addPKCS1Prefix(self): self.assertEqual(RSAKey.addPKCS1Prefix(data, 'sha1'), bytearray( b'0!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14' + b' sha-1 hash of data ')) class TestRSADecrypt(unittest.TestCase): @classmethod def setUpClass(cls): priv_key = """ -----B...
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) def _get_corr(a, b): a = a.rolling(
class _Rolling_and_Expanding(_Rolling): # only default unset pairwise = True if pairwise is None else pairwise other = self._shallow_copy(other) window = self._get_window(other) if not self.is_freq_type else self.win_freq def _get_corr(a, b): a = a.rolling(
import warnings import pytest from pandas import DataFrame, Series import pandas._testing as tm from pandas.core.algorithms import safe_sort
import warnings import numpy as np import pytest from pandas import DataFrame, Series, date_range import pandas._testing as tm from pandas.core.algorithms import safe_sort
class TestPairwise: for i, result in enumerate(results): if i > 0: self.compare(result, results[0])
class TestPairwise: for i, result in enumerate(results): if i > 0: self.compare(result, results[0]) def test_corr_freq_memory_error(self): # GH 31789 s = Series(range(5), index=date_range("2020", periods=5)) result = s.rolling("12H").corr(s) expec...
class DataFrame(NDFrame): " or if the Series has a name" ) if other.name is None: index = None else: # other must have the same index name as self, otherwise # index name will be reset index = In...
class DataFrame(NDFrame): " or if the Series has a name" ) index = Index([other.name], name=self.index.name) idx_diff = other.index.difference(self.columns) try: combined_columns = self.columns.append(idx_diff) except T...
class TestDataFrameConcatCommon: expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) tm.assert_frame_equal(result, expected) def test_update(self): df = DataFrame( [[1.5, np.nan, 3.0], [1.5, np.nan, 3.0], [1.5, np.nan, 3], [1.5, np.nan, 3]]
class TestDataFrameConcatCommon: expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "timestamp", ["2019-07-19 07:04:57+0100", "2019-07-19 07:04:57"] ) def test_append_timestamps_aware_or_naive(self, tz_...
import grp import os import re import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import grp import os import re import platform import pty import pwd import select import shutil import socket import subprocess import time from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): output_dim = self.cell.state_size[0] else: output_dim = self.cell.state_size if self.return_sequences: output_shape = (input_shape[0], input_shape[1], out...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): state_size = self.cell.state_size else: state_size = [self.cell.state_size] output_dim = state_size[0] if self.return_sequences: output_shape = (i...
class RNN(Layer): output_shape = (input_shape[0], output_dim) if self.return_state: state_shape = [(input_shape[0], output_dim) for _ in self.states] return [output_shape] + state_shape else: return output_shape
class RNN(Layer): output_shape = (input_shape[0], output_dim) if self.return_state: state_shape = [(input_shape[0], dim) for dim in state_size] return [output_shape] + state_shape else: return output_shape
def test_stacked_rnn_attributes(): assert layer.get_losses_for(x) == [y] @rnn_test def test_batch_size_equal_one(layer_class): inputs = Input(batch_shape=(1, timesteps, embedding_dim))
def test_stacked_rnn_attributes(): assert layer.get_losses_for(x) == [y] @keras_test def test_stacked_rnn_compute_output_shape(): cells = [recurrent.LSTMCell(3), recurrent.LSTMCell(6)] layer = recurrent.RNN(cells, return_state=True, return_sequences=True) output_shape = layer.compute_outp...
def generate_tokens(readline): stashed = tok continue if token == 'def': if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
def generate_tokens(readline): stashed = tok continue if token in ('def', 'for'): if (stashed and stashed[0] == NAME and stashed[1] == 'async'): ...
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, line_length=ll, mode=mode) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff(self) -> None: source, expected = read_data("fmtonoff")
class BlackTestCase(unittest.TestCase): self.assertFormatEqual(expected, actual) black.assert_stable(source, actual, line_length=ll, mode=mode) @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: source, expected = read_data("python37") actual = fs(sour...
import warnings from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) from django.core.exceptions import TooManyFieldsSent
import warnings from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, quote, quote_plus, scheme_chars, unquote, unquote_plus, urlencode as original_urlencode, uses_params, ) from django.c...
def is_safe_url(url, host=None, allowed_hosts=None, require_https=False): _is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https)) def _is_safe_url(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlpars...
def is_safe_url(url, host=None, allowed_hosts=None, require_https=False): _is_safe_url(url.replace('\\', '/'), allowed_hosts, require_https=require_https)) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', ) for good_url in good_urls: with ignore_warnings(category=RemovedInDjango21Warning):
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: with ignore_warnings(category=RemovedInDjango21Warning):
def test_load_blp2_dxt1(): def test_load_blp2_dxt1a(): with Image.open("Tests/images/blp/blp2_dxt1a.blp") as im: assert_image_equal_tofile(im, "Tests/images/blp/blp2_dxt1a.png")
def test_load_blp2_dxt1(): def test_load_blp2_dxt1a(): with Image.open("Tests/images/blp/blp2_dxt1a.blp") as im: assert_image_equal_tofile(im, "Tests/images/blp/blp2_dxt1a.png") @pytest.mark.parametrize( "test_file", [ "Tests/images/timeout-060745d3f534ad6e4128c51d336ea5489182c69d.blp", ...
class _BLPBaseDecoder(ImageFile.PyDecoder): raise OSError("Truncated Blp file") from e return 0, 0 def _read_palette(self): ret = [] for i in range(256): try: b, g, r, a = struct.unpack("<4B", self.fd.read(4)) except struct.error: ...
class _BLPBaseDecoder(ImageFile.PyDecoder): raise OSError("Truncated Blp file") from e return 0, 0 def _safe_read(self, length): return ImageFile._safe_read(self.fd, length) def _read_palette(self): ret = [] for i in range(256): try: b, g...
class BLP1Decoder(_BLPBaseDecoder): if self._blp_encoding in (4, 5): data = bytearray() palette = self._read_palette() _data = BytesIO(self.fd.read(self._blp_lengths[0])) while True: try: (offset,) = ...
class BLP1Decoder(_BLPBaseDecoder): if self._blp_encoding in (4, 5): data = bytearray() palette = self._read_palette() _data = BytesIO(self._safe_read(self._blp_lengths[0])) while True: try: (offset,)...
class BLP1Decoder(_BLPBaseDecoder): def _decode_jpeg_stream(self): from PIL.JpegImagePlugin import JpegImageFile (jpeg_header_size,) = struct.unpack("<I", self.fd.read(4)) jpeg_header = self.fd.read(jpeg_header_size) self.fd.read(self._blp_offsets[0] - self.fd.tell()) # What IS thi...
class BLP1Decoder(_BLPBaseDecoder): def _decode_jpeg_stream(self): from PIL.JpegImagePlugin import JpegImageFile (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4)) jpeg_header = self._safe_read(jpeg_header_size) self._safe_read(self._blp_offsets[0] - self.fd.tell()) # Wh...
class BLP2Decoder(_BLPBaseDecoder): # Uncompressed or DirectX compression if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED: _data = BytesIO(self.fd.read(self._blp_lengths[0])) while True: try: (offset,) = struct.unpac...
class BLP2Decoder(_BLPBaseDecoder): # Uncompressed or DirectX compression if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED: _data = BytesIO(self._safe_read(self._blp_lengths[0])) while True: try: (offset,) = struct.un...
class BLP2Decoder(_BLPBaseDecoder): linesize = (self.size[0] + 3) // 4 * 8 for yb in range((self.size[1] + 3) // 4): for d in decode_dxt1( self.fd.read(linesize), alpha=bool(self._blp_alpha_depth) ): ...
class BLP2Decoder(_BLPBaseDecoder): linesize = (self.size[0] + 3) // 4 * 8 for yb in range((self.size[1] + 3) // 4): for d in decode_dxt1( self._safe_read(linesize), alpha=bool(self._blp_alpha_depth) ): ...
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: if left_value != right_value: return False return True
def array_equivalent(left, right, strict_nan=False): if not isinstance(right_value, float) or not np.isnan(right_value): return False else: if np.any(left_value != right_value): return False return True
def test_array_equivalent_str(): ) @pytest.mark.parametrize( "dtype, na_value", [
def test_array_equivalent_str(): ) def test_array_equivalent_nested(): # reached in groupby aggregations, make sure we use np.any when checking # if the comparison is truthy left = np.array([np.array([50, 70, 90]), np.array([20, 30, 40])], dtype=object) right = np.array([np.array([50, 70, 90]...
class HttpRequest(object): if server_port != ('443' if self.is_secure() else '80'): host = '%s:%s' % (host, server_port) # There is no hostname validation when DEBUG=True if settings.DEBUG: return host domain, port = split_domain_port(host) if do...
class HttpRequest(object): if server_port != ('443' if self.is_secure() else '80'): host = '%s:%s' % (host, server_port) # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_h...
class HostValidationTests(SimpleTestCase): request.get_host() @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_disabled_in_debug_mode(self): """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass.""" request = HttpRequest() request.META =...
class HostValidationTests(SimpleTestCase): request.get_host() @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ valid_host...
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no'
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. ...
class DnfModule(YumDnf): results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package))
class DnfModule(YumDnf): results=[], ) # Validate GPG. This is NOT done in dnf.Base (it's done in the # upstream CLI subclass of dnf.Base) if not self.disable_gpg_check: for package in self.base.transaction....
try: except AttributeError: pass _openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } #: The list of supported SSL/TLS cipher suites. DEFAULT_SSL_CIPHER_LI...
try: except AttributeError: pass _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict( (v, k) for k, v in _st...
class PyOpenSSLContext(object): @property def verify_mode(self): return self._ctx.get_verify_mode() @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify(value, _verify_callback) def set_default_verify_paths(self): self._ctx.set_default_verify_paths()
class PyOpenSSLContext(object): @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify( _stdlib_to_openssl_verify[value], _verify_callback ) def set_d...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locations(ca_ce...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locat...
class Block(PandasObject): # length checking check_setitem_lengths(indexer, value, values) if is_empty_indexer(indexer, arr_value): # GH#8669 empty indexers pass
class Block(PandasObject): # length checking check_setitem_lengths(indexer, value, values) exact_match = ( len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and arr_value.size == values.size ) if is_empty_indexer(indexer, arr_valu...
class Block(PandasObject): # be e.g. a list; see GH#6043 values[indexer] = value # if we are an exact match (ex-broadcasting), # then use the resultant dtype elif ( len(arr_value.shape) and arr_value.shape[0] == values.shape[0] and ar...
class Block(PandasObject): # be e.g. a list; see GH#6043 values[indexer] = value elif ( exact_match and is_categorical_dtype(arr_value.dtype) and not is_categorical_dtype(values) ): # GH25495 - If the current dtype is not categori...
class TestDataFrameIndexingCategorical: df.value, range(0, 105, 10), right=False, labels=labels ) def test_loc_indexing_preserves_index_category_dtype(self): # GH 15166 df = DataFrame(
class TestDataFrameIndexingCategorical: df.value, range(0, 105, 10), right=False, labels=labels ) def test_setitem_single_row_categorical(self): # GH 25495 df = DataFrame({"Alpha": ["a"], "Numeric": [0]}) categories = pd.Categorical(df["Alpha"], categories=["a", ...
import logging import salt.utils.files import salt.utils.path import salt.payload from salt.ext import six
import logging import salt.utils.files import salt.utils.path import salt.utils.verify import salt.payload from salt.ext import six
def get_token(opts, tok): :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(opts)
def get_token(opts, tok): :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not salt.utils.verify.clean_path(opts['token_dir'], t_path): return {} if not os.path.isfile(t_path): return {} serial = salt.payload.Serial(op...
import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.user log = logging.getLogger(__name__)
import salt.utils.files import salt.utils.path import salt.utils.platform import salt.utils.user import salt.ext.six log = logging.getLogger(__name__)
def check_max_open_files(opts): log.log(level=level, msg=msg) def clean_path(root, path, subdir=False): ''' Accepts the root the path needs to be under and verifies that the path is under said root. Pass in subdir=True if the path can result in a subdirectory of the root instead of having to resid...
def check_max_open_files(opts): log.log(level=level, msg=msg) def _realpath_darwin(path): base = '' for part in path.split(os.path.sep)[1:]: if base != '': if os.path.islink(os.path.sep.join([base, part])): base = os.readlink(os.path.sep.join([base, part])) ...
def update_config(file_name, yaml_contents): dir_path = os.path.join(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) try: yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False) if not os.path.exists(dir_path): ...
def update_config(file_name, yaml_contents): dir_path = os.path.join(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) try: yaml_out = salt.utils.yaml.safe_dump( yaml_contents, default_flow_style=False, ) if not os....
def find(path, saltenv='base'): return ret for root in __opts__['file_roots'][saltenv]: full = os.path.join(root, path) if os.path.isfile(full): # Add it to the dict with salt.utils.files.fopen(full, 'rb') as fp_:
def find(path, saltenv='base'): return ret for root in __opts__['file_roots'][saltenv]: full = os.path.join(root, path) if not salt.utils.verify.clean_path(root, full): continue if os.path.isfile(full): # Add it to the dict with salt.utils.files.fo...
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) dest = os.path.join(__opts__['file_roots'][saltenv][index], path) dest_dir = os.path.dirname(dest) if not os.p...
def write(data, path, saltenv='base', index=0): if os.path.isabs(path): return ('The path passed in {0} is not relative to the environment ' '{1}').format(path, saltenv) root = __opts__['file_roots'][saltenv][index] dest = os.path.join(root, path) if not salt.utils.verify.clean_p...
class ClearFuncsPubTestCase(TestCase): ret_evt = raw break assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsPubTestCase(TestCase): ret_evt = raw break assert not os.path.exists(self.tmpfile), 'Evil file created' class ClearFuncsConfigTest(TestCase): def setUp(self): master_opts = AdaptedConfigurationTestCaseMixin.get_config('master') self.conf_dir...
class BadTestModuleNamesTestCase(TestCase): 'integration.loader.test_ext_modules', 'integration.logging.test_jid_logging', 'integration.master.test_event_return', 'integration.minion.test_blackout', 'integration.minion.test_pillar', 'integration.mi...
class BadTestModuleNamesTestCase(TestCase): 'integration.loader.test_ext_modules', 'integration.logging.test_jid_logging', 'integration.master.test_event_return', 'integration.master.test_clear_funcs', 'integration.minion.test_blackout', 'integrati...
import stat import shutil import tempfile import socket # Import third party libs if sys.platform.startswith('win'):
import stat import shutil import tempfile import socket import ctypes # Import third party libs if sys.platform.startswith('win'):
from salt.utils.verify import ( verify_log, verify_logs_filter, verify_log_files, ) # Import 3rd-party libs
from salt.utils.verify import ( verify_log, verify_logs_filter, verify_log_files, clean_path ) # Import 3rd-party libs
class TestVerifyLog(TestCase): self.assertFalse(os.path.exists(path)) verify_log_files([path], getpass.getuser()) self.assertTrue(os.path.exists(path))
class TestVerifyLog(TestCase): self.assertFalse(os.path.exists(path)) verify_log_files([path], getpass.getuser()) self.assertTrue(os.path.exists(path)) class TestCleanPath(TestCase): ''' salt.utils.clean_path works as expected ''' def setUp(self): self.tmpdir = tempfil...
def is_safe_url(url, host=None): url = url.strip() if not url: return False # Chrome treats \ completely as / url = url.replace('\\', '/') # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsa...
def is_safe_url(url, host=None): url = url.strip() if not url: return False # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def ...
class TestUtilsHttp(unittest.TestCase): 'javascript:alert("XSS")', '\njavascript:alert(x)', '\x08//example.com', '\n'): self.assertFalse(http.is_safe_url(bad_url, host='testserver'), "%s should be blocked" % bad_...
class TestUtilsHttp(unittest.TestCase): 'javascript:alert("XSS")', '\njavascript:alert(x)', '\x08//example.com', r'http://otherserver\@example.com', r'http:\\testserver\@example.com', ...
class TestUtilsHttp(unittest.TestCase): 'https://testserver/', 'HTTPS://testserver/', '//testserver/', '/url%20with%20spaces/'): self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur...
class TestUtilsHttp(unittest.TestCase): 'https://testserver/', 'HTTPS://testserver/', '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/'): self.assertTrue(http.is_...
class Response(object_ref): """ if isinstance(url, Link): url = url.url url = self.urljoin(url) return Request(url, callback, method=method,
class Response(object_ref): """ if isinstance(url, Link): url = url.url elif url is None: raise ValueError("url can't be None") url = self.urljoin(url) return Request(url, callback, method=method,
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_whitespace_url(self): self._assert_followed_url('foo ', 'http://example.com/foo%20')
class BaseResponseTest(unittest.TestCase): self._assert_followed_url(Link('http://example.com/foo'), 'http://example.com/foo') def test_follow_None_url(self): r = self.response_class("http://example.com") self.assertRaises(ValueError, r.follow, None) d...
class MinimumLengthValidator: ) % {'min_length': self.min_length} class UserAttributeSimilarityValidator: """ Validate that the password is sufficiently different from the user's
class MinimumLengthValidator: ) % {'min_length': self.min_length} def exceeds_maximum_length_ratio(password, max_similarity, value): """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing SequenceMatcher like this: for i in ran...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for att...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes if max_similarity < 0.1: raise ValueError('max_similarity must be at least 0.1') self.max_similarity = max_similarity ...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=0 rejects all passwords. with self.assertRaises(ValidationError) as...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # Very low max_similarity is rejected. msg = 'max_similarity must be at least 0.1' ...
def _period_array_cmp(cls, op): @unpack_zerodim_and_defer(opname) def wrapper(self, other): ordinal_op = getattr(self.asi8, opname) if isinstance(other, str): try:
def _period_array_cmp(cls, op): @unpack_zerodim_and_defer(opname) def wrapper(self, other): if isinstance(other, str): try:
def _period_array_cmp(cls, op): except ValueError: # string that can't be parsed as Period return invalid_comparison(self, other, op) elif isinstance(other, int): # TODO: sure we want to allow this? we dont for DTA/TDA # 2 tests rely on this ...
def _period_array_cmp(cls, op): except ValueError: # string that can't be parsed as Period return invalid_comparison(self, other, op) if isinstance(other, self._recognized_scalars) or other is NaT: other = self._scalar_type(other)
class TestPeriodArrayLikeComparisons: class TestPeriodIndexComparisons: # TODO: parameterize over boxes @pytest.mark.parametrize("other", ["2017", 2017]) def test_eq(self, other): idx = PeriodIndex(["2017", "2017", "2018"], freq="D") expected = np.array([True, True, False])
class TestPeriodArrayLikeComparisons: class TestPeriodIndexComparisons: # TODO: parameterize over boxes @pytest.mark.parametrize("other", ["2017", pd.Period("2017", freq="D")]) def test_eq(self, other): idx = PeriodIndex(["2017", "2017", "2018"], freq="D") expected = np.array([True, True, F...
class TestPeriodIndexComparisons: tm.assert_numpy_array_equal(result, expected) def test_pi_cmp_period(self): idx = period_range("2007-01", periods=20, freq="M")
class TestPeriodIndexComparisons: tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize( "other", [ 2017, [2017, 2017, 2017], np.array([2017, 2017, 2017]), np.array([2017, 2017, 2017], dtype=object), pd.Index([201...
class TestPeriodIndex(DatetimeLike): ts = Series(np.random.randn(len(idx)), index=idx) result = ts[2007] expected = ts[idx == 2007] tm.assert_series_equal(result, expected) def test_index_unique(self):
class TestPeriodIndex(DatetimeLike): ts = Series(np.random.randn(len(idx)), index=idx) result = ts[2007] expected = ts[idx == "2007"] tm.assert_series_equal(result, expected) def test_index_unique(self):
# All kinds of schemes besides just javascript: that can cause # execution: _is_image_dataurl = re.compile( r'^data:image/.+;base64', re.I).search _is_possibly_malicious_scheme = re.compile( r'(?:javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).search def _is_javascript_scheme(s): if _...
# All kinds of schemes besides just javascript: that can cause # execution: _find_image_dataurls = re.compile( r'^data:image/(.+);base64,', re.I).findall _is_possibly_malicious_scheme = re.compile( r'(javascript|jscript|livescript|vbscript|data|about|mocha):', re.I).findall # SVG images can contain script ...
import unittest from lxml.tests.common_imports import make_doctest
import base64 import gzip import unittest from lxml.tests.common_imports import make_doctest
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_formaction_attribute_in_button_input(self): # The formaction attribute overrides the form's action and should be # treated as a malicious link attribute
def test_sneaky_import_in_style(self): cleaned, "%s -> %s" % (style_code, cleaned)) def test_svg_data_links(self): # Remove SVG images with potentially insecure content. svg = b'<svg onload="alert(123)" />' svgz = gzip.compress(svg) svg_b64 = base64...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') ...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, ) if six.PY2: from urlparse import ( ParseResult, SplitRes...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def _is_safe_url(url, host): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.starts...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur...
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver...
See documentation in docs/topics/item.rst from pprint import pformat from collections import MutableMapping from abc import ABCMeta import six
See documentation in docs/topics/item.rst from pprint import pformat from collections import MutableMapping from abc import ABCMeta import six
class ItemMeta(ABCMeta): new_bases = tuple(base._class for base in bases if hasattr(base, '_class')) _class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs) fields = {} new_attrs = {} for n in dir(_class): v = getattr(_class, n)
class ItemMeta(ABCMeta): new_bases = tuple(base._class for base in bases if hasattr(base, '_class')) _class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs) fields = getattr(_class, 'fields', {}) new_attrs = {} for n in dir(_class): v = getatt...
class ItemTest(unittest.TestCase): self.assertSortedEqual(list(i.keys()), ['keys', 'values', 'name']) self.assertSortedEqual(list(i.values()), [u'Keys', u'Values', u'John']) def test_metaclass_inheritance(self): class BaseItem(Item): name = Field()
class ItemTest(unittest.TestCase): self.assertSortedEqual(list(i.keys()), ['keys', 'values', 'name']) self.assertSortedEqual(list(i.values()), [u'Keys', u'Values', u'John']) def test_metaclass_with_fields_attribute(self): class TestItem(Item): fields = {'new': Field(default='X')...
class ItemTest(unittest.TestCase): def test_metaclass_multiple_inheritance_simple(self): class A(Item): save = Field(default='A') class B(A): pass class C(Item): save = Field(default='C') class D(B, C): pass self.assertEqual(D(save='X')['save'], '...
class ItemTest(unittest.TestCase): def test_metaclass_multiple_inheritance_simple(self): class A(Item): fields = {'load': Field(default='A')} save = Field(default='A') class B(A): pass class C(Item): fields = {'load': Field(default='C')} sav...