jeudi 4 juin 2015

How to mock socket library's recvfrom in python?

I have the following code in python(sniffer.py) which sniffs for packet,

import socket 
#create an INET, raw socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

# receive a packet
while True:
    pkt = s.recvfrom(65565)
    process(pkt)

And I am writing a unit test for this piece of code, how do I mock the recvfrom function to return a dummy packet? This doesn't seem to work as I expected,

with patch('sniffer.socket.socket.recvfrom') as m_recvfrom:
    m_recvfrom.return_value = dummy_pkt

This just gives me a mock object and I am unable to access the dummy_pkt. How do I make this work?

Thanks!

Aucun commentaire:

Enregistrer un commentaire