我想测试一个复杂的类,它包装了socket
模块的一些方法: connect
,sendall
和recv
. 特别是,我想测试recv
这个类的方法。
下面的工作示例代码显示了我如何做到这一点(以基本的底层形式保持简单,testsocket
将对应于复杂的包装类):
import socket
# This is just a socket for testing purposes, binds to the loopback device
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 1234))
sock.listen(5)
# This is the socket later part of the complex socket wrapper.
# It just contains calls to connect, sendall and recv
testsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
testsocket.connect(("127.0.0.1", 1234))
testsocket.sendall("test_send")
# The testing socket connects to a client
(client, adr) = sock.accept()
print client.recv(1024)
# Now I can do the actual test: Test the receive method of the socket
# wrapped in the complex class
client.sendall("test_recv")
print testsocket.recv(1024) # <-- This is what I want to test !!
# close everything
testsocket.close()
client.close()
sock.close()
但是为了测试testsocket.recv
我需要使用testsocket.sendall
之前。
是否可以以简单的方式(没有分叉或线程)修改此代码以便在testsocket.recv
不使用该方法的情况下进行测试testsocket.sendall
?