Best Python code snippet using playwright-python
executor_serialization_test.py
Source:executor_serialization_test.py
...25class ExecutorServiceUtilsTest(tf.test.TestCase):26 def test_serialize_deserialize_tensor_value(self):27 x = tf.constant(10.0).numpy()28 type_spec = computation_types.TensorType(tf.as_dtype(x.dtype), x.shape)29 value_proto, value_type = executor_serialization.serialize_value(30 x, type_spec)31 self.assertIsInstance(value_proto, executor_pb2.Value)32 self.assertEqual(str(value_type), 'float32')33 y, type_spec = executor_serialization.deserialize_value(value_proto)34 self.assertEqual(str(type_spec), 'float32')35 self.assertTrue(np.array_equal(x, y))36 def test_serialize_deserialize_tensor_value_with_different_dtype(self):37 x = tf.constant(10.0).numpy()38 value_proto, value_type = (39 executor_serialization.serialize_value(40 x, computation_types.TensorType(tf.int32)))41 self.assertIsInstance(value_proto, executor_pb2.Value)42 self.assertEqual(str(value_type), 'int32')43 y, type_spec = executor_serialization.deserialize_value(value_proto)44 self.assertEqual(str(type_spec), 'int32')45 self.assertEqual(y, 10)46 def test_serialize_deserialize_tensor_value_with_nontrivial_shape(self):47 x = tf.constant([10, 20, 30]).numpy()48 value_proto, value_type = executor_serialization.serialize_value(49 x, computation_types.TensorType(tf.int32, [3]))50 self.assertIsInstance(value_proto, executor_pb2.Value)51 self.assertEqual(str(value_type), 'int32[3]')52 y, type_spec = executor_serialization.deserialize_value(value_proto)53 self.assertEqual(str(type_spec), 'int32[3]')54 self.assertTrue(np.array_equal(x, y))55 def test_serialize_sequence_bad_element_type(self):56 x = tf.data.Dataset.range(5).map(lambda x: x * 2)57 with self.assertRaisesRegex(58 TypeError, r'Cannot serialize dataset .* int64\* .* float32\*.*'):59 _ = executor_serialization.serialize_value(60 x, computation_types.SequenceType(tf.float32))61 def test_serialize_sequence_not_a_dataset(self):62 with self.assertRaisesRegex(63 TypeError, r'Cannot serialize Python type int as .* float32\*'):64 _ = executor_serialization.serialize_value(65 5, computation_types.SequenceType(tf.float32))66 # TODO(b/137602785): bring GPU test back after the fix for `wrap_function`.67 @test_utils.skip_test_for_gpu68 def test_serialize_deserialize_sequence_of_scalars(self):69 ds = tf.data.Dataset.range(5).map(lambda x: x * 2)70 value_proto, value_type = executor_serialization.serialize_value(71 ds, computation_types.SequenceType(tf.int64))72 self.assertIsInstance(value_proto, executor_pb2.Value)73 self.assertEqual(str(value_type), 'int64*')74 y, type_spec = executor_serialization.deserialize_value(value_proto)75 self.assertEqual(str(type_spec), 'int64*')76 self.assertAllEqual(list(y), [x * 2 for x in range(5)])77 # TODO(b/137602785): bring GPU test back after the fix for `wrap_function`.78 @test_utils.skip_test_for_gpu79 def test_serialize_deserialize_sequence_of_tuples(self):80 ds = tf.data.Dataset.range(5).map(81 lambda x: (x * 2, tf.cast(x, tf.int32), tf.cast(x - 1, tf.float32)))82 value_proto, value_type = executor_serialization.serialize_value(83 ds,84 computation_types.SequenceType(85 element=(tf.int64, tf.int32, tf.float32)))86 self.assertIsInstance(value_proto, executor_pb2.Value)87 self.assertEqual(str(value_type), '<int64,int32,float32>*')88 y, type_spec = executor_serialization.deserialize_value(value_proto)89 self.assertEqual(str(type_spec), '<int64,int32,float32>*')90 self.assertAllEqual(91 self.evaluate(list(y)), [(x * 2, x, x - 1.) for x in range(5)])92 # TODO(b/137602785): bring GPU test back after the fix for `wrap_function`.93 @test_utils.skip_test_for_gpu94 def test_serialize_deserialize_sequence_of_namedtuples(self):95 test_tuple_type = collections.namedtuple('TestTuple', ['a', 'b', 'c'])96 def make_test_tuple(x):97 return test_tuple_type(98 a=x * 2, b=tf.cast(x, tf.int32), c=tf.cast(x - 1, tf.float32))99 ds = tf.data.Dataset.range(5).map(make_test_tuple)100 element_type = computation_types.StructType([101 ('a', tf.int64),102 ('b', tf.int32),103 ('c', tf.float32),104 ])105 sequence_type = computation_types.SequenceType(element=element_type)106 value_proto, value_type = executor_serialization.serialize_value(107 ds, sequence_type)108 self.assertIsInstance(value_proto, executor_pb2.Value)109 self.assertEqual(value_type, sequence_type)110 y, type_spec = executor_serialization.deserialize_value(value_proto)111 self.assertEqual(type_spec, sequence_type)112 actual_values = self.evaluate(list(y))113 expected_values = [114 test_tuple_type(a=x * 2, b=x, c=x - 1.) for x in range(5)115 ]116 for actual, expected in zip(actual_values, expected_values):117 self.assertAllClose(actual, expected)118 # TODO(b/137602785): bring GPU test back after the fix for `wrap_function`.119 @test_utils.skip_test_for_gpu120 def test_serialize_deserialize_sequence_of_nested_structures(self):121 test_tuple_type = collections.namedtuple('TestTuple', ['u', 'v'])122 def _make_nested_tf_structure(x):123 return collections.OrderedDict([124 ('b', tf.cast(x, tf.int32)),125 ('a',126 tuple([127 x,128 test_tuple_type(x * 2, x * 3),129 collections.OrderedDict([('x', x**2), ('y', x**3)])130 ])),131 ])132 ds = tf.data.Dataset.range(5).map(_make_nested_tf_structure)133 element_type = computation_types.StructType([134 ('b', tf.int32),135 ('a',136 computation_types.StructType([137 (None, tf.int64),138 (None, test_tuple_type(tf.int64, tf.int64)),139 (None,140 computation_types.StructType([('x', tf.int64), ('y', tf.int64)])),141 ])),142 ])143 sequence_type = computation_types.SequenceType(element=element_type)144 value_proto, value_type = executor_serialization.serialize_value(145 ds, sequence_type)146 self.assertIsInstance(value_proto, executor_pb2.Value)147 self.assertEqual(value_type, sequence_type)148 y, type_spec = executor_serialization.deserialize_value(value_proto)149 # These aren't the same because ser/de destroys the PyContainer150 type_spec.check_equivalent_to(sequence_type)151 def _build_expected_structure(x):152 return collections.OrderedDict([153 ('b', x),154 ('a',155 tuple([156 x,157 test_tuple_type(x * 2, x * 3),158 collections.OrderedDict([('x', x**2), ('y', x**3)])159 ])),160 ])161 actual_values = self.evaluate(list(y))162 expected_values = [_build_expected_structure(x) for x in range(5)]163 for actual, expected in zip(actual_values, expected_values):164 self.assertEqual(type(actual), type(expected))165 self.assertAllClose(actual, expected)166 def test_serialize_deserialize_tensor_value_with_bad_shape(self):167 x = tf.constant([10, 20, 30]).numpy()168 with self.assertRaises(TypeError):169 executor_serialization.serialize_value(x, tf.int32)170 def test_serialize_deserialize_computation_value(self):171 @computations.tf_computation172 def comp():173 return tf.constant(10)174 value_proto, value_type = executor_serialization.serialize_value(comp)175 self.assertEqual(value_proto.WhichOneof('value'), 'computation')176 self.assertEqual(str(value_type), '( -> int32)')177 comp, type_spec = executor_serialization.deserialize_value(value_proto)178 self.assertIsInstance(comp, computation_pb2.Computation)179 self.assertEqual(str(type_spec), '( -> int32)')180 def test_serialize_deserialize_nested_tuple_value_with_names(self):181 x = collections.OrderedDict([('a', 10), ('b', [20, 30]),182 ('c', collections.OrderedDict([('d', 40)]))])183 x_type = computation_types.to_type(184 collections.OrderedDict([('a', tf.int32), ('b', [tf.int32, tf.int32]),185 ('c', collections.OrderedDict([('d', tf.int32)186 ]))]))187 value_proto, value_type = executor_serialization.serialize_value(x, x_type)188 self.assertIsInstance(value_proto, executor_pb2.Value)189 self.assertEqual(str(value_type), '<a=int32,b=<int32,int32>,c=<d=int32>>')190 y, type_spec = executor_serialization.deserialize_value(value_proto)191 self.assertEqual(str(type_spec), str(x_type))192 self.assertTrue(str(y), '<a=10,b=<20,30>,c=<d=40>>')193 def test_serialize_deserialize_nested_tuple_value_without_names(self):194 x = tuple([10, 20])195 x_type = computation_types.to_type(tuple([tf.int32, tf.int32]))196 value_proto, value_type = executor_serialization.serialize_value(x, x_type)197 self.assertIsInstance(value_proto, executor_pb2.Value)198 self.assertEqual(str(value_type), '<int32,int32>')199 y, type_spec = executor_serialization.deserialize_value(value_proto)200 self.assertEqual(str(type_spec), str(x_type))201 self.assertCountEqual(y, (10, 20))202 def test_serialize_deserialize_federated_at_clients(self):203 x = [10, 20]204 x_type = computation_types.at_clients(tf.int32)205 value_proto, value_type = executor_serialization.serialize_value(x, x_type)206 self.assertIsInstance(value_proto, executor_pb2.Value)207 self.assertEqual(str(value_type), '{int32}@CLIENTS')208 y, type_spec = executor_serialization.deserialize_value(value_proto)209 self.assertEqual(str(type_spec), str(x_type))210 self.assertEqual(y, [10, 20])211 def test_serialize_deserialize_federated_at_server(self):212 x = 10213 x_type = computation_types.at_server(tf.int32)214 value_proto, value_type = executor_serialization.serialize_value(x, x_type)215 self.assertIsInstance(value_proto, executor_pb2.Value)216 self.assertEqual(str(value_type), 'int32@SERVER')217 y, type_spec = executor_serialization.deserialize_value(value_proto)218 self.assertEqual(str(type_spec), str(x_type))219 self.assertEqual(y, 10)220class DatasetSerializationTest(test_case.TestCase):221 def test_serialize_sequence_not_a_dataset(self):222 with self.assertRaisesRegex(TypeError, r'Expected .*Dataset.* found int'):223 _ = executor_serialization._serialize_dataset(5)224 def test_serialize_sequence_bytes_too_large(self):225 with self.assertRaisesRegex(ValueError,226 r'Serialized size .* exceeds maximum allowed'):227 _ = executor_serialization._serialize_dataset(228 tf.data.Dataset.range(5), max_serialized_size_bytes=0)229 def test_roundtrip_sequence_of_scalars(self):230 x = tf.data.Dataset.range(5).map(lambda x: x * 2)231 serialized_bytes = executor_serialization._serialize_dataset(x)...
test_games.py
Source:test_games.py
...20 r = client.get('/games', headers={ 'X-Remote-User': owner.username })21 assert r.status_code == 20022 assert r.json() == [23 {24 'id': serialize_value(game.id),25 'created_at': serialize_value(game.created_at),26 'updated_at': serialize_value(game.updated_at),27 'description': 'My dummy game',28 'gender': None,29 'owner': {30 'id': serialize_value(owner.id),31 'created_at': serialize_value(owner.created_at),32 'updated_at': serialize_value(owner.updated_at),33 'username': owner.username34 }35 }36 ]37 # As guest38 r = client.get('/games', headers={ 'X-Remote-User': guest.username })39 assert r.status_code == 20040 assert r.json() == [41 {42 'id': serialize_value(game.id),43 'created_at': serialize_value(game.created_at),44 'updated_at': serialize_value(game.updated_at),45 'description': 'My dummy game',46 'gender': None,47 'owner': {48 'id': serialize_value(owner.id),49 'created_at': serialize_value(owner.created_at),50 'updated_at': serialize_value(owner.updated_at),51 'username': owner.username52 }53 }54 ]55 # As other56 r = client.get('/games', headers={ 'X-Remote-User': other.username })57 assert r.status_code == 20058 assert r.json() == []59def test_create_game(client: TestClient):60 # Without authentication61 r = client.post('/games', json={})62 assert r.status_code == 40163 # Creation64 r = client.post('/games', headers={ 'X-Remote-User': 'admin' }, json={65 'description': 'The description',66 'gender': 'M'67 })68 assert r.status_code == 20169 assert r.json().get('description') == 'The description'70 assert r.json().get('gender') == 'M'71 # Invalid gender72 r = client.post('/games', headers={ 'X-Remote-User': 'admin' }, json={73 'description': 'Invalid',74 'gender': 'T'75 })76 assert r.status_code == 42277 assert r.json() == {78 'detail': [79 { 80 'loc': ['body', 'gender'],81 'msg': "value is not a valid enumeration member; permitted: 'M', 'F'",82 'type': 'type_error.enum',83 'ctx': {84 'enum_values': ['M', 'F']85 }86 }87 ]88 }89def test_update_game(client: TestClient, database: Session):90 owner = insert_user(database, username='owner')91 guest = insert_user(database, username='guest')92 other = insert_user(database, username='other')93 game = insert_game(database, owner)94 insert_game_guest(database, game, guest)95 # As owner96 r = client.put(f'/games/{game.id}', headers={ 'X-Remote-User': owner.username }, json={ 'description': 'Update 1' })97 assert r.status_code == 20098 assert r.json().get('description') == 'Update 1'99 # As guest100 r = client.put(f'/games/{game.id}', headers={ 'X-Remote-User': guest.username }, json={ 'description': 'Update 2' })101 assert r.status_code == 200102 assert r.json().get('description') == 'Update 2'103 # As other104 r = client.put(f'/games/{game.id}', headers={ 'X-Remote-User': other.username }, json={ 'description': 'Update 3' })105 assert r.status_code == 404106 # Unknown game107 r = client.put(f'/games/00000000-0000-0000-0000-000000000000', headers={ 'X-Remote-User': other.username }, json={ 'description': 'Update 4' })108 assert r.status_code == 404109def test_delete_game(client: TestClient, database: Session, user: User):110 game = insert_game(database, user)111 other = insert_user(database, username='other')112 r = client.delete(f'/games/{game.id}')113 assert r.status_code == 401114 r = client.delete(f'/games/{game.id}', headers={ 'X-Remote-User': other.username })115 assert r.status_code == 404116 r = client.delete(f'/games/{game.id}', headers={ 'X-Remote-User': user.username })117 assert r.status_code == 204118 r = client.delete(f'/games/{game.id}', headers={ 'X-Remote-User': user.username })119 assert r.status_code == 404120def test_get_game_guests(client: TestClient, database: Session, user: User):121 game = insert_game(database, user)122 guests = list(insert_user(database, username=f'guest-{i}') for i in range(1, 4))123 # Without authent124 r = client.get(f'/games/{game.id}/guests')125 assert r.status_code == 401126 # Empty list127 r = client.get(f'/games/{game.id}/guests', headers={ 'X-Remote-User': user.username })128 assert r.status_code == 200129 assert r.json() == []130 # Invite guests131 for u in guests:132 insert_game_guest(database, game, u)133 # Guests list134 r = client.get(f'/games/{game.id}/guests', headers={ 'X-Remote-User': user.username })135 assert r.status_code == 200136 assert r.json() == list(137 {138 'id': serialize_value(u.id),139 'created_at': serialize_value(u.created_at),140 'updated_at': serialize_value(u.updated_at),141 'username': u.username,142 } for u in guests143 )144 # Unknown game145 r = client.get('/games/00000000-0000-0000-0000-000000000000/guests', headers={ 'X-Remote-User': user.username })146 assert r.status_code == 404147def test_add_game_guests(client: TestClient, database: Session, user: User):148 game = insert_game(database, user)149 guests = list(insert_user(database, username=f'guest-{i}') for i in range(1, 4))150 # Add guest 1 without authent151 r = client.post(f'/games/{game.id}/guests', json={ 'user_id': serialize_value(guests[0].id) })152 assert r.status_code == 401153 # Add guest 1154 r = client.post(f'/games/{game.id}/guests', headers={ 'X-Remote-User': user.username }, json={ 'user_id': serialize_value(guests[0].id) })155 assert r.status_code == 200156 assert r.json() == list(157 {158 'id': serialize_value(u.id),159 'created_at': serialize_value(u.created_at),160 'updated_at': serialize_value(u.updated_at),161 'username': u.username,162 } for u in guests[0:1]163 )164 # Add guest 1 again165 r = client.post(f'/games/{game.id}/guests', headers={ 'X-Remote-User': user.username }, json={ 'user_id': serialize_value(guests[0].id) })166 assert r.status_code == 422167 # Add guest 2168 r = client.post(f'/games/{game.id}/guests', headers={ 'X-Remote-User': user.username }, json={ 'user_id': serialize_value(guests[1].id) })169 assert r.status_code == 200170 assert r.json() == list(171 {172 'id': serialize_value(u.id),173 'created_at': serialize_value(u.created_at),174 'updated_at': serialize_value(u.updated_at),175 'username': u.username,176 } for u in guests[0:2]177 )178 # Add guest 3 as other user179 r = client.post(f'/games/{game.id}/guests', headers={ 'X-Remote-User': 'other' }, json={ 'user_id': serialize_value(guests[2].id) })180 assert r.status_code == 404181 # Add guest 3 to an unknown game182 r = client.post('/games/00000000-0000-0000-0000-000000000000/guests', headers={ 'X-Remote-User': 'other' }, json={ 'user_id': serialize_value(guests[2].id) })183 assert r.status_code == 404184def test_remove_game_guest(client: TestClient, database: Session, user: User):185 game = insert_game(database, user)186 guests = list(insert_user(database, username=f'guest-{i}') for i in range(1, 4))187 for u in guests:188 insert_game_guest(database, game, u)189 # Remove guest 1 without authent190 r = client.delete(f'/games/{game.id}/guests/{guests[0].id}')191 assert r.status_code == 401192 # Remove guest 1193 r = client.delete(f'/games/{game.id}/guests/{guests[0].id}', headers={ 'X-Remote-User': user.username })194 assert r.status_code == 200195 assert r.json() == list(196 {197 'id': serialize_value(u.id),198 'created_at': serialize_value(u.created_at),199 'updated_at': serialize_value(u.updated_at),200 'username': u.username,201 } for u in guests[1:]202 )203 # Remove guest 1 again204 r = client.delete(f'/games/{game.id}/guests/{guests[0].id}', headers={ 'X-Remote-User': user.username })205 assert r.status_code == 200206 assert r.json() == list(207 {208 'id': serialize_value(u.id),209 'created_at': serialize_value(u.created_at),210 'updated_at': serialize_value(u.updated_at),211 'username': u.username,212 } for u in guests[1:]213 )214 # Remove guest 2215 r = client.delete(f'/games/{game.id}/guests/{guests[1].id}', headers={ 'X-Remote-User': user.username })216 assert r.status_code == 200217 assert r.json() == list(218 {219 'id': serialize_value(u.id),220 'created_at': serialize_value(u.created_at),221 'updated_at': serialize_value(u.updated_at),222 'username': u.username,223 } for u in guests[2:]224 )225 # Remove guest 3 as other user226 r = client.delete(f'/games/{game.id}/guests/{guests[2].id}', headers={ 'X-Remote-User': 'other' })227 assert r.status_code == 404228 # Remove guest 3 to an unknown game229 r = client.delete(f'/games/00000000-0000-0000-0000-000000000000/guests/{guests[2].id}', headers={ 'X-Remote-User': 'other' })230 assert r.status_code == 404231def test_create_first_stage(client: TestClient, database: Session, user: User, name: Name):232 game = insert_game(database, user)233 # Create choice without authent234 r = client.post(f'/games/{game.id}/stage-1', json={ 'name_id': serialize_value(name.id), 'choice': True })235 assert r.status_code == 401236 # Create choice as other237 r = client.post(f'/games/{game.id}/stage-1', headers={ 'X-Remote-User': 'other' }, json={ 'name_id': serialize_value(name.id), 'choice': True })238 assert r.status_code == 404239 # Create choice as user240 r = client.post(f'/games/{game.id}/stage-1', headers={ 'X-Remote-User': user.username }, json={ 'name_id': serialize_value(name.id), 'choice': True })241 assert r.status_code == 201242 assert r.json().get('game') == {243 'id': serialize_value(game.id),244 'created_at': serialize_value(game.created_at),245 'updated_at': serialize_value(game.updated_at),246 'description': game.description,247 'gender': game.gender,248 'owner': serialize_value(user),249 }250 assert r.json().get('user') == serialize_value(user)251 assert r.json().get('name') == serialize_value(name)252 assert r.json().get('choice') == True253 # Create choice as user again254 r = client.post(f'/games/{game.id}/stage-1', headers={ 'X-Remote-User': user.username }, json={ 'name_id': serialize_value(name.id), 'choice': True })255 assert r.status_code == 422256 # Create choice as user to an unknown game257 r = client.post('/games/00000000-0000-0000-0000-000000000000/stage-1', headers={ 'X-Remote-User': user.username }, json={ 'name_id': serialize_value(name.id), 'choice': True })258 assert r.status_code == 404259def test_get_first_stage_next(client: TestClient, database: Session, user: User, name: Name):260 game = insert_game(database, user)261 # Without authent262 r = client.get(f'/games/{game.id}/stage-1/next')263 assert r.status_code == 401264 # As other265 r = client.get(f'/games/{game.id}/stage-1/next', headers={ 'X-Remote-User': 'other' })266 assert r.status_code == 404267 # As user268 r = client.get(f'/games/{game.id}/stage-1/next', headers={ 'X-Remote-User': user.username })269 assert r.status_code == 200270 assert r.json() == serialize_value(name)271 # Unknown game272 r = client.get('/games/00000000-0000-0000-0000-000000000000/stage-1/next', headers={ 'X-Remote-User': user.username })273 assert r.status_code == 404274def test_get_first_stage_result(client: TestClient, database: Session):275 users = list(276 insert_user(database, username=f'user-{i}') for i in range(1, 3)277 )278 game = insert_game(database, users[0])279 for u in users[1:]:280 insert_game_guest(database, game, u)281 names = list(282 insert_name(database, value=f'name-{i}') for i in range(1, 11)283 )284 for idx, name in enumerate(names):285 insert_first_stage(database, game, users[idx % 2], name, choice=True)286 insert_first_stage(database, game, users[(idx + 1) % 2], name, choice=False)287 match_name = insert_name(database, value='matched')288 for u in users[0:2]:289 insert_first_stage(database, game, u, match_name, choice=True)290 # Without authent291 r = client.get(f'/games/{game.id}/stage-1/result')292 assert r.status_code == 401293 # As other294 r = client.get(f'/games/{game.id}/stage-1/result', headers={ 'X-Remote-User': 'other' })295 assert r.status_code == 404296 # Unknown game297 r = client.get('/games/00000000-0000-0000-0000-000000000000/stage-1/result', headers={ 'X-Remote-User': users[0].username })298 assert r.status_code == 404299 # As user300 r = client.get(f'/games/{game.id}/stage-1/result', headers={ 'X-Remote-User': users[0].username })301 assert r.status_code == 200...
test_env.py
Source:test_env.py
...112 value="value4", is_active=False, property=cls.property_2113 )114 cls.value_5 = f.TCMSEnvValueFactory(value="value5", property=cls.property_2)115 @staticmethod116 def serialize_value(property_value):117 return {118 "id": property_value.pk,119 "value": property_value.value,120 "is_active": property_value.is_active,121 "property_id": property_value.property.pk,122 "property": property_value.property.name,123 }124 def test_filter_values(self):125 values = env.filter_values(126 self.request,127 {128 "is_active": False,129 "value": "value4",130 "property__pk": self.property_2.pk,131 },132 )133 self.assertListEqual([self.serialize_value(self.value_4)], values)134 def test_get_all_values(self):135 values = sorted(env.filter_values(self.request, {}), key=lambda item: item["id"])136 expected = [137 self.serialize_value(self.value_1),138 self.serialize_value(self.value_2),139 self.serialize_value(self.value_3),140 self.serialize_value(self.value_4),141 self.serialize_value(self.value_5),142 ]143 self.assertListEqual(expected, values)144 def test_active_values_by_default(self):145 result = sorted(env.get_values(self.request), key=lambda item: item["id"])146 expected = [147 self.serialize_value(self.value_2),148 self.serialize_value(self.value_3),149 self.serialize_value(self.value_5),150 ]151 self.assertListEqual(expected, result)152 def test_get_values_by_property_id(self):153 result = sorted(154 env.get_values(self.request, self.property_1.pk),155 key=lambda item: item["id"],156 )157 expected = [self.serialize_value(self.value_2)]158 self.assertListEqual(expected, result)159 def test_get_values_by_active_status(self):160 result = sorted(env.get_values(self.request, is_active=False), key=lambda item: item["id"])161 expected = [162 self.serialize_value(self.value_1),163 self.serialize_value(self.value_4),164 ]...
PHPSerialize.py
Source:PHPSerialize.py
...36 out = out + "%s|%s" % (k, self.serialize(v))37 return out38 39 def serialize(self, data):40 return self.serialize_value(data)41 def is_int(self, data):42 """43 Determine if a string var looks like an integer44 TODO: Make this do what PHP does, instead of a hack45 """46 try: 47 int(data)48 return True49 except:50 return False51 52 def serialize_key(self, data):53 """54 Serialize a key, which follows different rules than when 55 serializing values. Many thanks to Todd DeLuca for pointing 56 out that keys are serialized differently than values!57 58 From http://us2.php.net/manual/en/language.types.array.php59 A key may be either an integer or a string. 60 If a key is the standard representation of an integer, it will be61 interpreted as such (i.e. "8" will be interpreted as int 8,62 while "08" will be interpreted as "08"). 63 Floats in key are truncated to integer. 64 """65 # Integer, Long, Float, Boolean => integer66 if type(data) is types.IntType or type(data) is types.LongType \67 or type(data) is types.FloatType or type(data) is types.BooleanType:68 return "i:%s;" % int(data)69 70 # String => string or String => int (if string looks like int)71 elif type(data) is types.StringType:72 if self.is_int(data):73 return "i:%s;" % int(data)74 else:75 return "s:%i:\"%s\";" % (len(data), data);76 77 # None / NULL => empty string78 elif type(data) is types.NoneType:79 return "s:0:\"\";"80 81 # I dont know how to serialize this82 else:83 raise Exception("Unknown / Unhandled key type (%s)!" % type(data))84 def serialize_value(self, data):85 """86 Serialize a value.87 """88 # Integer => integer89 if type(data) is types.IntType:90 return "i:%s;" % data91 # Float, Long => double92 elif type(data) is types.FloatType or type(data) is types.LongType:93 return "d:%s;" % data94 # String => string or String => int (if string looks like int)95 # Thanks to Todd DeLuca for noticing that PHP strings that96 # look like integers are serialized as ints by PHP 97 elif type(data) is types.StringType:98 if self.is_int(data):99 return "i:%s;" % int(data)100 else:101 return "s:%i:\"%s\";" % (len(data), data);102 # None / NULL103 elif type(data) is types.NoneType:104 return "N;";105 # Tuple and List => array106 # The 'a' array type is the only kind of list supported by PHP.107 # array keys are automagically numbered up from 0108 elif type(data) is types.ListType or type(data) is types.TupleType:109 i = 0110 out = []111 # All arrays must have keys112 for k in data:113 out.append(self.serialize_key(i))114 out.append(self.serialize_value(k))115 i += 1116 return "a:%i:{%s}" % (len(data), "".join(out))117 # Dict => array118 # Dict is the Python analogy of a PHP array119 elif type(data) is types.DictType:120 out = []121 for k in data:122 out.append(self.serialize_key(k))123 out.append(self.serialize_value(data[k]))124 return "a:%i:{%s}" % (len(data), "".join(out))125 # Boolean => bool126 elif type(data) is types.BooleanType:127 return "b:%i;" % (data == 1)128 # I dont know how to serialize this129 else:...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!