11# coding=utf-8
22from __future__ import unicode_literals
33import socket
4- from collections import defaultdict
5- from io import BytesIO
6- from .compat import encode_utf8 , basestring , byte_type , text_type
74import collections
5+ from io import BytesIO
6+
87import decorator
98
9+ from .compat import encode_utf8 , basestring , byte_type , text_type
10+
1011__all__ = (
1112 'true_socket' ,
1213 'true_create_connection' ,
@@ -50,6 +51,7 @@ def __init__(self, family, type, proto=0):
5051 self ._sock = self
5152 self ._connected = False
5253 self ._buflen = 1024
54+ self ._entry = None
5355
5456 def setsockopt (self , level , optname , value ):
5557 if self .true_socket :
@@ -72,8 +74,11 @@ def makefile(self, mode='r', bufsize=-1):
7274 self ._bufsize = bufsize
7375 return self .fd
7476
77+ def get_entry (self , data ):
78+ return Mocket .get_entry (self ._host , self ._port , data )
79+
7580 def sendall (self , data , * args , ** kwargs ):
76- entry = Mocket .get_entry (self . _host , self . _port , data )
81+ entry = self .get_entry (data )
7782 if not entry :
7883 return self .true_sendall (data , * args , ** kwargs )
7984 entry .collect (data )
@@ -103,14 +108,22 @@ def true_sendall(self, data, *args, **kwargs):
103108 break
104109 self .fd .seek (- written , 1 )
105110
111+ def send (self , data , * args , ** kwargs ):
112+ entry = self .get_entry (data )
113+ if entry :
114+ if self ._entry != entry :
115+ self .sendall (data , * args , ** kwargs )
116+ self ._entry = entry
117+ return len (data )
118+
106119 def __getattr__ (self , name ):
107120 # useful when clients call methods on real
108121 # socket we do not provide on the fake one
109122 return getattr (self .true_socket , name )
110123
111124
112125class Mocket (object ):
113- _entries = defaultdict (list )
126+ _entries = collections . defaultdict (list )
114127 _requests = []
115128
116129 @classmethod
@@ -131,7 +144,7 @@ def collect(cls, data):
131144
132145 @classmethod
133146 def reset (cls ):
134- cls ._entries = defaultdict (list )
147+ cls ._entries = collections . defaultdict (list )
135148 cls ._requests = []
136149
137150 @classmethod
0 commit comments