mindflayer / python-mocket

a socket mock framework - for all kinds of socket animals, web-clients included
BSD 3-Clause "New" or "Revised" License
280 stars 42 forks source link

MocketEntry.request_class str vs bytes #175

Closed michael-lazar closed 2 years ago

michael-lazar commented 2 years ago

Hi, thanks for creating this awesome library!

I've just started using mocket to test raw socket connections and uncovered some weirdness with MocketEntry.request_cls. The default behavior is to cast the request data as a str, but this doesn't really make sense for python 3 because sockets use bytes. This results in the request data being mangled as a string. Here's an example

import socket

from mocket import Mocket, MocketEntry, Mocketizer

entry = MocketEntry(("example.com", 1965), "")
Mocket.register(entry)

with Mocketizer():
    with socket.create_connection(("example.com", 1965)) as sock:
        sock.sendall(b"example request data")

    request = Mocket.last_request()

    # I expect the request to contain the bytes that I sent, but it's actually a string object
    print(type(request), repr(request))
    # <class 'str'> "b'example request data'"

I suspect this is a holdout bug from the python 2 -> 3 conversion, and not the intended behavior. For now I've fixed it for myself by subclassing the mocket entry.

class RawMocketEntry(MocketEntry):
    request_cls = bytes
mindflayer commented 2 years ago

Hi, thanks for creating this awesome library!

I am glad you like it, and thanks for opening this issue.

I suspect this is a holdout bug from the python 2 -> 3 conversion

I believe you are right. Feel free to propose a PR with a small fix and a test if you like the idea.

mindflayer commented 2 years ago

Here is a version including your fix, many thanks!

https://pypi.org/project/mocket/3.10.5/