From bc1e55fc133ca98c64928321f5f8bb2505953a52 Mon Sep 17 00:00:00 2001 From: Adam Beckmeyer Date: Fri, 25 May 2018 12:02:16 -0400 Subject: [PATCH 1/3] Run black on project as-is Signed-off-by: Adam Beckmeyer --- docs/source/conf.py | 58 ++++--- matrix_client/api.py | 290 ++++++++++++++----------------- matrix_client/client.py | 132 +++++++------- matrix_client/errors.py | 6 +- matrix_client/room.py | 140 +++++++-------- matrix_client/user.py | 1 + samples/SimpleChatClient.py | 16 +- samples/UserPassOrTokenClient.py | 8 +- setup.py | 56 +++--- test/api_test.py | 72 ++++---- test/client_test.py | 172 +++++++++++------- test/response_examples.py | 91 +++------- 12 files changed, 507 insertions(+), 535 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 40d27511..b35d0929 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -18,7 +18,7 @@ import sphinx_rtd_theme -srcdir = os.path.abspath('../../') +srcdir = os.path.abspath("../../") sys.path.insert(0, srcdir) @@ -30,68 +30,74 @@ # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = '1.3' +needs_sphinx = "1.3" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [ - 'sphinx.ext.viewcode', - 'sphinx.ext.autodoc', - 'sphinx.ext.napoleon' -] +extensions = ["sphinx.ext.viewcode", "sphinx.ext.autodoc", "sphinx.ext.napoleon"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'Matrix Python SDK' -copyright = '2016, matrix.org' -author = 'matrix.org' +project = "Matrix Python SDK" +copyright = "2016, matrix.org" +author = "matrix.org" -version = '0.2.0' -release = '0.1.0' +version = "0.2.0" +release = "0.1.0" language = None exclude_patterns = [] -pygments_style = 'sphinx' +pygments_style = "sphinx" todo_include_todos = False html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] -html_title = 'Matrix Python SDK v' + version +html_title = "Matrix Python SDK v" + version # html_static_path = ['_static'] -htmlhelp_basename = 'MatrixPythonSDKdoc' -highlight_language = 'python' +htmlhelp_basename = "MatrixPythonSDKdoc" +highlight_language = "python" latex_documents = [ - (master_doc, 'MatrixPythonSDK.tex', 'Matrix Python SDK Documentation', - 'matrix.org', 'manual'), + ( + master_doc, + "MatrixPythonSDK.tex", + "Matrix Python SDK Documentation", + "matrix.org", + "manual", + ) ] man_pages = [ - (master_doc, 'matrixpythonsdk', 'Matrix Python SDK Documentation', - [author], 1) + (master_doc, "matrixpythonsdk", "Matrix Python SDK Documentation", [author], 1) ] texinfo_documents = [ - (master_doc, 'MatrixPythonSDK', 'Matrix Python SDK Documentation', - author, 'MatrixPythonSDK', 'SDK for writing Matrix Clients in Python', - 'Miscellaneous'), + ( + master_doc, + "MatrixPythonSDK", + "Matrix Python SDK Documentation", + author, + "MatrixPythonSDK", + "SDK for writing Matrix Clients in Python", + "Miscellaneous", + ) ] diff --git a/matrix_client/api.py b/matrix_client/api.py index 8220b019..226d4139 100644 --- a/matrix_client/api.py +++ b/matrix_client/api.py @@ -71,8 +71,14 @@ def initial_sync(self, limit=1): warnings.warn("initial_sync is deprecated. Use sync instead.", DeprecationWarning) return self._send("GET", "/initialSync", query_params={"limit": limit}) - def sync(self, since=None, timeout_ms=30000, filter=None, - full_state=None, set_presence=None): + def sync( + self, + since=None, + timeout_ms=30000, + filter=None, + full_state=None, + set_presence=None, + ): """ Perform a sync request. Args: @@ -101,13 +107,14 @@ def sync(self, since=None, timeout_ms=30000, filter=None, if set_presence: request["set_presence"] = set_presence - return self._send("GET", "/sync", query_params=request, - api_path=MATRIX_V2_API_PATH) + return self._send( + "GET", "/sync", query_params=request, api_path=MATRIX_V2_API_PATH + ) def validate_certificate(self, valid): self.validate_cert = valid - def register(self, content={}, kind='user'): + def register(self, content={}, kind="user"): """Performs /register. Args: @@ -135,10 +142,7 @@ def register(self, content={}, kind='user'): kind (str): Specify kind="guest" to register as guest. """ return self._send( - "POST", - "/register", - content=content, - query_params={'kind': kind} + "POST", "/register", content=content, query_params={"kind": kind} ) def login(self, login_type, **kwargs): @@ -148,9 +152,7 @@ def login(self, login_type, **kwargs): login_type (str): The value for the 'type' key. **kwargs: Additional key/values to add to the JSON submitted. """ - content = { - "type": login_type - } + content = {"type": login_type} for key in kwargs: content[key] = kwargs[key] @@ -169,9 +171,7 @@ def create_room(self, alias=None, is_public=False, invitees=()): is_public (bool): Optional. The public/private visibility. invitees (list): Optional. The list of user IDs to invite. """ - content = { - "visibility": "public" if is_public else "private" - } + content = {"visibility": "public" if is_public else "private"} if alias: content["room_alias_name"] = alias if invitees: @@ -199,18 +199,15 @@ def event_stream(self, from_token, timeout=30000): from_token (str): The 'from' query parameter. timeout (int): Optional. The 'timeout' query parameter. """ - warnings.warn("event_stream is deprecated. Use sync instead.", - DeprecationWarning) + warnings.warn("event_stream is deprecated. Use sync instead.", DeprecationWarning) path = "/events" return self._send( - "GET", path, query_params={ - "timeout": timeout, - "from": from_token - } + "GET", path, query_params={"timeout": timeout, "from": from_token} ) - def send_state_event(self, room_id, event_type, content, state_key="", - timestamp=None): + def send_state_event( + self, room_id, event_type, content, state_key="", timestamp=None + ): """Perform PUT /rooms/$room_id/state/$event_type Args: @@ -220,9 +217,7 @@ def send_state_event(self, room_id, event_type, content, state_key="", state_key(str): Optional. The state key for the event. timestamp (int): Set origin_server_ts (For application services only) """ - path = "/rooms/%s/state/%s" % ( - quote(room_id), quote(event_type), - ) + path = "/rooms/%s/state/%s" % (quote(room_id), quote(event_type)) if state_key: path += "/%s" % (quote(state_key)) params = {} @@ -230,8 +225,9 @@ def send_state_event(self, room_id, event_type, content, state_key="", params["ts"] = timestamp return self._send("PUT", path, content, query_params=params) - def send_message_event(self, room_id, event_type, content, txn_id=None, - timestamp=None): + def send_message_event( + self, room_id, event_type, content, txn_id=None, timestamp=None + ): """Perform PUT /rooms/$room_id/send/$event_type Args: @@ -247,7 +243,9 @@ def send_message_event(self, room_id, event_type, content, txn_id=None, self.txn_id = self.txn_id + 1 path = "/rooms/%s/send/%s/%s" % ( - quote(room_id), quote(event_type), quote(str(txn_id)), + quote(room_id), + quote(event_type), + quote(str(txn_id)), ) params = {} if timestamp: @@ -268,12 +266,10 @@ def redact_event(self, room_id, event_id, reason=None, txn_id=None, timestamp=No txn_id = str(self.txn_id) + str(int(time() * 1000)) self.txn_id = self.txn_id + 1 - path = '/rooms/%s/redact/%s/%s' % ( - room_id, event_id, txn_id - ) + path = "/rooms/%s/redact/%s/%s" % (room_id, event_id, txn_id) content = {} if reason: - content['reason'] = reason + content["reason"] = reason params = {} if timestamp: params["ts"] = timestamp @@ -282,8 +278,15 @@ def redact_event(self, room_id, event_id, reason=None, txn_id=None, timestamp=No # content_type can be a image,audio or video # extra information should be supplied, see # https://matrix.org/docs/spec/r0.0.1/client_server.html - def send_content(self, room_id, item_url, item_name, msg_type, - extra_information=None, timestamp=None): + def send_content( + self, + room_id, + item_url, + item_name, + msg_type, + extra_information=None, + timestamp=None, + ): if extra_information is None: extra_information = {} @@ -291,14 +294,16 @@ def send_content(self, room_id, item_url, item_name, msg_type, "url": item_url, "msgtype": msg_type, "body": item_name, - "info": extra_information + "info": extra_information, } - return self.send_message_event(room_id, "m.room.message", content_pack, - timestamp=timestamp) + return self.send_message_event( + room_id, "m.room.message", content_pack, timestamp=timestamp + ) # http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location - def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, - timestamp=None): + def send_location( + self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, timestamp=None + ): """Send m.location message event Args: @@ -309,18 +314,15 @@ def send_location(self, room_id, geo_uri, name, thumb_url=None, thumb_info=None, thumb_info (dict): Metadata about the thumbnail, type ImageInfo. timestamp (int): Set origin_server_ts (For application services only) """ - content_pack = { - "geo_uri": geo_uri, - "msgtype": "m.location", - "body": name, - } + content_pack = {"geo_uri": geo_uri, "msgtype": "m.location", "body": name} if thumb_url: content_pack["thumbnail_url"] = thumb_url if thumb_info: content_pack["thumbnail_info"] = thumb_info - return self.send_message_event(room_id, "m.room.message", content_pack, - timestamp=timestamp) + return self.send_message_event( + room_id, "m.room.message", content_pack, timestamp=timestamp + ) def send_message(self, room_id, text_content, msgtype="m.text", timestamp=None): """Perform PUT /rooms/$room_id/send/m.room.message @@ -331,9 +333,10 @@ def send_message(self, room_id, text_content, msgtype="m.text", timestamp=None): timestamp (int): Set origin_server_ts (For application services only) """ return self.send_message_event( - room_id, "m.room.message", + room_id, + "m.room.message", self.get_text_body(text_content, msgtype), - timestamp=timestamp + timestamp=timestamp, ) def send_emote(self, room_id, text_content, timestamp=None): @@ -345,9 +348,10 @@ def send_emote(self, room_id, text_content, timestamp=None): timestamp (int): Set origin_server_ts (For application services only) """ return self.send_message_event( - room_id, "m.room.message", + room_id, + "m.room.message", self.get_emote_body(text_content), - timestamp=timestamp + timestamp=timestamp, ) def send_notice(self, room_id, text_content, timestamp=None): @@ -358,12 +362,10 @@ def send_notice(self, room_id, text_content, timestamp=None): text_content (str): The m.notice body to send. timestamp (int): Set origin_server_ts (For application services only) """ - body = { - "msgtype": "m.notice", - "body": text_content - } - return self.send_message_event(room_id, "m.room.message", body, - timestamp=timestamp) + body = {"msgtype": "m.notice", "body": text_content} + return self.send_message_event( + room_id, "m.room.message", body, timestamp=timestamp + ) def get_room_messages(self, room_id, token, direction, limit=10, to=None): """Perform GET /rooms/{roomId}/messages. @@ -375,18 +377,17 @@ def get_room_messages(self, room_id, token, direction, limit=10, to=None): limit (int): The maximum number of events to return. to (str): The token to stop returning events at. """ - query = { - "roomId": room_id, - "from": token, - "dir": direction, - "limit": limit, - } + query = {"roomId": room_id, "from": token, "dir": direction, "limit": limit} if to: query["to"] = to - return self._send("GET", "/rooms/{}/messages".format(quote(room_id)), - query_params=query, api_path="/_matrix/client/r0") + return self._send( + "GET", + "/rooms/{}/messages".format(quote(room_id)), + query_params=query, + api_path="/_matrix/client/r0", + ) def get_room_name(self, room_id): """Perform GET /rooms/$room_id/state/m.room.name @@ -402,9 +403,7 @@ def set_room_name(self, room_id, name, timestamp=None): name (str): The new room name timestamp (int): Set origin_server_ts (For application services only) """ - body = { - "name": name - } + body = {"name": name} return self.send_state_event(room_id, "m.room.name", body, timestamp=timestamp) def get_room_topic(self, room_id): @@ -421,9 +420,7 @@ def set_room_topic(self, room_id, topic, timestamp=None): topic (str): The new room topic timestamp (int): Set origin_server_ts (For application services only) """ - body = { - "topic": topic - } + body = {"topic": topic} return self.send_state_event(room_id, "m.room.topic", body, timestamp=timestamp) def get_power_levels(self, room_id): @@ -432,8 +429,9 @@ def get_power_levels(self, room_id): Args: room_id(str): The room ID """ - return self._send("GET", "/rooms/" + quote(room_id) + - "/state/m.room.power_levels") + return self._send( + "GET", "/rooms/" + quote(room_id) + "/state/m.room.power_levels" + ) def set_power_levels(self, room_id, content): """Perform PUT /rooms/$room_id/state/m.room.power_levels @@ -497,9 +495,7 @@ def invite_user(self, room_id, user_id): room_id (str): The room ID user_id (str): The user ID of the invitee """ - body = { - "user_id": user_id - } + body = {"user_id": user_id} return self._send("POST", "/rooms/" + room_id + "/invite", body) def kick_user(self, room_id, user_id, reason=""): @@ -514,13 +510,11 @@ def get_membership(self, room_id, user_id): room_id (str): The room ID user_id (str): The user ID """ - return self._send( - "GET", - "/rooms/%s/state/m.room.member/%s" % (room_id, user_id) - ) + return self._send("GET", "/rooms/%s/state/m.room.member/%s" % (room_id, user_id)) - def set_membership(self, room_id, user_id, membership, reason="", profile={}, - timestamp=None): + def set_membership( + self, room_id, user_id, membership, reason="", profile={}, timestamp=None + ): """Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: @@ -530,17 +524,15 @@ def set_membership(self, room_id, user_id, membership, reason="", profile={}, reason (str): The reason timestamp (int): Set origin_server_ts (For application services only) """ - body = { - "membership": membership, - "reason": reason - } - if 'displayname' in profile: + body = {"membership": membership, "reason": reason} + if "displayname" in profile: body["displayname"] = profile["displayname"] - if 'avatar_url' in profile: + if "avatar_url" in profile: body["avatar_url"] = profile["avatar_url"] - return self.send_state_event(room_id, "m.room.member", body, state_key=user_id, - timestamp=timestamp) + return self.send_state_event( + room_id, "m.room.member", body, state_key=user_id, timestamp=timestamp + ) def ban_user(self, room_id, user_id, reason=""): """Perform POST /rooms/$room_id/ban @@ -550,10 +542,7 @@ def ban_user(self, room_id, user_id, reason=""): user_id (str): The user ID of the banee(sic) reason (str): The reason for this ban """ - body = { - "user_id": user_id, - "reason": reason - } + body = {"user_id": user_id, "reason": reason} return self._send("POST", "/rooms/" + room_id + "/ban", body) def unban_user(self, room_id, user_id): @@ -563,22 +552,14 @@ def unban_user(self, room_id, user_id): room_id (str): The room ID user_id (str): The user ID of the banee(sic) """ - body = { - "user_id": user_id - } + body = {"user_id": user_id} return self._send("POST", "/rooms/" + room_id + "/unban", body) def get_user_tags(self, user_id, room_id): - return self._send( - "GET", - "/user/%s/rooms/%s/tags" % (user_id, room_id), - ) + return self._send("GET", "/user/%s/rooms/%s/tags" % (user_id, room_id)) def remove_user_tag(self, user_id, room_id, tag): - return self._send( - "DELETE", - "/user/%s/rooms/%s/tags/%s" % (user_id, room_id, tag), - ) + return self._send("DELETE", "/user/%s/rooms/%s/tags/%s" % (user_id, room_id, tag)) def add_user_tag(self, user_id, room_id, tag, order=None, body=None): if body: @@ -588,23 +569,19 @@ def add_user_tag(self, user_id, room_id, tag, order=None, body=None): else: body = {} return self._send( - "PUT", - "/user/%s/rooms/%s/tags/%s" % (user_id, room_id, tag), - body, + "PUT", "/user/%s/rooms/%s/tags/%s" % (user_id, room_id, tag), body ) def set_account_data(self, user_id, type, account_data): return self._send( - "PUT", - "/user/%s/account_data/%s" % (user_id, type), - account_data, + "PUT", "/user/%s/account_data/%s" % (user_id, type), account_data ) def set_room_account_data(self, user_id, room_id, type, account_data): return self._send( "PUT", "/user/%s/rooms/%s/account_data/%s" % (user_id, room_id, type), - account_data + account_data, ) def get_room_state(self, room_id): @@ -616,28 +593,31 @@ def get_room_state(self, room_id): return self._send("GET", "/rooms/" + room_id + "/state") def get_text_body(self, text, msgtype="m.text"): - return { - "msgtype": msgtype, - "body": text - } + return {"msgtype": msgtype, "body": text} def get_emote_body(self, text): - return { - "msgtype": "m.emote", - "body": text - } + return {"msgtype": "m.emote", "body": text} def get_filter(self, user_id, filter_id): - return self._send("GET", "/user/{userId}/filter/{filterId}" - .format(userId=user_id, filterId=filter_id)) + return self._send( + "GET", + "/user/{userId}/filter/{filterId}".format(userId=user_id, filterId=filter_id), + ) def create_filter(self, user_id, filter_params): - return self._send("POST", - "/user/{userId}/filter".format(userId=user_id), - filter_params) + return self._send( + "POST", "/user/{userId}/filter".format(userId=user_id), filter_params + ) - def _send(self, method, path, content=None, query_params={}, headers={}, - api_path=MATRIX_V2_API_PATH): + def _send( + self, + method, + path, + content=None, + query_params={}, + headers={}, + api_path=MATRIX_V2_API_PATH, + ): method = method.upper() if method not in ["GET", "PUT", "DELETE", "POST"]: raise MatrixError("Unsupported HTTP method: %s" % method) @@ -657,11 +637,12 @@ def _send(self, method, path, content=None, query_params={}, headers={}, while True: try: response = self.session.request( - method, endpoint, + method, + endpoint, params=query_params, data=content, headers=headers, - verify=self.validate_cert + verify=self.validate_cert, ) except RequestException as e: raise MatrixHttpLibError(e, method, endpoint) @@ -669,11 +650,11 @@ def _send(self, method, path, content=None, query_params={}, headers={}, if response.status_code == 429: waittime = self.default_429_wait_ms / 1000 try: - waittime = response.json()['retry_after_ms'] / 1000 + waittime = response.json()["retry_after_ms"] / 1000 except KeyError: try: - errordata = json.loads(response.json()['error']) - waittime = errordata['retry_after_ms'] / 1000 + errordata = json.loads(response.json()["error"]) + waittime = errordata["retry_after_ms"] / 1000 except KeyError: pass sleep(waittime) @@ -681,23 +662,22 @@ def _send(self, method, path, content=None, query_params={}, headers={}, break if response.status_code < 200 or response.status_code >= 300: - raise MatrixRequestError( - code=response.status_code, content=response.text - ) + raise MatrixRequestError(code=response.status_code, content=response.text) return response.json() def media_upload(self, content, content_type): return self._send( - "POST", "", + "POST", + "", content=content, headers={"Content-Type": content_type}, - api_path="/_matrix/media/r0/upload" + api_path="/_matrix/media/r0/upload", ) def get_display_name(self, user_id): content = self._send("GET", "/profile/%s/displayname" % user_id) - return content.get('displayname', None) + return content.get("displayname", None) def set_display_name(self, user_id, display_name): content = {"displayname": display_name} @@ -705,14 +685,14 @@ def set_display_name(self, user_id, display_name): def get_avatar_url(self, user_id): content = self._send("GET", "/profile/%s/avatar_url" % user_id) - return content.get('avatar_url', None) + return content.get("avatar_url", None) def set_avatar_url(self, user_id, avatar_url): content = {"avatar_url": avatar_url} return self._send("PUT", "/profile/%s/avatar_url" % user_id, content) def get_download_url(self, mxcurl): - if mxcurl.startswith('mxc://'): + if mxcurl.startswith("mxc://"): return self.base_url + "/_matrix/media/r0/download/" + mxcurl[6:] else: raise ValueError("MXC URL did not begin with 'mxc://'") @@ -736,12 +716,11 @@ def set_room_alias(self, room_id, room_alias): room_id (str): The room id. room_alias (str): The room wanted alias name. """ - data = { - "room_id": room_id - } + data = {"room_id": room_id} - return self._send("PUT", "/directory/room/{}".format(quote(room_alias)), - content=data) + return self._send( + "PUT", "/directory/room/{}".format(quote(room_alias)), content=data + ) def remove_room_alias(self, room_alias): """Remove mapping of an alias @@ -770,9 +749,7 @@ def set_join_rule(self, room_id, join_rule): join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"] """ - content = { - "join_rule": join_rule - } + content = {"join_rule": join_rule} return self.send_state_event(room_id, "m.room.join_rules", content) def set_guest_access(self, room_id, guest_access): @@ -783,9 +760,7 @@ def set_guest_access(self, room_id, guest_access): guest_access(str): Wether guests can join. One of: ["can_join", "forbidden"] """ - content = { - "guest_access": guest_access - } + content = {"guest_access": guest_access} return self.send_state_event(room_id, "m.room.guest_access", content) def get_devices(self): @@ -803,9 +778,7 @@ def update_device_info(self, device_id, display_name): device_id (str): The device ID of the device to update. display_name (str): New display name for the device. """ - content = { - "display_name": display_name - } + content = {"display_name": display_name} return self._send("PUT", "/devices/%s" % device_id, content=content) def delete_device(self, auth_body, device_id): @@ -817,9 +790,7 @@ def delete_device(self, auth_body, device_id): auth_body (dict): Authentication params. device_id (str): The device ID of the device to delete. """ - content = { - "auth": auth_body - } + content = {"auth": auth_body} return self._send("DELETE", "/devices/%s" % device_id, content=content) def delete_devices(self, auth_body, devices): @@ -831,8 +802,5 @@ def delete_devices(self, auth_body, devices): auth_body (dict): Authentication params. devices (list): List of device ID"s to delete. """ - content = { - "auth": auth_body, - "devices": devices - } + content = {"auth": auth_body, "devices": devices} return self._send("POST", "/delete_devices", content=content) diff --git a/matrix_client/client.py b/matrix_client/client.py index be1abe74..b269aa9a 100644 --- a/matrix_client/client.py +++ b/matrix_client/client.py @@ -93,9 +93,15 @@ def global_callback(incoming_event): pass """ - def __init__(self, base_url, token=None, user_id=None, - valid_cert_check=True, sync_filter_limit=20, - cache_level=CACHE.ALL): + def __init__( + self, + base_url, + token=None, + user_id=None, + valid_cert_check=True, + sync_filter_limit=20, + cache_level=CACHE.ALL, + ): """ Create a new Matrix Client object. Args: @@ -136,8 +142,9 @@ def __init__(self, base_url, token=None, user_id=None, ) self.sync_token = None - self.sync_filter = '{ "room": { "timeline" : { "limit" : %i } } }' \ - % sync_filter_limit + self.sync_filter = ( + '{ "room": { "timeline" : { "limit" : %i } } }' % sync_filter_limit + ) self.sync_thread = None self.should_listen = False @@ -152,18 +159,24 @@ def __init__(self, base_url, token=None, user_id=None, self._sync() def get_sync_token(self): - warn("get_sync_token is deprecated. Directly access MatrixClient.sync_token.", - DeprecationWarning) + warn( + "get_sync_token is deprecated. Directly access MatrixClient.sync_token.", + DeprecationWarning, + ) return self.sync_token def set_sync_token(self, token): - warn("set_sync_token is deprecated. Directly access MatrixClient.sync_token.", - DeprecationWarning) + warn( + "set_sync_token is deprecated. Directly access MatrixClient.sync_token.", + DeprecationWarning, + ) self.sync_token = token def set_user_id(self, user_id): - warn("set_user_id is deprecated. Directly access MatrixClient.user_id.", - DeprecationWarning) + warn( + "set_user_id is deprecated. Directly access MatrixClient.user_id.", + DeprecationWarning, + ) self.user_id = user_id # TODO: combine register methods into single register method controlled by kwargs @@ -175,7 +188,7 @@ def register_as_guest(self): Raises: MatrixRequestError """ - response = self.api.register(kind='guest') + response = self.api.register(kind="guest") return self._post_registration(response) def register_with_password(self, username, password): @@ -195,7 +208,7 @@ def register_with_password(self, username, password): { "auth": {"type": "m.login.dummy"}, "username": username, - "password": password + "password": password, } ) return self._post_registration(response) @@ -222,9 +235,7 @@ def login_with_password_no_sync(self, username, password): Raises: MatrixRequestError """ - response = self.api.login( - "m.login.password", user=username, password=password - ) + response = self.api.login("m.login.password", user=username, password=password) self.user_id = response["user_id"] self.token = response["access_token"] self.hs = response["home_server"] @@ -291,9 +302,7 @@ def join_room(self, room_id_or_alias): MatrixRequestError """ response = self.api.join_room(room_id_or_alias) - room_id = ( - response["room_id"] if "room_id" in response else room_id_or_alias - ) + room_id = response["room_id"] if "room_id" in response else room_id_or_alias return self._mkroom(room_id) def get_rooms(self): @@ -302,8 +311,10 @@ def get_rooms(self): Returns: Room{}: Rooms the user has joined. """ - warn("get_rooms is deprecated. Directly access MatrixClient.rooms.", - DeprecationWarning) + warn( + "get_rooms is deprecated. Directly access MatrixClient.rooms.", + DeprecationWarning, + ) return self.rooms # TODO: create Listener class and push as much of this logic there as possible @@ -324,11 +335,7 @@ def add_listener(self, callback, event_type=None): # convenience method such that MatrixClient.listeners.new(Listener(...)) performs # MatrixClient.listeners[uuid4()] = Listener(...) self.listeners.append( - { - 'uid': listener_uid, - 'callback': callback, - 'event_type': event_type - } + {"uid": listener_uid, "callback": callback, "event_type": event_type} ) return listener_uid @@ -338,8 +345,9 @@ def remove_listener(self, uid): Args: uuid.UUID: Unique id of the listener to remove. """ - self.listeners[:] = (listener for listener in self.listeners - if listener['uid'] != uid) + self.listeners[:] = ( + listener for listener in self.listeners if listener["uid"] != uid + ) def add_presence_listener(self, callback): """ Add a presence listener that will send a callback when the client receives @@ -376,11 +384,7 @@ def add_ephemeral_listener(self, callback, event_type=None): """ listener_id = uuid4() self.ephemeral_listeners.append( - { - 'uid': listener_id, - 'callback': callback, - 'event_type': event_type - } + {"uid": listener_id, "callback": callback, "event_type": event_type} ) return listener_id @@ -390,8 +394,9 @@ def remove_ephemeral_listener(self, uid): Args: uuid.UUID: Unique id of the listener to remove. """ - self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners - if listener['uid'] != uid) + self.ephemeral_listeners[:] = ( + listener for listener in self.ephemeral_listeners if listener["uid"] != uid + ) def add_invite_listener(self, callback): """ Add a listener that will send a callback when the client receives @@ -426,8 +431,9 @@ def listen_for_events(self, timeout_ms=30000): # TODO: see docstring self._sync(timeout_ms) - def listen_forever(self, timeout_ms=30000, exception_handler=None, - bad_sync_timeout=5): + def listen_forever( + self, timeout_ms=30000, exception_handler=None, bad_sync_timeout=5 + ): """ Keep listening for events forever. Args: @@ -441,7 +447,7 @@ def listen_forever(self, timeout_ms=30000, exception_handler=None, """ _bad_sync_timeout = bad_sync_timeout self.should_listen = True - while (self.should_listen): + while self.should_listen: try: self._sync(timeout_ms) _bad_sync_timeout = bad_sync_timeout @@ -449,11 +455,13 @@ def listen_forever(self, timeout_ms=30000, exception_handler=None, except MatrixRequestError as e: logger.warning("A MatrixRequestError occured during sync.") if e.code >= 500: - logger.warning("Problem occured serverside. Waiting %i seconds", - bad_sync_timeout) + logger.warning( + "Problem occured serverside. Waiting %i seconds", bad_sync_timeout + ) sleep(bad_sync_timeout) - _bad_sync_timeout = min(_bad_sync_timeout * 2, - self.bad_sync_timeout_limit) + _bad_sync_timeout = min( + _bad_sync_timeout * 2, self.bad_sync_timeout_limit + ) elif exception_handler is not None: exception_handler(e) else: @@ -476,8 +484,9 @@ def start_listener_thread(self, timeout_ms=30000, exception_handler=None): thread. """ try: - thread = Thread(target=self.listen_forever, - args=(timeout_ms, exception_handler)) + thread = Thread( + target=self.listen_forever, args=(timeout_ms, exception_handler) + ) thread.daemon = True self.sync_thread = thread self.should_listen = True @@ -515,10 +524,7 @@ def upload(self, content, content_type): "The upload was successful, but content_uri wasn't found." ) except MatrixRequestError as e: - raise MatrixRequestError( - code=e.code, - content="Upload failed: %s" % e - ) + raise MatrixRequestError(code=e.code, content="Upload failed: %s" % e) def _mkroom(self, room_id): self.rooms[room_id] = Room(self, room_id) @@ -528,21 +534,21 @@ def _sync(self, timeout_ms=30000): response = self.api.sync(self.sync_token, timeout_ms, filter=self.sync_filter) self.sync_token = response["next_batch"] - for presence_update in response['presence']['events']: + for presence_update in response["presence"]["events"]: for callback in self.presence_listeners.values(): callback(presence_update) - for room_id, invite_room in response['rooms']['invite'].items(): + for room_id, invite_room in response["rooms"]["invite"].items(): for listener in self.invite_listeners: - listener(room_id, invite_room['invite_state']) + listener(room_id, invite_room["invite_state"]) - for room_id, left_room in response['rooms']['leave'].items(): + for room_id, left_room in response["rooms"]["leave"].items(): for listener in self.left_listeners: listener(room_id, left_room) if room_id in self.rooms: del self.rooms[room_id] - for room_id, sync_room in response['rooms']['join'].items(): + for room_id, sync_room in response["rooms"]["join"].items(): if room_id not in self.rooms: self._mkroom(room_id) room = self.rooms[room_id] @@ -550,11 +556,11 @@ def _sync(self, timeout_ms=30000): room.prev_batch = sync_room["timeline"]["prev_batch"] for event in sync_room["state"]["events"]: - event['room_id'] = room_id + event["room_id"] = room_id room._process_state_event(event) for event in sync_room["timeline"]["events"]: - event['room_id'] = room_id + event["room_id"] = room_id room._put_event(event) # TODO: global listeners can still exist but work by each @@ -563,21 +569,21 @@ def _sync(self, timeout_ms=30000): # Dispatch for client (global) listeners for listener in self.listeners: if ( - listener['event_type'] is None or - listener['event_type'] == event['type'] + listener["event_type"] is None + or listener["event_type"] == event["type"] ): - listener['callback'](event) + listener["callback"](event) - for event in sync_room['ephemeral']['events']: - event['room_id'] = room_id + for event in sync_room["ephemeral"]["events"]: + event["room_id"] = room_id room._put_ephemeral_event(event) for listener in self.ephemeral_listeners: if ( - listener['event_type'] is None or - listener['event_type'] == event['type'] + listener["event_type"] is None + or listener["event_type"] == event["type"] ): - listener['callback'](event) + listener["callback"](event) def get_user(self, user_id): """ Return a User by their id. diff --git a/matrix_client/errors.py b/matrix_client/errors.py index e9dc8fe3..048e01f7 100644 --- a/matrix_client/errors.py +++ b/matrix_client/errors.py @@ -41,8 +41,8 @@ class MatrixHttpLibError(MatrixError): def __init__(self, original_exception, method, endpoint): super(MatrixHttpLibError, self).__init__( - "Something went wrong in {} requesting {}: {}".format(method, - endpoint, - original_exception) + "Something went wrong in {} requesting {}: {}".format( + method, endpoint, original_exception + ) ) self.original_exception = original_exception diff --git a/matrix_client/room.py b/matrix_client/room.py index 2964ead2..63468d98 100644 --- a/matrix_client/room.py +++ b/matrix_client/room.py @@ -48,10 +48,12 @@ def __init__(self, client, room_id): self._prev_batch = None self._members = [] - def set_user_profile(self, - displayname=None, - avatar_url=None, - reason="Changing room profile information"): + def set_user_profile( + self, + displayname=None, + avatar_url=None, + reason="Changing room profile information", + ): """Set user profile within a room. This sets displayname and avatar_url for the logged in user only in a @@ -67,11 +69,9 @@ def set_user_profile(self, self.client.api.set_membership( self.room_id, self.client.user_id, - 'join', - reason, { - "displayname": displayname, - "avatar_url": avatar_url - } + "join", + reason, + {"displayname": displayname, "avatar_url": avatar_url}, ) @property @@ -84,19 +84,16 @@ def display_name(self): members = self.get_joined_members() # members without me - members[:] = [u.get_display_name() for u in members if - self.client.user_id != u.user_id] + members[:] = [ + u.get_display_name() for u in members if self.client.user_id != u.user_id + ] first_two = members[:2] if len(first_two) == 1: return first_two[0] elif len(members) == 2: - return "{0} and {1}".format( - first_two[0], - first_two[1]) + return "{0} and {1}".format(first_two[0], first_two[1]) elif len(members) > 2: - return "{0} and {1} others".format( - first_two[0], - len(members) - 1) + return "{0} and {1} others".format(first_two[0], len(members) - 1) elif len(first_two) == 0: # TODO i18n return "Empty room" @@ -109,10 +106,10 @@ def send_text(self, text): def get_html_content(self, html, body=None, msgtype="m.text"): return { - "body": body if body else re.sub('<[^<]+?>', '', html), + "body": body if body else re.sub("<[^<]+?>", "", html), "msgtype": msgtype, "format": "org.matrix.custom.html", - "formatted_body": html + "formatted_body": html, } def send_html(self, html, body=None, msgtype="m.text"): @@ -123,24 +120,23 @@ def send_html(self, html, body=None, msgtype="m.text"): body (str): The unformatted body of the message to be sent. """ return self.client.api.send_message_event( - self.room_id, "m.room.message", self.get_html_content(html, body, msgtype)) + self.room_id, "m.room.message", self.get_html_content(html, body, msgtype) + ) def set_account_data(self, type, account_data): return self.client.api.set_room_account_data( - self.client.user_id, self.room_id, type, account_data) + self.client.user_id, self.room_id, type, account_data + ) def get_tags(self): return self.client.api.get_user_tags(self.client.user_id, self.room_id) def remove_tag(self, tag): - return self.client.api.remove_user_tag( - self.client.user_id, self.room_id, tag - ) + return self.client.api.remove_user_tag(self.client.user_id, self.room_id, tag) def add_tag(self, tag, order=None, content=None): return self.client.api.add_user_tag( - self.client.user_id, self.room_id, - tag, order, content + self.client.user_id, self.room_id, tag, order, content ) def send_emote(self, text): @@ -160,8 +156,7 @@ def send_file(self, url, name, **fileinfo): """ return self.client.api.send_content( - self.room_id, url, name, "m.file", - extra_information=fileinfo + self.room_id, url, name, "m.file", extra_information=fileinfo ) def send_notice(self, text): @@ -182,8 +177,7 @@ def send_image(self, url, name, **imageinfo): imageinfo (): Extra information about the image. """ return self.client.api.send_content( - self.room_id, url, name, "m.image", - extra_information=imageinfo + self.room_id, url, name, "m.image", extra_information=imageinfo ) def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): @@ -198,8 +192,9 @@ def send_location(self, geo_uri, name, thumb_url=None, **thumb_info): thumb_url (str): URL to the thumbnail of the location. thumb_info (): Metadata about the thumbnail, type ImageInfo. """ - return self.client.api.send_location(self.room_id, geo_uri, name, - thumb_url, thumb_info) + return self.client.api.send_location( + self.room_id, geo_uri, name, thumb_url, thumb_info + ) def send_video(self, url, name, **videoinfo): """Send a pre-uploaded video to the room. @@ -212,8 +207,9 @@ def send_video(self, url, name, **videoinfo): name (str): The filename of the video. videoinfo (): Extra information about the video. """ - return self.client.api.send_content(self.room_id, url, name, "m.video", - extra_information=videoinfo) + return self.client.api.send_content( + self.room_id, url, name, "m.video", extra_information=videoinfo + ) def send_audio(self, url, name, **audioinfo): """Send a pre-uploaded audio to the room. @@ -226,8 +222,9 @@ def send_audio(self, url, name, **audioinfo): name (str): The filename of the audio. audioinfo (): Extra information about the audio. """ - return self.client.api.send_content(self.room_id, url, name, "m.audio", - extra_information=audioinfo) + return self.client.api.send_content( + self.room_id, url, name, "m.audio", extra_information=audioinfo + ) def redact_message(self, event_id, reason=None): """Redacts the message with specified event_id for the given reason. @@ -247,18 +244,15 @@ def add_listener(self, callback, event_type=None): """ listener_id = uuid4() self.listeners.append( - { - 'uid': listener_id, - 'callback': callback, - 'event_type': event_type - } + {"uid": listener_id, "callback": callback, "event_type": event_type} ) return listener_id def remove_listener(self, uid): """Remove listener with given uid.""" - self.listeners[:] = (listener for listener in self.listeners - if listener['uid'] != uid) + self.listeners[:] = ( + listener for listener in self.listeners if listener["uid"] != uid + ) def add_ephemeral_listener(self, callback, event_type=None): """Add a callback handler for ephemeral events going to this room. @@ -271,18 +265,15 @@ def add_ephemeral_listener(self, callback, event_type=None): """ listener_id = uuid4() self.ephemeral_listeners.append( - { - 'uid': listener_id, - 'callback': callback, - 'event_type': event_type - } + {"uid": listener_id, "callback": callback, "event_type": event_type} ) return listener_id def remove_ephemeral_listener(self, uid): """Remove ephemeral listener with given uid.""" - self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners - if listener['uid'] != uid) + self.ephemeral_listeners[:] = ( + listener for listener in self.ephemeral_listeners if listener["uid"] != uid + ) def add_state_listener(self, callback, event_type=None): """Add a callback handler for state events going to this room. @@ -291,30 +282,25 @@ def add_state_listener(self, callback, event_type=None): callback (func(roomchunk)): Callback called when an event arrives. event_type (str): The event_type to filter for. """ - self.state_listeners.append( - { - 'callback': callback, - 'event_type': event_type - } - ) + self.state_listeners.append({"callback": callback, "event_type": event_type}) def _put_event(self, event): self.events.append(event) if len(self.events) > self.event_history_limit: self.events.pop(0) - if 'state_key' in event: + if "state_key" in event: self._process_state_event(event) # Dispatch for room-specific listeners for listener in self.listeners: - if listener['event_type'] is None or listener['event_type'] == event['type']: - listener['callback'](self, event) + if listener["event_type"] is None or listener["event_type"] == event["type"]: + listener["callback"](self, event) def _put_ephemeral_event(self, event): # Dispatch for room-specific listeners for listener in self.ephemeral_listeners: - if listener['event_type'] is None or listener['event_type'] == event['type']: - listener['callback'](self, event) + if listener["event_type"] is None or listener["event_type"] == event["type"]: + listener["callback"](self, event) def get_events(self): """Get the most recent events for this room.""" @@ -420,10 +406,7 @@ def send_state_event(self, event_type, content, state_key): state_key (str, optional): A unique key to identify the state. """ return self.client.api.send_state_event( - self.room_id, - event_type, - content, - state_key + self.room_id, event_type, content, state_key ) def update_room_topic(self): @@ -485,9 +468,11 @@ def get_joined_members(self): for event in response["chunk"]: if event["content"]["membership"] == "join": self._mkmembers( - User(self.client.api, - event["state_key"], - event["content"].get("displayname")) + User( + self.client.api, + event["state_key"], + event["content"].get("displayname"), + ) ) return self._members @@ -506,8 +491,9 @@ def backfill_previous_messages(self, reverse=False, limit=10): order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back. """ - res = self.client.api.get_room_messages(self.room_id, self.prev_batch, - direction="b", limit=limit) + res = self.client.api.get_room_messages( + self.room_id, self.prev_batch, direction="b", limit=limit + ) events = res["chunk"] if not reverse: events = reversed(events) @@ -644,19 +630,21 @@ def _process_state_event(self, state_event): # tracking room members can be large e.g. #matrix:matrix.org if econtent["membership"] == "join": self._mkmembers( - User(self.client.api, - state_event["state_key"], - econtent.get("displayname")) + User( + self.client.api, + state_event["state_key"], + econtent.get("displayname"), + ) ) elif econtent["membership"] in ("leave", "kick", "invite"): self._rmmembers(state_event["state_key"]) for listener in self.state_listeners: if ( - listener['event_type'] is None or - listener['event_type'] == state_event['type'] + listener["event_type"] is None + or listener["event_type"] == state_event["type"] ): - listener['callback'](state_event) + listener["callback"](state_event) @property def prev_batch(self): diff --git a/matrix_client/user.py b/matrix_client/user.py index 6aceaf56..e794593d 100644 --- a/matrix_client/user.py +++ b/matrix_client/user.py @@ -18,6 +18,7 @@ class User(object): """ The User class can be used to call user specific functions. """ + def __init__(self, api, user_id, displayname=None): check_user_id(user_id) diff --git a/samples/SimpleChatClient.py b/samples/SimpleChatClient.py index b742e96f..2960bf4a 100755 --- a/samples/SimpleChatClient.py +++ b/samples/SimpleChatClient.py @@ -22,14 +22,14 @@ # Called when a message is recieved. def on_message(room, event): - if event['type'] == "m.room.member": - if event['membership'] == "join": - print("{0} joined".format(event['content']['displayname'])) - elif event['type'] == "m.room.message": - if event['content']['msgtype'] == "m.text": - print("{0}: {1}".format(event['sender'], event['content']['body'])) + if event["type"] == "m.room.member": + if event["membership"] == "join": + print("{0} joined".format(event["content"]["displayname"])) + elif event["type"] == "m.room.message": + if event["content"]["msgtype"] == "m.text": + print("{0}: {1}".format(event["sender"], event["content"]["body"])) else: - print(event['type']) + print(event["type"]) def main(host, username, password, room_id_alias): @@ -72,7 +72,7 @@ def main(host, username, password, room_id_alias): room.send_text(msg) -if __name__ == '__main__': +if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) host, username, password = samples_common.get_user_details(sys.argv) diff --git a/samples/UserPassOrTokenClient.py b/samples/UserPassOrTokenClient.py index 2c80c425..d438730b 100644 --- a/samples/UserPassOrTokenClient.py +++ b/samples/UserPassOrTokenClient.py @@ -26,13 +26,13 @@ def example(host, user, password, token): client = None try: if token: - print('token login') + print("token login") client = MatrixClient(host, token=token, user_id=user) else: - print('password login') + print("password login") client = MatrixClient(host) token = client.login_with_password(user, password) - print('got token: %s' % token) + print("got token: %s" % token) except MatrixRequestError as e: print(e) if e.code == 403: @@ -66,7 +66,7 @@ def main(): parser.add_argument("--token", type=str) args = parser.parse_args() if not args.password and not args.token: - print('password or token is required') + print("password or token is required") exit(1) example(args.host, args.user, args.password, args.token) diff --git a/setup.py b/setup.py index 38877ed6..4907c9b8 100644 --- a/setup.py +++ b/setup.py @@ -6,13 +6,13 @@ here = os.path.abspath(os.path.dirname(__file__)) -def read_file(names, encoding='utf-8'): +def read_file(names, encoding="utf-8"): file_path = os.path.join(here, *names) if encoding: with codecs.open(file_path, encoding=encoding) as f: return f.read() else: - with open(file_path, 'rb') as f: + with open(file_path, "rb") as f: return f.read() @@ -24,32 +24,34 @@ def exec_file(names): setup( - name='matrix_client', - version=exec_file(('matrix_client', '__init__.py',))['__version__'], - description='Client-Server SDK for Matrix', - long_description=read_file(('README.rst',)), - author='The Matrix.org Team', - author_email='team@matrix.org', - url='https://github.com/matrix-org/matrix-python-sdk', - packages=['matrix_client'], - license='Apache License, Version 2.0', + name="matrix_client", + version=exec_file(("matrix_client", "__init__.py"))["__version__"], + description="Client-Server SDK for Matrix", + long_description=read_file(("README.rst",)), + author="The Matrix.org Team", + author_email="team@matrix.org", + url="https://github.com/matrix-org/matrix-python-sdk", + packages=["matrix_client"], + license="Apache License, Version 2.0", classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 3', - 'Topic :: Communications :: Chat', - 'Topic :: Communications :: Conferencing', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", + "Topic :: Communications :: Chat", + "Topic :: Communications :: Conferencing", ], - keywords='chat sdk matrix matrix.org', - install_requires=[ - 'requests' - ], - setup_requires=['pytest-runner',], - tests_require=['pytest', 'responses',], + keywords="chat sdk matrix matrix.org", + install_requires=["requests"], + setup_requires=["pytest-runner"], + tests_require=["pytest", "responses"], extras_require={ - 'test': ['tox', 'pytest', 'flake8', 'responses'], - 'doc': ['Sphinx==1.4.6', 'sphinx-rtd-theme==0.1.9', 'sphinxcontrib-napoleon==0.5.3'], - } + "test": ["tox", "pytest", "flake8", "responses"], + "doc": [ + "Sphinx==1.4.6", + "sphinx-rtd-theme==0.1.9", + "sphinxcontrib-napoleon==0.5.3", + ], + }, ) diff --git a/test/api_test.py b/test/api_test.py index 4b359dfe..950bf2fa 100644 --- a/test/api_test.py +++ b/test/api_test.py @@ -11,33 +11,30 @@ class TestTagsApi: @responses.activate def test_get_user_tags(self): - tags_url = "http://example.com" \ - "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags" - responses.add(responses.GET, tags_url, body='{}') + tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags" + responses.add(responses.GET, tags_url, body="{}") self.cli.api.get_user_tags(self.user_id, self.room_id) req = responses.calls[0].request assert req.url == tags_url - assert req.method == 'GET' + assert req.method == "GET" @responses.activate def test_add_user_tags(self): - tags_url = "http://example.com" \ - "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" - responses.add(responses.PUT, tags_url, body='{}') + tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" + responses.add(responses.PUT, tags_url, body="{}") self.cli.api.add_user_tag(self.user_id, self.room_id, "foo", body={"order": "5"}) req = responses.calls[0].request assert req.url == tags_url - assert req.method == 'PUT' + assert req.method == "PUT" @responses.activate def test_remove_user_tags(self): - tags_url = "http://example.com" \ - "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" - responses.add(responses.DELETE, tags_url, body='{}') + tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" + responses.add(responses.DELETE, tags_url, body="{}") self.cli.api.remove_user_tag(self.user_id, self.room_id, "foo") req = responses.calls[0].request assert req.url == tags_url - assert req.method == 'DELETE' + assert req.method == "DELETE" class TestAccountDataApi: @@ -47,23 +44,21 @@ class TestAccountDataApi: @responses.activate def test_set_account_data(self): - account_data_url = "http://example.com" \ - "/_matrix/client/r0/user/@user:matrix.org/account_data/foo" - responses.add(responses.PUT, account_data_url, body='{}') - self.cli.api.set_account_data(self.user_id, 'foo', {'bar': 1}) + account_data_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/account_data/foo" + responses.add(responses.PUT, account_data_url, body="{}") + self.cli.api.set_account_data(self.user_id, "foo", {"bar": 1}) req = responses.calls[0].request assert req.url == account_data_url - assert req.method == 'PUT' + assert req.method == "PUT" @responses.activate def test_set_room_account_data(self): - account_data_url = "http://example.com/_matrix/client/r0/user" \ - "/@user:matrix.org/rooms/#foo:matrix.org/account_data/foo" - responses.add(responses.PUT, account_data_url, body='{}') - self.cli.api.set_room_account_data(self.user_id, self.room_id, 'foo', {'bar': 1}) + account_data_url = "http://example.com/_matrix/client/r0/user" "/@user:matrix.org/rooms/#foo:matrix.org/account_data/foo" + responses.add(responses.PUT, account_data_url, body="{}") + self.cli.api.set_room_account_data(self.user_id, self.room_id, "foo", {"bar": 1}) req = responses.calls[0].request assert req.url == account_data_url - assert req.method == 'PUT' + assert req.method == "PUT" class TestUnbanApi: @@ -73,13 +68,12 @@ class TestUnbanApi: @responses.activate def test_unban(self): - unban_url = "http://example.com" \ - "/_matrix/client/r0/rooms/#foo:matrix.org/unban" - responses.add(responses.POST, unban_url, body='{}') + unban_url = "http://example.com" "/_matrix/client/r0/rooms/#foo:matrix.org/unban" + responses.add(responses.POST, unban_url, body="{}") self.cli.api.unban_user(self.room_id, self.user_id) req = responses.calls[0].request assert req.url == unban_url - assert req.method == 'POST' + assert req.method == "POST" class TestDeviceApi: @@ -90,47 +84,47 @@ class TestDeviceApi: "auth": { "type": "example.type.foo", "session": "xxxxx", - "example_credential": "verypoorsharedsecret" + "example_credential": "verypoorsharedsecret", } } @responses.activate def test_get_devices(self): get_devices_url = "http://example.com/_matrix/client/r0/devices" - responses.add(responses.GET, get_devices_url, body='{}') + responses.add(responses.GET, get_devices_url, body="{}") self.cli.api.get_devices() req = responses.calls[0].request assert req.url == get_devices_url - assert req.method == 'GET' + assert req.method == "GET" @responses.activate def test_get_device(self): get_device_url = "http://example.com/_matrix/client/r0/devices/QBUAZIFURK" - responses.add(responses.GET, get_device_url, body='{}') + responses.add(responses.GET, get_device_url, body="{}") self.cli.api.get_device(self.device_id) req = responses.calls[0].request assert req.url == get_device_url - assert req.method == 'GET' + assert req.method == "GET" @responses.activate def test_update_device_info(self): update_url = "http://example.com/_matrix/client/r0/devices/QBUAZIFURK" - responses.add(responses.PUT, update_url, body='{}') + responses.add(responses.PUT, update_url, body="{}") self.cli.api.update_device_info(self.device_id, self.display_name) req = responses.calls[0].request assert req.url == update_url - assert req.method == 'PUT' + assert req.method == "PUT" @responses.activate def test_delete_device(self): delete_device_url = "http://example.com/_matrix/client/r0/devices/QBUAZIFURK" - responses.add(responses.DELETE, delete_device_url, body='{}') + responses.add(responses.DELETE, delete_device_url, body="{}") # Test for 401 status code of User-Interactive Auth API - responses.add(responses.DELETE, delete_device_url, body='{}', status=401) + responses.add(responses.DELETE, delete_device_url, body="{}", status=401) self.cli.api.delete_device(self.auth_body, self.device_id) req = responses.calls[0].request assert req.url == delete_device_url - assert req.method == 'DELETE' + assert req.method == "DELETE" with pytest.raises(MatrixRequestError): self.cli.api.delete_device(self.auth_body, self.device_id) @@ -138,13 +132,13 @@ def test_delete_device(self): @responses.activate def test_delete_devices(self): delete_devices_url = "http://example.com/_matrix/client/r0/delete_devices" - responses.add(responses.POST, delete_devices_url, body='{}') + responses.add(responses.POST, delete_devices_url, body="{}") # Test for 401 status code of User-Interactive Auth API - responses.add(responses.POST, delete_devices_url, body='{}', status=401) + responses.add(responses.POST, delete_devices_url, body="{}", status=401) self.cli.api.delete_devices(self.auth_body, [self.device_id]) req = responses.calls[0].request assert req.url == delete_devices_url - assert req.method == 'POST' + assert req.method == "POST" with pytest.raises(MatrixRequestError): self.cli.api.delete_devices(self.auth_body, [self.device_id]) diff --git a/test/client_test.py b/test/client_test.py index 4071d5bf..a7002adc 100644 --- a/test/client_test.py +++ b/test/client_test.py @@ -5,6 +5,7 @@ from matrix_client.client import MatrixClient, Room, User, CACHE from matrix_client.api import MATRIX_V2_API_PATH from . import response_examples + try: from urllib import quote except ImportError: @@ -60,9 +61,7 @@ def test_bad_state_events(): client = MatrixClient("http://example.com") room = client._mkroom("!abc:matrix.org") - ev = { - "tomato": False - } + ev = {"tomato": False} room._process_state_event(ev) @@ -75,10 +74,7 @@ def test_state_event(): room.topic = False room.aliases = False - ev = { - "type": "m.room.name", - "content": {} - } + ev = {"type": "m.room.name", "content": {}} room._process_state_event(ev) assert room.name is None @@ -106,13 +102,13 @@ def test_state_event(): # test member join event ev["type"] = "m.room.member" - ev["content"] = {'membership': 'join', 'displayname': 'stereo'} + ev["content"] = {"membership": "join", "displayname": "stereo"} ev["state_key"] = "@stereo:xxx.org" room._process_state_event(ev) assert len(room._members) == 1 assert room._members[0].user_id == "@stereo:xxx.org" # test member leave event - ev["content"]['membership'] = 'leave' + ev["content"]["membership"] = "leave" room._process_state_event(ev) assert len(room._members) == 0 @@ -152,6 +148,7 @@ def test_get_download_url(): def test_remove_listener(): + def dummy_listener(): pass @@ -185,19 +182,22 @@ def test_register_as_guest(self): def _sync(self): self._sync_called = True + cli.__dict__[_sync.__name__] = _sync.__get__(cli, cli.__class__) register_guest_url = HOSTNAME + MATRIX_V2_API_PATH + "/register" - response_body = json.dumps({ - 'access_token': 'EXAMPLE_ACCESS_TOKEN', - 'device_id': 'guest_device', - 'home_server': 'example.com', - 'user_id': '@455:example.com' - }) + response_body = json.dumps( + { + "access_token": "EXAMPLE_ACCESS_TOKEN", + "device_id": "guest_device", + "home_server": "example.com", + "user_id": "@455:example.com", + } + ) responses.add(responses.POST, register_guest_url, body=response_body) cli.register_as_guest() - assert cli.token == cli.api.token == 'EXAMPLE_ACCESS_TOKEN' - assert cli.hs == 'example.com' - assert cli.user_id == '@455:example.com' + assert cli.token == cli.api.token == "EXAMPLE_ACCESS_TOKEN" + assert cli.hs == "example.com" + assert cli.user_id == "@455:example.com" assert cli._sync_called @@ -205,7 +205,7 @@ def test_get_rooms_display_name(): def add_members(api, room, num): for i in range(num): - room._mkmembers(User(api, '@frho%s:matrix.org' % i, 'ho%s' % i)) + room._mkmembers(User(api, "@frho%s:matrix.org" % i, "ho%s" % i)) client = MatrixClient("http://example.com") client.user_id = "@frho0:matrix.org" @@ -233,6 +233,7 @@ def test_presence_listener(): def dummy_callback(event): accumulator.append(event) + presence_events = [ { "content": { @@ -240,10 +241,10 @@ def dummy_callback(event): "currently_active": False, "last_active_ago": 2478593, "presence": "online", - "user_id": "@example:localhost" + "user_id": "@example:localhost", }, "event_id": "$WLGTSEFSEF:localhost", - "type": "m.presence" + "type": "m.presence", }, { "content": { @@ -251,10 +252,10 @@ def dummy_callback(event): "currently_active": True, "last_active_ago": 1478593, "presence": "online", - "user_id": "@example2:localhost" + "user_id": "@example2:localhost", }, "event_id": "$CIGTXEFREF:localhost", - "type": "m.presence" + "type": "m.presence", }, { "content": { @@ -262,10 +263,10 @@ def dummy_callback(event): "currently_active": False, "last_active_ago": 24795, "presence": "offline", - "user_id": "@example3:localhost" + "user_id": "@example3:localhost", }, "event_id": "$ZEGASEDSEF:localhost", - "type": "m.presence" + "type": "m.presence", }, ] sync_response = deepcopy(response_examples.example_sync) @@ -290,17 +291,25 @@ def test_changing_user_power_levels(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) - PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.power_levels" + PL_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.power_levels" + ) # Code should first get current power_levels and then modify them - responses.add(responses.GET, PL_state_path, - json=response_examples.example_pl_event["content"]) - responses.add(responses.PUT, PL_state_path, - json=response_examples.example_event_response) + responses.add( + responses.GET, PL_state_path, json=response_examples.example_pl_event["content"] + ) + responses.add( + responses.PUT, PL_state_path, json=response_examples.example_event_response + ) # Removes user from user and adds user to to users list - assert room.modify_user_power_levels(users={"@example:localhost": None, - "@foobar:example.com": 49}) + assert room.modify_user_power_levels( + users={"@example:localhost": None, "@foobar:example.com": 49} + ) expected_request = deepcopy(response_examples.example_pl_event["content"]) del expected_request["users"]["@example:localhost"] @@ -314,14 +323,21 @@ def test_changing_default_power_level(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) - PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.power_levels" + PL_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.power_levels" + ) # Code should first get current power_levels and then modify them - responses.add(responses.GET, PL_state_path, - json=response_examples.example_pl_event["content"]) - responses.add(responses.PUT, PL_state_path, - json=response_examples.example_event_response) + responses.add( + responses.GET, PL_state_path, json=response_examples.example_pl_event["content"] + ) + responses.add( + responses.PUT, PL_state_path, json=response_examples.example_event_response + ) assert room.modify_user_power_levels(users_default=23) expected_request = deepcopy(response_examples.example_pl_event["content"]) @@ -335,17 +351,25 @@ def test_changing_event_required_power_levels(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) - PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.power_levels" + PL_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.power_levels" + ) # Code should first get current power_levels and then modify them - responses.add(responses.GET, PL_state_path, - json=response_examples.example_pl_event["content"]) - responses.add(responses.PUT, PL_state_path, - json=response_examples.example_event_response) + responses.add( + responses.GET, PL_state_path, json=response_examples.example_pl_event["content"] + ) + responses.add( + responses.PUT, PL_state_path, json=response_examples.example_event_response + ) # Remove event from events and adds new controlled event - assert room.modify_required_power_levels(events={"m.room.name": None, - "example.event": 51}) + assert room.modify_required_power_levels( + events={"m.room.name": None, "example.event": 51} + ) expected_request = deepcopy(response_examples.example_pl_event["content"]) del expected_request["events"]["m.room.name"] @@ -359,17 +383,23 @@ def test_changing_other_required_power_levels(): client = MatrixClient(HOSTNAME) room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) - PL_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.power_levels" + PL_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.power_levels" + ) # Code should first get current power_levels and then modify them - responses.add(responses.GET, PL_state_path, - json=response_examples.example_pl_event["content"]) - responses.add(responses.PUT, PL_state_path, - json=response_examples.example_event_response) + responses.add( + responses.GET, PL_state_path, json=response_examples.example_pl_event["content"] + ) + responses.add( + responses.PUT, PL_state_path, json=response_examples.example_event_response + ) # Remove event from events and adds new controlled event - assert room.modify_required_power_levels(kick=53, redact=2, - state_default=None) + assert room.modify_required_power_levels(kick=53, redact=2, state_default=None) expected_request = deepcopy(response_examples.example_pl_event["content"]) expected_request["kick"] = 53 @@ -428,11 +458,19 @@ def test_room_join_rules(): room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) assert room.invite_only is None - join_rules_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.join_rules" + join_rules_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.join_rules" + ) - responses.add(responses.PUT, join_rules_state_path, - json=response_examples.example_event_response) + responses.add( + responses.PUT, + join_rules_state_path, + json=response_examples.example_event_response, + ) assert room.set_invite_only(True) assert room.invite_only @@ -444,11 +482,19 @@ def test_room_guest_access(): room_id = "!UcYsUzyxTGDxLBEvLz:matrix.org" room = client._mkroom(room_id) assert room.guest_access is None - guest_access_state_path = HOSTNAME + MATRIX_V2_API_PATH + \ - "/rooms/" + quote(room_id) + "/state/m.room.guest_access" + guest_access_state_path = ( + HOSTNAME + + MATRIX_V2_API_PATH + + "/rooms/" + + quote(room_id) + + "/state/m.room.guest_access" + ) - responses.add(responses.PUT, guest_access_state_path, - json=response_examples.example_event_response) + responses.add( + responses.PUT, + guest_access_state_path, + json=response_examples.example_event_response, + ) assert room.set_guest_access(True) assert room.guest_access diff --git a/test/response_examples.py b/test/response_examples.py index 2ae565fc..42b1cf1b 100644 --- a/test/response_examples.py +++ b/test/response_examples.py @@ -5,9 +5,7 @@ { "sender": "@alice:example.com", "type": "m.presence", - "content": { - "presence": "online" - } + "content": {"presence": "online"}, } ] }, @@ -15,9 +13,7 @@ "events": [ { "type": "org.example.custom.config", - "content": { - "custom_config_key": "custom_config_value" - } + "content": {"custom_config_key": "custom_config_value"}, } ] }, @@ -30,11 +26,9 @@ "sender": "@alice:example.com", "type": "m.room.member", "state_key": "@alice:example.com", - "content": { - "membership": "join" - }, + "content": {"membership": "join"}, "origin_server_ts": 1417731086795, - "event_id": "$66697273743031:example.com" + "event_id": "$66697273743031:example.com", } ] }, @@ -44,63 +38,41 @@ "sender": "@bob:example.com", "type": "m.room.member", "state_key": "@bob:example.com", - "content": { - "membership": "join" - }, - "prev_content": { - "membership": "invite" - }, + "content": {"membership": "join"}, + "prev_content": {"membership": "invite"}, "origin_server_ts": 1417731086795, - "event_id": "$7365636s6r6432:example.com" + "event_id": "$7365636s6r6432:example.com", }, { "sender": "@alice:example.com", "type": "m.room.message", "age": 124524, "txn_id": "1234", - "content": { - "body": "I am a fish", - "msgtype": "m.text" - }, + "content": {"body": "I am a fish", "msgtype": "m.text"}, "origin_server_ts": 1417731086797, - "event_id": "$74686972643033:example.com" - } + "event_id": "$74686972643033:example.com", + }, ], "limited": True, - "prev_batch": "t34-23535_0_0" + "prev_batch": "t34-23535_0_0", }, "ephemeral": { "events": [ { "type": "m.typing", - "content": { - "user_ids": [ - "@alice:example.com" - ] - } + "content": {"user_ids": ["@alice:example.com"]}, } ] }, "account_data": { "events": [ - { - "type": "m.tag", - "content": { - "tags": { - "work": { - "order": 1 - } - } - } - }, + {"type": "m.tag", "content": {"tags": {"work": {"order": 1}}}}, { "type": "org.example.custom.room.config", - "content": { - "custom_config_key": "custom_config_value" - } - } + "content": {"custom_config_key": "custom_config_value"}, + }, ] - } + }, } }, "invite": { @@ -111,52 +83,41 @@ "sender": "@alice:example.com", "type": "m.room.name", "state_key": "", - "content": { - "name": "My Room Name" - } + "content": {"name": "My Room Name"}, }, { "sender": "@alice:example.com", "type": "m.room.member", "state_key": "@bob:example.com", - "content": { - "membership": "invite" - } - } + "content": {"membership": "invite"}, + }, ] } } }, - "leave": {} - } + "leave": {}, + }, } example_pl_event = { "age": 242352, "content": { "ban": 50, - "events": { - "m.room.name": 100, - "m.room.power_levels": 100 - }, + "events": {"m.room.name": 100, "m.room.power_levels": 100}, "events_default": 0, "invite": 50, "kick": 50, "redact": 50, "state_default": 50, - "users": { - "@example:localhost": 100 - }, - "users_default": 0 + "users": {"@example:localhost": 100}, + "users_default": 0, }, "event_id": "$WLGTSEFSEF:localhost", "origin_server_ts": 1431961217939, "room_id": "!Cuyf34gef24t:localhost", "sender": "@example:localhost", "state_key": "", - "type": "m.room.power_levels" + "type": "m.room.power_levels", } -example_event_response = { - "event_id": "YUwRidLecu" -} +example_event_response = {"event_id": "YUwRidLecu"} From d13255cc2acd4cc850d44432c5ffaff69d2ce056 Mon Sep 17 00:00:00 2001 From: Adam Beckmeyer Date: Fri, 25 May 2018 12:25:09 -0400 Subject: [PATCH 2/3] Make changes to make black able to give PEP8 compliant results Signed-off-by: Adam Beckmeyer --- test/api_test.py | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/test/api_test.py b/test/api_test.py index 950bf2fa..73ed9200 100644 --- a/test/api_test.py +++ b/test/api_test.py @@ -5,13 +5,16 @@ class TestTagsApi: + base_url = "http://example.com" cli = client.MatrixClient("http://example.com") user_id = "@user:matrix.org" room_id = "#foo:matrix.org" @responses.activate def test_get_user_tags(self): - tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags" + tags_url = self.base_url + "/_matrix/client/r0/user/{}/rooms/{}/tags".format( + self.user_id, self.room_id + ) responses.add(responses.GET, tags_url, body="{}") self.cli.api.get_user_tags(self.user_id, self.room_id) req = responses.calls[0].request @@ -20,7 +23,9 @@ def test_get_user_tags(self): @responses.activate def test_add_user_tags(self): - tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" + tags_url = self.base_url + "/_matrix/client/r0/user/{}/rooms/{}/tags/foo".format( + self.user_id, self.room_id + ) responses.add(responses.PUT, tags_url, body="{}") self.cli.api.add_user_tag(self.user_id, self.room_id, "foo", body={"order": "5"}) req = responses.calls[0].request @@ -29,7 +34,9 @@ def test_add_user_tags(self): @responses.activate def test_remove_user_tags(self): - tags_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/rooms/#foo:matrix.org/tags/foo" + tags_url = self.base_url + "/_matrix/client/r0/user/{}/rooms/{}/tags/foo".format( + self.user_id, self.room_id + ) responses.add(responses.DELETE, tags_url, body="{}") self.cli.api.remove_user_tag(self.user_id, self.room_id, "foo") req = responses.calls[0].request @@ -38,13 +45,17 @@ def test_remove_user_tags(self): class TestAccountDataApi: + base_url = "http://example.com" cli = client.MatrixClient("http://example.com") user_id = "@user:matrix.org" room_id = "#foo:matrix.org" @responses.activate def test_set_account_data(self): - account_data_url = "http://example.com" "/_matrix/client/r0/user/@user:matrix.org/account_data/foo" + account_data_url = ( + self.base_url + + "/_matrix/client/r0/user/{}/account_data/foo".format(self.user_id) + ) responses.add(responses.PUT, account_data_url, body="{}") self.cli.api.set_account_data(self.user_id, "foo", {"bar": 1}) req = responses.calls[0].request @@ -53,7 +64,12 @@ def test_set_account_data(self): @responses.activate def test_set_room_account_data(self): - account_data_url = "http://example.com/_matrix/client/r0/user" "/@user:matrix.org/rooms/#foo:matrix.org/account_data/foo" + account_data_url = ( + self.base_url + + "/_matrix/client/r0/user/{}/rooms/{}/account_data/foo".format( + self.user_id, self.room_id + ) + ) responses.add(responses.PUT, account_data_url, body="{}") self.cli.api.set_room_account_data(self.user_id, self.room_id, "foo", {"bar": 1}) req = responses.calls[0].request @@ -62,13 +78,16 @@ def test_set_room_account_data(self): class TestUnbanApi: + base_url = "http://example.com" cli = client.MatrixClient("http://example.com") user_id = "@user:matrix.org" room_id = "#foo:matrix.org" @responses.activate def test_unban(self): - unban_url = "http://example.com" "/_matrix/client/r0/rooms/#foo:matrix.org/unban" + unban_url = self.base_url + "/_matrix/client/r0/rooms/{}/unban".format( + self.room_id + ) responses.add(responses.POST, unban_url, body="{}") self.cli.api.unban_user(self.room_id, self.user_id) req = responses.calls[0].request From 010c99c5a6d37f1d598ebb119b5637944768aef7 Mon Sep 17 00:00:00 2001 From: Adam Beckmeyer Date: Fri, 25 May 2018 13:51:30 -0400 Subject: [PATCH 3/3] Make tox check black compliance Signed-off-by: Adam Beckmeyer --- setup.py | 3 ++- tox.ini | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index 4907c9b8..1a5dfadd 100644 --- a/setup.py +++ b/setup.py @@ -47,11 +47,12 @@ def exec_file(names): setup_requires=["pytest-runner"], tests_require=["pytest", "responses"], extras_require={ - "test": ["tox", "pytest", "flake8", "responses"], + "test": ["tox", "pytest", "responses"], "doc": [ "Sphinx==1.4.6", "sphinx-rtd-theme==0.1.9", "sphinxcontrib-napoleon==0.5.3", ], + "format": ["flake8", "black"], }, ) diff --git a/tox.ini b/tox.ini index 9c766cc6..982f3214 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py27,py34,py35,py36,packaging,pep8,docs +envlist = py27,py34,py35,py36,packaging,format,docs [testenv] passenv = TRAVIS TRAVIS_* @@ -14,9 +14,12 @@ commands= coverage report - coveralls -[testenv:pep8] +[testenv:format] +deps = .[format] skip_install = True -commands = /bin/bash -c "flake8 matrix_client samples test {env:PEP8SUFFIX:}" +commands = + /bin/bash -c "flake8 matrix_client samples test {env:PEP8SUFFIX:}" + /bin/bash -c "black -l 90 --check matrix_client samples test setup.py docs" [testenv:packaging] deps =