mindflayer / python-mocket

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

Server respond first upon client connect #196

Closed rbuckland closed 1 year ago

rbuckland commented 1 year ago

We have a real-world systm, where on tcp connect, the server responds first.

Is there a way to setup a "MocketEntry" that is fired on first connect. The behaviour i have observed is that an entry only comes after a client sends. This makes sense; we have the scenario to mock where the server talks first.

Below is an example. the example of course does not have to be asyncio.

import asyncio
import pytest
from mocket import Mocket, MocketEntry
from mocket.async_mocket import async_mocketize

@async_mocketize
@pytest.mark.asyncio
async def test_async_server_respond():

        async def process(reader, writer) -> str:
             return await reader.readline()

        addr = ('127.0.0.1', 9977)
        entry = MocketEntry(addr, [ b'hello' ])
        Mocket.register(entry)
        reader, writer = await asyncio.open_connection(addr[0], addr[1])
        result = None
        try:
            result = await asyncio.wait_for(process(reader, writer), timeout=2)
        except asyncio.TimeoutError as te:
            assert False, "timeout occurred"
        finally:
            writer.close()
        assert result == "hello"
        Mocket.assert_fail_if_entries_not_served()
mindflayer commented 1 year ago

Hi @rbuckland, I have the suspect that it won't be that easy. Every MocketEntry is bound to a request, which triggers it. So, depending on what data the client sends, Mocket understands if there's something to be served or it has to talk to a real socket instead. In your case there is nothing, because you expect Mocket to react straight after a connect(). You could try patching it and see what happens.