def test_class_should_inherit_pyckson_parameters(): @dataclass @no_camel_case class Parent: my_attribute: str @dataclass class Child(Parent): foo_bar: str assert serialize(Parent('foo')) == {'my_attribute': 'foo'} assert serialize(Child('foo', 'bar')) == {'my_attribute': 'foo', 'foo_bar': 'bar'}
def update_orbits(self, username: str, fleets: List[Fleet]): requests = [ DeleteMany({'username': username, 'sourceType': SourceType.planet.name}), ] for fleet in fleets: requests.append(InsertOne(serialize(fleet))) self.collection.bulk_write(requests)
def test_should_apply_no_camel_case_to_all(defaults): class Foo: def __init__(self, some_thing: str): self.some_thing = some_thing set_defaults(no_camel_case) assert serialize(Foo('bar')) == {'some_thing': 'bar'}
def respond(self, response_url: str, message: Message): reply = requests.post(response_url, json=serialize(message)) try: reply.raise_for_status() except HTTPError: logging.getLogger(__name__).error(reply.text) print('##### blocks #####') print(dumps(message.blocks)) raise
def test_serialize_date_with_formatter(): @date_formatter(TestFormatter()) class Foo: def __init__(self, bar: date): self.bar = bar result = serialize(Foo(date(2018, 3, 8))) assert result == {'bar': 43}
def save(self, resa: Resa): self.collection.update( { 'galaxy': resa.galaxy, 'sector': resa.sector, 'position': resa.position }, serialize(resa), upsert=True)
def test_annotation_should_override_defaults(defaults): @use_camel_case class Foo: def __init__(self, some_thing: str): self.some_thing = some_thing set_defaults(no_camel_case) assert serialize(Foo('bar')) == {'someThing': 'bar'}
def test_date_default(defaults): class Foo: def __init__(self, day: datetime): self.day = day set_defaults(date_formatter(ArrowStringFormatter())) assert serialize(Foo(datetime(2013, 5, 5, 12, 30, 45))) == { 'day': '2013-05-05T12:30:45+00:00' }
def test_json_serialize(): """オブジェクトのJson変換(jackson的な)のテスト """ # dictionary型に変換される a = TestJsonSerialize("p1", "p2") # ログ出し current_app.logger.info(vars(a)) # dictionaryをjson文字列に変換する return json.jsonify(pyckson.serialize(a))
def handle_reply(self, reply): if reply is None: return '', 204 elif isinstance(reply, dict): return reply elif isinstance(reply, str): return reply elif isinstance(reply, tuple): return reply else: return serialize(reply)
def test_should_apply_multiple_defaults(defaults): class Foo: def __init__(self, some_thing: str, other_thing: Optional[str]): self.some_thing = some_thing self.other_thing = other_thing set_defaults(no_camel_case, explicit_nulls) assert serialize(Foo('bar', None)) == { 'some_thing': 'bar', 'other_thing': None }
def post_message(self, channel_id: str, message: Message) -> PostMessageReply: blocks = [serialize(block) for block in message.blocks] if message.blocks is not None else None try: result = self.client.chat_postMessage(channel=channel_id, text=message.text, blocks=blocks) return PostMessageReply(result['channel'], result['ts']) except SlackApiError as e: if e.response['error'] == 'not_in_channel': self.client.conversations_join(channel=channel_id) result = self.client.chat_postMessage(channel=channel_id, text=message.text, blocks=blocks) return PostMessageReply(result['channel'], result['ts']) else: raise e
def run_ws(self, method, plugin: Type[AntibotPlugin], **kwargs): request_key = request.params.get('apikey') or request.headers.get('X-Gitlab-Token') if not getattr(method, NO_AUTH, False) and self.configuration.ws_api_key != request_key: abort(401, 'Could not verify api key') ip = request.get_header('X-Forwarded-For', request.environ.get('REMOTE_ADDR')) instance = self.injector.get(plugin) with self.debugger.wrap(request.json): reply = method(instance, **kwargs) if reply is not None: if getattr(method, WS_JSON_VALUES, False): return serialize(reply) return reply
def run_command(self, method, plugin: Type[AntibotPlugin]): print(method) print(request.route) instance = self.injector.get_instance(plugin) data = request.forms user = self.users.get_user(data['user_id']) kwargs = {} if getattr(method, METHOD_HAS_USER_ATTR, False): kwargs['user'] = user reply = method(instance, **kwargs) if isinstance(reply, Message): return serialize(reply)
def run_callback(self): message = loads(InteractiveMessage, request.forms['payload']) for callback in self.find_callback(message.callback_id): instance = self.injector.get_instance(callback.plugin_cls) kwargs = {} if getattr(callback.method, METHOD_HAS_CALLBACK_ID_ATTR, False): kwargs['callback_id'] = message.callback_id if getattr(callback.method, METHOD_HAS_USER_ATTR, False): user = self.users.get_user(message.user.id) kwargs['user'] = user if getattr(callback.method, METHOD_HAS_ACTIONS_ATTR, False): kwargs['actions'] = message.actions if getattr(callback.method, METHOD_HAS_CHANNEL_ATTR, False): channel = Channel(message.channel.id, message.channel.name) kwargs['channel'] = channel reply = callback.method(instance, **kwargs) if isinstance(reply, Message): return serialize(reply)
def run(self, payload: dict): message = parse(ViewSubmitPayload, payload) for descriptor in self.find_callback(message.view.callback_id): user = self.users.get_user(message.user.id) reply = self.endpoints.run( descriptor.plugin, descriptor.method, user=user, callback_id=message.view.callback_id, values=message.view.state.values, view_id=message.view.id, private_metadata=message.view.private_metadata) if isinstance(reply, View): return {'response_action': 'update', 'view': serialize(reply)} if isinstance(reply, ViewError): return { 'response_action': 'errors', 'errors': { reply.block_id: reply.message } }
def update_orbit(self, username: str, fleet: Fleet): self.collection.replace_one({'username': username, 'sourceType': SourceType.planet.name, 'sourceId': fleet.source_id }, serialize(fleet), upsert=True)
def create(self, message: SlackMessage): self.collection.insert_one(serialize(message))
def update_view(self, parent_view_id: str, view: View) -> str: result = self.client.views_update(view_id=parent_view_id, view=serialize(view)) return result['view']['id']
def test_should_serialize_class_with_forwarf_list(self): result = serialize( ClsWithForwardList([ForwardListType(1), ForwardListType(2)])) self.assertEqual(result, {'x': [{'y': 1}, {'y': 2}]})
def update_message(self, channel_id: str, timestamp: str, message: Message) -> PostMessageReply: blocks = [serialize(block) for block in message.blocks] if message.blocks is not None else None result = self.client.chat_update(channel=channel_id, ts=timestamp, text=message.text, blocks=blocks) return PostMessageReply(result['channel'], result['ts'])
def test_custom_serializer_on_param_forwardref(): result = serialize(Foo2(Bar(12))) assert result == {'bar': 42}
def create(self, user: User, points: int) -> UserPoints: up = UserPoints(user, points) self.collection.insert_one(serialize(up)) return up
def update(self, error: ErrorCount): self.collection.update({'user.id': error.user.id, 'month': error.month}, serialize(error), upsert=True)
def update_places(self, places: List[Place]): mongo_places = [MongoPlace.from_place(place) for place in places] requests = [ReplaceOne({'_id': place.id}, serialize(place), upsert=True) for place in mongo_places] self.collection.bulk_write(requests)
def test_custom_serializer_forwardref(): result = serialize(Foo(42)) assert result == {'toto': 42}
def update(self, order: Order): self.collection.replace_one({'_id': order.id}, serialize(order))
def push_modal(self, trigger_id: str, view: View) -> str: result = self.client.views_push(trigger_id=trigger_id, view=serialize(view)) return result['view']['id']
def create(self, user: User) -> Order: order = Order(str(uuid4()), user, today()) self.collection.insert_one(serialize(order)) return order
def update(self, order: Order): self.collection.update({'_id': order._id}, serialize(order))
def create(self, username: str, password: str): user = User(username, generate_password_hash(password), False, str(uuid4())) self.collection.insert(serialize(user))