Exemplo n.º 1
0
def test_cookies_mixin():
    sut = helpers.CookieMixin()

    assert sut.cookies == {}
    assert str(sut.cookies) == ""

    sut.set_cookie("name", "value")
    assert str(sut.cookies) == "Set-Cookie: name=value; Path=/"
    sut.set_cookie("name", "other_value")
    assert str(sut.cookies) == "Set-Cookie: name=other_value; Path=/"

    sut.cookies["name"] = "another_other_value"
    sut.cookies["name"]["max-age"] = 10
    assert (
        str(sut.cookies) == "Set-Cookie: name=another_other_value; Max-Age=10; Path=/"
    )

    sut.del_cookie("name")
    expected = (
        'Set-Cookie: name=("")?; '
        "expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/"
    )
    assert Matches(expected) == str(sut.cookies)

    sut.set_cookie("name", "value", domain="local.host")
    expected = "Set-Cookie: name=value; Domain=local.host; Path=/"
    assert str(sut.cookies) == expected
Exemplo n.º 2
0
def test_reagent_config(db, config_cls, obj, db_access, key, expected, info,
                        monkeypatch, mock_plugins):
    db.name = '/path/to/db'
    config = config_cls(obj)
    layer = one(config.load())

    if db_access == 'cache':
        layer.db = db

    if db_access.startswith('obj'):
        attr = db_access.split('.')[1] if '.' in db_access else 'db'
        setattr(obj, attr, db)

    if db_access == 'load':
        monkeypatch.setattr(freezerbox.model, 'load_db', lambda: db)
    else:
        monkeypatch.setattr(freezerbox.model, 'load_db',
                            lambda: NotImplemented)

    log = Log()
    values = list(layer.iter_values(key, log))

    assert values == expected

    for actual, pattern in zip_equal(log.err.info_strs, info):
        Matches(pattern).assert_matches(actual)
Exemplo n.º 3
0
def test_match_with_tabs():
    with pytest.raises(AssertionError) as excinfo:
        Matches('f.o.o').assert_matches('f\to\tx\n')
    msg, = excinfo.value.args
    assert msg == (' regex failed to match at:\n'
                   '\n'
                   '> f\to\tx\n'
                   '   \t \t^')
Exemplo n.º 4
0
def check_output(captured, expected, file=sys.stdout):
    expected = expected.format(DATE=DATE).strip()
    captured = captured.replace('\r', '').strip()

    print(repr(captured), file=file)
    print(repr(expected), file=file)

    Matches(expected, flags=re.DOTALL).assert_matches(captured)
Exemplo n.º 5
0
def test_repr_with_failure():
    obj = Matches('^foo')
    assert obj != 'fa'
    assert repr(obj) == ("Matches('^foo')\n"
                         '    # regex failed to match at:\n'
                         '    #\n'
                         '    #> fa\n'
                         '    #   ^')
Exemplo n.º 6
0
async def test_chunked_encoding_forbidden_for_http_10() -> None:
    req = make_request("GET", "/", version=HttpVersion10)
    resp = StreamResponse()
    resp.enable_chunked_encoding()

    with pytest.raises(RuntimeError) as ctx:
        await resp.prepare(req)
    assert Matches("Using chunked encoding is forbidden for HTTP/1.0") == str(ctx.value)
Exemplo n.º 7
0
async def test_regular_match_info(router: Any) -> None:
    handler = make_handler()
    router.add_route("GET", "/get/{name}", handler)

    req = make_mocked_request("GET", "/get/john")
    match_info = await router.resolve(req)
    assert {"name": "john"} == match_info
    assert Matches("<MatchInfo {'name': 'john'}: .+<Dynamic.+>>") == repr(
        match_info)
Exemplo n.º 8
0
def test_fail_multiple_lines():
    with pytest.raises(AssertionError) as excinfo:
        Matches('foo.bar', re.DOTALL).assert_matches('foo\nbr')
    msg, = excinfo.value.args
    assert msg == (' regex failed to match at:\n'
                   '\n'
                   '> foo\n'
                   '> br\n'
                   '   ^')
Exemplo n.º 9
0
async def test_repr(app: Any) -> None:
    signal = Signal(app)

    callback = make_mocked_coro()

    signal.append(callback)

    assert Matches(r"<Signal owner=<Application .+>, frozen=False, "
                   r"\[<Mock id='\d+'>\]>") == repr(signal)
Exemplo n.º 10
0
def test_double_add_url_with_the_same_name(router: Any) -> None:
    handler1 = make_handler()
    handler2 = make_handler()
    router.add_route("GET", "/get", handler1, name="name")

    regexp = "Duplicate 'name', already handled by"
    with pytest.raises(ValueError) as ctx:
        router.add_route("GET", "/get_other", handler2, name="name")
    assert Matches(regexp) == str(ctx.value)
Exemplo n.º 11
0
 async def test___repr__waiter(self) -> None:
     loop = asyncio.get_event_loop()
     stream = self._make_one()
     stream._waiter = loop.create_future()
     assert Matches(r"<StreamReader w=<Future pending[\S ]*>>") == repr(stream)
     stream._waiter.set_result(None)
     await stream._waiter
     stream._waiter = None
     assert "<StreamReader>" == repr(stream)
Exemplo n.º 12
0
def test_response_cookie__issue_del_cookie() -> None:
    resp = StreamResponse()

    assert resp.cookies == {}
    assert str(resp.cookies) == ""

    resp.del_cookie("name")
    expected = ('Set-Cookie: name=("")?; '
                "expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/")
    assert Matches(expected) == str(resp.cookies)
Exemplo n.º 13
0
def test_fail_at_end_of_line_mismatching_newline():
    with pytest.raises(AssertionError) as excinfo:
        Matches('foo.', re.DOTALL).assert_matches('foo')
    msg, = excinfo.value.args
    assert msg == (
        ' regex failed to match at:\n'
        '\n'
        '> foo\n'
        '     ^'
    )
Exemplo n.º 14
0
def test_fail_at_beginning():
    with pytest.raises(AssertionError) as excinfo:
        Matches('foo').assert_matches('bar')
    msg, = excinfo.value.args
    assert msg == (
        ' regex failed to match at:\n'
        '\n'
        '> bar\n'
        '  ^'
    )
Exemplo n.º 15
0
def test_sutonse_cookie__issue_del_cookie():
    sut = helpers.CookieMixin()

    assert sut.cookies == {}
    assert str(sut.cookies) == ""

    sut.del_cookie("name")
    expected = ('Set-Cookie: name=("")?; '
                "expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/")
    assert Matches(expected) == str(sut.cookies)
Exemplo n.º 16
0
async def test_send_headers_for_empty_body(buf: Any, writer: Any) -> None:
    req = make_request("GET", "/", writer=writer)
    resp = Response()

    await resp.prepare(req)
    await resp.write_eof()
    txt = buf.decode("utf8")
    assert (Matches("HTTP/1.1 200 OK\r\n"
                    "Content-Length: 0\r\n"
                    "Content-Type: application/octet-stream\r\n"
                    "Date: .+\r\n"
                    "Server: .+\r\n\r\n") == txt)
Exemplo n.º 17
0
async def test_render_with_body(buf, writer) -> None:
    req = make_request("GET", "/", writer=writer)
    resp = Response(body=b"data")

    await resp.prepare(req)
    await resp.write_eof()

    txt = buf.decode("utf8")
    assert (Matches("HTTP/1.1 200 OK\r\n"
                    "Content-Length: 4\r\n"
                    "Content-Type: application/octet-stream\r\n"
                    "Date: .+\r\n"
                    "Server: .+\r\n\r\n"
                    "data") == txt)
Exemplo n.º 18
0
async def test_send_set_cookie_header(buf: Any, writer: Any) -> None:
    resp = Response()
    resp.cookies["name"] = "value"
    req = make_request("GET", "/", writer=writer)

    await resp.prepare(req)
    await resp.write_eof()

    txt = buf.decode("utf8")
    assert (Matches("HTTP/1.1 200 OK\r\n"
                    "Content-Length: 0\r\n"
                    "Set-Cookie: name=value\r\n"
                    "Content-Type: application/octet-stream\r\n"
                    "Date: .+\r\n"
                    "Server: .+\r\n\r\n") == txt)
Exemplo n.º 19
0
def test_connector_loop(loop: Any) -> None:
    with contextlib.ExitStack() as stack:
        another_loop = asyncio.new_event_loop()
        stack.enter_context(contextlib.closing(another_loop))

        async def make_connector():
            return TCPConnector()

        connector = another_loop.run_until_complete(make_connector())

        stack.enter_context(contextlib.closing(connector))
        with pytest.raises(RuntimeError) as ctx:

            async def make_sess():
                return ClientSession(connector=connector)

            loop.run_until_complete(make_sess())
        assert Matches("Session and connector have to use same event loop") == str(
            ctx.value
        )
Exemplo n.º 20
0
def test_product_configs(db, config_cls, products, products_attr, key,
                         expected, info, error, mock_plugins):
    db.name = 'path/to/db'
    if not products:
        products = db.keys()

    obj = MockObj()

    if products_attr:
        setattr(obj, products_attr,
                [db[k].make_intermediate(i) for k, i in products.items()])

    config = config_cls(obj)
    layer = one(config.load())

    with error:
        log = Log()
        values = list(layer.iter_values(key, log))
        pprint(log.err.info_strs)

        assert values == expected

        for actual, pattern in zip_equal(log.err.info_strs, info):
            Matches(pattern).assert_matches(actual)
Exemplo n.º 21
0
def test_response_cookies() -> None:
    resp = StreamResponse()

    assert resp.cookies == {}
    assert str(resp.cookies) == ""

    resp.set_cookie("name", "value")
    assert str(resp.cookies) == "Set-Cookie: name=value; Path=/"
    resp.set_cookie("name", "other_value")
    assert str(resp.cookies) == "Set-Cookie: name=other_value; Path=/"

    resp.cookies["name"] = "another_other_value"
    resp.cookies["name"]["max-age"] = 10
    assert (str(resp.cookies) ==
            "Set-Cookie: name=another_other_value; Max-Age=10; Path=/")

    resp.del_cookie("name")
    expected = ('Set-Cookie: name=("")?; '
                "expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/")
    assert Matches(expected) == str(resp.cookies)

    resp.set_cookie("name", "value", domain="local.host")
    expected = "Set-Cookie: name=value; Domain=local.host; Path=/"
    assert str(resp.cookies) == expected
Exemplo n.º 22
0
def test_static_repr(router: Any) -> None:
    router.add_static("/get",
                      pathlib.Path(aiohttp.__file__).parent,
                      name="name")
    assert Matches(r"<StaticResource 'name' /get") == repr(router["name"])
Exemplo n.º 23
0
def test_matches_repr_with_flags():
    ret = repr(Matches('^foo', re.I))
    assert ret == "Matches('^foo', flags=regex.I | regex.V0)"
Exemplo n.º 24
0
def test_typeerror_equality_different_type():
    with pytest.raises(TypeError):
        Matches('foo') == b'foo'
Exemplo n.º 25
0
def test_matches_repr_plain():
    assert repr(Matches('^foo')) == "Matches('^foo')"
Exemplo n.º 26
0
def test_from_pattern():
    pattern = re.compile('^foo', flags=re.I)
    assert Matches.from_pattern(pattern) == 'FOO'
Exemplo n.º 27
0
async def test_parse_volume_remote(client: Client) -> None:
    expr = StrExpr(
        POS, POS, "${{ parse_volume('storage:path/to:/mnt/path:rw').remote }}")
    ret = await expr.eval(Root({}, client))
    assert Matches("storage:[^:]+/path/to") == ret
Exemplo n.º 28
0
def test_assert_success():
    obj = Matches('foo')
    assert obj == 'food'
    obj.assert_matches('food')