async def test_call_not_proxied( client: WSRPCClient, handler: WebSocketAsync, route: Route ): async with client: handler.add_route("reverse", route) with pytest.raises(ClientException): await client.proxy.reverse.foo()
async def test_call_func(client: WSRPCClient, handler: WebSocketAsync): def get_data(_): return DATA_TO_RETURN handler.add_route("get_data", get_data) async with client: response = await client.proxy.get_data() assert response == DATA_TO_RETURN
def launch(*subprocess_args): """Starts the websocket server that will be hosted in the Photoshop extension. """ from avalon import api, photoshop api.install(photoshop) sys.excepthook = safe_excepthook # Launch Photoshop and the websocket server. process = subprocess.Popen(subprocess_args, stdout=subprocess.PIPE) websocket_server = WebServerTool() # Add Websocket route websocket_server.add_route("*", "/ws/", WebSocketAsync) # Add after effects route to websocket handler route_name = 'Photoshop' print("Adding {} route".format(route_name)) WebSocketAsync.add_route( route_name, PhotoshopRoute # keep same name as in extension ) websocket_server.start_server() while True: if process.poll() is not None: print("Photoshop process is not alive. Exiting") websocket_server.stop() sys.exit(1) try: _stub = photoshop.stub() if _stub: break except Exception: time.sleep(0.5) # Wait for application launch to show Workfiles. if os.environ.get("AVALON_PHOTOSHOP_WORKFILES_ON_LAUNCH", True): if os.getenv("WORKFILES_SAVE_AS"): workfiles.show(save=False) else: workfiles.show() # Photoshop could be closed immediately, withou workfile selection try: if photoshop.stub(): api.emit("application.launched") self.callback_queue = queue.Queue() while True: main_thread_listen(process, websocket_server) except ConnectionNotEstablishedYet: pass finally: # Wait on Photoshop to close before closing the websocket server process.wait() websocket_server.stop()
async def test_call_method(client: WSRPCClient, handler: WebSocketAsync): class DataStore: def get_data(self, _): return DATA_TO_RETURN handler.add_route("get_data", DataStore().get_data) async with client: response = await client.proxy.get_data() assert response == DATA_TO_RETURN
async def test_call_dash_masked(client: WSRPCClient, handler: WebSocketAsync): async with client: handler.add_route("reverse", ReverseRouteAllowed) await client.proxy.reverse(data="") with pytest.raises(ClientException) as e: await client.proxy._hack_me() assert "not implemented" in e.value.message
async def test_call_masked(client: WSRPCClient, handler: WebSocketAsync, route: Route): async with client: handler.add_route("reverse", route) await client.proxy.reverse(data="") with pytest.raises(ClientException) as e: await client.proxy.reverse.private() assert e.value.message == "Method masked"
async def test_method_kwarg(client: WSRPCClient, handler: WebSocketAsync): test_value = 123 def test_me(_, method): assert method == test_value return method handler.add_route("test_me", test_me) async with client: response = await client.proxy.test_me(method=test_value) assert response == test_value
async def test_call(client: WSRPCClient, handler: WebSocketAsync, route: Route): async with client: handler.add_route("reverse", route) data = str(uuid.uuid4()) await client.proxy.reverse(data=data) await client.proxy.reverse.reverse() response = await client.proxy.reverse.get_data() assert response == data[::-1]
async def test_call_timeout(client: WSRPCClient, handler: WebSocketAsync): async def will_sleep_for(_, seconds): with timeout(0.5): await asyncio.sleep(seconds) return DATA_TO_RETURN handler.add_route("will_sleep_for", will_sleep_for) async with client: response = await client.proxy.will_sleep_for(seconds=0.1) assert response == DATA_TO_RETURN with pytest.raises(ClientException): await client.proxy.will_sleep_for(seconds=1)
async def test_broadcast(client: WSRPCClient, handler: WebSocketAsync, route: Route, loop): async with client: future = loop.create_future() async def on_broadcast(_, result): nonlocal future future.set_result(result) client.add_route("broadcast", on_broadcast) handler.add_route("reverse", route) await client.proxy.reverse(data=None) await asyncio.wait_for(client.proxy.reverse.broadcast(), timeout=999) assert await asyncio.wait_for(future, timeout=5)
async def test_call_when_params_none(client: WSRPCClient, handler: WebSocketAsync, route: Route): async with client: handler.add_route("reverse", route) data = str(uuid.uuid4()) await client.proxy.reverse(data=data) await client.socket.send_json(data={ "id": 80, "method": "reverse.reverse" }) response = await client.proxy.reverse.get_data() assert response == data[::-1]
def launch(*subprocess_args): """Starts the websocket server that will be hosted in the Photoshop extension. """ from avalon import api, photoshop api.install(photoshop) sys.excepthook = safe_excepthook # Launch Photoshop and the websocket server. ConsoleTrayApp.process = subprocess.Popen( subprocess_args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) websocket_server = WebServerTool() route_name = 'Photoshop' if websocket_server.port_occupied(websocket_server.host_name, websocket_server.port): log.info("Server already running, sending actual context and exit") asyncio.run(websocket_server.send_context_change(route_name)) sys.exit(1) # Add Websocket route websocket_server.add_route("*", "/ws/", WebSocketAsync) # Add after effects route to websocket handler print("Adding {} route".format(route_name)) WebSocketAsync.add_route( route_name, PhotoshopRoute # keep same name as in extension ) websocket_server.start_server() ConsoleTrayApp.websocket_server = websocket_server if os.environ.get("AVALON_PHOTOSHOP_WORKFILES_ON_LAUNCH", True): save = False if os.getenv("WORKFILES_SAVE_AS"): save = True ConsoleTrayApp.execute_in_main_thread(lambda: workfiles.show(save))
async def delayed(self, delay=0): await asyncio.sleep(delay) return "I'm delayed {0} seconds".format(delay) async def getEpoch(self): return self.loop.time() async def requiredArgument(self, _my_secret_arg): return True async def _secure_method(self): return 'WTF???' async def exc(self): raise Exception(u"Test Тест テスト 测试") async def getJoke(self): joke = choice(self.JOKES) result = await self.socket.proxy.joke(joke=joke) log.info('Client said that was "{0}"'.format('awesome' if result else 'awful')) return 'Cool' if result else 'Hmm.. Try again.' WebSocketAsync.add_route('test', TestRoute) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) aiohttp.web.run_app(app, port=8000)
import logging import uuid import aiohttp.web import asyncio from wsrpc_aiohttp import WebSocketAsync, STATIC_DIR loop = asyncio.get_event_loop() app = aiohttp.web.Application(loop=loop) log = logging.getLogger(__name__) app.router.add_route("*", "/ws/", WebSocketAsync) app.router.add_static('/js', STATIC_DIR) app.router.add_static('/', ".") def get_random_uuid(socket: WebSocketAsync): return str(uuid.uuid4()) WebSocketAsync.add_route('uuid4', get_random_uuid) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) aiohttp.web.run_app(app, port=8000)
async def web_server(): web_app = web.Application(client_max_size=30000000, middlewares=[error_middleware]) storage = EncryptedCookieStorage(urandom(32)) aiohttp_session.setup(web_app, storage) policy = auth.SessionTktAuthentication(urandom(32), 86400000, include_ip=True) auth.setup(web_app, policy) web_app.add_routes(routes) aiohttp_jinja2.setup( web_app, loader=jinja2.FileSystemLoader('book/webserver/template')) web_app['static_root_url'] = '/static' web_app.router.add_static("/static", "book/webserver/template/static") web_app.router.add_route("*", "/ws/", WebSocketAsync) web_app.router.add_static("/js", STATIC_DIR) web_app.router.add_static("/", ".") WebSocketAsync.add_route("list_people", ws_routes.list_people.list_people) WebSocketAsync.add_route("get_people", ws_routes.get_people.get_people) WebSocketAsync.add_route("delete_people", ws_routes.delete_people.delete_people) WebSocketAsync.add_route("create_people", ws_routes.create_people.create_people) WebSocketAsync.add_route("update_people", ws_routes.update_people.update_people) WebSocketAsync.add_route("update_password", ws_routes.user_profile.update_password) WebSocketAsync.add_route("list_users", ws_routes.user_profile.list_all_users) WebSocketAsync.add_route("create_user", ws_routes.user_profile.create_user) WebSocketAsync.add_route("edit_user", ws_routes.user_profile.edit_user) WebSocketAsync.add_route("remove_user", ws_routes.user_profile.remove_user) return web_app
import asyncio import logging import uuid import aiohttp.web from wsrpc_aiohttp import STATIC_DIR, WebSocketAsync loop = asyncio.get_event_loop() app = aiohttp.web.Application(loop=loop) log = logging.getLogger(__name__) app.router.add_route("*", "/ws/", WebSocketAsync) app.router.add_static("/js", STATIC_DIR) app.router.add_static("/", ".") def get_random_uuid(socket: WebSocketAsync): return str(uuid.uuid4()) WebSocketAsync.add_route("uuid4", get_random_uuid) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) aiohttp.web.run_app(app, port=8000)