def add_write_resp(aresponses: ResponsesMockServer, count, status=200):
    async def handler(request):
        return web.json_response(await request.json(), status=status)
    aresponses.add(path_pattern='/history/datastore/set',
                   method_pattern='POST',
                   response=handler,
                   repeat=count)
예제 #2
0
async def test_ranges(app, client, aresponses: ResponsesMockServer):
    vic = victoria.fget(app)

    result = {
        'metric': {
            '__name__': 'sparkey/sensor'
        },
        'values': [
            [1626367339.856, '1'],
            [1626367349.856, '2'],
            [1626367359.856, '3'],
        ],
    }

    aresponses.add(
        path_pattern='/victoria/api/v1/query_range',
        method_pattern='POST',
        repeat=3,
        response={
            'status': 'success',
            'data': {
                'resultType': 'matrix',
                'result': [result],
            },
        },
    )

    args = TimeSeriesRangesQuery(fields=['f1', 'f2', 'f3'])
    retv = await vic.ranges(args)
    assert retv == [TimeSeriesRange(**result)] * 3
예제 #3
0
async def test_fields(app, client, aresponses: ResponsesMockServer):
    vic = victoria.fget(app)

    aresponses.add(path_pattern='/victoria/api/v1/series',
                   method_pattern='POST',
                   response={
                       'status':
                       'success',
                       'data': [
                           {
                               '__name__':
                               'spock/setpoint-sensor-pair-2/setting[degC]'
                           },
                           {
                               '__name__': 'spock/actuator-1/value'
                           },
                           {
                               '__name__': 'sparkey/HERMS MT PID/integralReset'
                           },
                           {
                               '__name__':
                               'sparkey/HERMS HLT PID/inputValue[degC]'
                           },
                       ]
                   })

    args = TimeSeriesFieldsQuery(duration='1d')
    assert await vic.fields(args) == [
        'sparkey/HERMS HLT PID/inputValue[degC]',
        'sparkey/HERMS MT PID/integralReset',
        'spock/actuator-1/value',
        'spock/setpoint-sensor-pair-2/setting[degC]',
    ]
def add_check_resp(aresponses: ResponsesMockServer, count, status=200):
    async def handler(request):
        return web.json_response({'ping': 'pong'}, status=status)
    aresponses.add(path_pattern='/history/datastore/ping',
                   method_pattern='GET',
                   response=handler,
                   repeat=count)
def test_getmyip_json_service(aresponses: ResponsesMockServer,
                              event_loop: BaseEventLoop):
    response = Response(body='{"ip": "1.2.3.5"}',
                        content_type='application/json')
    aresponses.add('json.com', '/', 'GET', response)
    assert get_ip([JSONService('http://json.com', 'ip')],
                  event_loop) == '1.2.3.5'
예제 #6
0
    async def test_make_request(self, aresponses: ResponsesMockServer):
        aresponses.add(
            aresponses.ANY,
            "/bot42:TEST/method",
            "post",
            aresponses.Response(
                status=200,
                text='{"ok": true, "result": 42}',
                headers={"Content-Type": "application/json"},
            ),
        )

        session = AiohttpSession()

        class TestMethod(TelegramMethod[int]):
            __returning__ = int

            def build_request(self) -> Request:
                return Request(method="method", data={})

        call = TestMethod()
        with patch(
                "aiogram.api.client.session.base.BaseSession.raise_for_status"
        ) as patched_raise_for_status:
            result = await session.make_request("42:TEST", call)
            assert isinstance(result, int)
            assert result == 42

            assert patched_raise_for_status.called_once()
예제 #7
0
파일: movie_test.py 프로젝트: ljiatu/movies
async def test_resolve_rate(aresponses: ResponsesMockServer,
                            ok_response: Dict[str, Any]):
    aresponses.add(TMDB_API_HOST, URL_PATH, "POST", response=ok_response)
    result = await resolve_rate(movie_id=MOVIE_ID, rating=1.0)
    assert result is True

    aresponses.assert_plan_strictly_followed()
예제 #8
0
파일: movie_test.py 프로젝트: ljiatu/movies
async def test_resolve_rate_tmdb_exception(aresponses: ResponsesMockServer):
    aresponses.add(TMDB_API_HOST, URL_PATH, "POST",
                   aresponses.Response(status=500))

    with pytest.raises(HTTPException):
        await resolve_rate(movie_id=MOVIE_ID, rating=10.0)

    aresponses.assert_plan_strictly_followed()
def test_getmyip_differing_ips(aresponses: ResponsesMockServer,
                               event_loop: BaseEventLoop):
    aresponses.add('bad0.com', '/', 'GET', '1.2.3.6')
    aresponses.add('bad1.com', '/', 'GET', '1.2.3.7')

    with pytest.raises(InconsistentIPAddressesFound):
        get_ip(
            [TextService('http://bad0.com'),
             TextService('http://bad1.com')], event_loop)
예제 #10
0
async def test_text_request(aresponses: ResponsesMockServer) -> None:
    """Test non XML response is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/response/text",
        "GET",
        aresponses.Response(status=200, text="OK"),
    )
    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        response = await client._request("response/text")
        assert response == "OK"
예제 #11
0
async def test_remote_search(aresponses: ResponsesMockServer) -> None:
    """Test remote search keypress is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/search/browse",
        "POST",
        aresponses.Response(status=200),
    )

    async with ClientSession() as session:
        roku = Roku(HOST, session=session)
        await roku.remote("search")
예제 #12
0
async def test_get_dns_state(
    aresponses: ResponsesMockServer,
    resolver: AsyncMock,
    freezer,
) -> None:
    """Test get_dns_state is handled correctly."""
    aresponses.add(
        f"192.168.1.99:{PORT}",
        "/support/hostname",
        "GET",
        aresponses.Response(status=200, text="OK"),
    )

    aresponses.add(
        f"192.168.1.89:{PORT}",
        "/support/hostname",
        "GET",
        aresponses.Response(status=200, text="OK"),
    )

    async with ClientSession() as session:
        roku = Roku(HOST, session=session)
        assert roku.get_dns_state() == {
            "enabled": False,
            "hostname": None,
            "ip_address": None,
            "resolved_at": None,
        }

        roku2 = Roku("roku.dev", session=session)
        assert roku2.get_dns_state() == {
            "enabled": True,
            "hostname": "roku.dev",
            "ip_address": None,
            "resolved_at": None,
        }

        resolver.return_value = fake_addrinfo_results(["192.168.1.99"])
        assert await roku2._request("support/hostname")
        dns = roku2.get_dns_state()
        assert dns["enabled"]
        assert dns["hostname"] == "roku.dev"
        assert dns["ip_address"] == "192.168.1.99"
        assert dns["resolved_at"] == datetime(2022, 3, 27, 0, 0)

        resolver.return_value = fake_addrinfo_results(["192.168.1.89"])
        freezer.tick(delta=timedelta(hours=3))
        assert await roku2._request("support/hostname")
        dns = roku2.get_dns_state()
        assert dns["enabled"]
        assert dns["hostname"] == "roku.dev"
        assert dns["ip_address"] == "192.168.1.89"
        assert dns["resolved_at"] == datetime(2022, 3, 27, 3, 0)
예제 #13
0
async def test_http_error500(aresponses: ResponsesMockServer) -> None:
    """Test HTTP 500 response handling."""
    aresponses.add(
        MATCH_HOST,
        "/http/500",
        "GET",
        aresponses.Response(text="Internal Server Error", status=500),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        with pytest.raises(RokuError):
            assert await client._request("http/500")
예제 #14
0
async def test_ping(app, client, aresponses: ResponsesMockServer):
    vic = victoria.fget(app)

    aresponses.add(path_pattern='/victoria/health',
                   method_pattern='GET',
                   response='OK')
    await vic.ping()

    aresponses.add(path_pattern='/victoria/health',
                   method_pattern='GET',
                   response='NOK')
    with pytest.raises(ConnectionError):
        await vic.ping()
예제 #15
0
async def test_request_port(aresponses: ResponsesMockServer) -> None:
    """Test the handling of non-standard API port."""
    aresponses.add(
        f"{HOST}:{NON_STANDARD_PORT}",
        "/support/port",
        "GET",
        aresponses.Response(status=200, text="OK"),
    )

    async with ClientSession() as session:
        client = Roku(host=HOST, port=NON_STANDARD_PORT, session=session)
        response = await client._request("support/port")
        assert response == "OK"
예제 #16
0
async def test_post_request(aresponses: ResponsesMockServer) -> None:
    """Test POST requests are handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/method/post",
        "POST",
        aresponses.Response(status=200, text="OK"),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        response = await client._request("method/post", method="POST")
        assert response == "OK"
예제 #17
0
async def test_search(aresponses: ResponsesMockServer) -> None:
    """Test search is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/search/browse?keyword=test",
        "POST",
        aresponses.Response(status=200, text="OK"),
        match_querystring=True,
    )

    async with ClientSession() as session:
        roku = Roku(HOST, session=session)
        await roku.search("test")
예제 #18
0
async def test_tune(aresponses: ResponsesMockServer) -> None:
    """Test tune is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/launch/tvinput.dtv?ch=13.4",
        "POST",
        aresponses.Response(status=200, text="OK"),
        match_querystring=True,
    )

    async with ClientSession() as session:
        roku = Roku(HOST, session=session)
        await roku.tune("13.4")
예제 #19
0
async def test_http_error404(aresponses: ResponsesMockServer) -> None:
    """Test HTTP 404 response handling."""
    aresponses.add(
        MATCH_HOST,
        "/http/404",
        "GET",
        aresponses.Response(text="Not Found!", status=404),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        with pytest.raises(RokuError):
            assert await client._request("http/404")
예제 #20
0
async def test_batch_get_success(
    aresponses: ResponsesMockServer,
    context: Dict[str, Any],
    query_paths: List[str],
    json_companies: List[Dict[str, Any]],
    company_keys: List[int],
):
    for path, json_company in zip(query_paths, json_companies):
        aresponses.add(TMDB_API_HOST, path, "GET", response=json_company)

    company_loader = CompanyLoader.for_context(context)
    companies = await company_loader.load_many(company_keys)
    assert companies == [Company(**jc) for jc in json_companies]

    aresponses.assert_plan_strictly_followed()
async def discovery_resp(app, aresponses: ResponsesMockServer, loop, mocker):
    config = app['config']
    mdns_host = config['mdns_host']
    mdns_port = config['mdns_port']

    for i in range(100):
        aresponses.add(
            f'{mdns_host}:{mdns_port}', '/mdns/discover', 'POST',
            web.json_response({'host': 'enterprise', 'port': 1234})
        )
        aresponses.add(
            f'mdns_error_host:{mdns_port}', '/mdns/discover', 'POST',
            web.json_response({}, status=500)
        )
    return aresponses
예제 #22
0
async def test_csv(app, client, aresponses: ResponsesMockServer):
    vic = victoria.fget(app)

    aresponses.add(
        path_pattern='/victoria/api/v1/export',
        method_pattern='POST',
        response='\n'.join([
            '{"metric":{"__name__":"sparkey/HERMS BK PWM/setting"},' +
            '"values":[0,0,0,0,0,0,0],' +
            '"timestamps":[1626368070381,1626368075435,1626368080487,1626368085534,'
            + '1626368090630,1626368095687,1626368100749]}',
            '{"metric":{"__name__":"sparkey/HERMS BK PWM/setting"},' +
            '"values":[0,0,0,0],' +
            '"timestamps":[1626368105840,1626368110891,1626368115940,1626368121034]}',
            '{"metric":{"__name__":"spock/actuator-1/value"},' +
            '"values":[40,40,40,40,40,40,40,40,40,40,40],' +
            '"timestamps":[1626368070380,1626368078080,1626368083130,1626368088178,'
            +
            '1626368093272,1626368098328,1626368103383,1626368108480,1626368113533,1626368118579,1626368123669]}',
            '{"metric":{"__name__":"spock/pin-actuator-1/state"},' +
            '"values":[0,0,0,0,0,0,0,0,0,0,0],' +
            '"timestamps":[1626368070380,1626368078080,1626368083130,1626368088178,'
            +
            '1626368093272,1626368098328,1626368103383,1626368108480,1626368113533,1626368118579,1626368123669]}',
        ]))
    args = TimeSeriesCsvQuery(
        fields=[
            'sparkey/HERMS BK PWM/setting', 'spock/pin-actuator-1/state',
            'spock/actuator-1/value'
        ],
        precision='ISO8601',
    )

    result = []
    async for line in vic.csv(args):
        result.append(line)
    assert len(result) == 23  # headers, 11 from sparkey, 11 from spock
    assert result[0] == ','.join(['time'] + args.fields)

    # line 1: values from spock
    line = result[1].split(',')
    assert ciso8601.parse_datetime(line[0])
    assert line[1:] == ['', '0', '40']

    # line 2: values from sparkey
    line = result[2].split(',')
    assert ciso8601.parse_datetime(line[0])
    assert line[1:] == ['0', '', '']
예제 #23
0
async def test_get_active_app(aresponses: ResponsesMockServer) -> None:
    """Test _get_active_app method is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/query/active-app",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text=load_fixture("active-app-amazon.xml"),
        ),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        assert await client._get_active_app()
예제 #24
0
def add_read_resp(aresponses: ResponsesMockServer, count, status=200):
    async def handler(request):
        return web.json_response(
            {
                'values': [{
                    'id': const.GLOBAL_UNITS_ID,
                    'namespace': const.GLOBAL_NAMESPACE,
                    'temperature': 'degF',
                }]
            },
            status=status)

    aresponses.add(path_pattern='/history/datastore/mget',
                   method_pattern='POST',
                   response=handler,
                   repeat=count)
예제 #25
0
async def test_get_media_state_play(aresponses: ResponsesMockServer) -> None:
    """Test _get_media_state method is handled correctly with playing media."""
    aresponses.add(
        MATCH_HOST,
        "/query/media-player",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text=load_fixture("media-player-pluto-play.xml"),
        ),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        assert await client._get_media_state()
예제 #26
0
async def test_play_on_roku(aresponses: ResponsesMockServer) -> None:
    """Test play_on_roku is handled correctly."""
    video_url = "http://example.com/video file÷awe.mp4?v=2"
    encoded = "http%3A%2F%2Fexample.com%2Fvideo+file%C3%B7awe.mp4%3Fv%3D2"

    aresponses.add(
        MATCH_HOST,
        f"/input/15985?t=v&u={encoded}",
        "POST",
        aresponses.Response(status=200),
        match_querystring=True,
    )

    async with ClientSession() as session:
        roku = Roku(HOST, session=session)
        await roku.play_on_roku(video_url)
예제 #27
0
async def test_get_tv_channels(aresponses: ResponsesMockServer) -> None:
    """Test _get_tv_channels method is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/query/tv-channels",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text="<other>value</other>",
        ),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        with pytest.raises(RokuError):
            assert await client._get_tv_channels()
예제 #28
0
async def test_get_apps_single_app(aresponses: ResponsesMockServer) -> None:
    """Test _get_apps method is handled correctly with single app."""
    aresponses.add(
        MATCH_HOST,
        "/query/apps",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text=load_fixture("apps-single.xml"),
        ),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        res = await client._get_apps()
        assert isinstance(res, list)
        assert len(res) == 1
예제 #29
0
async def test_internal_session(aresponses: ResponsesMockServer) -> None:
    """Test JSON response is handled correctly with internal session."""
    aresponses.add(
        MATCH_HOST,
        "/response/xml",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text="<status>OK</status>",
        ),
    )

    async with Roku(HOST) as client:
        response = await client._request("response/xml")

        assert isinstance(response, dict)
        assert response["status"] == "OK"
예제 #30
0
async def test_xml_request_parse_error(
        aresponses: ResponsesMockServer) -> None:
    """Test invalid XML response is handled correctly."""
    aresponses.add(
        MATCH_HOST,
        "/response/xml-parse-error",
        "GET",
        aresponses.Response(
            status=200,
            headers={"Content-Type": "application/xml"},
            text="<!status>>",
        ),
    )

    async with ClientSession() as session:
        client = Roku(HOST, session=session)
        with pytest.raises(RokuError):
            assert await client._request("response/xml-parse-error")