How to use the mocket.compat.decode_from_bytes function in mocket

To help you get started, we’ve selected a few mocket examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mindflayer / python-mocket / mocket / mockhttp.py View on Github external
def __init__(self, data):
        _, self.body = decode_from_bytes(data).split('\r\n\r\n', 1)
        self.rfile = BytesIO(encode_to_bytes(data))
        self.raw_requestline = self.rfile.readline()
        self.error_code = self.error_message = None
        self.parse_request()
        self.method = self.command
        self.querystring = parse_qs(unquote_utf8(urlsplit(self.path).query), keep_blank_values=True)
github mindflayer / python-mocket / mocket / mockhttp.py View on Github external
def can_handle(self, data):
        r"""
        >>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b''),))
        >>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: */*\r\n\r\n')
        False
        >>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b''),))
        >>> e.can_handle(b'GET /?bar=foo&foobar HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: */*\r\n\r\n')
        True
        """
        try:
            requestline, _ = decode_from_bytes(data).split(CRLF, 1)
            method, path, version = self._parse_requestline(requestline)
        except ValueError:
            try:
                return self == Mocket._last_entry
            except AttributeError:
                return False
        uri = urlsplit(path)
        can_handle = uri.path == self.path and method == self.method
        if self._match_querystring:
            kw = dict(keep_blank_values=True)
            can_handle = can_handle and parse_qs(uri.query, **kw) == parse_qs(self.query, **kw)
        if can_handle:
            Mocket._last_entry = self
        return can_handle
github mindflayer / python-mocket / mocket / mocket.py View on Github external
recv = self.true_socket.recv(self._buflen)

                if not recv and encoded_response:
                    break
                encoded_response += recv

            # dump the resulting dictionary to a JSON file
            if Mocket.get_truesocket_recording_dir():

                # update the dictionary with request and response lines
                response_dict["request"] = req
                response_dict["response"] = hexdump.dump(encoded_response)

                with io.open(path, mode="w") as f:
                    f.write(
                        decode_from_bytes(
                            json.dumps(responses, indent=4, sort_keys=True)
                        )
                    )

        # response back to .sendall() which writes it to the Mocket socket and flush the BytesIO
        return encoded_response
github mindflayer / python-mocket / mocket / mocket.py View on Github external
def send(self, data, *args, **kwargs):  # pragma: no cover
        entry = self.get_entry(data)
        if entry and self._entry != entry:
            self.sendall(data, entry=entry, *args, **kwargs)
        else:
            req = Mocket.last_request()
            if hasattr(req, "add_data"):
                req.add_data(decode_from_bytes(data))
        self._entry = entry
        return len(data)
github mindflayer / python-mocket / mocket / mocket.py View on Github external
def true_sendall(self, data, *args, **kwargs):
        req = decode_from_bytes(data)
        # make request unique again
        req_signature = _hash_request(hasher, req)
        # port should be always a string
        port = text_type(self._port)

        # prepare responses dictionary
        responses = dict()

        if Mocket.get_truesocket_recording_dir():
            path = os.path.join(
                Mocket.get_truesocket_recording_dir(), Mocket.get_namespace() + ".json"
            )
            # check if there's already a recorded session dumped to a JSON file
            try:
                with io.open(path) as f:
                    responses = json.load(f)
github mindflayer / python-mocket / mocket / mockhttp.py View on Github external
def set_base_headers(self):
        self.headers = {
            'Status': str(self.status),
            'Date': time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime()),
            'Server': 'Python/Mocket',
            'Connection': 'close',
            'Content-Length': str(len(self.body)),
        }
        if not self.is_file_object:
            self.headers['Content-Type'] = 'text/plain; charset=utf-8'
        elif self.magic:
            self.headers['Content-Type'] = decode_from_bytes(magic.from_buffer(self.body, mime=True))