简体   繁体   中英

How to test server sent events in python as client

I created a basic process for printing server sent events as the python client receives them. I will later change the state of the module depending on the coming data. Most of the examples are for testing the python side as the event emitter. I would like to use the python as the client.

#subscriber.py

class Subscriber():
    def __init__(self):

    def start_listening(self):
        messages = sseclient.SSEClient(SOME_URL_THAT_PUBLISHES_EVENT_STREAM)

        for event in messages:
            print(event)


I would like to test this but I could not find a way to mock streaming data that the sseclient uses. I tried to use responses library as below but it did not work out. I would like to at least see the prints of the given events when I test it. Is there a simple way to achieve this?


def test_subscriber():

    events = ["event1", "event2", "event3", "event4"]

    def sse_success(request):    
        headers = {'X-EventSource-Event': "new_event"}
    
        for event in events:
            time.sleep(3)
            yield 200, headers, {"data": event}


    responses.add_callback(
       responses.GET,
        SOME_URL_THAT_PUBLISHES_EVENT_STREAM,
        callback=sse_success
    )

    sub = Subscriber()
    sub.start_listening()

The subscriber class is blocking the python execution when it waits for messages. The easiest way to get around this is to run the subscriber from one process, and then in another process run a script which tests the subscriber

A better way to do this, in general, is to use an asynchronous library so that the subscriber is not blocking the python process whilst waiting for data. I have used pyzmq before - here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM