'Tests proper functionality of ConnectionHandler.server_reconnect mock.
If we have a disconnect on a secure connection that\'s transparently
proxified to an upstream http proxy, we need to send the CONNECT
request again.'

def test_reconnect(self):

    class MockOnce:
        call = 0
        def mock_once(self, http1obj, req):
            self.call += 1
            if (self.call == 2):
                headers = http1.assemble_request_head(req)
                http1obj.server_conn.wfile.write(headers)
                http1obj.server_conn.wfile.flush()
                raise exceptions.TcpDisconnect
            else:
                headers = http1.assemble_request_head(req)
                http1obj.server_conn.wfile.write(headers)
                http1obj.server_conn.wfile.flush()
    self.chain[0].tmaster.addons.add(RequestKiller([1, 2]))
    self.chain[1].tmaster.addons.add(RequestKiller([1]))
    p = self.pathoc()
    with p.connect():
        req = p.request('get:\'/p/418:b"content"\'')
        assert (req.content == 'content')
        assert (req.status_code == 418)
        assert (len(self.proxy.tmaster.state.flows) == 1)
        assert (len(self.chain[0].tmaster.state.flows) == 1)
        assert (len(self.chain[1].tmaster.state.flows) == 1)
        with mock.patch('mitmproxy.proxy.protocol.http1.Http1Layer.send_request_headers', side_effect=MockOnce().mock_once, autospec=True):
            req = p.request('get:\'/p/418:b"content2"\'')
        assert (req.status_code == 502)
        assert (len(self.proxy.tmaster.state.flows) == 2)
        assert (len(self.chain[0].tmaster.state.flows) == 2)
        assert (len(self.chain[1].tmaster.state.flows) == 3)
        assert (not self.chain[1].tmaster.state.flows[(-1)].response)
        assert (not self.chain[1].tmaster.state.flows[(-2)].response)
        with pytest.raises(exceptions.HttpException):
            p.request('get:\'/p/418:b"content3"\'')
