1
# Test just the SSL support in the socket module, in a moderately bogus way.
5
from test import test_support
15
warnings.filterwarnings(
17
'socket.ssl.. is deprecated. Use ssl.wrap_socket.. instead.',
20
# Optionally test SSL support, if we have it in the tested platform
21
skip_expected = not hasattr(socket, "ssl")
23
HOST = test_support.HOST
25
class ConnectedTests(unittest.TestCase):
27
def urlopen(self, host, *args, **kwargs):
28
# Connecting to remote hosts is flaky. Make it more robust
29
# by retrying the connection several times.
32
return urllib.urlopen(host, *args, **kwargs)
47
print "didn't raise TypeError"
48
socket.RAND_add("this is a random string", 75.0)
50
with test_support.transient_internet():
51
f = self.urlopen('https://sf.net')
55
def testTimeout(self):
56
def error_msg(extra_msg):
57
print >> sys.stderr, """\
58
WARNING: an attempt to connect to %r %s, in
59
testTimeout. That may be legitimate, but is not the outcome we
60
hoped for. If this message is seen often, testTimeout should be
61
changed to use a more reliable address.""" % (ADDR, extra_msg)
63
# A service which issues a welcome banner (without need to write
65
ADDR = "pop.gmail.com", 995
71
except socket.timeout:
72
error_msg('timed out')
74
except socket.error, exc: # In case connection is refused.
75
if exc.args[0] == errno.ECONNREFUSED:
76
error_msg('was refused')
82
# Read part of return welcome banner twice.
87
class BasicTests(unittest.TestCase):
89
def testRudeShutdown(self):
90
listener_ready = threading.Event()
91
listener_gone = threading.Event()
92
sock = socket.socket()
93
port = test_support.bind_port(sock)
95
# `listener` runs in a thread. It opens a socket and sits in accept()
96
# until the main thread connects. Then it rudely closes the socket,
97
# and sets Event `listener_gone` to let the main thread know the socket
103
s = None # reclaim the socket object, which also closes it
107
listener_ready.wait()
109
s.connect((HOST, port))
112
ssl_sock = socket.ssl(s)
113
except socket.sslerror:
116
raise test_support.TestFailed(
117
'connecting to closed SSL socket should have failed')
119
t = threading.Thread(target=listener, args=(sock,))
124
def connect(self, s, host_port):
125
# Connecting to remote hosts is flaky. Make it more robust
126
# by retrying the connection several times.
129
return s.connect(host_port)
137
def test_978833(self):
138
if not test_support.is_resource_enabled("network"):
140
if test_support.verbose:
141
print "test_978833 ..."
143
import os, httplib, ssl
144
with test_support.transient_internet():
145
s = socket.socket(socket.AF_INET)
147
self.connect(s, ("svn.python.org", 443))
149
print >> sys.stderr, """\
150
WARNING: an attempt to connect to svn.python.org:443 failed, in
151
test_978833. That may be legitimate, but is not the outcome we
152
hoped for. If this message is seen often, test_978833 should be
153
changed to use a more reliable address."""
155
fd = s._sock.fileno()
156
sock = ssl.wrap_socket(s)
164
raise test_support.TestFailed("Failed to close socket")
166
class OpenSSLTests(unittest.TestCase):
170
s.connect((HOST, OpenSSLServer.PORT))
174
self.assertEqual(i, "Foo\n")
177
def testMethods(self):
178
# read & write is already tried in the Basic test
179
# now we'll try to get the server info about certificates
180
# this came from the certificate I used, one I found in /usr/share/openssl
181
info = "/C=PT/ST=Queensland/L=Lisboa/O=Neuronio, Lda./OU=Desenvolvimento/CN=brutus.neuronio.pt/emailAddress=sampo@iki.fi"
184
s.connect((HOST, OpenSSLServer.PORT))
187
self.assertEqual(cert, info)
189
self.assertEqual(cert, info)
193
class OpenSSLServer(threading.Thread):
197
self.keepServing = True
200
threading.Thread.__init__(self)
203
# let's find the .pem files
204
curdir = os.path.dirname(__file__) or os.curdir
205
cert_file = os.path.join(curdir, "ssl_cert.pem")
206
if not os.access(cert_file, os.F_OK):
207
raise ValueError("No cert file found! (tried %r)" % cert_file)
208
key_file = os.path.join(curdir, "ssl_key.pem")
209
if not os.access(key_file, os.F_OK):
210
raise ValueError("No key file found! (tried %r)" % key_file)
213
# XXX TODO: on Windows, this should make more effort to use the
214
# openssl.exe that would have been built by the pcbuild.sln.
215
OpenSSLServer.PORT = test_support.find_unused_port()
216
args = (OpenSSLServer.PORT, cert_file, key_file)
217
cmd = "openssl s_server -accept %d -cert %s -key %s -quiet" % args
218
self.s = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE,
219
stdout=subprocess.PIPE,
220
stderr=subprocess.STDOUT)
223
self.haveServer = False
225
# let's try if it is actually up
228
s.connect((HOST, OpenSSLServer.PORT))
230
if self.s.stdout.readline() != "ERROR\n":
233
self.haveServer = False
235
self.haveServer = True
238
while self.keepServing:
240
l = self.s.stdout.readline()
241
self.s.stdin.write(l)
244
self.keepServing = False
247
if sys.platform == "win32":
248
subprocess.TerminateProcess(int(self.s._handle), -1)
250
os.kill(self.s.pid, 15)
253
if not hasattr(socket, "ssl"):
254
raise test_support.TestSkipped("socket module has no ssl support")
258
if test_support.is_resource_enabled('network'):
259
tests.append(ConnectedTests)
261
# in these platforms we can kill the openssl process
262
if sys.platform in ("sunos5", "darwin", "linux1",
263
"linux2", "win32", "hp-ux11"):
265
server = OpenSSLServer()
266
if server.haveServer:
267
tests.append(OpenSSLTests)
272
thread_info = test_support.threading_setup()
275
test_support.run_unittest(*tests)
277
if server is not None and server.haveServer:
280
test_support.threading_cleanup(*thread_info)
282
if __name__ == "__main__":