How to use json_format method in Behave

Best Python code snippet using behave

json_format_test.py

Source:json_format_test.py Github

copy

Full Screen

1#! /usr/bin/env python2#3# Protocol Buffers - Google's data interchange format4# Copyright 2008 Google Inc. All rights reserved.5# https://developers.google.com/protocol-buffers/6#7# Redistribution and use in source and binary forms, with or without8# modification, are permitted provided that the following conditions are9# met:10#11# * Redistributions of source code must retain the above copyright12# notice, this list of conditions and the following disclaimer.13# * Redistributions in binary form must reproduce the above14# copyright notice, this list of conditions and the following disclaimer15# in the documentation and/or other materials provided with the16# distribution.17# * Neither the name of Google Inc. nor the names of its18# contributors may be used to endorse or promote products derived from19# this software without specific prior written permission.20#21# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR24# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT27# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,28# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY29# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT30# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE31# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.32"""Test for google.protobuf.json_format."""33__author__ = 'jieluo@google.com (Jie Luo)'34import json35import math36import sys37try:38 import unittest2 as unittest #PY2639except ImportError:40 import unittest41from google.protobuf import any_pb242from google.protobuf import duration_pb243from google.protobuf import field_mask_pb244from google.protobuf import struct_pb245from google.protobuf import timestamp_pb246from google.protobuf import wrappers_pb247from google.protobuf.internal import well_known_types48from google.protobuf import json_format49from google.protobuf.util import json_format_proto3_pb250class JsonFormatBase(unittest.TestCase):51 def FillAllFields(self, message):52 message.int32_value = 2053 message.int64_value = -2054 message.uint32_value = 312098765455 message.uint64_value = 1234567890056 message.float_value = float('-inf')57 message.double_value = 3.141558 message.bool_value = True59 message.string_value = 'foo'60 message.bytes_value = b'bar'61 message.message_value.value = 1062 message.enum_value = json_format_proto3_pb2.BAR63 # Repeated64 message.repeated_int32_value.append(0x7FFFFFFF)65 message.repeated_int32_value.append(-2147483648)66 message.repeated_int64_value.append(9007199254740992)67 message.repeated_int64_value.append(-9007199254740992)68 message.repeated_uint32_value.append(0xFFFFFFF)69 message.repeated_uint32_value.append(0x7FFFFFF)70 message.repeated_uint64_value.append(9007199254740992)71 message.repeated_uint64_value.append(9007199254740991)72 message.repeated_float_value.append(0)73 message.repeated_double_value.append(1E-15)74 message.repeated_double_value.append(float('inf'))75 message.repeated_bool_value.append(True)76 message.repeated_bool_value.append(False)77 message.repeated_string_value.append('Few symbols!#$,;')78 message.repeated_string_value.append('bar')79 message.repeated_bytes_value.append(b'foo')80 message.repeated_bytes_value.append(b'bar')81 message.repeated_message_value.add().value = 1082 message.repeated_message_value.add().value = 1183 message.repeated_enum_value.append(json_format_proto3_pb2.FOO)84 message.repeated_enum_value.append(json_format_proto3_pb2.BAR)85 self.message = message86 def CheckParseBack(self, message, parsed_message):87 json_format.Parse(json_format.MessageToJson(message),88 parsed_message)89 self.assertEqual(message, parsed_message)90 def CheckError(self, text, error_message):91 message = json_format_proto3_pb2.TestMessage()92 self.assertRaisesRegexp(93 json_format.ParseError,94 error_message,95 json_format.Parse, text, message)96class JsonFormatTest(JsonFormatBase):97 def testEmptyMessageToJson(self):98 message = json_format_proto3_pb2.TestMessage()99 self.assertEqual(json_format.MessageToJson(message),100 '{}')101 parsed_message = json_format_proto3_pb2.TestMessage()102 self.CheckParseBack(message, parsed_message)103 def testPartialMessageToJson(self):104 message = json_format_proto3_pb2.TestMessage(105 string_value='test',106 repeated_int32_value=[89, 4])107 self.assertEqual(json.loads(json_format.MessageToJson(message)),108 json.loads('{"stringValue": "test", '109 '"repeatedInt32Value": [89, 4]}'))110 parsed_message = json_format_proto3_pb2.TestMessage()111 self.CheckParseBack(message, parsed_message)112 def testAllFieldsToJson(self):113 message = json_format_proto3_pb2.TestMessage()114 text = ('{"int32Value": 20, '115 '"int64Value": "-20", '116 '"uint32Value": 3120987654,'117 '"uint64Value": "12345678900",'118 '"floatValue": "-Infinity",'119 '"doubleValue": 3.1415,'120 '"boolValue": true,'121 '"stringValue": "foo",'122 '"bytesValue": "YmFy",'123 '"messageValue": {"value": 10},'124 '"enumValue": "BAR",'125 '"repeatedInt32Value": [2147483647, -2147483648],'126 '"repeatedInt64Value": ["9007199254740992", "-9007199254740992"],'127 '"repeatedUint32Value": [268435455, 134217727],'128 '"repeatedUint64Value": ["9007199254740992", "9007199254740991"],'129 '"repeatedFloatValue": [0],'130 '"repeatedDoubleValue": [1e-15, "Infinity"],'131 '"repeatedBoolValue": [true, false],'132 '"repeatedStringValue": ["Few symbols!#$,;", "bar"],'133 '"repeatedBytesValue": ["Zm9v", "YmFy"],'134 '"repeatedMessageValue": [{"value": 10}, {"value": 11}],'135 '"repeatedEnumValue": ["FOO", "BAR"]'136 '}')137 self.FillAllFields(message)138 self.assertEqual(139 json.loads(json_format.MessageToJson(message)),140 json.loads(text))141 parsed_message = json_format_proto3_pb2.TestMessage()142 json_format.Parse(text, parsed_message)143 self.assertEqual(message, parsed_message)144 def testJsonEscapeString(self):145 message = json_format_proto3_pb2.TestMessage()146 if sys.version_info[0] < 3:147 message.string_value = '&\n<\"\r>\b\t\f\\\001/\xe2\x80\xa8\xe2\x80\xa9'148 else:149 message.string_value = '&\n<\"\r>\b\t\f\\\001/'150 message.string_value += (b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8')151 self.assertEqual(152 json_format.MessageToJson(message),153 '{\n "stringValue": '154 '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}')155 parsed_message = json_format_proto3_pb2.TestMessage()156 self.CheckParseBack(message, parsed_message)157 text = u'{"int32Value": "\u0031"}'158 json_format.Parse(text, message)159 self.assertEqual(message.int32_value, 1)160 def testAlwaysSeriliaze(self):161 message = json_format_proto3_pb2.TestMessage(162 string_value='foo')163 self.assertEqual(164 json.loads(json_format.MessageToJson(message, True)),165 json.loads('{'166 '"repeatedStringValue": [],'167 '"stringValue": "foo",'168 '"repeatedBoolValue": [],'169 '"repeatedUint32Value": [],'170 '"repeatedInt32Value": [],'171 '"enumValue": "FOO",'172 '"int32Value": 0,'173 '"floatValue": 0,'174 '"int64Value": "0",'175 '"uint32Value": 0,'176 '"repeatedBytesValue": [],'177 '"repeatedUint64Value": [],'178 '"repeatedDoubleValue": [],'179 '"bytesValue": "",'180 '"boolValue": false,'181 '"repeatedEnumValue": [],'182 '"uint64Value": "0",'183 '"doubleValue": 0,'184 '"repeatedFloatValue": [],'185 '"repeatedInt64Value": [],'186 '"repeatedMessageValue": []}'))187 parsed_message = json_format_proto3_pb2.TestMessage()188 self.CheckParseBack(message, parsed_message)189 def testMapFields(self):190 message = json_format_proto3_pb2.TestMap()191 message.bool_map[True] = 1192 message.bool_map[False] = 2193 message.int32_map[1] = 2194 message.int32_map[2] = 3195 message.int64_map[1] = 2196 message.int64_map[2] = 3197 message.uint32_map[1] = 2198 message.uint32_map[2] = 3199 message.uint64_map[1] = 2200 message.uint64_map[2] = 3201 message.string_map['1'] = 2202 message.string_map['null'] = 3203 self.assertEqual(204 json.loads(json_format.MessageToJson(message, True)),205 json.loads('{'206 '"boolMap": {"false": 2, "true": 1},'207 '"int32Map": {"1": 2, "2": 3},'208 '"int64Map": {"1": 2, "2": 3},'209 '"uint32Map": {"1": 2, "2": 3},'210 '"uint64Map": {"1": 2, "2": 3},'211 '"stringMap": {"1": 2, "null": 3}'212 '}'))213 parsed_message = json_format_proto3_pb2.TestMap()214 self.CheckParseBack(message, parsed_message)215 def testOneofFields(self):216 message = json_format_proto3_pb2.TestOneof()217 # Always print does not affect oneof fields.218 self.assertEqual(219 json_format.MessageToJson(message, True),220 '{}')221 message.oneof_int32_value = 0222 self.assertEqual(223 json_format.MessageToJson(message, True),224 '{\n'225 ' "oneofInt32Value": 0\n'226 '}')227 parsed_message = json_format_proto3_pb2.TestOneof()228 self.CheckParseBack(message, parsed_message)229 def testTimestampMessage(self):230 message = json_format_proto3_pb2.TestTimestamp()231 message.value.seconds = 0232 message.value.nanos = 0233 message.repeated_value.add().seconds = 20234 message.repeated_value[0].nanos = 1235 message.repeated_value.add().seconds = 0236 message.repeated_value[1].nanos = 10000237 message.repeated_value.add().seconds = 100000000238 message.repeated_value[2].nanos = 0239 # Maximum time240 message.repeated_value.add().seconds = 253402300799241 message.repeated_value[3].nanos = 999999999242 # Minimum time243 message.repeated_value.add().seconds = -62135596800244 message.repeated_value[4].nanos = 0245 self.assertEqual(246 json.loads(json_format.MessageToJson(message, True)),247 json.loads('{'248 '"value": "1970-01-01T00:00:00Z",'249 '"repeatedValue": ['250 ' "1970-01-01T00:00:20.000000001Z",'251 ' "1970-01-01T00:00:00.000010Z",'252 ' "1973-03-03T09:46:40Z",'253 ' "9999-12-31T23:59:59.999999999Z",'254 ' "0001-01-01T00:00:00Z"'255 ']'256 '}'))257 parsed_message = json_format_proto3_pb2.TestTimestamp()258 self.CheckParseBack(message, parsed_message)259 text = (r'{"value": "1970-01-01T00:00:00.01+08:00",'260 r'"repeatedValue":['261 r' "1970-01-01T00:00:00.01+08:30",'262 r' "1970-01-01T00:00:00.01-01:23"]}')263 json_format.Parse(text, parsed_message)264 self.assertEqual(parsed_message.value.seconds, -8 * 3600)265 self.assertEqual(parsed_message.value.nanos, 10000000)266 self.assertEqual(parsed_message.repeated_value[0].seconds, -8.5 * 3600)267 self.assertEqual(parsed_message.repeated_value[1].seconds, 3600 + 23 * 60)268 def testDurationMessage(self):269 message = json_format_proto3_pb2.TestDuration()270 message.value.seconds = 1271 message.repeated_value.add().seconds = 0272 message.repeated_value[0].nanos = 10273 message.repeated_value.add().seconds = -1274 message.repeated_value[1].nanos = -1000275 message.repeated_value.add().seconds = 10276 message.repeated_value[2].nanos = 11000000277 message.repeated_value.add().seconds = -315576000000278 message.repeated_value.add().seconds = 315576000000279 self.assertEqual(280 json.loads(json_format.MessageToJson(message, True)),281 json.loads('{'282 '"value": "1s",'283 '"repeatedValue": ['284 ' "0.000000010s",'285 ' "-1.000001s",'286 ' "10.011s",'287 ' "-315576000000s",'288 ' "315576000000s"'289 ']'290 '}'))291 parsed_message = json_format_proto3_pb2.TestDuration()292 self.CheckParseBack(message, parsed_message)293 def testFieldMaskMessage(self):294 message = json_format_proto3_pb2.TestFieldMask()295 message.value.paths.append('foo.bar')296 message.value.paths.append('bar')297 self.assertEqual(298 json_format.MessageToJson(message, True),299 '{\n'300 ' "value": "foo.bar,bar"\n'301 '}')302 parsed_message = json_format_proto3_pb2.TestFieldMask()303 self.CheckParseBack(message, parsed_message)304 def testWrapperMessage(self):305 message = json_format_proto3_pb2.TestWrapper()306 message.bool_value.value = False307 message.int32_value.value = 0308 message.string_value.value = ''309 message.bytes_value.value = b''310 message.repeated_bool_value.add().value = True311 message.repeated_bool_value.add().value = False312 message.repeated_int32_value.add()313 self.assertEqual(314 json.loads(json_format.MessageToJson(message, True)),315 json.loads('{\n'316 ' "int32Value": 0,'317 ' "boolValue": false,'318 ' "stringValue": "",'319 ' "bytesValue": "",'320 ' "repeatedBoolValue": [true, false],'321 ' "repeatedInt32Value": [0],'322 ' "repeatedUint32Value": [],'323 ' "repeatedFloatValue": [],'324 ' "repeatedDoubleValue": [],'325 ' "repeatedBytesValue": [],'326 ' "repeatedInt64Value": [],'327 ' "repeatedUint64Value": [],'328 ' "repeatedStringValue": []'329 '}'))330 parsed_message = json_format_proto3_pb2.TestWrapper()331 self.CheckParseBack(message, parsed_message)332 def testStructMessage(self):333 message = json_format_proto3_pb2.TestStruct()334 message.value['name'] = 'Jim'335 message.value['age'] = 10336 message.value['attend'] = True337 message.value['email'] = None338 message.value.get_or_create_struct('address')['city'] = 'SFO'339 message.value['address']['house_number'] = 1024340 struct_list = message.value.get_or_create_list('list')341 struct_list.extend([6, 'seven', True, False, None])342 struct_list.add_struct()['subkey2'] = 9343 message.repeated_value.add()['age'] = 11344 message.repeated_value.add()345 self.assertEqual(346 json.loads(json_format.MessageToJson(message, False)),347 json.loads(348 '{'349 ' "value": {'350 ' "address": {'351 ' "city": "SFO", '352 ' "house_number": 1024'353 ' }, '354 ' "age": 10, '355 ' "name": "Jim", '356 ' "attend": true, '357 ' "email": null, '358 ' "list": [6, "seven", true, false, null, {"subkey2": 9}]'359 ' },'360 ' "repeatedValue": [{"age": 11}, {}]'361 '}'))362 parsed_message = json_format_proto3_pb2.TestStruct()363 self.CheckParseBack(message, parsed_message)364 def testValueMessage(self):365 message = json_format_proto3_pb2.TestValue()366 message.value.string_value = 'hello'367 message.repeated_value.add().number_value = 11.1368 message.repeated_value.add().bool_value = False369 message.repeated_value.add().null_value = 0370 self.assertEqual(371 json.loads(json_format.MessageToJson(message, False)),372 json.loads(373 '{'374 ' "value": "hello",'375 ' "repeatedValue": [11.1, false, null]'376 '}'))377 parsed_message = json_format_proto3_pb2.TestValue()378 self.CheckParseBack(message, parsed_message)379 # Can't parse back if the Value message is not set.380 message.repeated_value.add()381 self.assertEqual(382 json.loads(json_format.MessageToJson(message, False)),383 json.loads(384 '{'385 ' "value": "hello",'386 ' "repeatedValue": [11.1, false, null, null]'387 '}'))388 def testListValueMessage(self):389 message = json_format_proto3_pb2.TestListValue()390 message.value.values.add().number_value = 11.1391 message.value.values.add().null_value = 0392 message.value.values.add().bool_value = True393 message.value.values.add().string_value = 'hello'394 message.value.values.add().struct_value['name'] = 'Jim'395 message.repeated_value.add().values.add().number_value = 1396 message.repeated_value.add()397 self.assertEqual(398 json.loads(json_format.MessageToJson(message, False)),399 json.loads(400 '{"value": [11.1, null, true, "hello", {"name": "Jim"}]\n,'401 '"repeatedValue": [[1], []]}'))402 parsed_message = json_format_proto3_pb2.TestListValue()403 self.CheckParseBack(message, parsed_message)404 def testAnyMessage(self):405 message = json_format_proto3_pb2.TestAny()406 value1 = json_format_proto3_pb2.MessageType()407 value2 = json_format_proto3_pb2.MessageType()408 value1.value = 1234409 value2.value = 5678410 message.value.Pack(value1)411 message.repeated_value.add().Pack(value1)412 message.repeated_value.add().Pack(value2)413 message.repeated_value.add()414 self.assertEqual(415 json.loads(json_format.MessageToJson(message, True)),416 json.loads(417 '{\n'418 ' "repeatedValue": [ {\n'419 ' "@type": "type.googleapis.com/proto3.MessageType",\n'420 ' "value": 1234\n'421 ' }, {\n'422 ' "@type": "type.googleapis.com/proto3.MessageType",\n'423 ' "value": 5678\n'424 ' },\n'425 ' {}],\n'426 ' "value": {\n'427 ' "@type": "type.googleapis.com/proto3.MessageType",\n'428 ' "value": 1234\n'429 ' }\n'430 '}\n'))431 parsed_message = json_format_proto3_pb2.TestAny()432 self.CheckParseBack(message, parsed_message)433 def testWellKnownInAnyMessage(self):434 message = any_pb2.Any()435 int32_value = wrappers_pb2.Int32Value()436 int32_value.value = 1234437 message.Pack(int32_value)438 self.assertEqual(439 json.loads(json_format.MessageToJson(message, True)),440 json.loads(441 '{\n'442 ' "@type": \"type.googleapis.com/google.protobuf.Int32Value\",\n'443 ' "value": 1234\n'444 '}\n'))445 parsed_message = any_pb2.Any()446 self.CheckParseBack(message, parsed_message)447 timestamp = timestamp_pb2.Timestamp()448 message.Pack(timestamp)449 self.assertEqual(450 json.loads(json_format.MessageToJson(message, True)),451 json.loads(452 '{\n'453 ' "@type": "type.googleapis.com/google.protobuf.Timestamp",\n'454 ' "value": "1970-01-01T00:00:00Z"\n'455 '}\n'))456 self.CheckParseBack(message, parsed_message)457 duration = duration_pb2.Duration()458 duration.seconds = 1459 message.Pack(duration)460 self.assertEqual(461 json.loads(json_format.MessageToJson(message, True)),462 json.loads(463 '{\n'464 ' "@type": "type.googleapis.com/google.protobuf.Duration",\n'465 ' "value": "1s"\n'466 '}\n'))467 self.CheckParseBack(message, parsed_message)468 field_mask = field_mask_pb2.FieldMask()469 field_mask.paths.append('foo.bar')470 field_mask.paths.append('bar')471 message.Pack(field_mask)472 self.assertEqual(473 json.loads(json_format.MessageToJson(message, True)),474 json.loads(475 '{\n'476 ' "@type": "type.googleapis.com/google.protobuf.FieldMask",\n'477 ' "value": "foo.bar,bar"\n'478 '}\n'))479 self.CheckParseBack(message, parsed_message)480 struct_message = struct_pb2.Struct()481 struct_message['name'] = 'Jim'482 message.Pack(struct_message)483 self.assertEqual(484 json.loads(json_format.MessageToJson(message, True)),485 json.loads(486 '{\n'487 ' "@type": "type.googleapis.com/google.protobuf.Struct",\n'488 ' "value": {"name": "Jim"}\n'489 '}\n'))490 self.CheckParseBack(message, parsed_message)491 nested_any = any_pb2.Any()492 int32_value.value = 5678493 nested_any.Pack(int32_value)494 message.Pack(nested_any)495 self.assertEqual(496 json.loads(json_format.MessageToJson(message, True)),497 json.loads(498 '{\n'499 ' "@type": "type.googleapis.com/google.protobuf.Any",\n'500 ' "value": {\n'501 ' "@type": "type.googleapis.com/google.protobuf.Int32Value",\n'502 ' "value": 5678\n'503 ' }\n'504 '}\n'))505 self.CheckParseBack(message, parsed_message)506 def testParseNull(self):507 message = json_format_proto3_pb2.TestMessage()508 parsed_message = json_format_proto3_pb2.TestMessage()509 self.FillAllFields(parsed_message)510 json_format.Parse('{"int32Value": null, '511 '"int64Value": null, '512 '"uint32Value": null,'513 '"uint64Value": null,'514 '"floatValue": null,'515 '"doubleValue": null,'516 '"boolValue": null,'517 '"stringValue": null,'518 '"bytesValue": null,'519 '"messageValue": null,'520 '"enumValue": null,'521 '"repeatedInt32Value": null,'522 '"repeatedInt64Value": null,'523 '"repeatedUint32Value": null,'524 '"repeatedUint64Value": null,'525 '"repeatedFloatValue": null,'526 '"repeatedDoubleValue": null,'527 '"repeatedBoolValue": null,'528 '"repeatedStringValue": null,'529 '"repeatedBytesValue": null,'530 '"repeatedMessageValue": null,'531 '"repeatedEnumValue": null'532 '}',533 parsed_message)534 self.assertEqual(message, parsed_message)535 self.assertRaisesRegexp(536 json_format.ParseError,537 'Failed to parse repeatedInt32Value field: '538 'null is not allowed to be used as an element in a repeated field.',539 json_format.Parse,540 '{"repeatedInt32Value":[1, null]}',541 parsed_message)542 def testNanFloat(self):543 message = json_format_proto3_pb2.TestMessage()544 message.float_value = float('nan')545 text = '{\n "floatValue": "NaN"\n}'546 self.assertEqual(json_format.MessageToJson(message), text)547 parsed_message = json_format_proto3_pb2.TestMessage()548 json_format.Parse(text, parsed_message)549 self.assertTrue(math.isnan(parsed_message.float_value))550 def testParseEmptyText(self):551 self.CheckError('',552 r'Failed to load JSON: (Expecting value)|(No JSON).')553 def testParseBadEnumValue(self):554 self.CheckError(555 '{"enumValue": 1}',556 'Enum value must be a string literal with double quotes. '557 'Type "proto3.EnumType" has no value named 1.')558 self.CheckError(559 '{"enumValue": "baz"}',560 'Enum value must be a string literal with double quotes. '561 'Type "proto3.EnumType" has no value named baz.')562 def testParseBadIdentifer(self):563 self.CheckError('{int32Value: 1}',564 (r'Failed to load JSON: Expecting property name'565 r'( enclosed in double quotes)?: line 1'))566 self.CheckError('{"unknownName": 1}',567 'Message type "proto3.TestMessage" has no field named '568 '"unknownName".')569 def testDuplicateField(self):570 # Duplicate key check is not supported for python2.6571 if sys.version_info < (2, 7):572 return573 self.CheckError('{"int32Value": 1,\n"int32Value":2}',574 'Failed to load JSON: duplicate key int32Value.')575 def testInvalidBoolValue(self):576 self.CheckError('{"boolValue": 1}',577 'Failed to parse boolValue field: '578 'Expected true or false without quotes.')579 self.CheckError('{"boolValue": "true"}',580 'Failed to parse boolValue field: '581 'Expected true or false without quotes.')582 def testInvalidIntegerValue(self):583 message = json_format_proto3_pb2.TestMessage()584 text = '{"int32Value": 0x12345}'585 self.assertRaises(json_format.ParseError,586 json_format.Parse, text, message)587 self.CheckError('{"int32Value": 012345}',588 (r'Failed to load JSON: Expecting \'?,\'? delimiter: '589 r'line 1.'))590 self.CheckError('{"int32Value": 1.0}',591 'Failed to parse int32Value field: '592 'Couldn\'t parse integer: 1.0.')593 self.CheckError('{"int32Value": " 1 "}',594 'Failed to parse int32Value field: '595 'Couldn\'t parse integer: " 1 ".')596 self.CheckError('{"int32Value": "1 "}',597 'Failed to parse int32Value field: '598 'Couldn\'t parse integer: "1 ".')599 self.CheckError('{"int32Value": 12345678901234567890}',600 'Failed to parse int32Value field: Value out of range: '601 '12345678901234567890.')602 self.CheckError('{"int32Value": 1e5}',603 'Failed to parse int32Value field: '604 'Couldn\'t parse integer: 100000.0.')605 self.CheckError('{"uint32Value": -1}',606 'Failed to parse uint32Value field: '607 'Value out of range: -1.')608 def testInvalidFloatValue(self):609 self.CheckError('{"floatValue": "nan"}',610 'Failed to parse floatValue field: Couldn\'t '611 'parse float "nan", use "NaN" instead.')612 def testInvalidBytesValue(self):613 self.CheckError('{"bytesValue": "AQI"}',614 'Failed to parse bytesValue field: Incorrect padding.')615 self.CheckError('{"bytesValue": "AQI*"}',616 'Failed to parse bytesValue field: Incorrect padding.')617 def testInvalidMap(self):618 message = json_format_proto3_pb2.TestMap()619 text = '{"int32Map": {"null": 2, "2": 3}}'620 self.assertRaisesRegexp(621 json_format.ParseError,622 'Failed to parse int32Map field: invalid literal',623 json_format.Parse, text, message)624 text = '{"int32Map": {1: 2, "2": 3}}'625 self.assertRaisesRegexp(626 json_format.ParseError,627 (r'Failed to load JSON: Expecting property name'628 r'( enclosed in double quotes)?: line 1'),629 json_format.Parse, text, message)630 text = '{"boolMap": {"null": 1}}'631 self.assertRaisesRegexp(632 json_format.ParseError,633 'Failed to parse boolMap field: Expected "true" or "false", not null.',634 json_format.Parse, text, message)635 if sys.version_info < (2, 7):636 return637 text = r'{"stringMap": {"a": 3, "\u0061": 2}}'638 self.assertRaisesRegexp(639 json_format.ParseError,640 'Failed to load JSON: duplicate key a',641 json_format.Parse, text, message)642 def testInvalidTimestamp(self):643 message = json_format_proto3_pb2.TestTimestamp()644 text = '{"value": "10000-01-01T00:00:00.00Z"}'645 self.assertRaisesRegexp(646 json_format.ParseError,647 'time data \'10000-01-01T00:00:00\' does not match'648 ' format \'%Y-%m-%dT%H:%M:%S\'.',649 json_format.Parse, text, message)650 text = '{"value": "1970-01-01T00:00:00.0123456789012Z"}'651 self.assertRaisesRegexp(652 well_known_types.ParseError,653 'nanos 0123456789012 more than 9 fractional digits.',654 json_format.Parse, text, message)655 text = '{"value": "1972-01-01T01:00:00.01+08"}'656 self.assertRaisesRegexp(657 well_known_types.ParseError,658 (r'Invalid timezone offset value: \+08.'),659 json_format.Parse, text, message)660 # Time smaller than minimum time.661 text = '{"value": "0000-01-01T00:00:00Z"}'662 self.assertRaisesRegexp(663 json_format.ParseError,664 'Failed to parse value field: year is out of range.',665 json_format.Parse, text, message)666 # Time bigger than maxinum time.667 message.value.seconds = 253402300800668 self.assertRaisesRegexp(669 OverflowError,670 'date value out of range',671 json_format.MessageToJson, message)672 def testInvalidOneof(self):673 message = json_format_proto3_pb2.TestOneof()674 text = '{"oneofInt32Value": 1, "oneofStringValue": "2"}'675 self.assertRaisesRegexp(676 json_format.ParseError,677 'Message type "proto3.TestOneof"'678 ' should not have multiple "oneof_value" oneof fields.',679 json_format.Parse, text, message)680 def testInvalidListValue(self):681 message = json_format_proto3_pb2.TestListValue()682 text = '{"value": 1234}'683 self.assertRaisesRegexp(684 json_format.ParseError,685 r'Failed to parse value field: ListValue must be in \[\] which is 1234',686 json_format.Parse, text, message)687 def testInvalidStruct(self):688 message = json_format_proto3_pb2.TestStruct()689 text = '{"value": 1234}'690 self.assertRaisesRegexp(691 json_format.ParseError,692 'Failed to parse value field: Struct must be in a dict which is 1234',693 json_format.Parse, text, message)694 def testInvalidAny(self):695 message = any_pb2.Any()696 text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'697 self.assertRaisesRegexp(698 KeyError,699 'value',700 json_format.Parse, text, message)701 text = '{"value": 1234}'702 self.assertRaisesRegexp(703 json_format.ParseError,704 '@type is missing when parsing any message.',705 json_format.Parse, text, message)706 text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'707 self.assertRaisesRegexp(708 TypeError,709 'Can not find message descriptor by type_url: '710 'type.googleapis.com/MessageNotExist.',711 json_format.Parse, text, message)712 # Only last part is to be used: b/25630112713 text = (r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'714 r'"value": 1234}')715 json_format.Parse(text, message)716if __name__ == '__main__':...

Full Screen

Full Screen

geetest.py

Source:geetest.py Github

copy

Full Screen

1#!coding:utf82import sys3import random4import json5import requests6import time7from hashlib import md58if sys.version_info >= (3,):9 xrange = range 10VERSION = "3.0.0"11class GeetestLib(object):12 FN_CHALLENGE = "geetest_challenge"13 FN_VALIDATE = "geetest_validate"14 FN_SECCODE = "geetest_seccode"15 GT_STATUS_SESSION_KEY = "gt_server_status"16 API_URL = "http://api.geetest.com"17 REGISTER_HANDLER = "/register.php"18 VALIDATE_HANDLER = "/validate.php"19 JSON_FORMAT = False20 def __init__(self, captcha_id, private_key):21 self.private_key = private_key22 self.captcha_id = captcha_id23 self.sdk_version = VERSION24 self._response_str = ""25 def pre_process(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):26 """27 验证初始化预处理.28 //TO DO arrage the parameter29 """30 status, challenge = self._register(user_id,new_captcha,JSON_FORMAT,client_type,ip_address)31 self._response_str = self._make_response_format(status, challenge,new_captcha)32 return status33 def _register(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):34 pri_responce = self._register_challenge(user_id,new_captcha,JSON_FORMAT,client_type,ip_address)35 if pri_responce:36 if JSON_FORMAT == 1:37 response_dic = json.loads(pri_responce)38 challenge = response_dic["challenge"]39 else:40 challenge = pri_responce41 else:42 challenge=" "43 if len(challenge) == 32:44 challenge = self._md5_encode("".join([challenge, self.private_key]))45 return 1,challenge46 else:47 return 0, self._make_fail_challenge()48 def get_response_str(self):49 return self._response_str50 def _make_fail_challenge(self):51 rnd1 = random.randint(0, 99)52 rnd2 = random.randint(0, 99)53 md5_str1 = self._md5_encode(str(rnd1))54 md5_str2 = self._md5_encode(str(rnd2))55 challenge = md5_str1 + md5_str2[0:2]56 return challenge57 def _make_response_format(self, success=1, challenge=None,new_captcha=1):58 if not challenge:59 challenge = self._make_fail_challenge()60 if new_captcha:61 string_format = json.dumps(62 {'success': success, 'gt':self.captcha_id, 'challenge': challenge,"new_captcha":True})63 else:64 string_format = json.dumps(65 {'success': success, 'gt':self.captcha_id, 'challenge': challenge,"new_captcha":False})66 return string_format67 def _register_challenge(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):68 if user_id:69 register_url = "{api_url}{handler}?gt={captcha_ID}&user_id={user_id}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format(70 api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id, user_id=user_id,new_captcha=new_captcha,JSON_FORMAT=JSON_FORMAT,client_type=client_type,ip_address=ip_address)71 else:72 register_url = "{api_url}{handler}?gt={captcha_ID}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format(73 api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id,new_captcha=new_captcha,JSON_FORMAT=JSON_FORMAT,client_type=client_type,ip_address=ip_address)74 try:75 response = requests.get(register_url, timeout=2)76 if response.status_code == requests.codes.ok:77 res_string = response.text78 else:79 res_string = ""80 except:81 res_string = ""82 return res_string83 def success_validate(self, challenge, validate, seccode, user_id=None,gt=None,data='',userinfo='',JSON_FORMAT=1):84 """85 正常模式的二次验证方式.向geetest server 请求验证结果.86 """87 if not self._check_para(challenge, validate, seccode):88 return 089 if not self._check_result(challenge, validate):90 return 091 validate_url = "{api_url}{handler}".format(92 api_url=self.API_URL, handler=self.VALIDATE_HANDLER)93 query = {94 "seccode": seccode,95 "sdk": ''.join( ["python_",self.sdk_version]),96 "user_id": user_id,97 "data":data,98 "timestamp":time.time(),99 "challenge":challenge,100 "userinfo":userinfo,101 "captchaid":gt,102 "json_format":JSON_FORMAT103 }104 backinfo = self._post_values(validate_url, query)105 if JSON_FORMAT == 1:106 backinfo = json.loads(backinfo)107 backinfo = backinfo["seccode"]108 if backinfo == self._md5_encode(seccode):109 return 1110 else:111 return 0112 def _post_values(self, apiserver, data):113 response = requests.post(apiserver, data)114 return response.text115 def _check_result(self, origin, validate):116 encodeStr = self._md5_encode(self.private_key + "geetest" + origin)117 if validate == encodeStr:118 return True119 else:120 return False121 def failback_validate(self, challenge, validate, seccode):122 """123 failback模式的二次验证方式.在本地对轨迹进行简单的判断返回验证结果.124 """125 if not self._check_para(challenge, validate, seccode):126 return 0127 validate_result = self._failback_check_result(128 challenge, validate,)129 return validate_result130 def _failback_check_result(self,challenge,validate):131 encodeStr = self._md5_encode(challenge)132 if validate == encodeStr:133 return True134 else:135 return False136 def _check_para(self, challenge, validate, seccode):137 return (bool(challenge.strip()) and bool(validate.strip()) and bool(seccode.strip()))138 def _md5_encode(self, values):139 if type(values) == str:140 values = values.encode()141 m = md5(values)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Behave automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful