├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── procbridge ├── __init__.py ├── const.py ├── errors.py └── protocol.py ├── setup.py └── tests ├── __init__.py ├── article.txt ├── server.py └── test_procbridge.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # IDE 107 | .idea 108 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Gong Zhang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .ONESHELL: 2 | test: 3 | python3 -m unittest 4 | 5 | clean: 6 | rm -rf build; 7 | rm -rf dist; 8 | rm -rf procbridge.egg-info 9 | 10 | setup: 11 | python3 -m pip install --upgrade setuptools wheel twine 12 | 13 | build: 14 | # https://packaging.python.org/tutorials/packaging-projects/ 15 | python3 setup.py sdist bdist_wheel 16 | 17 | upload_test: 18 | twine upload --repository-url https://test.pypi.org/legacy/ dist/* 19 | 20 | upload: 21 | twine upload dist/* 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # procbridge-python 2 | 3 | ProcBridge is a super-lightweight IPC (Inter-Process Communication) protocol over TCP socket or Unix domain socket. It enables you to **send and recieve JSON** between processes easily. ProcBridge is much like a simplified version of HTTP protocol, but only transfer JSON values. 4 | 5 | Please note that this repo is the **Python implementation** of ProcBridge protocol. You can find detailed introduction of ProcBridge protocol in the main repository: [gongzhang/procbridge](https://github.com/gongzhang/procbridge). 6 | 7 | # Installation 8 | 9 | ``` 10 | pip install procbridge==1.2.2 11 | ``` 12 | 13 | # Example 14 | 15 | Server Side: 16 | 17 | ```python 18 | import procbridge as pb 19 | 20 | def delegate(method, args): 21 | 22 | # define remote methods: 23 | if method == 'echo': 24 | return args 25 | 26 | elif method == 'sum': 27 | return sum(x for x in args) 28 | 29 | elif method == 'err': 30 | raise RuntimeError("an server error") 31 | 32 | 33 | if __name__ == '__main__': 34 | PORT = 8000 35 | s = pb.Server('0.0.0.0', PORT, delegate) 36 | s.start(daemon=False) 37 | print("Server is on {}...".format(PORT)) 38 | ``` 39 | 40 | Client Side: 41 | 42 | ```python 43 | import procbridge as pb 44 | client = pb.Client('127.0.0.1', 8000) 45 | 46 | # call remote methods: 47 | client.request("echo", 123) # 123 48 | client.request("echo", ['a', 'b', 'c']) # ['a', 'b', 'c'] 49 | client.request("sum", [1, 2, 3, 4]) # 10 50 | ``` 51 | -------------------------------------------------------------------------------- /procbridge/__init__.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import socket 3 | from . import protocol as p 4 | from typing import Any, Callable 5 | from .errors import ProtocolError, ServerError 6 | from .const import StatusCode, Versions 7 | 8 | __all__ = ["Server", "Client", "Versions", "ProtocolError", "ServerError"] 9 | 10 | 11 | class Client: 12 | 13 | def __init__(self, host: str, port: int): 14 | self.family = socket.AF_INET 15 | self.host = host 16 | self.port = port 17 | self.path = None 18 | 19 | @classmethod 20 | def from_unix(cls, path: str): 21 | ins = cls('', 0) 22 | ins.family = socket.AF_UNIX 23 | ins.path = path 24 | return ins 25 | 26 | @classmethod 27 | def from_inet(cls, host: str, port: int): 28 | return cls(host, port) 29 | 30 | def request(self, method: str, payload: Any = None) -> Any: 31 | if self.path is not None: 32 | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 33 | s.connect(self.path) 34 | else: 35 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 36 | s.connect((self.host, self.port)) 37 | try: 38 | p.write_request(s, method, payload) 39 | code, result = p.read_response(s) 40 | if code == StatusCode.GOOD_RESPONSE: 41 | return result 42 | else: 43 | raise ServerError(result) 44 | finally: 45 | s.close() 46 | 47 | 48 | class Server: 49 | 50 | def __init__(self, host: str, port: int, delegate: Callable[[str, Any], Any]): 51 | self.family = socket.AF_INET 52 | self.host = host 53 | self.port = port 54 | self.path = None 55 | self.started = False 56 | self.lock = threading.Lock() 57 | self.socket = None 58 | self.delegate = delegate 59 | 60 | @classmethod 61 | def from_unix(cls, path: str, delegate: Callable[[str, Any], Any]): 62 | ins = cls('', 0, delegate) 63 | ins.family = socket.AF_UNIX 64 | ins.path = path 65 | return ins 66 | 67 | @classmethod 68 | def from_inet(cls, host: str, port: int, delegate: Callable[[str, Any], Any]): 69 | return cls(host, port, delegate) 70 | 71 | def start(self, daemon=True): 72 | self.lock.acquire() 73 | try: 74 | if self.started: 75 | return 76 | 77 | if self.path is not None: 78 | self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 79 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 80 | self.socket.bind(self.path) 81 | else: 82 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 83 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 84 | self.socket.bind((self.host, self.port)) 85 | self.socket.listen(0) 86 | t = threading.Thread(target=_start_server_listener, args=(self,), daemon=daemon) 87 | t.start() 88 | self.started = True 89 | except OSError as err: 90 | self.socket.close() 91 | raise err 92 | finally: 93 | self.lock.release() 94 | 95 | def stop(self): 96 | self.lock.acquire() 97 | try: 98 | if not self.started: 99 | return 100 | self.socket.close() 101 | self.socket = None 102 | self.started = False 103 | finally: 104 | self.lock.release() 105 | 106 | 107 | def _start_server_listener(server: Server): 108 | try: 109 | while True: 110 | server.lock.acquire() 111 | if not server.started: 112 | return 113 | server.lock.release() 114 | 115 | # assert started == true: 116 | conn, _ = server.socket.accept() 117 | t = threading.Thread(target=_start_connection, args=(server, conn,), daemon=True) 118 | t.start() 119 | except ConnectionAbortedError: 120 | # socket stopped 121 | pass 122 | 123 | 124 | def _start_connection(server: Server, s: socket.socket): 125 | try: 126 | method, payload = p.read_request(s) 127 | try: 128 | result = server.delegate(method, payload) 129 | p.write_good_response(s, result) 130 | except Exception as err: 131 | p.write_bad_response(s, str(err)) 132 | except Exception as err: 133 | pass 134 | finally: 135 | s.close() 136 | -------------------------------------------------------------------------------- /procbridge/const.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class Versions(Enum): 5 | V1_0 = b'\x01\x00' 6 | V1_1 = b'\x01\x01' 7 | 8 | @staticmethod 9 | def current(): 10 | return Versions.V1_1 11 | 12 | 13 | class StatusCode(Enum): 14 | REQUEST = 0 15 | GOOD_RESPONSE = 1 16 | BAD_RESPONSE = 2 17 | 18 | 19 | class Keys(Enum): 20 | METHOD = 'method' 21 | PAYLOAD = 'payload' 22 | MESSAGE = 'message' 23 | -------------------------------------------------------------------------------- /procbridge/errors.py: -------------------------------------------------------------------------------- 1 | class ErrorMessages: 2 | UNRECOGNIZED_PROTOCOL = 'unrecognized protocol' 3 | INCOMPATIBLE_VERSION = 'incompatible protocol version' 4 | INCOMPLETE_DATA = 'incomplete data' 5 | INVALID_STATUS_CODE = 'invalid status code' 6 | INVALID_BODY = 'invalid body' 7 | UNKNOWN_SERVER_ERROR = 'unknown server error' 8 | 9 | 10 | class ProtocolError(Exception): 11 | def __init__(self, message: str, detail: str = None): 12 | self.message = message 13 | self.detail = detail 14 | 15 | 16 | class ServerError(Exception): 17 | def __init__(self, message: str): 18 | self.message = message 19 | -------------------------------------------------------------------------------- /procbridge/protocol.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import json 3 | from typing import Any 4 | 5 | from .const import StatusCode, Keys, Versions 6 | from .errors import ProtocolError, ErrorMessages 7 | 8 | 9 | def read_bytes(s: socket.socket, count: int) -> bytes: 10 | rst = b'' 11 | if count == 0: 12 | return rst 13 | while True: 14 | tmp = s.recv(count - len(rst)) 15 | if len(tmp) == 0: 16 | break 17 | rst += tmp 18 | if len(rst) == count: 19 | break 20 | return rst 21 | 22 | 23 | def read_socket(s: socket.socket) -> (int, dict): 24 | # 1. FLAG 'pb' 25 | flag = read_bytes(s, 2) 26 | if flag != b'pb': 27 | raise ProtocolError(ErrorMessages.UNRECOGNIZED_PROTOCOL) 28 | 29 | # 2. VERSION 30 | ver = read_bytes(s, 2) 31 | if ver != Versions.current().value: 32 | raise ProtocolError(ErrorMessages.INCOMPATIBLE_VERSION, 33 | "need version {} but found {}".format(Versions.current(), ver)) 34 | 35 | # 3. STATUS CODE 36 | status_code = read_bytes(s, 1) 37 | if len(status_code) != 1: 38 | raise ProtocolError(ErrorMessages.INCOMPLETE_DATA) 39 | code = status_code[0] 40 | 41 | # 4. RESERVED (2 bytes) 42 | reserved = read_bytes(s, 2) 43 | if len(reserved) != 2: 44 | raise ProtocolError(ErrorMessages.INCOMPLETE_DATA) 45 | 46 | # 5. LENGTH (4-byte, little endian) 47 | len_bytes = read_bytes(s, 4) 48 | if len(len_bytes) != 4: 49 | raise ProtocolError(ErrorMessages.INCOMPLETE_DATA) 50 | json_len = len_bytes[0] 51 | json_len += len_bytes[1] << 8 52 | json_len += len_bytes[2] << 16 53 | json_len += len_bytes[3] << 24 54 | 55 | # 6. JSON OBJECT 56 | text_bytes = read_bytes(s, json_len) 57 | if len(text_bytes) != json_len: 58 | raise ProtocolError(ErrorMessages.INCOMPLETE_DATA, 59 | 'expect ' + str(json_len) + ' bytes but found ' + str(len(text_bytes))) 60 | try: 61 | obj = json.loads(str(text_bytes, encoding='utf-8')) 62 | except Exception as err: 63 | raise ProtocolError(ErrorMessages.INVALID_BODY, "{}".format(err)) 64 | 65 | return code, obj 66 | 67 | 68 | def write_socket(s: socket.socket, status_code: StatusCode, json_obj: dict): 69 | # 1. FLAG 70 | s.sendall(b'pb') 71 | # 2. VERSION 72 | s.sendall(Versions.current().value) 73 | # 3. STATUS CODE 74 | s.sendall(bytes([status_code.value])) 75 | # 4. RESERVED 2 BYTES 76 | s.sendall(b'\x00\x00') 77 | 78 | # 5. LENGTH (little endian) 79 | json_text = json.dumps(json_obj) 80 | json_bytes = bytes(json_text, encoding='utf-8') 81 | len_bytes = len(json_bytes).to_bytes(4, byteorder='little') 82 | s.sendall(len_bytes) 83 | 84 | # 6. JSON 85 | s.sendall(json_bytes) 86 | 87 | 88 | def write_request(s: socket.socket, method: str, payload: Any): 89 | body = {} 90 | if method is not None: 91 | body[Keys.METHOD.value] = method 92 | if payload is not None: 93 | body[Keys.PAYLOAD.value] = payload 94 | write_socket(s, StatusCode.REQUEST, body) 95 | 96 | 97 | def write_good_response(s: socket.socket, payload: Any): 98 | body = {} 99 | if payload is not None: 100 | body[Keys.PAYLOAD.value] = payload 101 | write_socket(s, StatusCode.GOOD_RESPONSE, body) 102 | 103 | 104 | def write_bad_response(s: socket.socket, message: str): 105 | body = {} 106 | if message is not None: 107 | body[Keys.MESSAGE.value] = message 108 | write_socket(s, StatusCode.BAD_RESPONSE, body) 109 | 110 | 111 | def read_request(s: socket.socket) -> (str, Any): 112 | status_code, obj = read_socket(s) 113 | if status_code != StatusCode.REQUEST.value: 114 | raise ProtocolError(ErrorMessages.INVALID_STATUS_CODE, "{}".format(status_code)) 115 | method = None 116 | payload = None 117 | if Keys.METHOD.value in obj: 118 | method = str(obj[Keys.METHOD.value]) 119 | if Keys.PAYLOAD.value in obj: 120 | payload = obj[Keys.PAYLOAD.value] 121 | return method, payload 122 | 123 | 124 | def read_response(s: socket.socket) -> (StatusCode, Any): 125 | status_code, obj = read_socket(s) 126 | if status_code == StatusCode.GOOD_RESPONSE.value: 127 | if Keys.PAYLOAD.value not in obj: 128 | return StatusCode.GOOD_RESPONSE, None 129 | else: 130 | return StatusCode.GOOD_RESPONSE, obj[Keys.PAYLOAD.value] 131 | elif status_code == StatusCode.BAD_RESPONSE.value: 132 | if Keys.MESSAGE.value not in obj: 133 | return StatusCode.BAD_RESPONSE, ErrorMessages.UNKNOWN_SERVER_ERROR 134 | else: 135 | return StatusCode.BAD_RESPONSE, str(obj[Keys.MESSAGE.value]) 136 | else: 137 | raise ProtocolError(ErrorMessages.INVALID_STATUS_CODE, "{}".format(status_code)) 138 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="procbridge", 8 | version="1.2.2", 9 | author="Gong Zhang", 10 | author_email="gong@me.com", 11 | description="A super-lightweight IPC (Inter-Process Communication) protocol over TCP socket.", 12 | license="MIT License", 13 | platforms=['any'], 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | url="https://github.com/gongzhang/procbridge-python", 17 | packages=setuptools.find_packages(exclude=["tests"]), 18 | classifiers=[ 19 | "Programming Language :: Python :: 3", 20 | "License :: OSI Approved :: MIT License", 21 | "Operating System :: OS Independent", 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gongzhang/procbridge-python/ab90412d1419596a06084d171945c4289efc8548/tests/__init__.py -------------------------------------------------------------------------------- /tests/article.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, ligula suspendisse nulla pretium, rhoncus tempor fermentum, enim integer ad vestibulum volutpat. Nisl rhoncus turpis est, vel elit, congue wisi enim nunc ultricies sit, magna tincidunt. Maecenas aliquam maecenas ligula nostra, accumsan taciti. Sociis mauris in integer, a dolor netus non dui aliquet, sagittis felis sodales, dolor sociis mauris, vel eu libero cras. Faucibus at. Arcu habitasse elementum est, ipsum purus pede porttitor class, ut adipiscing, aliquet sed auctor, imperdiet arcu per diam dapibus libero duis. Enim eros in vel, volutpat nec pellentesque leo, temporibus scelerisque nec. 2 | Ac dolor ac adipiscing amet bibendum nullam, lacus molestie ut libero nec, diam et, pharetra sodales, feugiat ullamcorper id tempor id vitae. Mauris pretium aliquet, lectus tincidunt. Porttitor mollis imperdiet libero senectus pulvinar. Etiam molestie mauris ligula laoreet, vehicula eleifend. Repellat orci erat et, sem cum, ultricies sollicitudin amet eleifend dolor nullam erat, malesuada est leo ac. Varius natoque turpis elementum est. Duis montes, tellus lobortis lacus amet arcu et. In vitae vel, wisi at, id praesent bibendum libero faucibus porta egestas, quisque praesent ipsum fermentum tempor. Curabitur auctor, erat mollis sed, turpis vivamus a dictumst congue magnis. Aliquam amet ullamcorper dignissim molestie, mollis. Tortor vitae tortor eros wisi facilisis. 3 | Consectetuer arcu ipsum ornare pellentesque vehicula, in vehicula diam, ornare magna erat felis wisi a risus. Justo fermentum id. Malesuada eleifend, tortor molestie, a a vel et. Mauris at suspendisse, neque aliquam faucibus adipiscing, vivamus in. Wisi mattis leo suscipit nec amet, nisl fermentum tempor ac a, augue in eleifend in venenatis, cras sit id in vestibulum felis in, sed ligula. In sodales suspendisse mauris quam etiam erat, quia tellus convallis eros rhoncus diam orci, porta lectus esse adipiscing posuere et, nisl arcu vitae laoreet. Morbi integer molestie, amet suspendisse morbi, amet maecenas, a maecenas mauris neque proin nisl mollis. Suscipit nec ligula ipsum orci nulla, in posuere ut quis ultrices, lectus primis vehicula velit hasellus lectus, vestibulum orci laoreet inceptos vitae, at consectetuer amet et consectetuer. Congue porta scelerisque praesent at, lacus vestibulum et at dignissim cras urna, ante convallis turpis duis lectus sed aliquet, at et ultricies. Eros sociis nec hamenaeos dignissimos imperdiet, luctus ac eros sed vestibulum, lobortis adipiscing praesent. Nec eros eu ridiculus libero felis. 4 | Donec arcu risus diam amet sit. Congue tortor risus vestibulum commodo nisl, luctus augue amet quis aenean maecenas sit, donec velit iusto, morbi felis elit et nibh. Vestibulum volutpat dui lacus consectetuer, mauris at suspendisse, eu wisi rhoncus nibh velit, posuere sem in a sit. Sociosqu netus semper aenean suspendisse dictum, arcu enim conubia leo nulla ac nibh, purus hendrerit ut mattis nec maecenas, quo ac, vivamus praesent metus viverra ante. Natoque sed sit hendrerit, dapibus velit molestiae leo a, ut lorem sit et lacus aliquam. Sodales nulla ante auctor excepturi wisi, dolor lacinia dignissim eros condimentum dis pellentesque, sodales lacus nunc, feugiat at. In orci ligula suscipit luctus, sed dolor eleifend aliquam dui, ut diam mauris, sollicitudin sed nisl lacus. -------------------------------------------------------------------------------- /tests/server.py: -------------------------------------------------------------------------------- 1 | import time 2 | import procbridge as pb 3 | 4 | PORT = 8000 5 | 6 | 7 | def delegate(method, payload): 8 | if method == 'echo': 9 | return payload 10 | elif method == 'sum': 11 | return sum(x for x in payload) 12 | elif method == 'err': 13 | raise RuntimeError("generated error") 14 | elif method == 'sleep': 15 | time.sleep(payload) 16 | 17 | 18 | if __name__ == '__main__': 19 | s = pb.Server('0.0.0.0', PORT, delegate) 20 | s.start(daemon=False) 21 | print("Test Server is on {}...".format(PORT)) 22 | -------------------------------------------------------------------------------- /tests/test_procbridge.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import procbridge as pb 3 | from .server import PORT 4 | from .server import delegate 5 | 6 | 7 | class TestProcBridge(unittest.TestCase): 8 | 9 | server = None 10 | 11 | @classmethod 12 | def setUpClass(cls): 13 | try: 14 | cls.server = pb.Server('0.0.0.0', PORT, delegate) 15 | cls.server.start() 16 | except OSError: 17 | print("use existing server on port {}".format(PORT)) 18 | cls.server = None 19 | 20 | @classmethod 21 | def tearDownClass(cls): 22 | if cls.server is not None: 23 | cls.server.stop() 24 | cls.server = None 25 | 26 | def setUp(self): 27 | self.client = pb.Client('127.0.0.1', PORT) 28 | 29 | def tearDown(self): 30 | self.client = None 31 | 32 | def testNone(self): 33 | reply = self.client.request(None, None) 34 | self.assertIsNone(reply) 35 | reply = self.client.request("echo", None) 36 | self.assertIsNone(reply) 37 | reply = self.client.request(None, "hello") 38 | self.assertIsNone(reply) 39 | 40 | def testEcho(self): 41 | reply = self.client.request("echo", 123) 42 | self.assertEqual(123, reply) 43 | reply = self.client.request("echo", 3.14) 44 | self.assertEqual(3.14, reply) 45 | reply = self.client.request("echo", "hello") 46 | self.assertEqual("hello", reply) 47 | reply = self.client.request("echo", ["a", "b"]) 48 | self.assertEqual(["a", "b"], reply) 49 | reply = self.client.request("echo", {"key": "value"}) 50 | self.assertEqual({"key": "value"}, reply) 51 | 52 | def testSum(self): 53 | reply = self.client.request("sum", [1, 2, 3, 4]) 54 | self.assertEqual(10, reply) 55 | 56 | def testError(self): 57 | try: 58 | self.client.request("err") 59 | except pb.ServerError as err: 60 | self.assertEqual("generated error", err.message) 61 | else: 62 | self.fail() 63 | 64 | def testBigPayload(self): 65 | with open('./tests/article.txt', encoding='utf-8') as f: 66 | text = f.read() 67 | reply = self.client.request("echo", text) 68 | self.assertEqual(text, reply) 69 | 70 | 71 | if __name__ == '__main__': 72 | unittest.main() 73 | --------------------------------------------------------------------------------