function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def testDeterminismParameters(self, message_module): # This message is always deterministically serialized, even if determinism # is disabled, so we can use it to verify that all the determinism # parameters work correctly. golden_data = (b'\xe2\x02\nOne string' b'\xe2\x02\nTwo string' b'\xe2\x02\nRed string' b'\xe2\x02\x0bBlue string') golden_message = message_module.TestAllTypes() golden_message.repeated_string.extend([ 'One string', 'Two string', 'Red string', 'Blue string', ]) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=None)) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=False)) self.assertEqual(golden_data, golden_message.SerializeToString(deterministic=True)) class BadArgError(Exception): pass class BadArg(object): def __nonzero__(self): raise BadArgError() def __bool__(self): raise BadArgError() with self.assertRaises(BadArgError): golden_message.SerializeToString(deterministic=BadArg())
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testPickleNestedMessage(self, message_module): golden_message = message_module.TestPickleNestedMessage.NestedMessage(bb=1) pickled_message = pickle.dumps(golden_message) unpickled_message = pickle.loads(pickled_message) self.assertEqual(unpickled_message, golden_message)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testPositiveInfinity(self, message_module): if message_module is unittest_pb2: golden_data = (b'\x5D\x00\x00\x80\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF0\x7F' b'\xCD\x02\x00\x00\x80\x7F' b'\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\x7F') else: golden_data = (b'\x5D\x00\x00\x80\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF0\x7F' b'\xCA\x02\x04\x00\x00\x80\x7F' b'\xD2\x02\x08\x00\x00\x00\x00\x00\x00\xF0\x7F') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsPosInf(golden_message.optional_float)) self.assertTrue(IsPosInf(golden_message.optional_double)) self.assertTrue(IsPosInf(golden_message.repeated_float[0])) self.assertTrue(IsPosInf(golden_message.repeated_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString())
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testNotANumber(self, message_module): golden_data = (b'\x5D\x00\x00\xC0\x7F' b'\x61\x00\x00\x00\x00\x00\x00\xF8\x7F' b'\xCD\x02\x00\x00\xC0\x7F' b'\xD1\x02\x00\x00\x00\x00\x00\x00\xF8\x7F') golden_message = message_module.TestAllTypes() golden_message.ParseFromString(golden_data) self.assertTrue(isnan(golden_message.optional_float)) self.assertTrue(isnan(golden_message.optional_double)) self.assertTrue(isnan(golden_message.repeated_float[0])) self.assertTrue(isnan(golden_message.repeated_double[0])) # The protocol buffer may serialize to any one of multiple different # representations of a NaN. Rather than verify a specific representation, # verify the serialized string can be converted into a correctly # behaving protocol buffer. serialized = golden_message.SerializeToString() message = message_module.TestAllTypes() message.ParseFromString(serialized) self.assertTrue(isnan(message.optional_float)) self.assertTrue(isnan(message.optional_double)) self.assertTrue(isnan(message.repeated_float[0])) self.assertTrue(isnan(message.repeated_double[0]))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testNegativeInfinityPacked(self, message_module): golden_data = (b'\xA2\x06\x04\x00\x00\x80\xFF' b'\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\xFF') golden_message = message_module.TestPackedTypes() golden_message.ParseFromString(golden_data) self.assertTrue(IsNegInf(golden_message.packed_float[0])) self.assertTrue(IsNegInf(golden_message.packed_double[0])) self.assertEqual(golden_data, golden_message.SerializeToString())
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtremeFloatValues(self, message_module): message = message_module.TestAllTypes() # Most positive exponent, no significand bits set. kMostPosExponentNoSigBits = math.pow(2, 127) message.optional_float = kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostPosExponentNoSigBits) # Most positive exponent, one significand bit set. kMostPosExponentOneSigBit = 1.5 * math.pow(2, 127) message.optional_float = kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostPosExponentOneSigBit) # Repeat last two cases with values of same magnitude, but negative. message.optional_float = -kMostPosExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostPosExponentNoSigBits) message.optional_float = -kMostPosExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostPosExponentOneSigBit) # Most negative exponent, no significand bits set. kMostNegExponentNoSigBits = math.pow(2, -127) message.optional_float = kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostNegExponentNoSigBits) # Most negative exponent, one significand bit set. kMostNegExponentOneSigBit = 1.5 * math.pow(2, -127) message.optional_float = kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == kMostNegExponentOneSigBit) # Repeat last two cases with values of the same magnitude, but negative. message.optional_float = -kMostNegExponentNoSigBits message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostNegExponentNoSigBits) message.optional_float = -kMostNegExponentOneSigBit message.ParseFromString(message.SerializeToString()) self.assertTrue(message.optional_float == -kMostNegExponentOneSigBit) # Max 4 bytes float value max_float = float.fromhex('0x1.fffffep+127') message.optional_float = max_float self.assertAlmostEqual(message.optional_float, max_float) serialized_data = message.SerializeToString() message.ParseFromString(serialized_data) self.assertAlmostEqual(message.optional_float, max_float) # Test set double to float field. message.optional_float = 3.4028235e+39 self.assertEqual(message.optional_float, float('inf')) serialized_data = message.SerializeToString() message.ParseFromString(serialized_data) self.assertEqual(message.optional_float, float('inf')) message.optional_float = -3.4028235e+39 self.assertEqual(message.optional_float, float('-inf')) message.optional_float = 1.4028235e-39 self.assertAlmostEqual(message.optional_float, 1.4028235e-39)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testFloatPrinting(self, message_module): message = message_module.TestAllTypes() message.optional_float = 2.0 self.assertEqual(str(message), 'optional_float: 2.0\n')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testHighPrecisionDoublePrinting(self, message_module): msg = message_module.TestAllTypes() msg.optional_double = 0.12345678912345678 if sys.version_info >= (3,): self.assertEqual(str(msg), 'optional_double: 0.12345678912345678\n') else: self.assertEqual(str(msg), 'optional_double: 0.123456789123\n')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testAppendRepeatedCompositeField(self, message_module): msg = message_module.TestAllTypes() msg.repeated_nested_message.append( message_module.TestAllTypes.NestedMessage(bb=1)) nested = message_module.TestAllTypes.NestedMessage(bb=2) msg.repeated_nested_message.append(nested) try: msg.repeated_nested_message.append(1) except TypeError: pass self.assertEqual(2, len(msg.repeated_nested_message)) self.assertEqual([1, 2], [m.bb for m in msg.repeated_nested_message])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromRepeatedField(self, message_module): msg = message_module.TestAllTypes() msg.repeated_int32.append(1) msg.repeated_int32.append(3) msg.repeated_nested_message.add(bb=1) msg.repeated_nested_message.add(bb=2) other_msg = message_module.TestAllTypes() other_msg.repeated_nested_message.add(bb=3) other_msg.repeated_nested_message.add(bb=4) other_msg.repeated_int32.append(5) other_msg.repeated_int32.append(7) msg.repeated_int32.MergeFrom(other_msg.repeated_int32) self.assertEqual(4, len(msg.repeated_int32)) msg.repeated_nested_message.MergeFrom(other_msg.repeated_nested_message) self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedContains(self, message_module): msg = message_module.TestAllTypes() msg.repeated_int32.extend([1, 2, 3]) self.assertIn(2, msg.repeated_int32) self.assertNotIn(0, msg.repeated_int32) msg.repeated_nested_message.add(bb=1) sub_msg1 = msg.repeated_nested_message[0] sub_msg2 = message_module.TestAllTypes.NestedMessage(bb=2) sub_msg3 = message_module.TestAllTypes.NestedMessage(bb=3) msg.repeated_nested_message.append(sub_msg2) msg.repeated_nested_message.insert(0, sub_msg3) self.assertIn(sub_msg1, msg.repeated_nested_message) self.assertIn(sub_msg2, msg.repeated_nested_message) self.assertIn(sub_msg3, msg.repeated_nested_message)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedNestedFieldIteration(self, message_module): msg = message_module.TestAllTypes() msg.repeated_nested_message.add(bb=1) msg.repeated_nested_message.add(bb=2) msg.repeated_nested_message.add(bb=3) msg.repeated_nested_message.add(bb=4) self.assertEqual([1, 2, 3, 4], [m.bb for m in msg.repeated_nested_message]) self.assertEqual([4, 3, 2, 1], [m.bb for m in reversed(msg.repeated_nested_message)]) self.assertEqual([4, 3, 2, 1], [m.bb for m in msg.repeated_nested_message[::-1]])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSortingRepeatedScalarFieldsCustomComparator(self, message_module): """Check some different types with custom comparator.""" message = message_module.TestAllTypes() message.repeated_int32.append(-3) message.repeated_int32.append(-2) message.repeated_int32.append(-1) message.repeated_int32.sort(key=abs) self.assertEqual(message.repeated_int32[0], -1) self.assertEqual(message.repeated_int32[1], -2) self.assertEqual(message.repeated_int32[2], -3) message.repeated_string.append('aaa') message.repeated_string.append('bb') message.repeated_string.append('c') message.repeated_string.sort(key=len) self.assertEqual(message.repeated_string[0], 'c') self.assertEqual(message.repeated_string[1], 'bb') self.assertEqual(message.repeated_string[2], 'aaa')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSortingRepeatedCompositeFieldsStable(self, message_module): """Check passing a custom comparator to sort a repeated composite field.""" message = message_module.TestAllTypes() message.repeated_nested_message.add().bb = 21 message.repeated_nested_message.add().bb = 20 message.repeated_nested_message.add().bb = 13 message.repeated_nested_message.add().bb = 33 message.repeated_nested_message.add().bb = 11 message.repeated_nested_message.add().bb = 24 message.repeated_nested_message.add().bb = 10 message.repeated_nested_message.sort(key=lambda z: z.bb // 10) self.assertEqual( [13, 11, 10, 21, 20, 24, 33], [n.bb for n in message.repeated_nested_message]) # Make sure that for the C++ implementation, the underlying fields # are actually reordered. pb = message.SerializeToString() message.Clear() message.MergeFromString(pb) self.assertEqual( [13, 11, 10, 21, 20, 24, 33], [n.bb for n in message.repeated_nested_message])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedScalarFieldSortArguments(self, message_module): """Check sorting a scalar field using list.sort() arguments.""" message = message_module.TestAllTypes() message.repeated_int32.append(-3) message.repeated_int32.append(-2) message.repeated_int32.append(-1) message.repeated_int32.sort(key=abs) self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) message.repeated_int32.sort(key=abs, reverse=True) self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) if sys.version_info < (3,): # No cmp sorting in PY3. abs_cmp = lambda a, b: cmp(abs(a), abs(b)) message.repeated_int32.sort(sort_function=abs_cmp) self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) message.repeated_int32.sort(cmp=abs_cmp, reverse=True) self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) message.repeated_string.append('aaa') message.repeated_string.append('bb') message.repeated_string.append('c') message.repeated_string.sort(key=len) self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) message.repeated_string.sort(key=len, reverse=True) self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c']) if sys.version_info < (3,): # No cmp sorting in PY3. len_cmp = lambda a, b: cmp(len(a), len(b)) message.repeated_string.sort(sort_function=len_cmp) self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) message.repeated_string.sort(cmp=len_cmp, reverse=True) self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c'])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedFieldsAreSequences(self, message_module): m = message_module.TestAllTypes() self.assertIsInstance(m.repeated_int32, collections_abc.MutableSequence) self.assertIsInstance(m.repeated_nested_message, collections_abc.MutableSequence)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedFieldInsideNestedMessage(self, message_module): m = message_module.NestedTestAllTypes() m.payload.repeated_int32.extend([]) self.assertTrue(m.HasField('payload'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromString(self, message_module): m1 = message_module.TestAllTypes() m2 = message_module.TestAllTypes() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual(0, m1.optional_nested_message.bb) m2.optional_nested_message.bb = 1 # Make sure cmessage pointing to a mutable message after merge instead of # the lazily created message. m1.MergeFromString(m2.SerializeToString()) self.assertEqual(1, m1.optional_nested_message.bb)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromStringUsingMemoryViewWorksInPy3(self, message_module): m2 = message_module.TestAllTypes() m2.optional_string = 'scalar string' m2.repeated_string.append('repeated string') m2.optional_bytes = b'scalar bytes' m2.repeated_bytes.append(b'repeated bytes') serialized = m2.SerializeToString() memview = memoryview(serialized) m1 = message_module.TestAllTypes.FromString(memview) self.assertEqual(m1.optional_bytes, b'scalar bytes') self.assertEqual(m1.repeated_bytes, [b'repeated bytes']) self.assertEqual(m1.optional_string, 'scalar string') self.assertEqual(m1.repeated_string, ['repeated string']) # Make sure that the memoryview was correctly converted to bytes, and # that a sub-sliced memoryview is not being used. self.assertIsInstance(m1.optional_bytes, bytes) self.assertIsInstance(m1.repeated_bytes[0], bytes) self.assertIsInstance(m1.optional_string, six.text_type) self.assertIsInstance(m1.repeated_string[0], six.text_type)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromStringUsingMemoryViewIsPy2Error(self, message_module): memview = memoryview(b'') with self.assertRaises(TypeError): message_module.TestAllTypes.FromString(memview)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def ensureNestedMessageExists(self, msg, attribute): """Make sure that a nested message object exists. As soon as a nested message attribute is accessed, it will be present in the _fields dict, without being marked as actually being set. """ getattr(msg, attribute) self.assertFalse(msg.HasField(attribute))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofDefaultValues(self, message_module): m = message_module.TestAllTypes() self.assertIs(None, m.WhichOneof('oneof_field')) self.assertFalse(m.HasField('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) # Oneof is set even when setting it to a default value. m.oneof_uint32 = 0 self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_field')) self.assertTrue(m.HasField('oneof_uint32')) self.assertFalse(m.HasField('oneof_string')) m.oneof_string = "" self.assertEqual('oneof_string', m.WhichOneof('oneof_field')) self.assertTrue(m.HasField('oneof_string')) self.assertFalse(m.HasField('oneof_uint32'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofCompositeFieldReadAccess(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 self.ensureNestedMessageExists(m, 'oneof_nested_message') self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field')) self.assertEqual(11, m.oneof_uint32)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofClearField(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m.ClearField('oneof_field') if message_module is unittest_pb2: self.assertFalse(m.HasField('oneof_field')) self.assertFalse(m.HasField('oneof_uint32')) self.assertIs(None, m.WhichOneof('oneof_field'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofClearUnsetField(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 self.ensureNestedMessageExists(m, 'oneof_nested_message') m.ClearField('oneof_nested_message') self.assertEqual(11, m.oneof_uint32) if message_module is unittest_pb2: self.assertTrue(m.HasField('oneof_field')) self.assertTrue(m.HasField('oneof_uint32')) self.assertEqual('oneof_uint32', m.WhichOneof('oneof_field'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofCopyFrom(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m2 = message_module.TestAllTypes() m2.CopyFrom(m) self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofMessageMergeFrom(self, message_module): m = message_module.NestedTestAllTypes() m.payload.oneof_nested_message.bb = 11 m.child.payload.oneof_nested_message.bb = 12 m2 = message_module.NestedTestAllTypes() m2.payload.oneof_uint32 = 13 m2.MergeFrom(m) self.assertEqual('oneof_nested_message', m2.payload.WhichOneof('oneof_field')) self.assertEqual('oneof_nested_message', m2.child.payload.WhichOneof('oneof_field'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testOneofClear(self, message_module): m = message_module.TestAllTypes() m.oneof_uint32 = 11 m.Clear() self.assertIsNone(m.WhichOneof('oneof_field')) m.oneof_bytes = b'bb' self.assertEqual('oneof_bytes', m.WhichOneof('oneof_field'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testLongValuedSlice(self, message_module): """It should be possible to use long-valued indices in slices. This didn't used to work in the v2 C++ implementation. """ m = message_module.TestAllTypes() # Repeated scalar m.repeated_int32.append(1) sl = m.repeated_int32[long(0):long(len(m.repeated_int32))] self.assertEqual(len(m.repeated_int32), len(sl)) # Repeated composite m.repeated_nested_message.add().bb = 3 sl = m.repeated_nested_message[long(0):long(len(m.repeated_nested_message))] self.assertEqual(len(m.repeated_nested_message), len(sl))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendInt32WithNothing(self, message_module): """Test no-ops extending repeated int32 fields.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_int32) # TODO(ptucker): Deprecate this behavior. b/18413862 for falsy_value in MessageTest.FALSY_VALUES: m.repeated_int32.extend(falsy_value) self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend([]) self.assertSequenceEqual([], m.repeated_int32)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendStringWithNothing(self, message_module): """Test no-ops extending repeated string fields.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) # TODO(ptucker): Deprecate this behavior. b/18413862 for falsy_value in MessageTest.FALSY_VALUES: m.repeated_string.extend(falsy_value) self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend([]) self.assertSequenceEqual([], m.repeated_string)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendFloatWithPythonList(self, message_module): """Test extending repeated float fields with python lists.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_float) m.repeated_float.extend([0.0]) self.assertSequenceEqual([0.0], m.repeated_float) m.repeated_float.extend([1.0, 2.0]) self.assertSequenceEqual([0.0, 1.0, 2.0], m.repeated_float) m.repeated_float.extend([3.0, 4.0]) self.assertSequenceEqual([0.0, 1.0, 2.0, 3.0, 4.0], m.repeated_float)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendStringWithString(self, message_module): """Test extending repeated string fields with characters from a string.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend('abc') self.assertSequenceEqual(['a', 'b', 'c'], m.repeated_string)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def __init__(self, values=None): self._list = values or []
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def __len__(self): return len(self._list)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendInt32WithIterable(self, message_module): """Test extending repeated int32 fields with iterable.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([0])) self.assertSequenceEqual([0], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([1, 2])) self.assertSequenceEqual([0, 1, 2], m.repeated_int32) m.repeated_int32.extend(MessageTest.TestIterable([3, 4])) self.assertSequenceEqual([0, 1, 2, 3, 4], m.repeated_int32)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testExtendStringWithIterable(self, message_module): """Test extending repeated string fields with iterable.""" m = message_module.TestAllTypes() self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable([])) self.assertSequenceEqual([], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable([''])) self.assertSequenceEqual([''], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable(['1', '2'])) self.assertSequenceEqual(['', '1', '2'], m.repeated_string) m.repeated_string.extend(MessageTest.TestIterable(['3', '4'])) self.assertSequenceEqual(['', '1', '2', '3', '4'], m.repeated_string)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSortEmptyRepeatedCompositeContainer(self, message_module): """Exercise a scenario that has led to segfaults in the past. """ m = message_module.TestAllTypes() m.repeated_nested_message.sort()
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedScalarFieldPop(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(IndexError) as _: m.repeated_int32.pop() m.repeated_int32.extend(range(5)) self.assertEqual(4, m.repeated_int32.pop()) self.assertEqual(0, m.repeated_int32.pop(0)) self.assertEqual(2, m.repeated_int32.pop(1)) self.assertEqual([1, 3], m.repeated_int32)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testRepeatedCompareWithSelf(self, message_module): m = message_module.TestAllTypes() for i in range(5): m.repeated_int32.insert(i, i) n = m.repeated_nested_message.add() n.bb = i self.assertSequenceEqual(m.repeated_int32, m.repeated_int32) self.assertEqual(m.repeated_nested_message, m.repeated_nested_message)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSetRepeatedComposite(self, message_module): m = message_module.TestAllTypes() with self.assertRaises(AttributeError): m.repeated_int32 = [] m.repeated_int32.append(1) with self.assertRaises(AttributeError): m.repeated_int32 = []
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testFieldPresence(self): message = unittest_pb2.TestAllTypes() self.assertFalse(message.HasField("optional_int32")) self.assertFalse(message.HasField("optional_bool")) self.assertFalse(message.HasField("optional_nested_message")) with self.assertRaises(ValueError): message.HasField("field_doesnt_exist") with self.assertRaises(ValueError): message.HasField("repeated_int32") with self.assertRaises(ValueError): message.HasField("repeated_nested_message") self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb) # Fields are set even when setting the values to default values. message.optional_int32 = 0 message.optional_bool = False message.optional_nested_message.bb = 0 self.assertTrue(message.HasField("optional_int32")) self.assertTrue(message.HasField("optional_bool")) self.assertTrue(message.HasField("optional_nested_message")) # Set the fields to non-default values. message.optional_int32 = 5 message.optional_bool = True message.optional_nested_message.bb = 15 self.assertTrue(message.HasField(u"optional_int32")) self.assertTrue(message.HasField("optional_bool")) self.assertTrue(message.HasField("optional_nested_message")) # Clearing the fields unsets them and resets their value to default. message.ClearField("optional_int32") message.ClearField(u"optional_bool") message.ClearField("optional_nested_message") self.assertFalse(message.HasField("optional_int32")) self.assertFalse(message.HasField("optional_bool")) self.assertFalse(message.HasField("optional_nested_message")) self.assertEqual(0, message.optional_int32) self.assertEqual(False, message.optional_bool) self.assertEqual(0, message.optional_nested_message.bb)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testUnknownEnumMap(self): m = map_proto2_unittest_pb2.TestEnumMap() m.known_map_field[123] = 0 with self.assertRaises(ValueError): m.unknown_map_field[1] = 123
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromExtensions(self): msg1 = more_extensions_pb2.TopLevelMessage() msg2 = more_extensions_pb2.TopLevelMessage() # Cpp extension will lazily create a sub message which is immutable. self.assertEqual(0, msg1.submessage.Extensions[ more_extensions_pb2.optional_int_extension]) self.assertFalse(msg1.HasField('submessage')) msg2.submessage.Extensions[ more_extensions_pb2.optional_int_extension] = 123 # Make sure cmessage and extensions pointing to a mutable message # after merge instead of the lazily created message. msg1.MergeFrom(msg2) self.assertEqual(123, msg1.submessage.Extensions[ more_extensions_pb2.optional_int_extension])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testGoldenPackedExtensions(self): golden_data = test_util.GoldenFileData('golden_packed_fields_message') golden_message = unittest_pb2.TestPackedExtensions() golden_message.ParseFromString(golden_data) all_set = unittest_pb2.TestPackedExtensions() test_util.SetAllPackedExtensions(all_set) self.assertEqual(all_set, golden_message) self.assertEqual(golden_data, all_set.SerializeToString()) golden_copy = copy.deepcopy(golden_message) self.assertEqual(golden_data, golden_copy.SerializeToString())
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testParsingMerge(self): """Check the merge behavior when a required or optional field appears multiple times in the input.""" messages = [ unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes(), unittest_pb2.TestAllTypes() ] messages[0].optional_int32 = 1 messages[1].optional_int64 = 2 messages[2].optional_int32 = 3 messages[2].optional_string = 'hello' merged_message = unittest_pb2.TestAllTypes() merged_message.optional_int32 = 3 merged_message.optional_int64 = 2 merged_message.optional_string = 'hello' generator = unittest_pb2.TestParsingMerge.RepeatedFieldsGenerator() generator.field1.extend(messages) generator.field2.extend(messages) generator.field3.extend(messages) generator.ext1.extend(messages) generator.ext2.extend(messages) generator.group1.add().field1.MergeFrom(messages[0]) generator.group1.add().field1.MergeFrom(messages[1]) generator.group1.add().field1.MergeFrom(messages[2]) generator.group2.add().field1.MergeFrom(messages[0]) generator.group2.add().field1.MergeFrom(messages[1]) generator.group2.add().field1.MergeFrom(messages[2]) data = generator.SerializeToString() parsing_merge = unittest_pb2.TestParsingMerge() parsing_merge.ParseFromString(data) # Required and optional fields should be merged. self.assertEqual(parsing_merge.required_all_types, merged_message) self.assertEqual(parsing_merge.optional_all_types, merged_message) self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types, merged_message) self.assertEqual(parsing_merge.Extensions[ unittest_pb2.TestParsingMerge.optional_ext], merged_message) # Repeated fields should not be merged. self.assertEqual(len(parsing_merge.repeated_all_types), 3) self.assertEqual(len(parsing_merge.repeatedgroup), 3) self.assertEqual(len(parsing_merge.Extensions[ unittest_pb2.TestParsingMerge.repeated_ext]), 3)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testPythonicInitWithDict(self): # Both string/unicode field name keys should work. kwargs = { 'optional_int32': 100, u'optional_fixed32': 200, } msg = unittest_pb2.TestAllTypes(**kwargs) self.assertEqual(100, msg.optional_int32) self.assertEqual(200, msg.optional_fixed32)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def assertMapIterEquals(self, map_iter, dict_value): # Avoid mutating caller's copy. dict_value = dict(dict_value) for k, v in map_iter: self.assertEqual(v, dict_value[k]) del dict_value[k] self.assertEqual({}, dict_value)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testProto3ParserDropDefaultScalar(self): message_proto2 = unittest_pb2.TestAllTypes() message_proto2.optional_int32 = 0 message_proto2.optional_string = '' message_proto2.optional_bytes = b'' self.assertEqual(len(message_proto2.ListFields()), 3) message_proto3 = unittest_proto3_arena_pb2.TestAllTypes() message_proto3.ParseFromString(message_proto2.SerializeToString()) self.assertEqual(len(message_proto3.ListFields()), 0)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testAssignUnknownEnum(self): """Assigning an unknown enum value is allowed and preserves the value.""" m = unittest_proto3_arena_pb2.TestAllTypes() # Proto3 can assign unknown enums. m.optional_nested_enum = 1234567 self.assertEqual(1234567, m.optional_nested_enum) m.repeated_nested_enum.append(22334455) self.assertEqual(22334455, m.repeated_nested_enum[0]) # Assignment is a different code path than append for the C++ impl. m.repeated_nested_enum[0] = 7654321 self.assertEqual(7654321, m.repeated_nested_enum[0]) serialized = m.SerializeToString() m2 = unittest_proto3_arena_pb2.TestAllTypes() m2.ParseFromString(serialized) self.assertEqual(1234567, m2.optional_nested_enum) self.assertEqual(7654321, m2.repeated_nested_enum[0])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testScalarMapDefaults(self): msg = map_unittest_pb2.TestMap() # Scalars start out unset. self.assertFalse(-123 in msg.map_int32_int32) self.assertFalse(-2**33 in msg.map_int64_int64) self.assertFalse(123 in msg.map_uint32_uint32) self.assertFalse(2**33 in msg.map_uint64_uint64) self.assertFalse(123 in msg.map_int32_double) self.assertFalse(False in msg.map_bool_bool) self.assertFalse('abc' in msg.map_string_string) self.assertFalse(111 in msg.map_int32_bytes) self.assertFalse(888 in msg.map_int32_enum) # Accessing an unset key returns the default. self.assertEqual(0, msg.map_int32_int32[-123]) self.assertEqual(0, msg.map_int64_int64[-2**33]) self.assertEqual(0, msg.map_uint32_uint32[123]) self.assertEqual(0, msg.map_uint64_uint64[2**33]) self.assertEqual(0.0, msg.map_int32_double[123]) self.assertTrue(isinstance(msg.map_int32_double[123], float)) self.assertEqual(False, msg.map_bool_bool[False]) self.assertTrue(isinstance(msg.map_bool_bool[False], bool)) self.assertEqual('', msg.map_string_string['abc']) self.assertEqual(b'', msg.map_int32_bytes[111]) self.assertEqual(0, msg.map_int32_enum[888]) # It also sets the value in the map self.assertTrue(-123 in msg.map_int32_int32) self.assertTrue(-2**33 in msg.map_int64_int64) self.assertTrue(123 in msg.map_uint32_uint32) self.assertTrue(2**33 in msg.map_uint64_uint64) self.assertTrue(123 in msg.map_int32_double) self.assertTrue(False in msg.map_bool_bool) self.assertTrue('abc' in msg.map_string_string) self.assertTrue(111 in msg.map_int32_bytes) self.assertTrue(888 in msg.map_int32_enum) self.assertIsInstance(msg.map_string_string['abc'], six.text_type) # Accessing an unset key still throws TypeError if the type of the key # is incorrect. with self.assertRaises(TypeError): msg.map_string_string[123] with self.assertRaises(TypeError): 123 in msg.map_string_string
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testScalarMap(self): msg = map_unittest_pb2.TestMap() self.assertEqual(0, len(msg.map_int32_int32)) self.assertFalse(5 in msg.map_int32_int32) msg.map_int32_int32[-123] = -456 msg.map_int64_int64[-2**33] = -2**34 msg.map_uint32_uint32[123] = 456 msg.map_uint64_uint64[2**33] = 2**34 msg.map_int32_float[2] = 1.2 msg.map_int32_double[1] = 3.3 msg.map_string_string['abc'] = '123' msg.map_bool_bool[True] = True msg.map_int32_enum[888] = 2 # Unknown numeric enum is supported in proto3. msg.map_int32_enum[123] = 456 self.assertEqual([], msg.FindInitializationErrors()) self.assertEqual(1, len(msg.map_string_string)) # Bad key. with self.assertRaises(TypeError): msg.map_string_string[123] = '123' # Verify that trying to assign a bad key doesn't actually add a member to # the map. self.assertEqual(1, len(msg.map_string_string)) # Bad value. with self.assertRaises(TypeError): msg.map_string_string['123'] = 123 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) # Bad key. with self.assertRaises(TypeError): msg2.map_string_string[123] = '123' # Bad value. with self.assertRaises(TypeError): msg2.map_string_string['123'] = 123 self.assertEqual(-456, msg2.map_int32_int32[-123]) self.assertEqual(-2**34, msg2.map_int64_int64[-2**33]) self.assertEqual(456, msg2.map_uint32_uint32[123]) self.assertEqual(2**34, msg2.map_uint64_uint64[2**33]) self.assertAlmostEqual(1.2, msg.map_int32_float[2]) self.assertEqual(3.3, msg.map_int32_double[1]) self.assertEqual('123', msg2.map_string_string['abc']) self.assertEqual(True, msg2.map_bool_bool[True]) self.assertEqual(2, msg2.map_int32_enum[888]) self.assertEqual(456, msg2.map_int32_enum[123]) self.assertEqual('{-123: -456}', str(msg2.map_int32_int32))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testStringUnicodeConversionInMap(self): msg = map_unittest_pb2.TestMap() unicode_obj = u'\u1234' bytes_obj = unicode_obj.encode('utf8') msg.map_string_string[bytes_obj] = bytes_obj (key, value) = list(msg.map_string_string.items())[0] self.assertEqual(key, unicode_obj) self.assertEqual(value, unicode_obj) self.assertIsInstance(key, six.text_type) self.assertIsInstance(value, six.text_type)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testNestedMessageMapItemDelete(self): msg = map_unittest_pb2.TestMap() msg.map_int32_all_types[1].optional_nested_message.bb = 1 del msg.map_int32_all_types[1] msg.map_int32_all_types[2].optional_nested_message.bb = 2 self.assertEqual(1, len(msg.map_int32_all_types)) msg.map_int32_all_types[1].optional_nested_message.bb = 1 self.assertEqual(2, len(msg.map_int32_all_types)) serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) keys = [1, 2] # The loop triggers PyErr_Occurred() in c extension. for key in keys: del msg2.map_int32_all_types[key]
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFrom(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[12] = 34 msg.map_int32_int32[56] = 78 msg.map_int64_int64[22] = 33 msg.map_int32_foreign_message[111].c = 5 msg.map_int32_foreign_message[222].c = 10 msg2 = map_unittest_pb2.TestMap() msg2.map_int32_int32[12] = 55 msg2.map_int64_int64[88] = 99 msg2.map_int32_foreign_message[222].c = 15 msg2.map_int32_foreign_message[222].d = 20 old_map_value = msg2.map_int32_foreign_message[222] msg2.MergeFrom(msg) # Compare with expected message instead of call # msg2.map_int32_foreign_message[222] to make sure MergeFrom does not # sync with repeated field and there is no duplicated keys. expected_msg = map_unittest_pb2.TestMap() expected_msg.CopyFrom(msg) expected_msg.map_int64_int64[88] = 99 self.assertEqual(msg2, expected_msg) self.assertEqual(34, msg2.map_int32_int32[12]) self.assertEqual(78, msg2.map_int32_int32[56]) self.assertEqual(33, msg2.map_int64_int64[22]) self.assertEqual(99, msg2.map_int64_int64[88]) self.assertEqual(5, msg2.map_int32_foreign_message[111].c) self.assertEqual(10, msg2.map_int32_foreign_message[222].c) self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d')) if api_implementation.Type() != 'cpp': # During the call to MergeFrom(), the C++ implementation will have # deallocated the underlying message, but this is very difficult to detect # properly. The line below is likely to cause a segmentation fault. # With the Python implementation, old_map_value is just 'detached' from # the main message. Using it will not crash of course, but since it still # have a reference to the parent message I'm sure we can find interesting # ways to cause inconsistencies. self.assertEqual(15, old_map_value.c) # Verify that there is only one entry per key, even though the MergeFrom # may have internally created multiple entries for a single key in the # list representation. as_dict = {} for key in msg2.map_int32_foreign_message: self.assertFalse(key in as_dict) as_dict[key] = msg2.map_int32_foreign_message[key].c self.assertEqual({111: 5, 222: 10}, as_dict) # Special case: test that delete of item really removes the item, even if # there might have physically been duplicate keys due to the previous merge. # This is only a special case for the C++ implementation which stores the # map as an array. del msg2.map_int32_int32[12] self.assertFalse(12 in msg2.map_int32_int32) del msg2.map_int32_foreign_message[222] self.assertFalse(222 in msg2.map_int32_foreign_message) with self.assertRaises(TypeError): del msg2.map_int32_foreign_message['']
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMergeFromBadType(self): msg = map_unittest_pb2.TestMap() with self.assertRaisesRegexp( TypeError, r'Parameter to MergeFrom\(\) must be instance of same class: expected ' r'.*TestMap got int\.'): msg.MergeFrom(1)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testIntegerMapWithLongs(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[long(-123)] = long(-456) msg.map_int64_int64[long(-2**33)] = long(-2**34) msg.map_uint32_uint32[long(123)] = long(456) msg.map_uint64_uint64[long(2**33)] = long(2**34) serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) self.assertEqual(-456, msg2.map_int32_int32[-123]) self.assertEqual(-2**34, msg2.map_int64_int64[-2**33]) self.assertEqual(456, msg2.map_uint32_uint32[123]) self.assertEqual(2**34, msg2.map_uint64_uint64[2**33])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapAssignmentCausesPresenceForSubmessages(self): msg = map_unittest_pb2.TestMapSubmessage() msg.test_map.map_int32_foreign_message[123].c = 5 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMapSubmessage() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) # Now test that various mutations of the map properly invalidate the # cached size of the submessage. msg.test_map.map_int32_foreign_message[888].c = 7 serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) msg.test_map.map_int32_foreign_message[888].MergeFrom( msg.test_map.map_int32_foreign_message[123]) serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2) msg.test_map.map_int32_foreign_message.clear() serialized = msg.SerializeToString() msg2.ParseFromString(serialized) self.assertEqual(msg, msg2)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSubmessageMap(self): msg = map_unittest_pb2.TestMap() submsg = msg.map_int32_foreign_message[111] self.assertIs(submsg, msg.map_int32_foreign_message[111]) self.assertIsInstance(submsg, unittest_pb2.ForeignMessage) submsg.c = 5 serialized = msg.SerializeToString() msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(serialized) self.assertEqual(5, msg2.map_int32_foreign_message[111].c) # Doesn't allow direct submessage assignment. with self.assertRaises(ValueError): msg.map_int32_foreign_message[88] = unittest_pb2.ForeignMessage()
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testPython2Map(self): if sys.version_info < (3,): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[2] = 4 msg.map_int32_int32[3] = 6 msg.map_int32_int32[4] = 8 msg.map_int32_int32[5] = 10 map_int32 = msg.map_int32_int32 self.assertEqual(4, len(map_int32)) msg2 = map_unittest_pb2.TestMap() msg2.ParseFromString(msg.SerializeToString()) def CheckItems(seq, iterator): self.assertEqual(next(iterator), seq[0]) self.assertEqual(list(iterator), seq[1:]) CheckItems(map_int32.items(), map_int32.iteritems()) CheckItems(map_int32.keys(), map_int32.iterkeys()) CheckItems(map_int32.values(), map_int32.itervalues()) self.assertEqual(6, map_int32.get(3)) self.assertEqual(None, map_int32.get(999)) self.assertEqual(6, map_int32.pop(3)) self.assertEqual(0, map_int32.pop(3)) self.assertEqual(3, len(map_int32)) key, value = map_int32.popitem() self.assertEqual(2 * key, value) self.assertEqual(2, len(map_int32)) map_int32.clear() self.assertEqual(0, len(map_int32)) with self.assertRaises(KeyError): map_int32.popitem() self.assertEqual(0, map_int32.setdefault(2)) self.assertEqual(1, len(map_int32)) map_int32.update(msg2.map_int32_int32) self.assertEqual(4, len(map_int32)) with self.assertRaises(TypeError): map_int32.update(msg2.map_int32_int32, msg2.map_int32_int32) with self.assertRaises(TypeError): map_int32.update(0) with self.assertRaises(TypeError): map_int32.update(value=12)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapDeterministicSerialization(self): golden_data = (b'r\x0c\n\x07init_op\x12\x01d' b'r\n\n\x05item1\x12\x01e' b'r\n\n\x05item2\x12\x01f' b'r\n\n\x05item3\x12\x01g' b'r\x0b\n\x05item4\x12\x02QQ' b'r\x12\n\rlocal_init_op\x12\x01a' b'r\x0e\n\tsummaries\x12\x01e' b'r\x18\n\x13trainable_variables\x12\x01b' b'r\x0e\n\tvariables\x12\x01c') msg = map_unittest_pb2.TestMap() msg.map_string_string['local_init_op'] = 'a' msg.map_string_string['trainable_variables'] = 'b' msg.map_string_string['variables'] = 'c' msg.map_string_string['init_op'] = 'd' msg.map_string_string['summaries'] = 'e' msg.map_string_string['item1'] = 'e' msg.map_string_string['item2'] = 'f' msg.map_string_string['item3'] = 'g' msg.map_string_string['item4'] = 'QQ' # If deterministic serialization is not working correctly, this will be # "flaky" depending on the exact python dict hash seed. # # Fortunately, there are enough items in this map that it is extremely # unlikely to ever hit the "right" in-order combination, so the test # itself should fail reliably. self.assertEqual(golden_data, msg.SerializeToString(deterministic=True))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapConstruction(self): msg = map_unittest_pb2.TestMap(map_int32_int32={1: 2, 3: 4}) self.assertEqual(2, msg.map_int32_int32[1]) self.assertEqual(4, msg.map_int32_int32[3]) msg = map_unittest_pb2.TestMap( map_int32_foreign_message={3: unittest_pb2.ForeignMessage(c=5)}) self.assertEqual(5, msg.map_int32_foreign_message[3].c)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapMessageFieldConstruction(self): msg1 = map_unittest_pb2.TestMap() msg1.map_string_foreign_message['test'].c = 42 msg2 = map_unittest_pb2.TestMap( map_string_foreign_message=msg1.map_string_foreign_message) self.assertEqual(42, msg2.map_string_foreign_message['test'].c)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapValidAfterFieldCleared(self): # Map needs to work even if field is cleared. # For the C++ implementation this tests the correctness of # MapContainer::Release() msg = map_unittest_pb2.TestMap() int32_map = msg.map_int32_int32 int32_map[2] = 4 int32_map[3] = 6 int32_map[4] = 8 msg.ClearField('map_int32_int32') self.assertEqual(b'', msg.SerializeToString()) matching_dict = {2: 4, 3: 6, 4: 8} self.assertMapIterEquals(int32_map.items(), matching_dict)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMessageMapItemValidAfterTopMessageCleared(self): # Message map item needs to work even if it is cleared. # For the C++ implementation this tests the correctness of # MapContainer::Release() msg = map_unittest_pb2.TestMap() msg.map_int32_all_types[2].optional_string = 'bar' if api_implementation.Type() == 'cpp': # Need to keep the map reference because of b/27942626. # TODO(jieluo): Remove it. unused_map = msg.map_int32_all_types # pylint: disable=unused-variable msg_value = msg.map_int32_all_types[2] msg.Clear() # Reset to trigger sync between repeated field and map in c++. msg.map_int32_all_types[3].optional_string = 'foo' self.assertEqual(msg_value.optional_string, 'bar')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapDelete(self): msg = map_unittest_pb2.TestMap() self.assertEqual(0, len(msg.map_int32_int32)) msg.map_int32_int32[4] = 6 self.assertEqual(1, len(msg.map_int32_int32)) with self.assertRaises(KeyError): del msg.map_int32_int32[88] del msg.map_int32_int32[4] self.assertEqual(0, len(msg.map_int32_int32)) with self.assertRaises(KeyError): del msg.map_int32_all_types[32]
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testMapsCompare(self): msg = map_unittest_pb2.TestMap() msg.map_int32_int32[-123] = -456 self.assertEqual(msg.map_int32_int32, msg.map_int32_int32) self.assertEqual(msg.map_int32_foreign_message, msg.map_int32_foreign_message) self.assertNotEqual(msg.map_int32_int32, 0)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testStrictUtf8Check(self): # Test u'\ud801' is rejected at parser in both python2 and python3. serialized = (b'r\x03\xed\xa0\x81') msg = unittest_proto3_arena_pb2.TestAllTypes() with self.assertRaises(Exception) as context: msg.MergeFromString(serialized) if api_implementation.Type() == 'python': self.assertIn('optional_string', str(context.exception)) else: self.assertIn('Error parsing message', str(context.exception)) # Test optional_string=u'😍' is accepted. serialized = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'😍').SerializeToString() msg2 = unittest_proto3_arena_pb2.TestAllTypes() msg2.MergeFromString(serialized) self.assertEqual(msg2.optional_string, u'😍') msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud001') self.assertEqual(msg.optional_string, u'\ud001')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSurrogatesInPython3(self): # Surrogates like U+D83D is an invalid unicode character, it is # supported by Python2 only because in some builds, unicode strings # use 2-bytes code units. Since Python 3.3, we don't have this problem. # # Surrogates are utf16 code units, in a unicode string they are invalid # characters even when they appear in pairs like u'\ud801\udc01'. Protobuf # Python3 reject such cases at setters and parsers. Python2 accpect it # to keep same features with the language itself. 'Unpaired pairs' # like u'\ud801' are rejected at parsers when strict utf8 check is enabled # in proto3 to keep same behavior with c extension. # Surrogates are rejected at setters in Python3. with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\udc01') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=b'\xed\xa0\x81') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801') with self.assertRaises(ValueError): unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\ud801')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testSurrogatesInPython2(self): # Test optional_string=u'\ud801\udc01'. # surrogate pair is acceptable in python2. msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\udc01') # TODO(jieluo): Change pure python to have same behavior with c extension. # Some build in python2 consider u'\ud801\udc01' and u'\U00010401' are # equal, some are not equal. if api_implementation.Type() == 'python': self.assertEqual(msg.optional_string, u'\ud801\udc01') else: self.assertEqual(msg.optional_string, u'\U00010401') serialized = msg.SerializeToString() msg2 = unittest_proto3_arena_pb2.TestAllTypes() msg2.MergeFromString(serialized) self.assertEqual(msg2.optional_string, u'\U00010401') # Python2 does not reject surrogates at setters. msg = unittest_proto3_arena_pb2.TestAllTypes( optional_string=b'\xed\xa0\x81') unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801') unittest_proto3_arena_pb2.TestAllTypes( optional_string=u'\ud801\ud801')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def assertImportFromName(self, msg, base_name): # Parse <type 'module.class_name'> to extra 'some.name' as a string. tp_name = str(type(msg)).split("'")[1] valid_names = ('Repeated%sContainer' % base_name, 'Repeated%sFieldContainer' % base_name) self.assertTrue(any(tp_name.endswith(v) for v in valid_names), '%r does end with any of %r' % (tp_name, valid_names)) parts = tp_name.split('.') class_name = parts[-1] module_name = '.'.join(parts[:-1]) __import__(module_name, fromlist=[class_name])
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def setMessage(self, message): message.repeated_int32.append(1) message.repeated_int64.append(1) message.repeated_uint32.append(1) message.repeated_uint64.append(1) message.repeated_sint32.append(1) message.repeated_sint64.append(1) message.repeated_fixed32.append(1) message.repeated_fixed64.append(1) message.repeated_sfixed32.append(1) message.repeated_sfixed64.append(1) message.repeated_float.append(1.0) message.repeated_double.append(1.0) message.repeated_bool.append(True) message.repeated_nested_enum.append(1)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testUnpackedFields(self): message = packed_field_test_pb2.TestUnpackedTypes() self.setMessage(message) golden_data = (b'\x08\x01' b'\x10\x01' b'\x18\x01' b'\x20\x01' b'\x28\x02' b'\x30\x02' b'\x3D\x01\x00\x00\x00' b'\x41\x01\x00\x00\x00\x00\x00\x00\x00' b'\x4D\x01\x00\x00\x00' b'\x51\x01\x00\x00\x00\x00\x00\x00\x00' b'\x5D\x00\x00\x80\x3f' b'\x61\x00\x00\x00\x00\x00\x00\xf0\x3f' b'\x68\x01' b'\x70\x01') self.assertEqual(golden_data, message.SerializeToString())
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def setUpClass(cls): # At the moment, reference cycles between DescriptorPool and Message classes # are not detected and these objects are never freed. # To avoid errors with ReferenceLeakChecker, we create the class only once. file_desc = """ name: "f/f.msg2" package: "f" message_type { name: "msg1" field { name: "payload" number: 1 label: LABEL_OPTIONAL type: TYPE_STRING } } message_type { name: "msg2" field { name: "field" number: 1 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: "msg1" } } """ pool = descriptor_pool.DescriptorPool() desc = descriptor_pb2.FileDescriptorProto() text_format.Parse(file_desc, desc) pool.Add(desc) cls.proto_cls = message_factory.MessageFactory(pool).GetPrototype( pool.FindMessageTypeByName('f.msg2'))
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def testAssertOversizeProto(self): from google.protobuf.pyext._message import SetAllowOversizeProtos SetAllowOversizeProtos(False) q = self.proto_cls() try: q.ParseFromString(self.p_serialized) except message.DecodeError as e: self.assertEqual(str(e), 'Error parsing message')
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def main(): url = '%s/%s/%s/%s' % (SERVER, PATH, REVISION, FILENAME) sysroot = os.path.join(SCRIPT_DIR, os.pardir, 'third_party', 'linux', 'sysroot') stamp = os.path.join(sysroot, '.stamp') if os.path.exists(stamp): with open(stamp) as s: if s.read() == url: return print('Installing Debian root image from %s' % url) if os.path.isdir(sysroot): shutil.rmtree(sysroot) os.mkdir(sysroot) tarball = os.path.join(sysroot, FILENAME) print('Downloading %s' % url) for _ in range(3): response = urllib.request.urlopen(url) with open(tarball, 'wb') as f: f.write(response.read()) break else: raise Exception('Failed to download %s' % url) subprocess.check_call(['tar', 'xf', tarball, '-C', sysroot]) os.remove(tarball) with open(stamp, 'w') as s: s.write(url)
nwjs/chromium.src
[ 136, 133, 136, 45, 1453904223 ]
def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % o for o in c.encode("utf-8")]) break return retval
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", ] for uri in invariant: self.assertEqual(uri, iri2uri(uri))
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def LocalFileToURL(localFileName): "Convert a filename to an XPCOM nsIFileURL object." # Create an nsILocalFile localFile = components.classes["@mozilla.org/file/local;1"] \ .createInstance(components.interfaces.nsILocalFile) localFile.initWithPath(localFileName) # Use the IO Service to create the interface, then QI for a FileURL io_service = components.classes["@mozilla.org/network/io-service;1"] \ .getService(components.interfaces.nsIIOService) url = io_service.newFileURI(localFile).queryInterface(components.interfaces.nsIFileURL) # Setting the "file" attribute causes initialization... url.file = localFile return url
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def __init__(self, name_thingy = None, mode="r"): self.lockob = threading.Lock() self.inputStream = self.outputStream = None if name_thingy is not None: self.init(name_thingy, mode)
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def _lock(self): self.lockob.acquire()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def read(self, n = -1): assert self.inputStream is not None, "Not setup for read!" self._lock() try: return str(self.inputStream.read(n)) finally: self._release()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def write(self, data): assert self.outputStream is not None, "Not setup for write!" self._lock() try: self.outputStream.write(data, len(data)) finally: self._release()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def flush(self): self._lock() try: if self.outputStream is not None: self.outputStream.flush() finally: self._release()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def init(self, url, mode="r"): self.close() if mode != "r": raise ValueError, "only 'r' mode supported'" io_service = components.classes["@mozilla.org/network/io-service;1"] \ .getService(components.interfaces.nsIIOService) if hasattr(url, "queryInterface"): url_ob = url else: url_ob = io_service.newURI(url, None, None) # Mozilla asserts and starts saying "NULL POINTER" if this is wrong! if not url_ob.scheme: raise ValueError, ("The URI '%s' is invalid (no scheme)" % (url_ob.spec,)) self.channel = io_service.newChannelFromURI(url_ob) self.inputStream = self.channel.open()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def __init__(self, *args): self.fileIO = None _File.__init__(self, *args)
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def close(self): if self.fileIO is not None: self.fileIO.close() self.fileIO = None _File.close(self)
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def _DoTestRead(file, expected): # read in a couple of chunks, just to test that our various arg combinations work. got = file.read(3) got = got + file.read(300) got = got + file.read(0) got = got + file.read() if got != expected: raise RuntimeError, "Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected))
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def _TestLocalFile(): import tempfile, os fname = tempfile.mktemp() data = "Hello from Python" test_file = LocalFile(fname, "w") try: test_file.write(data) test_file.close() # Make sure Python can read it OK. f = open(fname, "r") assert f.read() == data, "Eeek - Python could not read the data back correctly!" f.close() # For the sake of the test, try a re-init. test_file.init(fname, "r") got = str(test_file.read()) assert got == data, got test_file.close() # Try reading in chunks. test_file = LocalFile(fname, "r") got = test_file.read(10) + test_file.read() assert got == data, got test_file.close() # Open the same file again for writing - this should delete the old one. if not os.path.isfile(fname): raise RuntimeError, "The file '%s' does not exist, but we are explicitly testing create semantics when it does" % (fname,) test_file = LocalFile(fname, "w") test_file.write(data) test_file.close() # Make sure Python can read it OK. f = open(fname, "r") assert f.read() == data, "Eeek - Python could not read the data back correctly after recreating an existing file!" f.close() # XXX - todo - test "a" mode! finally: os.unlink(fname)
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def _TestURI(url): test_file = URIFile(url) print "Opened file is", test_file got = test_file.read() print "Read %d bytes of data from %r" % (len(got), url) test_file.close()
ruibarreira/linuxtrail
[ 2, 2, 2, 1, 1434186057 ]
def sample_request(request): polyline = GPolyline('LINESTRING(101 26, 112 26, 102 31)') event = GEvent('click', 'function() { location.href = "http://www.google.com"}') polyline.add_event(event) return render_to_response('mytemplate.html', {'google' : GoogleMap(polylines=[polyline])})
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, event, action): """ Initializes a GEvent object. Parameters: event: string for the event, such as 'click'. The event must be a valid event for the object in the Google Maps API. There is no validation of the event type within Django. action: string containing a Javascript function, such as 'function() { location.href = "newurl";}' The string must be a valid Javascript function. Again there is no validation fo the function within Django. """ self.event = event self.action = action
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self): self.events = []
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def add_event(self, event): "Attaches a GEvent to the overlay object." self.events.append(event)
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, poly, stroke_color='#0000ff', stroke_weight=2, stroke_opacity=1, fill_color='#0000ff', fill_opacity=0.4): """ The GPolygon object initializes on a GEOS Polygon or a parameter that may be instantiated into GEOS Polygon. Please note that this will not depict a Polygon's internal rings. Keyword Options: stroke_color: The color of the polygon outline. Defaults to '#0000ff' (blue). stroke_weight: The width of the polygon outline, in pixels. Defaults to 2. stroke_opacity: The opacity of the polygon outline, between 0 and 1. Defaults to 1. fill_color: The color of the polygon fill. Defaults to '#0000ff' (blue). fill_opacity: The opacity of the polygon fill. Defaults to 0.4. """ if isinstance(poly, six.string_types): poly = fromstr(poly) if isinstance(poly, (tuple, list)): poly = Polygon(poly) if not isinstance(poly, Polygon): raise TypeError('GPolygon may only initialize on GEOS Polygons.') # Getting the envelope of the input polygon (used for automatically # determining the zoom level). self.envelope = poly.envelope # Translating the coordinates into a JavaScript array of # Google `GLatLng` objects. self.points = self.latlng_from_coords(poly.shell.coords) # Stroke settings. self.stroke_color, self.stroke_opacity, self.stroke_weight = stroke_color, stroke_opacity, stroke_weight # Fill settings. self.fill_color, self.fill_opacity = fill_color, fill_opacity super(GPolygon, self).__init__()
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def js_params(self): return '%s, "%s", %s, %s, "%s", %s' % (self.points, self.stroke_color, self.stroke_weight, self.stroke_opacity, self.fill_color, self.fill_opacity)
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, geom, color='#0000ff', weight=2, opacity=1): """ The GPolyline object may be initialized on GEOS LineStirng, LinearRing, and Polygon objects (internal rings not supported) or a parameter that may instantiated into one of the above geometries. Keyword Options: color: The color to use for the polyline. Defaults to '#0000ff' (blue). weight: The width of the polyline, in pixels. Defaults to 2. opacity: The opacity of the polyline, between 0 and 1. Defaults to 1. """ # If a GEOS geometry isn't passed in, try to construct one. if isinstance(geom, six.string_types): geom = fromstr(geom) if isinstance(geom, (tuple, list)): geom = Polygon(geom) # Generating the lat/lng coordinate pairs. if isinstance(geom, (LineString, LinearRing)): self.latlngs = self.latlng_from_coords(geom.coords) elif isinstance(geom, Polygon): self.latlngs = self.latlng_from_coords(geom.shell.coords) else: raise TypeError('GPolyline may only initialize on GEOS LineString, LinearRing, and/or Polygon geometries.') # Getting the envelope for automatic zoom determination. self.envelope = geom.envelope self.color, self.weight, self.opacity = color, weight, opacity super(GPolyline, self).__init__()
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def js_params(self): return '%s, "%s", %s, %s' % (self.latlngs, self.color, self.weight, self.opacity)
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __init__(self, varname, image=None, iconsize=None, shadow=None, shadowsize=None, iconanchor=None, infowindowanchor=None): self.varname = varname self.image = image self.iconsize = iconsize self.shadow = shadow self.shadowsize = shadowsize self.iconanchor = iconanchor self.infowindowanchor = infowindowanchor
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]
def __lt__(self, other): return self.varname < other.varname
Vvucinic/Wander
[ 1, 1, 1, 11, 1449375044 ]