コード例 #1
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_writer_flush_error(self):
     s = BytesIO()
     s = tcp.Writer(s)
     o = mock.MagicMock()
     o.flush = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(TcpDisconnect, s.flush)
コード例 #2
0
def test_client_greeting_assert_socks5():
    raw = tutils.treader("\x00\x00")
    msg = socks.ClientGreeting.from_file(raw)
    tutils.raises(socks.SocksError, msg.assert_socks5)

    raw = tutils.treader("HTTP/1.1 200 OK" + " " * 100)
    msg = socks.ClientGreeting.from_file(raw)
    try:
        msg.assert_socks5()
    except socks.SocksError as e:
        assert "Invalid SOCKS version" in str(e)
        assert "HTTP" not in str(e)
    else:
        assert False

    raw = tutils.treader("GET / HTTP/1.1" + " " * 100)
    msg = socks.ClientGreeting.from_file(raw)
    try:
        msg.assert_socks5()
    except socks.SocksError as e:
        assert "Invalid SOCKS version" in str(e)
        assert "HTTP" in str(e)
    else:
        assert False

    raw = tutils.treader("XX")
    tutils.raises(
        socks.SocksError,
        socks.ClientGreeting.from_file,
        raw,
        fail_early=True)
コード例 #3
0
ファイル: test_dump.py プロジェクト: DrakeCaraker/mitmproxy
    def test_replay(self):
        o = dump.Options(server_replay=["nonexistent"], kill=True)
        tutils.raises(dump.DumpError, dump.DumpMaster, None, o)

        with tutils.tmpdir() as t:
            p = os.path.join(t, "rep")
            self.flowfile(p)

            o = dump.Options(server_replay=[p], kill=True)
            o.verbosity = 0
            o.flow_detail = 0
            m = dump.DumpMaster(None, o)

            self.cycle(m, b"content")
            self.cycle(m, b"content")

            o = dump.Options(server_replay=[p], kill=False)
            o.verbosity = 0
            o.flow_detail = 0
            m = dump.DumpMaster(None, o)
            self.cycle(m, b"nonexistent")

            o = dump.Options(client_replay=[p], kill=False)
            o.verbosity = 0
            o.flow_detail = 0
            m = dump.DumpMaster(None, o)
コード例 #4
0
ファイル: test_semantics.py プロジェクト: fireswood/netlib
    def test_legacy_first_line(self):
        req = tutils.treq()

        assert req.legacy_first_line('relative') == "GET /path HTTP/1.1"
        assert req.legacy_first_line('authority') == "GET address:22 HTTP/1.1"
        assert req.legacy_first_line('absolute') == "GET http://address:22/path HTTP/1.1"
        tutils.raises(http.HttpError, req.legacy_first_line, 'foobar')
コード例 #5
0
ファイル: test_frames.py プロジェクト: pombredanne/netlib
def test_invalid_flags():
    tutils.raises(
        ValueError,
        DataFrame,
        flags=ContinuationFrame.FLAG_END_HEADERS,
        stream_id=0x1234567,
        payload='foobar')
コード例 #6
0
ファイル: test_frames.py プロジェクト: tempbottle/netlib
def test_settings_frame_to_bytes():
    f = SettingsFrame(
        length=0,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0)
    assert f.to_bytes().encode('hex') == '000000040000000000'

    f = SettingsFrame(
        length=0,
        flags=SettingsFrame.FLAG_ACK,
        stream_id=0x0)
    assert f.to_bytes().encode('hex') == '000000040100000000'

    f = SettingsFrame(
        length=6,
        flags=SettingsFrame.FLAG_ACK,
        stream_id=0x0,
        settings={
            SettingsFrame.SETTINGS.SETTINGS_ENABLE_PUSH: 1})
    assert f.to_bytes().encode('hex') == '000006040100000000000200000001'

    f = SettingsFrame(
        length=12,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        settings={
            SettingsFrame.SETTINGS.SETTINGS_ENABLE_PUSH: 1,
            SettingsFrame.SETTINGS.SETTINGS_MAX_CONCURRENT_STREAMS: 0x12345678})
    assert f.to_bytes().encode('hex') == '00000c040000000000000200000001000312345678'

    f = SettingsFrame(
        length=0,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x1234567)
    tutils.raises(ValueError, f.to_bytes)
コード例 #7
0
def test_too_large_frames():
    f = DataFrame(
        length=9000,
        flags=Frame.FLAG_END_STREAM,
        stream_id=0x1234567,
        payload='foobar' * 3000)
    tutils.raises(FrameSizeError, f.to_bytes)
コード例 #8
0
ファイル: test_frames.py プロジェクト: pombredanne/netlib
def test_priority_frame_to_bytes():
    f = PriorityFrame(
        length=5,
        flags=(Frame.FLAG_NO_FLAGS),
        stream_id=0x1234567,
        exclusive=True,
        stream_dependency=0x0,
        weight=42)
    assert_equal(f.to_bytes().encode('hex'), '000005020001234567800000002a')

    f = PriorityFrame(
        length=5,
        flags=(Frame.FLAG_NO_FLAGS),
        stream_id=0x1234567,
        exclusive=False,
        stream_dependency=0x7654321,
        weight=21)
    assert_equal(f.to_bytes().encode('hex'), '0000050200012345670765432115')

    f = PriorityFrame(
        length=5,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        stream_dependency=0x1234567)
    tutils.raises(ValueError, f.to_bytes)
コード例 #9
0
ファイル: test_frames.py プロジェクト: pombredanne/netlib
def test_push_promise_frame_to_bytes():
    f = PushPromiseFrame(
        length=10,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x1234567,
        promised_stream=0x7654321,
        header_block_fragment='foobar')
    assert_equal(
        f.to_bytes().encode('hex'),
        '00000a05000123456707654321666f6f626172')

    f = PushPromiseFrame(
        length=14,
        flags=HeadersFrame.FLAG_PADDED,
        stream_id=0x1234567,
        promised_stream=0x7654321,
        header_block_fragment='foobar',
        pad_length=3)
    assert_equal(
        f.to_bytes().encode('hex'),
        '00000e0508012345670307654321666f6f626172000000')

    f = PushPromiseFrame(
        length=4,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        promised_stream=0x1234567)
    tutils.raises(ValueError, f.to_bytes)

    f = PushPromiseFrame(
        length=4,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x1234567,
        promised_stream=0x0)
    tutils.raises(ValueError, f.to_bytes)
コード例 #10
0
ファイル: test_frames.py プロジェクト: pombredanne/netlib
def test_too_large_frames():
    f = DataFrame(
        length=9000,
        flags=Frame.FLAG_END_STREAM,
        stream_id=0x1234567,
        payload='foobar' * 3000)
    tutils.raises(HttpSyntaxException, f.to_bytes)
コード例 #11
0
def test_options():
    o = TO(two="three")
    assert o.keys() == set(["one", "two"])

    assert o.one is None
    assert o.two == "three"
    o.one = "one"
    assert o.one == "one"

    with tutils.raises(TypeError):
        TO(nonexistent = "value")
    with tutils.raises("no such option"):
        o.nonexistent = "value"
    with tutils.raises("no such option"):
        o.update(nonexistent = "value")

    rec = []

    def sub(opts, updated):
        rec.append(copy.copy(opts))

    o.changed.connect(sub)

    o.one = "ninety"
    assert len(rec) == 1
    assert rec[-1].one == "ninety"

    o.update(one="oink")
    assert len(rec) == 2
    assert rec[-1].one == "oink"
コード例 #12
0
 def test_reader_read_error(self):
     s = cStringIO.StringIO("foobar\nfoobar")
     s = tcp.Reader(s)
     o = mock.MagicMock()
     o.read = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(tcp.NetLibDisconnect, s.read, 10)
コード例 #13
0
ファイル: test_server.py プロジェクト: camerony/mitmproxy
    def test_ignore(self):
        spec = '304:h"Alternate-Protocol"="mitmproxy-will-remove-this"'
        n = self.pathod(spec)
        self._ignore_on()
        i = self.pathod(spec)
        i2 = self.pathod(spec)
        self._ignore_off()

        assert i.status_code == i2.status_code == n.status_code == 304
        assert "Alternate-Protocol" in i.headers
        assert "Alternate-Protocol" in i2.headers
        assert "Alternate-Protocol" not in n.headers

        # Test that we get the original SSL cert
        if self.ssl:
            i_cert = SSLCert(i.sslinfo.certchain[0])
            i2_cert = SSLCert(i2.sslinfo.certchain[0])
            n_cert = SSLCert(n.sslinfo.certchain[0])

            assert i_cert == i2_cert
            assert i_cert != n_cert

        # Test Non-HTTP traffic
        spec = "200:i0,@100:d0"  # this results in just 100 random bytes
        # mitmproxy responds with bad gateway
        assert self.pathod(spec).status_code == 502
        self._ignore_on()
        tutils.raises(
            "invalid server response",
            self.pathod,
            spec)  # pathoc tries to parse answer as HTTP
        self._ignore_off()
コード例 #14
0
ファイル: test_utils.py プロジェクト: Angelcold/mitmproxy
def test_bidi():
    b = utils.BiDi(a=1, b=2)
    assert b.a == 1
    assert b.get_name(1) == "a"
    assert b.get_name(5) is None
    tutils.raises(AttributeError, getattr, b, "c")
    tutils.raises(ValueError, utils.BiDi, one=1, two=1)
コード例 #15
0
 def test_writer_flush_error(self):
     s = cStringIO.StringIO()
     s = tcp.Writer(s)
     o = mock.MagicMock()
     o.flush = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(tcp.NetLibDisconnect, s.flush)
コード例 #16
0
ファイル: test_frames.py プロジェクト: pombredanne/netlib
def test_goaway_frame_to_bytes():
    f = GoAwayFrame(
        length=8,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        last_stream=0x1234567,
        error_code=0x87654321,
        data=b'')
    assert_equal(
        f.to_bytes().encode('hex'),
        '0000080700000000000123456787654321')

    f = GoAwayFrame(
        length=14,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        last_stream=0x1234567,
        error_code=0x87654321,
        data=b'foobar')
    assert_equal(
        f.to_bytes().encode('hex'),
        '00000e0700000000000123456787654321666f6f626172')

    f = GoAwayFrame(
        length=8,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x1234567,
        last_stream=0x1234567,
        error_code=0x87654321)
    tutils.raises(ValueError, f.to_bytes)
コード例 #17
0
ファイル: test_read.py プロジェクト: ellerbrock/mitmproxy
def test_read_chunked():
    req = treq(content=None)
    req.headers["Transfer-Encoding"] = "chunked"

    data = b"1\r\na\r\n0\r\n"
    with raises(HttpSyntaxException):
        b"".join(_read_chunked(BytesIO(data)))

    data = b"1\r\na\r\n0\r\n\r\n"
    assert b"".join(_read_chunked(BytesIO(data))) == b"a"

    data = b"\r\n\r\n1\r\na\r\n1\r\nb\r\n0\r\n\r\n"
    assert b"".join(_read_chunked(BytesIO(data))) == b"ab"

    data = b"\r\n"
    with raises("closed prematurely"):
        b"".join(_read_chunked(BytesIO(data)))

    data = b"1\r\nfoo"
    with raises("malformed chunked body"):
        b"".join(_read_chunked(BytesIO(data)))

    data = b"foo\r\nfoo"
    with raises(HttpSyntaxException):
        b"".join(_read_chunked(BytesIO(data)))

    data = b"5\r\naaaaa\r\n0\r\n\r\n"
    with raises("too large"):
        b"".join(_read_chunked(BytesIO(data), limit=2))
コード例 #18
0
ファイル: test_strutils.py プロジェクト: mkagenius/mitmproxy
def test_always_bytes():
    assert strutils.always_bytes(bytes(bytearray(range(256)))) == bytes(bytearray(range(256)))
    assert strutils.always_bytes("foo") == b"foo"
    with tutils.raises(ValueError):
        strutils.always_bytes(u"\u2605", "ascii")
    with tutils.raises(TypeError):
        strutils.always_bytes(42, "ascii")
コード例 #19
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_reader_read_error(self):
     s = BytesIO(b"foobar\nfoobar")
     s = tcp.Reader(s)
     o = mock.MagicMock()
     o.read = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(TcpDisconnect, s.read, 10)
コード例 #20
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_clientcert_err(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     c.connect()
     tutils.raises(
         TlsException,
         c.convert_to_ssl,
         cert=tutils.test_data.path("data/clientcert/make")
     )
コード例 #21
0
ファイル: test_dump.py プロジェクト: nask0/mitmproxy
    def test_read(self):
        with tutils.tmpdir() as t:
            p = os.path.join(t, "read")
            self._flowfile(p)
            assert "GET" in self._dummy_cycle(0, None, "", flow_detail=1, rfile=p)

            tutils.raises(dump.DumpError, self._dummy_cycle, 0, None, "", verbosity=1, rfile="/nonexistent")
            tutils.raises(dump.DumpError, self._dummy_cycle, 0, None, "", verbosity=1, rfile="test_dump.py")
コード例 #22
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_echo(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     c.connect()
     tutils.raises(
         "cipher specification",
         c.convert_to_ssl,
         sni=b"foo.com",
         cipher_list="bogus")
コード例 #23
0
ファイル: test_models.py プロジェクト: pombredanne/netlib
    def test_getitem(self):
        headers = Headers(Host="example.com")
        assert headers["Host"] == "example.com"
        assert headers["host"] == "example.com"
        tutils.raises(KeyError, headers.__getitem__, "Accept")

        headers = self._2host()
        assert headers["Host"] == "example.com, example.org"
コード例 #24
0
ファイル: test_protocol.py プロジェクト: camerony/netlib
    def test_invalid_headers(self):
        data = """
            HTTP/1.1 200 OK
            \tContent-Length: 3

            foo
        """
        tutils.raises("invalid headers", self.tst, data, "GET", None)
コード例 #25
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_echo(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     c.connect()
     c.convert_to_ssl()
     # Exercise SSL.SysCallError
     c.rfile.read(10)
     c.close()
     tutils.raises(TcpDisconnect, c.wfile.write, b"foo")
コード例 #26
0
ファイル: test_tcp.py プロジェクト: bemre/mitmproxy
 def test_echo(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     c.connect()
     c.convert_to_ssl()
     # Excercise SSL.ZeroReturnError
     c.rfile.read(10)
     c.close()
     tutils.raises(TcpDisconnect, c.wfile.write, b"foo")
     tutils.raises(queue.Empty, self.q.get_nowait)
コード例 #27
0
ファイル: test_dump.py プロジェクト: nask0/mitmproxy
 def test_script(self):
     ret = self._dummy_cycle(1, None, "", scripts=[tutils.test_data.path("scripts/all.py")], verbosity=1)
     assert "XCLIENTCONNECT" in ret
     assert "XSERVERCONNECT" in ret
     assert "XREQUEST" in ret
     assert "XRESPONSE" in ret
     assert "XCLIENTDISCONNECT" in ret
     tutils.raises(dump.DumpError, self._dummy_cycle, 1, None, "", scripts=["nonexistent"])
     tutils.raises(dump.DumpError, self._dummy_cycle, 1, None, "", scripts=["starterr.py"])
コード例 #28
0
ファイル: test_human.py プロジェクト: eftychis/mitmproxy
def test_parse_size():
    assert human.parse_size("0") == 0
    assert human.parse_size("0b") == 0
    assert human.parse_size("1") == 1
    assert human.parse_size("1k") == 1024
    assert human.parse_size("1m") == 1024**2
    assert human.parse_size("1g") == 1024**3
    tutils.raises(ValueError, human.parse_size, "1f")
    tutils.raises(ValueError, human.parse_size, "ak")
コード例 #29
0
ファイル: test_dump.py プロジェクト: keithsun80/mitmproxy
 def test_write_err(self):
     tutils.raises(
         dump.DumpError,
         self._dummy_cycle,
         1,
         None,
         "",
         outfile = ("nonexistentdir/foo", "wb")
     )
コード例 #30
0
    def test_modify(self):
        md = TImmutableMultiDict()
        with tutils.raises(TypeError):
            md["foo"] = "bar"

        with tutils.raises(TypeError):
            del md["foo"]

        with tutils.raises(TypeError):
            md.add("foo", "bar")
コード例 #31
0
ファイル: test_read.py プロジェクト: skywind0218/mitmproxy
def test_parse_authority_form():
    assert _parse_authority_form(b"foo:42") == (b"foo", 42)
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo:bar")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo:99999999")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"f\x00oo:80")
コード例 #32
0
    def test_add_cv(self):
        class TestContentView(cv.View):
            name = "test"
            prompt = ("t", "test")

        tcv = TestContentView()
        cv.add(tcv)

        # repeated addition causes exception
        tutils.raises(ContentViewException, cv.add, tcv)
コード例 #33
0
ファイル: test_read.py プロジェクト: ellerbrock/mitmproxy
def test_parse_authority_form():
    assert _parse_authority_form(b"foo:42") == (b"foo", 42)
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo:bar")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"foo:99999999")
    with raises(HttpSyntaxException):
        _parse_authority_form(b"f\x00oo:80")
コード例 #34
0
def test_check_http_version():
    _check_http_version(b"HTTP/0.9")
    _check_http_version(b"HTTP/1.0")
    _check_http_version(b"HTTP/1.1")
    _check_http_version(b"HTTP/2.0")
    with raises(HttpSyntaxException):
        _check_http_version(b"WTF/1.0")
    with raises(HttpSyntaxException):
        _check_http_version(b"HTTP/1.10")
    with raises(HttpSyntaxException):
        _check_http_version(b"HTTP/1.b")
コード例 #35
0
ファイル: test_pathoc.py プロジェクト: eftychis/mitmproxy
 def test_connect_fail(self):
     to = ("foobar", 80)
     c = pathoc.Pathoc(("127.0.0.1", self.d.port), fp=None)
     c.rfile, c.wfile = StringIO(), StringIO()
     with raises("connect failed"):
         c.http_connect(to)
     c.rfile = StringIO("HTTP/1.1 500 OK\r\n")
     with raises("connect failed"):
         c.http_connect(to)
     c.rfile = StringIO("HTTP/1.1 200 OK\r\n")
     c.http_connect(to)
コード例 #36
0
ファイル: test_protocol.py プロジェクト: fireswood/netlib
 def test_absolute_form_in(self):
     tutils.raises(
         "Bad HTTP request line",
         self.tst,
         "GET oops-no-protocol.com HTTP/1.1"
     )
     v = self.tst("GET http://address:22/ HTTP/1.1")
     assert v.form_in == "absolute"
     assert v.port == 22
     assert v.host == "address"
     assert v.scheme == "http"
コード例 #37
0
ファイル: test_protocol.py プロジェクト: fireswood/netlib
 def test_connect(self):
     tutils.raises(
         "Bad HTTP request line",
         self.tst,
         "CONNECT oops-no-port.com HTTP/1.1"
     )
     v = self.tst("CONNECT foo.com:443 HTTP/1.1")
     assert v.form_in == "authority"
     assert v.method == "CONNECT"
     assert v.port == 443
     assert v.host == "foo.com"
コード例 #38
0
ファイル: test_frames.py プロジェクト: yonatan-py/netlib
def test_headers_frame_to_bytes():
    f = HeadersFrame(
        length=6,
        flags=(Frame.FLAG_NO_FLAGS),
        stream_id=0x1234567,
        header_block_fragment='668594e75e31d9'.decode('hex'))
    assert f.to_bytes().encode('hex') == '000007010001234567668594e75e31d9'

    f = HeadersFrame(
        length=10,
        flags=(HeadersFrame.FLAG_PADDED),
        stream_id=0x1234567,
        header_block_fragment='668594e75e31d9'.decode('hex'),
        pad_length=3)
    assert f.to_bytes().encode('hex') == '00000b01080123456703668594e75e31d9000000'

    f = HeadersFrame(
        length=10,
        flags=(HeadersFrame.FLAG_PRIORITY),
        stream_id=0x1234567,
        header_block_fragment='668594e75e31d9'.decode('hex'),
        exclusive=True,
        stream_dependency=0x7654321,
        weight=42)
    assert f.to_bytes().encode('hex') == '00000c012001234567876543212a668594e75e31d9'

    f = HeadersFrame(
        length=14,
        flags=(HeadersFrame.FLAG_PADDED | HeadersFrame.FLAG_PRIORITY),
        stream_id=0x1234567,
        header_block_fragment='668594e75e31d9'.decode('hex'),
        pad_length=3,
        exclusive=True,
        stream_dependency=0x7654321,
        weight=42)
    assert f.to_bytes().encode('hex') == '00001001280123456703876543212a668594e75e31d9000000'

    f = HeadersFrame(
        length=14,
        flags=(HeadersFrame.FLAG_PADDED | HeadersFrame.FLAG_PRIORITY),
        stream_id=0x1234567,
        header_block_fragment='668594e75e31d9'.decode('hex'),
        pad_length=3,
        exclusive=False,
        stream_dependency=0x7654321,
        weight=42)
    assert f.to_bytes().encode('hex') == '00001001280123456703076543212a668594e75e31d9000000'

    f = HeadersFrame(
        length=6,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0,
        header_block_fragment='668594e75e31d9'.decode('hex'))
    tutils.raises(ValueError, f.to_bytes)
コード例 #39
0
    def test_headers_odict(self):
        tutils.raises(AssertionError, semantics.Response,
            (1, 1),
            200,
            headers='foobar',
        )

        resp = semantics.Response(
            (1, 1),
            200,
        )
        assert isinstance(resp.headers, odict.ODictCaseless)
コード例 #40
0
    def test_perform_server_connection_preface(self):
        c = tcp.TCPClient(("127.0.0.1", self.port))
        c.connect()
        protocol = HTTP2Protocol(c)

        assert not protocol.connection_preface_performed
        protocol.perform_server_connection_preface()
        assert protocol.connection_preface_performed

        tutils.raises(TcpDisconnect,
                      protocol.perform_server_connection_preface,
                      force=True)
コード例 #41
0
def test_rst_stream_frame_to_bytes():
    f = RstStreamFrame(
        length=4,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x1234567,
        error_code=0x7654321)
    assert_equal(f.to_bytes().encode('hex'), '00000403000123456707654321')

    f = RstStreamFrame(
        length=4,
        flags=Frame.FLAG_NO_FLAGS,
        stream_id=0x0)
    tutils.raises(ValueError, f.to_bytes)
コード例 #42
0
    def test_headers(self):
        tutils.raises(
            AssertionError,
            semantics.Response,
            (1, 1),
            200,
            headers='foobar',
        )

        resp = semantics.Response(
            (1, 1),
            200,
        )
        assert isinstance(resp.headers, http.Headers)
コード例 #43
0
def test_continuation_frame_to_bytes():
    f = ContinuationFrame(
        length=6,
        flags=ContinuationFrame.FLAG_END_HEADERS,
        stream_id=0x1234567,
        header_block_fragment='foobar')
    assert_equal(f.to_bytes().encode('hex'), '000006090401234567666f6f626172')

    f = ContinuationFrame(
        length=6,
        flags=ContinuationFrame.FLAG_END_HEADERS,
        stream_id=0x0,
        header_block_fragment='foobar')
    tutils.raises(ValueError, f.to_bytes)
コード例 #44
0
def test_escaped_str_to_bytes():
    assert strutils.escaped_str_to_bytes("foo") == b"foo"
    assert strutils.escaped_str_to_bytes("\x08") == b"\b"
    assert strutils.escaped_str_to_bytes("&!?=\\\\)") == br"&!?=\)"
    assert strutils.escaped_str_to_bytes(u"\\x08") == b"\b"
    assert strutils.escaped_str_to_bytes(u"&!?=\\\\)") == br"&!?=\)"
    assert strutils.escaped_str_to_bytes(u"\u00fc") == b'\xc3\xbc'

    if six.PY2:
        with tutils.raises(ValueError):
            strutils.escaped_str_to_bytes(42)
    else:
        with tutils.raises(ValueError):
            strutils.escaped_str_to_bytes(b"very byte")
コード例 #45
0
ファイル: test_tcp.py プロジェクト: yonatan-py/netlib
    def test_mode_strict_should_fail(self):
        c = tcp.TCPClient(("127.0.0.1", self.port))
        c.connect()

        tutils.raises(
            InvalidCertificateException,
            c.convert_to_ssl,
            verify_options=SSL.VERIFY_PEER,
            ca_pemfile=tutils.test_data.path("data/verificationcerts/trusted.pem"))

        assert c.ssl_verification_error is not None

        # Unknown issuing certificate authority for first certificate
        assert c.ssl_verification_error['errno'] == 20
        assert c.ssl_verification_error['depth'] == 0
コード例 #46
0
def test_get_first_line():
    rfile = BytesIO(b"foo\r\nbar")
    assert _get_first_line(rfile) == b"foo"

    rfile = BytesIO(b"\r\nfoo\r\nbar")
    assert _get_first_line(rfile) == b"foo"

    with raises(HttpReadDisconnect):
        rfile = BytesIO(b"")
        _get_first_line(rfile)

    with raises(HttpReadDisconnect):
        rfile = Mock()
        rfile.readline.side_effect = TcpDisconnect
        _get_first_line(rfile)
コード例 #47
0
def test_setter():
    o = TO(two="three")
    f = o.setter("two")
    f("xxx")
    assert o.two == "xxx"
    with tutils.raises("no such option"):
        o.setter("nonexistent")
コード例 #48
0
def test_expected_http_body_size():
    # Expect: 100-continue
    assert expected_http_body_size(
        treq(headers=Headers(expect="100-continue", content_length="42"))) == 0

    # http://tools.ietf.org/html/rfc7230#section-3.3
    assert expected_http_body_size(
        treq(method=b"HEAD"), tresp(headers=Headers(content_length="42"))) == 0
    assert expected_http_body_size(treq(method=b"CONNECT"), tresp()) == 0
    for code in (100, 204, 304):
        assert expected_http_body_size(treq(), tresp(status_code=code)) == 0

    # chunked
    assert expected_http_body_size(
        treq(headers=Headers(transfer_encoding="chunked")), ) is None

    # explicit length
    for val in (b"foo", b"-7"):
        with raises(HttpSyntaxException):
            expected_http_body_size(treq(headers=Headers(content_length=val)))
    assert expected_http_body_size(
        treq(headers=Headers(content_length="42"))) == 42

    # no length
    assert expected_http_body_size(treq(headers=Headers())) == 0
    assert expected_http_body_size(treq(headers=Headers()),
                                   tresp(headers=Headers())) == -1
コード例 #49
0
def test_bytes_to_escaped_str():
    assert strutils.bytes_to_escaped_str(b"foo") == "foo"
    assert strutils.bytes_to_escaped_str(b"\b") == r"\x08"
    assert strutils.bytes_to_escaped_str(br"&!?=\)") == r"&!?=\\)"
    assert strutils.bytes_to_escaped_str(b'\xc3\xbc') == r"\xc3\xbc"
    assert strutils.bytes_to_escaped_str(b"'") == r"'"
    assert strutils.bytes_to_escaped_str(b'"') == r'"'

    assert strutils.bytes_to_escaped_str(b"'",
                                         escape_single_quotes=True) == r"\'"
    assert strutils.bytes_to_escaped_str(b'"',
                                         escape_single_quotes=True) == r'"'

    assert strutils.bytes_to_escaped_str(b"\r\n\t") == "\\r\\n\\t"
    assert strutils.bytes_to_escaped_str(b"\r\n\t", True) == "\r\n\t"

    assert strutils.bytes_to_escaped_str(b"\n", True) == "\n"
    assert strutils.bytes_to_escaped_str(b"\\n",
                                         True) == "\\ \\ n".replace(" ", "")
    assert strutils.bytes_to_escaped_str(b"\\\n",
                                         True) == "\\ \\ \n".replace(" ", "")
    assert strutils.bytes_to_escaped_str(b"\\\\n",
                                         True) == "\\ \\ \\ \\ n".replace(
                                             " ", "")

    with tutils.raises(ValueError):
        strutils.bytes_to_escaped_str(u"such unicode")
コード例 #50
0
 def test_ask_shutdown(self):
     q = queue.Queue()
     done = Event()
     done.set()
     channel = controller.Channel(q, done)
     with raises(Kill):
         channel.ask("test", Mock())
コード例 #51
0
 def test_check_alpn(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     c.connect()
     c.convert_to_ssl(alpn_protos=[b'h2'])
     protocol = HTTP2Protocol(c)
     with raises(NotImplementedError):
         protocol.check_alpn()
コード例 #52
0
def test_deflate():
    assert b"string" == encoding.decode(encoding.encode(b"string", "deflate"),
                                        "deflate")
    assert b"string" == encoding.decode(
        encoding.encode(b"string", "deflate")[2:-4], "deflate")
    with tutils.raises(ValueError):
        encoding.decode(b"bogus", "deflate")
コード例 #53
0
ファイル: test_server.py プロジェクト: mackjoner/mitmproxy
    def test_ignore(self):
        n = self.pathod("304")
        self._ignore_on()
        i = self.pathod("305")
        i2 = self.pathod("306")
        self._ignore_off()

        self.master.masterq.join()

        assert n.status_code == 304
        assert i.status_code == 305
        assert i2.status_code == 306
        assert any(f.response.status_code == 304 for f in self.master.state.flows)
        assert not any(f.response.status_code == 305 for f in self.master.state.flows)
        assert not any(f.response.status_code == 306 for f in self.master.state.flows)

        # Test that we get the original SSL cert
        if self.ssl:
            i_cert = SSLCert(i.sslinfo.certchain[0])
            i2_cert = SSLCert(i2.sslinfo.certchain[0])
            n_cert = SSLCert(n.sslinfo.certchain[0])

            assert i_cert == i2_cert
            assert i_cert != n_cert

        # Test Non-HTTP traffic
        spec = "200:i0,@100:d0"  # this results in just 100 random bytes
        # mitmproxy responds with bad gateway
        assert self.pathod(spec).status_code == 502
        self._ignore_on()
        with raises(HttpException):
            self.pathod(spec)  # pathoc tries to parse answer as HTTP

        self._ignore_off()
コード例 #54
0
ファイル: test_tcp.py プロジェクト: tdickers/mitmproxy
 def test_readlog(self):
     s = BytesIO(b"foobar\nfoobar")
     s = tcp.Reader(s)
     assert not s.is_logging()
     s.start_log()
     assert s.is_logging()
     s.readline()
     assert s.get_log() == b"foobar\n"
     s.read(1)
     assert s.get_log() == b"foobar\nf"
     s.start_log()
     assert s.get_log() == b""
     s.read(1)
     assert s.get_log() == b"o"
     s.stop_log()
     tutils.raises(ValueError, s.get_log)
コード例 #55
0
ファイル: test_message.py プロジェクト: skywind0218/mitmproxy
 def test_unknown_ce(self):
     r = tresp()
     r.headers["content-type"] = "text/html; charset=wtf"
     r.raw_content = b"foo"
     with tutils.raises(ValueError):
         assert r.text == u"foo"
     assert r.get_text(strict=False) == u"foo"
コード例 #56
0
ファイル: test_tcp.py プロジェクト: yonatan-py/netlib
    def test_mode_strict_should_fail(self):
        c = tcp.TCPClient(("127.0.0.1", self.port))
        c.connect()

        tutils.raises(
            "certificate verify failed",
            c.convert_to_ssl,
            verify_options=SSL.VERIFY_PEER,
            ca_pemfile=tutils.test_data.path("data/verificationcerts/trusted.pem"))

        assert c.ssl_verification_error is not None

        # Untrusted self-signed certificate at second position in certificate
        # chain
        assert c.ssl_verification_error['errno'] == 19
        assert c.ssl_verification_error['depth'] == 1
コード例 #57
0
ファイル: test_headers.py プロジェクト: timmc/mitmproxy
    def test_init(self):
        headers = Headers()
        assert len(headers) == 0

        headers = Headers([[b"Host", b"example.com"]])
        assert len(headers) == 1
        assert headers["Host"] == "example.com"

        headers = Headers(Host="example.com")
        assert len(headers) == 1
        assert headers["Host"] == "example.com"

        headers = Headers(
            [[b"Host", b"invalid"]],
            Host="example.com"
        )
        assert len(headers) == 1
        assert headers["Host"] == "example.com"

        headers = Headers(
            [[b"Host", b"invalid"], [b"Accept", b"text/plain"]],
            Host="example.com"
        )
        assert len(headers) == 2
        assert headers["Host"] == "example.com"
        assert headers["Accept"] == "text/plain"

        with raises(TypeError):
            Headers([[b"Host", u"not-bytes"]])
コード例 #58
0
ファイル: test_tcp.py プロジェクト: tdickers/mitmproxy
 def test_should_fail_without_sni(self):
     c = tcp.TCPClient(("127.0.0.1", self.port))
     with c.connect():
         with tutils.raises(TlsException):
             c.convert_to_ssl(
                 verify_options=SSL.VERIFY_PEER,
                 ca_pemfile=tutils.test_data.path(
                     "data/verificationcerts/trusted-root.crt"))
コード例 #59
0
ファイル: test_message.py プロジェクト: skywind0218/mitmproxy
    def test_cannot_decode(self):
        r = tresp()
        r.encode("gzip")
        r.raw_content = b"foo"
        with tutils.raises(ValueError):
            assert r.content
        assert r.headers["content-encoding"]
        assert r.get_content(strict=False) == b"foo"

        with tutils.raises(ValueError):
            r.decode()
        assert r.raw_content == b"foo"
        assert "content-encoding" in r.headers

        r.decode(strict=False)
        assert r.content == b"foo"
        assert "content-encoding" not in r.headers
コード例 #60
0
ファイル: test_message.py プロジェクト: skywind0218/mitmproxy
    def test_cannot_decode(self):
        r = tresp()
        r.headers["content-type"] = "text/html; charset=utf8"
        r.raw_content = b"\xFF"
        with tutils.raises(ValueError):
            assert r.text

        assert r.get_text(strict=False) == '\udcff'