def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()
        # self.loop.set_debug(False)
        self.app = self.get_app(self.loop)

        self.client = TestClient(self.app, )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.first_headers = {
            'Authorization': self.first_token,
            'Content-Type': 'application/json',
        }

        self.second_headers = {
            'Authorization': self.second_token,
            'Content-Type': 'application/json',
        }

        self.loop.run_until_complete(self.install_chat())
Example #2
0
def test_checkVersion():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_checkVersion():
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/common/checkVersion")
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
        else:
            assert jsonresp

    # Test
    loop.run_until_complete(test_handle_checkVersion())

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Example #3
0
    async def test_parallel_connection(
        self,
        client: TestClient,
        client_name: str,
        namespace_prefix: str,
        current_registry: prometheus_client.CollectorRegistry,
    ):
        results = await asyncio.gather(client.get("/200"), client.get("/200"))
        await asyncio.gather(*(r.json() for r in results))

        current_frozen_registry: List[prometheus_client.Metric] = list(
            current_registry.collect())

        assert_metric_exists(
            current_frozen_registry,
            f"{namespace_prefix}aiohttp_client_connection_create_seconds",
            f"{namespace_prefix}aiohttp_client_connection_create_seconds_bucket",
            labels={
                "client_name": client_name,
            },
        )

        assert_metric_value(
            current_frozen_registry,
            f"{namespace_prefix}aiohttp_client_connection_reuseconn",
            f"{namespace_prefix}aiohttp_client_connection_reuseconn_total",
            1.0,
            labels={
                "client_name": client_name,
            },
        )
Example #4
0
def test_postLookup():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_lookup(postbody=None):
        resp = await client.post("/lookup.do", json=postbody)

        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["result"] == "ok"
        else:
            assert jsonresp

    # Test FindBest
    postbody = {"todo": "FindBest", "service": "EcoMsgNew"}
    # Test
    loop.run_until_complete(test_handle_lookup(postbody))

    # Test EcoUpdate
    postbody = {"todo": "FindBest", "service": "EcoUpdate"}
    # Test
    loop.run_until_complete(test_handle_lookup(postbody))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Example #5
0
def test_logout():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_logout(token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/logout?accessToken={}".
            format(token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
        else:
            assert jsonresp

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(test_handle_logout(token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Example #6
0
    async def setUp(self) -> None:
        self.mc_server = mock.MagicMock()
        self.mc_server.sensors = SensorSet()
        self.mc_server.orig_sensors = SensorSet()

        self.mc_server.sensors.add(
            Sensor(str,
                   'products',
                   '',
                   default='["product1", "product2"]',
                   initial_status=Sensor.Status.NOMINAL))
        self.mc_server.sensors.add(
            Sensor(str,
                   'gui-urls',
                   '',
                   default=json.dumps(ROOT_GUI_URLS),
                   initial_status=Sensor.Status.NOMINAL))

        self.mc_server.orig_sensors.add(
            Sensor(str,
                   'product1.gui-urls',
                   '',
                   default=json.dumps(PRODUCT1_GUI_URLS),
                   initial_status=Sensor.Status.NOMINAL))
        self.mc_server.orig_sensors.add(
            Sensor(str,
                   'product2.cal.1.gui-urls',
                   '',
                   default=json.dumps(PRODUCT2_CAL_GUI_URLS),
                   initial_status=Sensor.Status.NOMINAL))
        self.mc_server.orig_sensors.add(
            Sensor(str,
                   'product2.ingest.1.gui-urls',
                   '',
                   default=json.dumps(PRODUCT2_CAL_GUI_URLS),
                   initial_status=Sensor.Status.UNKNOWN))
        for sensor in self.mc_server.orig_sensors.values():
            if self.haproxy_bind is not None and sensor.name.endswith(
                    '.gui-urls'):
                new_value = web.rewrite_gui_urls(EXTERNAL_URL, sensor)
                new_sensor = Sensor(sensor.stype, sensor.name,
                                    sensor.description, sensor.units)
                new_sensor.set_value(new_value,
                                     timestamp=sensor.timestamp,
                                     status=sensor.status)
                self.mc_server.sensors.add(new_sensor)
            else:
                self.mc_server.sensors.add(sensor)

        self.app = web.make_app(self.mc_server, self.haproxy_bind)
        self.server = TestServer(self.app)
        self.client = TestClient(self.server)
        await self.client.start_server()
        self.addCleanup(self.client.close)
        self.mc_server.add_interface_changed_callback.assert_called_once()
        self.dirty_set = self.mc_server.add_interface_changed_callback.mock_calls[
            0][1][0]
        self.dirty_set()
        await self.advance(1)
Example #7
0
    def _create_from_app_factory(app_factory, *args, **kwargs):
        nonlocal test_client, rpc_client
        app = app_factory(loop, *args, **kwargs)
        test_client = TestClient(TestServer(app), loop=loop)
        yield from test_client.start_server()

        rpc_client = ServerProxy('', loop=loop, client=test_client)
        return rpc_client
def client(event_loop, app, cookie_jar):
    from aiohttp.test_utils import TestServer, TestClient

    _server = TestServer(app, loop=event_loop)
    _client = TestClient(_server, loop=event_loop, cookie_jar=cookie_jar)
    event_loop.run_until_complete(_client.start_server())
    yield _client
    event_loop.run_until_complete(_client.close())
Example #9
0
def test_test_client_close_is_idempotent():
    """
    a test client, called multiple times, should
    not attempt to close the loop again.
    """
    with loop_context() as loop:
        app = _create_example_app(loop)
        client = TestClient(app)
        client.close()
    client.close()
Example #10
0
def test_test_client_close_is_idempotent():
    """
    a test client, called multiple times, should
    not attempt to close the loop again.
    """
    loop = setup_test_loop()
    app = _create_example_app(loop)
    client = TestClient(app)
    client.close()
    teardown_test_loop(loop)
    client.close()
Example #11
0
 async def connect(self):
     self._loop = asyncio.get_running_loop()
     client = TestClient(self._server)
     async with client.ws_connect('/') as websocket:
         try:
             self._websocket = websocket
             self._connected_event.set_result(True)
             async for request in websocket:
                 self._messages_queue.append(request)
                 self._message_event.set_result(True)
         except asyncio.CancelledError:
             await self.stop()
async def test_route_asgi(loop, client: test_utils.TestClient):
    async with client.get("/asgi") as response:
        response.raise_for_status()
        body = await response.json()

    assert body == {'message': 'Hello World', 'root_path': ''}

    async with client.get("/not-found") as response:
        with pytest.raises(aiohttp.ClientError) as err:
            response.raise_for_status()

        assert err.value.status == 404
Example #13
0
 def run(self):
     try:
         backend = Backend(graph_path=str(TEST_GRAPH_PATH))
         with backend:
             with loop_context() as loop:
                 app = make_app(backend=backend, debug=True)
                 client = TestClient(TestServer(app), loop=loop)
                 loop.run_until_complete(client.start_server())
                 url = client.make_url("/graph/")
                 self.q.put(url)
                 loop.run_forever()
     except Exception as e:
         self.q.put(e)
Example #14
0
    async def go(__param, *, server_kwargs=None, **kwargs):  # type: ignore
        if isinstance(__param, Application):
            server_kwargs = server_kwargs or {}
            server = TestServer(__param, **server_kwargs)
            client = TestClient(server, **kwargs)
        elif isinstance(__param, BaseTestServer):
            client = TestClient(__param, **kwargs)
        else:
            raise ValueError("Unknown argument type: %r" % type(__param))

        await client.start_server()
        clients.append(client)
        return client
Example #15
0
def test_server_with_create_test_teardown():
    with loop_context() as loop:
        app = _create_example_app(loop)
        client = TestClient(app)

        @asyncio.coroutine
        def test_get_route():
            resp = yield from client.request("GET", "/")
            assert resp.status == 200
            text = yield from resp.text()
            assert "Hello, world" in text

        loop.run_until_complete(test_get_route())
        client.close()
Example #16
0
def test_server_with_create_test_teardown():
    with loop_context() as loop:
        app = _create_example_app(loop)
        client = TestClient(app)

        @asyncio.coroutine
        def test_get_route():
            resp = yield from client.request("GET", "/")
            assert resp.status == 200
            text = yield from resp.text()
            assert "Hello, world" in text

        loop.run_until_complete(test_get_route())
        client.close()
Example #17
0
def test_checkLogin():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_checkLogin(token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/checkLogin?accessToken={}"
            .format(token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
            assert "accessToken" in jsonresp["data"]
            if not token:
                assert jsonresp["data"]["accessToken"] != "token_1234"
            else:
                assert jsonresp["data"]["accessToken"] == "token_1234"

            assert "uid" in jsonresp["data"]
            assert "username" in jsonresp["data"]
        else:
            assert jsonresp

    # Test
    loop.run_until_complete(test_handle_checkLogin())

    # Add a user to db and test with existing users
    bumper.user_add("testuser")
    # Test
    loop.run_until_complete(test_handle_checkLogin())

    # Remove dev from tmpuser
    bumper.user_remove_device("tmpuser", "dev_1234")

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(test_handle_checkLogin(token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Example #18
0
def test_grade_api(app):
    with loop_context() as loop:
        with TestClient(app, loop=loop) as client:

            async def get_headers():
                nonlocal client
                auth_header = {
                    'Authorization':
                    'Basic %s' %
                    base64.b64encode(b'2014210761:2014210761').decode()
                }
                async with aiohttp.ClientSession(
                        headers=auth_header) as session:
                    async with session.get(
                            'http://info_login_service:8080/api/info/login/'
                    ) as resp:
                        assert resp.status == 200
                        json_data = await resp.json()
                        auth_header.update(json_data.get('cookie'))
                        cookie_header = auth_header
                        cookie_header['Sid'] = json_data.get('sid')
                        return cookie_header

            async def _test_grade_get_api():
                nonlocal client
                cookie_header = await get_headers()
                resp = await client.get('/api/grade/?xnm=2014&xqm=3',
                                        headers=cookie_header)
                assert resp.status == 200
                print(".... grade get api [OK]")

            loop.run_until_complete(_test_grade_get_api())
Example #19
0
async def _test_client(config):
    from aiohttp.test_utils import TestServer, TestClient

    db = Gino()
    app = web.Application(middlewares=[db])
    app['config'] = dict(gino=config)
    db.init_app(app)

    class User(db.Model):
        __tablename__ = 'gino_users'

        id = db.Column(db.BigInteger(), primary_key=True)
        nickname = db.Column('name', db.Unicode(), default='noname')

    routes = web.RouteTableDef()

    @routes.get('/')
    async def root(request):
        return web.Response(text='Hello, world!')

    @routes.get('/users/{uid}')
    async def get_user(request):
        uid = int(request.match_info['uid'])
        method = request.query.get('method')
        q = User.query.where(User.id == uid)
        if method == '1':
            return web.json_response((await q.gino.first_or_404()).to_dict())
        elif method == '2':
            return web.json_response(
                (await request['connection'].first_or_404(q)).to_dict())
        elif method == '3':
            return web.json_response((await db.bind.first_or_404(q)).to_dict())
        elif method == '4':
            return web.json_response(
                (await request.app['db'].first_or_404(q)).to_dict())
        else:
            return web.json_response((await User.get_or_404(uid)).to_dict())

    @routes.post('/users')
    async def add_user(request):
        form = await request.post()
        u = await User.create(nickname=form.get('name'))
        await u.query.gino.first_or_404()
        await db.first_or_404(u.query)
        await db.bind.first_or_404(u.query)
        await request['connection'].first_or_404(u.query)
        return web.json_response(u.to_dict())

    app.router.add_routes(routes)

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            async with TestClient(TestServer(app)) as rv:
                await yield_(rv)
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Example #20
0
def test_info_login_api(app):
    with loop_context() as loop:
        with TestClient(app, loop=loop) as client:

            async def _test_info_login_api():
                auth_header1 = {
                    'Authorization':
                    'Basic %s' %
                    base64.b64encode(b'2014210761:2014210761').decode()
                }
                auth_header2 = {
                    'Authorization':
                    'Basic %s' %
                    base64.b64encode(b'2014210761:fuckccnu').decode()
                }
                auth_header3 = {}
                resp = await client.get('/api/info/login/',
                                        headers=auth_header1)
                assert resp.status == 200
                resp = await client.get('/api/info/login/',
                                        headers=auth_header2)
                assert resp.status == 403
                resp = await client.get('/api/info/login/',
                                        headers=auth_header3)
                assert resp.status == 401
                print('... test info login api [ok]')

            loop.run_until_complete(_test_info_login_api())
 async def setUp(self):
     usecase_context.initialize()
     api_context.initialize()
     self.openchat = OpenChat()
     self.app = await self.openchat.create_app()
     self.client = TestClient(TestServer(self.app), loop=self.loop)
     await self.client.start_server()
    async def aiohttp_faraday_client(self):
        app = web.Application()
        app.router.add_get(self.wrap_route("/_api/v3/info"), get_info(self))
        app.router.add_post(
            self.wrap_route("/_api/v3/agent_registration"),
            get_agent_registration(self),
        )
        app.router.add_post(
            self.wrap_route("/_api/v3/agent_websocket_token"),
            get_agent_websocket_token(self),
        )
        for workspace in self.workspaces:
            app.router.add_post(
                self.wrap_route(f"/_api/v3/ws/{workspace}/bulk_create"),
                get_bulk_create(self),
            )
        app.router.add_post(
            self.wrap_route("/_api/v3/ws/error500/bulk_create"),
            get_bulk_create(self))
        app.router.add_post(
            self.wrap_route("/_api/v3/ws/error429/bulk_create"),
            get_bulk_create(self))
        app.router.add_get(self.wrap_route("/websockets"),
                           get_ws_handler(self))

        server = TestServer(app)
        server_params = {}
        if self.is_ssl:
            ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_context.load_cert_chain(self.ssl_cert_path / "ok.crt",
                                        self.ssl_cert_path / "ok.key")
            server_params["ssl"] = ssl_context
        await server.start_server(**server_params)
        client = TestClient(server, raise_for_status=True)
        return client
    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()
        # self.loop.set_debug(False)
        self.app = self.get_app(
            self.loop
        )

        self.client = TestClient(
            self.app,
        )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.first_headers = {
            'Authorization': self.first_token,
            'Content-Type': 'application/json',
        }

        self.second_headers = {
            'Authorization': self.second_token,
            'Content-Type': 'application/json',
        }

        self.loop.run_until_complete(self.install_chat())
Example #24
0
    async def test_resolves_handler_parameters(self):
        expected_user_name = "Some User Name"

        class User:
            def __init__(self, name):
                self.name = name

        def insert_user_into_type_registry(handler):
            async def _wrapper(request: web.Request):
                request["types_registry"].set(User(name=expected_user_name))
                return await call_http_handler(request, handler)

            return _wrapper

        @self.app.route(["/"], type=RouteTypes.HTTP, methods=["GET"])
        @insert_user_into_type_registry
        async def handler(user: User):
            return web.json_response({"name": user.name})

        with mock.patch.dict(os.environ, ASYNCWORKER_HTTP_PORT="9999"):
            settings_mock = Settings()
            with mock.patch(
                "asyncworker.signals.handlers.http.settings", settings_mock
            ):
                await self.signal_handler.startup(self.app)
                async with TestClient(
                    TestServer(self.app[RouteTypes.HTTP]["app"]),
                    loop=asyncio.get_event_loop(),
                ) as client:
                    resp = await client.get("/")
                    self.assertEqual(200, resp.status)
                    resp_data = await resp.json()
                    self.assertEqual({"name": expected_user_name}, resp_data)
                await self.signal_handler.shutdown(self.app)
Example #25
0
    async def test_resolves_handler_parameters_when_receiving_request(self):
        def my_decorator(handler):
            async def _wrapper(request: web.Request):
                return await call_http_handler(request, handler)

            return _wrapper

        @self.app.route(["/"], type=RouteTypes.HTTP, methods=["GET"])
        @my_decorator
        async def handler(request: web.Request):
            return web.json_response({"num": request.query["num"]})

        with mock.patch.dict(os.environ, ASYNCWORKER_HTTP_PORT="9999"):
            settings_mock = Settings()
            with mock.patch(
                "asyncworker.signals.handlers.http.settings", settings_mock
            ):
                await self.signal_handler.startup(self.app)
                async with TestClient(
                    TestServer(self.app[RouteTypes.HTTP]["app"]),
                    loop=asyncio.get_event_loop(),
                ) as client:
                    resp = await client.get("/", params={"num": 42})
                    self.assertEqual(200, resp.status)
                    resp_data = await resp.json()
                    self.assertEqual({"num": "42"}, resp_data)
                await self.signal_handler.shutdown(self.app)
Example #26
0
    async def go(
        __param: Application | BaseTestServer,
        *args: Any,
        server_kwargs: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> TestClient:

        if isinstance(__param, Callable) and not isinstance(  # type: ignore[arg-type]
            __param, (Application, BaseTestServer)
        ):
            __param = __param(loop, *args, **kwargs)
            kwargs = {}
        else:
            assert not args, "args should be empty"

        if isinstance(__param, Application):
            server_kwargs = server_kwargs or {}
            server = TestServer(__param, loop=loop, **server_kwargs)
            client = CoalescingClient(server, loop=loop, **kwargs)
        elif isinstance(__param, BaseTestServer):
            client = TestClient(__param, loop=loop, **kwargs)
        else:
            raise ValueError("Unknown argument type: %r" % type(__param))

        await client.start_server()
        clients.append(client)
        return client
Example #27
0
    async def go(__param, *args, server_kwargs=None, **kwargs):
        server_kwargs = server_kwargs or {}
        server = TestServer(__param, loop=loop, **server_kwargs)
        client = TestClient(server, loop=loop, **kwargs)

        await client.start_server()
        clients.append(client)
        return client
Example #28
0
async def test_simple(compressor, client: test_utils.TestClient):
    headers = {hdrs.ACCEPT_ENCODING: compressor}

    async with client.get("/data", headers=headers) as response:
        response.raise_for_status()
        body = await response.json()
        assert compressor in response.headers[hdrs.CONTENT_ENCODING]
        assert isinstance(body, dict)
Example #29
0
    async def go(app):
        server = TestServer(app, loop=loop)
        client = TestClient(server, loop=loop)

        await client.start_server()

        clients.append(client)

        return client
async def load_cookie(client: TestClient,
                      redis: aioredis.commands.Redis) -> Any:
    cookies = client.session.cookie_jar.filter_cookies(client.make_url('/'))
    key = cookies['AIOHTTP_SESSION']
    with await redis as conn:
        encoded = await conn.get('AIOHTTP_SESSION_' + key.value)
        s = encoded.decode('utf-8')
        value = json.loads(s)
        return value
Example #31
0
    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()

        self.app = self.get_app(self.loop)

        self.client = TestClient(self.app)

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.headers = {
            'Authorization': self.token,
            'Content-Type': 'application/json'
        }
Example #32
0
def clients_context_num(routine, num=2, patch_nyms=nyms):
    with patch('websockets_server.core.server.nyms', patch_nyms):
        with loop_context() as loopext:
            app = HXApplication()
            server = TestServer(app)
            clients = []
            for i in range(num):
                client = TestClient(server, loop=loopext)
                if i == 0:
                    loopext.run_until_complete(client.start_server())
                clients.append(client)

            try:
                loopext.run_until_complete(routine(app, *clients))
            finally:
                loopext.run_until_complete(clients[0]._server.close())
                for client in clients:
                    loopext.run_until_complete(client.close())
 async def close_client_but_not_server(cli: TestClient):
     # pylint: disable=protected-access
     if not cli._closed:
         for resp in cli._responses:
             resp.close()
         for ws in cli._websockets:
             await ws.close()
         await cli._session.close()
         cli._closed = True
Example #34
0
def test_getAuthCode():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_getAuthCode(uid=None, token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/getAuthCode?uid={}&accessToken={}"
            .format(uid, token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            if token:
                assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
                assert "authCode" in jsonresp["data"]
                assert "ecovacsUid" in jsonresp["data"]
            else:
                assert jsonresp["code"] == bumper.ERR_TOKEN_INVALID
        else:
            assert jsonresp

    # Test without user or token
    loop.run_until_complete(test_handle_getAuthCode())

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(
        test_handle_getAuthCode(uid="testuser", token="token_1234"))

    # The above should have added an authcode to token, try again to test with existing authcode
    # Test
    loop.run_until_complete(
        test_handle_getAuthCode(uid="testuser", token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Example #35
0
    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()

        self.app = self.get_app(
            self.loop
        )

        self.client = TestClient(
            self.app
        )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.headers = {
            'Authorization': self.token,
            'Content-Type': 'application/json'
        }
Example #36
0
class TestChatApi(AioHTTPTestCase):
    data = {}
    headers = {}
    token = None

    client_in_request = None

    def get_app(self, loop):
        server = app(
            loop=loop
        )

        server['db'] = self.database(
            loop=loop
        )

        return server

    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()

        self.app = self.get_app(
            self.loop
        )

        self.client = TestClient(
            self.app
        )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.headers = {
            'Authorization': self.token,
            'Content-Type': 'application/json'
        }

    def load_data(self):
        with open('fixtures.json') as data:
            self.data = json.load(data)

    def install_client(self):
        data = json.dumps(self.data)
        request = yield from self.client.post(
            path="/client/create/",
            data=data
        )

        yield from request.json()

    def auth_client(self):
        data = json.dumps(self.data)
        request = yield from self.client.post(
            path="/client/auth/",
            data=data
        )

        auth_data = yield from request.json()
        self.token = auth_data.get('token')

    @unittest_run_loop
    async def test_create_chat_without_token(self):
        request = await self.client.post(
            path='/chat/create/',
        )

        result = await request.json()
        assert result.get('status') is False

    @unittest_run_loop
    async def test_receive_chat_list(self):
        request = await self.client.get(
            path='/chat/list/',
            headers=self.headers
        )

        result = await request.json()
        assert result.get('status') is True

    @unittest_run_loop
    async def test_create_and_delete_chat(self):
        create_chat_request = await self.client.post(
            path='/chat/create/',
            headers=self.headers
        )

        chat_info = await create_chat_request.json()

        assert chat_info.get('status') is True

        data = {
            'id': chat_info.get('chat')
        }

        delete_chat_request = await self.client.post(
            path='/chat/delete/',
            headers=self.headers,
            data=json.dumps(data)
        )

        result = await delete_chat_request.json()

        assert result.get('status') is True

    @unittest_run_loop
    async def test_delete_chat_with_not_correct_pk(self):

        data = json.dumps({
            'id': '57652fa9f4e00b15bcd17f7d'
        })

        request = await self.client.post(
            path='/chat/delete/',
            headers=self.headers,
            data=data
        )

        result = await request.json()
        assert result.get('status') is False
class TestChatApi(AioHTTPTestCase):
    data = {}
    headers = {}

    first_headers = None
    second_headers = None

    first_token = None
    second_token = None

    first_client = {}
    second_client = {}

    client_in_request = None

    def get_app(self, loop):
        server = app(
            loop=loop
        )

        server['db'] = self.database(
            loop=loop
        )

        return server

    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()
        self.app = self.get_app(
            self.loop
        )

        self.client = TestClient(
            self.app,
        )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.first_headers = {
            'Authorization': self.first_token,
            'Content-Type': 'application/json',
        }

        self.second_headers = {
            'Authorization': self.second_token,
            'Content-Type': 'application/json',
        }

        self.loop.run_until_complete(self.install_chat())

    def load_data(self):
        with open('ws_chat_fixtures.json') as data:
            self.data = json.load(data)

    def install_client(self):
        #   Grab data for create users
        first_client = self.data.get('clients').get('first')
        second_client = self.data.get('clients').get('second')

        #   Create request for create first client
        first_client_auth_request = yield from self.client.post(
            path="/client/create/",
            data=json.dumps(first_client)
        )

        # Create request for create second client
        second_client_auth_request = yield from self.client.post(
            path="/client/create/",
            data=json.dumps(second_client)
        )

        yield

    def auth_client(self):
        first_client = self.data.get('clients').get('first')
        second_client = self.data.get('clients').get('second')

        #   auth  and get token for first client
        first_client_request = yield from self.client.post(
            path="/client/auth/",
            data=json.dumps(first_client)
        )

        self.first_client = yield from first_client_request.json()
        self.first_token = self.first_client.get('token')

        #   auth  and get token for second client
        second_client_request = yield from self.client.post(
            path="/client/auth/",
            data=json.dumps(second_client)
        )

        self.second_client = yield from second_client_request.json()

        self.second_token = self.second_client.get('token')

    def install_chat(self):
        request = yield from self.client.post(
            path='/chat/create/',
            headers=self.first_headers
        )

        result = yield from request.json()
        os.environ['TEST_CHAT_PK'] = result.get('chat')

    def delete_test_chat(self):
        chat = os.environ['TEST_CHAT_PK']

        data = json.dumps({
            'id': chat
        })

        request = yield from self.client.post(
            path='/chat/delete/',
            headers=self.first_headers,
            data=data
        )

        result = yield from request.json()

    def tearDown(self):
        self.delete_test_chat()
        super(TestChatApi, self).tearDown()

    @property
    def chat_path(self):
        chat = os.environ['TEST_CHAT_PK']
        path = "/chat/ws/{}/".format(chat)
        return path

    def message(self, content, sender, receiver=None):
        if receiver:
            msg = '{"msg" : "%s", "sender": "%s", "receiver": "%s"}' % (
                content, sender, receiver
            )
        else:
            msg = '{"msg" : "%s", "sender": "%s"}' % (
                content, sender
            )
        return msg

    @unittest_run_loop
    async def test_open_ws_connect(self):
        print("========================")
        print("test_open_ws_connect")

        request = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.first_headers
        )

        assert request.closed is False
        request.send_str('{"msg": "Hello world"}')
        await request.close()
        assert request.closed is True

    @unittest_run_loop
    async def test_chat_btw_users(self):
        print("========================")
        print("test_chat_btw_users")

        first_client = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.first_headers
        )

        second_client = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.second_headers
        )

        messages_for_first_client = []
        messages_for_second_client = []
        count_messages = 20

        for period in range(count_messages):
            gen_message = ''.join(
                random.choice(string.ascii_uppercase + string.digits) for _ in range(random.choice([4, 10]))).lower()

            if len(messages_for_first_client) <= 10:
                messages_for_first_client.append(gen_message)
            else:
                messages_for_second_client.append(gen_message)

        def message(content, sender):
            msg = '{"msg": "%s", "sender" : "%s", "send_at": "%s"}' % (content, sender, datetime.datetime.now())
            return msg

        receive_by_first_client = []
        receive_by_second_client = []

        def first_sender(client):
            for msg in messages_for_first_client:
                first_client.send_str(message(msg, client.get('client_id')))

        def second_sender(client):
            for msg in messages_for_first_client:
                second_client.send_str(message(msg, client.get('client_id')))

        first_sender(self.first_client)
        second_sender(self.second_client)

        async def messages_first_client():
            while len(receive_by_first_client) != count_messages:
                msg = await first_client.receive()
                receive_by_first_client.append(msg)

        async def messages_second_client():

            while len(receive_by_second_client) != count_messages:
                msg = await second_client.receive()
                receive_by_second_client.append(msg)

        await messages_first_client()
        await messages_second_client()

        print(receive_by_first_client)
        print(receive_by_second_client)

        await first_client.close()
        await second_client.close()

        assert first_client.closed is True
        assert second_client.closed is True

    @unittest_run_loop
    async def test_send_private_message(self):
        first_client = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.first_headers
        )

        second_client = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.second_headers
        )

        #   отправка публичного сообщения
        first_client.send_str(self.message("Hello second client", self.first_client.get('client_id')))
        second_client.send_str(self.message("Hello first client", self.second_client.get('client_id')))

        #   отправка приватного сообщения
        first_client.send_str(
            self.message(
                content="Hello second client from private message",
                sender=self.first_client.get('client_id'),
                receiver=self.second_client.get('client_id')
            )
        )

        receive_by_first_client = []
        receive_by_second_client = []

        async def messages_first_client():
            while len(receive_by_first_client) != 2:
                msg = await first_client.receive()
                receive_by_first_client.append(msg)

        async def messages_second_client():

            while len(receive_by_second_client) != 3:
                msg = await second_client.receive()
                receive_by_second_client.append(msg)

        await messages_first_client()
        await messages_second_client()

        print(receive_by_first_client)
        print(receive_by_second_client)

        await first_client.close()
        await second_client.close()

        assert first_client.closed is True
        assert second_client.closed is True

    @unittest_run_loop
    async def test_get_list_of_client_in_chat(self):
        print("========================")
        print("test_get_list_of_client_in_chat")
        path = "/chat/byId/{}/".format(os.environ['TEST_CHAT_PK'])
        request = await self.client.get(
            path=path,
            headers=self.first_headers
        )

        result = await request.json()

        assert result.get('status') is True
class TestChatApi(AioHTTPTestCase):
    data = {}
    headers = {}

    first_headers = None
    second_headers = None

    first_token = None
    second_token = None

    first_client = {}
    second_client = {}

    client_in_request = None

    def get_app(self, loop):
        server = app(
            loop=loop
        )

        server['db'] = self.database(
            loop=loop
        )

        return server

    def setUp(self):
        self.load_data()

        self.database = DB()
        self.loop = asyncio.new_event_loop()
        # self.loop.set_debug(False)
        self.app = self.get_app(
            self.loop
        )

        self.client = TestClient(
            self.app,
        )

        self.loop.run_until_complete(self.install_client())

        self.loop.run_until_complete(self.auth_client())

        self.first_headers = {
            'Authorization': self.first_token,
            'Content-Type': 'application/json',
        }

        self.second_headers = {
            'Authorization': self.second_token,
            'Content-Type': 'application/json',
        }

        self.loop.run_until_complete(self.install_chat())

    def load_data(self):
        with open('ws_chat_fixtures.json') as data:
            self.data = json.load(data)

    def install_client(self):
        #   Grab data for create users
        first_client = self.data.get('clients').get('first')
        second_client = self.data.get('clients').get('second')

        #   Create request for create first client
        first_client_auth_request = yield from self.client.post(
            path="/client/create/",
            data=json.dumps(first_client)
        )

        # Create request for create second client
        second_client_auth_request = yield from self.client.post(
            path="/client/create/",
            data=json.dumps(second_client)
        )

        yield

    def auth_client(self):
        first_client = self.data.get('clients').get('first')
        second_client = self.data.get('clients').get('second')

        #   auth  and get token for first client
        first_client_request = yield from self.client.post(
            path="/client/auth/",
            data=json.dumps(first_client)
        )

        self.first_client = yield from first_client_request.json()
        self.first_token = self.first_client.get('token')

        #   auth  and get token for second client
        second_client_request = yield from self.client.post(
            path="/client/auth/",
            data=json.dumps(second_client)
        )

        self.second_client = yield from second_client_request.json()

        self.second_token = self.second_client.get('token')

    def install_chat(self):
        request = yield from self.client.post(
            path='/chat/create/',
            headers=self.first_headers
        )

        result = yield from request.json()
        os.environ['TEST_CHAT_PK'] = result.get('chat')

    def delete_test_chat(self):
        chat = os.environ['TEST_CHAT_PK']

        data = json.dumps({
            'id': chat
        })

        request = yield from self.client.post(
            path='/chat/delete/',
            headers=self.first_headers,
            data=data
        )

        result = yield from request.json()

    def tearDown(self):
        self.delete_test_chat()
        super(TestChatApi, self).tearDown()

    @property
    def chat_path(self):
        chat = os.environ['TEST_CHAT_PK']
        path = "/chat/ws/{}/{}/".format(chat, self.first_client.get('client_id'))
        return path

    @property
    def second_path(self):
        chat = os.environ['TEST_CHAT_PK']
        path = "/chat/ws/{}/{}/".format(chat, self.second_client.get('client_id'))
        return path

    @unittest_run_loop
    async def test_open_ws_connect(self):
        print("========================")
        print("test_open_ws_connect")

        request = await self.client.ws_connect(
            path=self.chat_path,
            headers=self.first_headers
        )

        assert request.closed is False

        msg = await request.receive()
        print(msg)

        request.send_str(data='{"msg": "Hello"}')
Example #39
0
def test_client(loop, app):
    client = TestClient(app)
    yield client
    client.close()