@@ -26,10 +26,8 @@ class CreationTestCase(unittest.TestCase):
26
26
"""Test case for socket.gettimeout() and socket.settimeout()"""
27
27
28
28
def setUp (self ):
29
- self .sock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
30
-
31
- def tearDown (self ):
32
- self .sock .close ()
29
+ self .sock = self .enterContext (
30
+ socket .socket (socket .AF_INET , socket .SOCK_STREAM ))
33
31
34
32
def testObjectCreation (self ):
35
33
# Test Socket creation
@@ -113,8 +111,6 @@ class TimeoutTestCase(unittest.TestCase):
113
111
def setUp (self ):
114
112
raise NotImplementedError ()
115
113
116
- tearDown = setUp
117
-
118
114
def _sock_operation (self , count , timeout , method , * args ):
119
115
"""
120
116
Test the specified socket method.
@@ -142,12 +138,10 @@ class TCPTimeoutTestCase(TimeoutTestCase):
142
138
"""TCP test case for socket.socket() timeout functions"""
143
139
144
140
def setUp (self ):
145
- self .sock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
141
+ self .sock = self .enterContext (
142
+ socket .socket (socket .AF_INET , socket .SOCK_STREAM ))
146
143
self .addr_remote = resolve_address ('www.python.org.' , 80 )
147
144
148
- def tearDown (self ):
149
- self .sock .close ()
150
-
151
145
def testConnectTimeout (self ):
152
146
# Testing connect timeout is tricky: we need to have IP connectivity
153
147
# to a host that silently drops our packets. We can't simulate this
@@ -190,19 +184,16 @@ def testConnectTimeout(self):
190
184
# for the current configuration.
191
185
192
186
skip = True
193
- sock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
194
- timeout = support .LOOPBACK_TIMEOUT
195
- sock .settimeout (timeout )
196
- try :
197
- sock .connect ((whitehole ))
198
- except TimeoutError :
199
- pass
200
- except OSError as err :
201
- if err .errno == errno .ECONNREFUSED :
202
- skip = False
203
- finally :
204
- sock .close ()
205
- del sock
187
+ with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as sock :
188
+ try :
189
+ timeout = support .LOOPBACK_TIMEOUT
190
+ sock .settimeout (timeout )
191
+ sock .connect ((whitehole ))
192
+ except TimeoutError :
193
+ pass
194
+ except OSError as err :
195
+ if err .errno == errno .ECONNREFUSED :
196
+ skip = False
206
197
207
198
if skip :
208
199
self .skipTest (
@@ -269,10 +260,8 @@ class UDPTimeoutTestCase(TimeoutTestCase):
269
260
"""UDP test case for socket.socket() timeout functions"""
270
261
271
262
def setUp (self ):
272
- self .sock = socket .socket (socket .AF_INET , socket .SOCK_DGRAM )
273
-
274
- def tearDown (self ):
275
- self .sock .close ()
263
+ self .sock = self .enterContext (
264
+ socket .socket (socket .AF_INET , socket .SOCK_DGRAM ))
276
265
277
266
def testRecvfromTimeout (self ):
278
267
# Test recvfrom() timeout
0 commit comments