0

socketモジュール のいくつかのメソッドをラップする複雑なクラスをテストしたい: connectsendallおよび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ますか?

4

2 に答える 2

1

を使用してはsocket.socketpairどうですか?:

import socket

client, testsocket = socket.socketpair()
client.sendall("test_recv")
print testsocket.recv(1024)
testsocket.close()
client.close()

Unix でのみ使用できます。


使用するmock

import mock

testsocket = mock.Mock()
testsocket.configure_mock(**{'recv.return_value': 'test_recv'})
print testsocket.recv(1024)
于 2013-10-21T07:41:29.023 に答える