code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_clientPresentsBadCertificate(self):
"""
When the server verifies and the client presents an invalid certificate
for that verification by passing it to
L{sslverify.optionsForClientTLS}, the connection cannot be established
with an SSL error.
"""
cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
u"valid.example.com",
u"valid.example.com",
validCertificate=True,
serverVerifies=True,
validClientCertificate=False,
clientPresentsCertificate=True,
)
self.assertEqual(cWrapped.data,
b'')
cErr = cWrapped.lostReason.value
sErr = sWrapped.lostReason.value
self.assertIsInstance(cErr, SSL.Error)
self.assertIsInstance(sErr, SSL.Error) | When the server verifies and the client presents an invalid certificate
for that verification by passing it to
L{sslverify.optionsForClientTLS}, the connection cannot be established
with an SSL error. | test_clientPresentsBadCertificate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_hostnameIsIndicated(self):
"""
Specifying the C{hostname} argument to L{CertificateOptions} also sets
the U{Server Name Extension
<https://en.wikipedia.org/wiki/Server_Name_Indication>} TLS indication
field to the correct value.
"""
names = []
def setupServerContext(ctx):
def servername_received(conn):
names.append(conn.get_servername().decode("ascii"))
ctx.set_tlsext_servername_callback(servername_received)
cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
u"valid.example.com",
u"valid.example.com",
setupServerContext
)
self.assertEqual(names, [u"valid.example.com"]) | Specifying the C{hostname} argument to L{CertificateOptions} also sets
the U{Server Name Extension
<https://en.wikipedia.org/wiki/Server_Name_Indication>} TLS indication
field to the correct value. | test_hostnameIsIndicated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_hostnameEncoding(self):
"""
Hostnames are encoded as IDNA.
"""
names = []
hello = u"h\N{LATIN SMALL LETTER A WITH ACUTE}llo.example.com"
def setupServerContext(ctx):
def servername_received(conn):
serverIDNA = _idnaText(conn.get_servername())
names.append(serverIDNA)
ctx.set_tlsext_servername_callback(servername_received)
cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
hello, hello, setupServerContext
)
self.assertEqual(names, [hello])
self.assertEqual(cWrapped.data,
b'greetings!')
cErr = cWrapped.lostReason
sErr = sWrapped.lostReason
self.assertIsNone(cErr)
self.assertIsNone(sErr) | Hostnames are encoded as IDNA. | test_hostnameEncoding | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def get_peer_certificate(self):
"""
Fake of L{OpenSSL.SSL.Connection.get_peer_certificate}.
@return: A certificate with a known common name.
@rtype: L{OpenSSL.crypto.X509}
"""
cert = X509()
cert.get_subject().commonName = name
return cert | Fake of L{OpenSSL.SSL.Connection.get_peer_certificate}.
@return: A certificate with a known common name.
@rtype: L{OpenSSL.crypto.X509} | test_fallback.get_peer_certificate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_fallback(self):
"""
L{sslverify.simpleVerifyHostname} checks string equality on the
commonName of a connection's certificate's subject, doing nothing if it
matches and raising L{VerificationError} if it doesn't.
"""
name = 'something.example.com'
class Connection(object):
def get_peer_certificate(self):
"""
Fake of L{OpenSSL.SSL.Connection.get_peer_certificate}.
@return: A certificate with a known common name.
@rtype: L{OpenSSL.crypto.X509}
"""
cert = X509()
cert.get_subject().commonName = name
return cert
conn = Connection()
self.assertIs(
sslverify.simpleVerifyHostname(conn, u'something.example.com'),
None
)
self.assertRaises(
sslverify.SimpleVerificationError,
sslverify.simpleVerifyHostname, conn, u'nonsense'
) | L{sslverify.simpleVerifyHostname} checks string equality on the
commonName of a connection's certificate's subject, doing nothing if it
matches and raising L{VerificationError} if it doesn't. | test_fallback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_surpriseFromInfoCallback(self):
"""
pyOpenSSL isn't always so great about reporting errors. If one occurs
in the verification info callback, it should be logged and the
connection should be shut down (if possible, anyway; the app_data could
be clobbered but there's no point testing for that).
"""
cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(
u"correct-host.example.com",
u"correct-host.example.com",
buggyInfoCallback=True,
)
self.assertEqual(cWrapped.data, b'')
self.assertEqual(sWrapped.data, b'')
cErr = cWrapped.lostReason.value
sErr = sWrapped.lostReason.value
self.assertIsInstance(cErr, ZeroDivisionError)
self.assertIsInstance(sErr, (ConnectionClosed, SSL.Error))
errors = self.flushLoggedErrors(ZeroDivisionError)
self.assertTrue(errors) | pyOpenSSL isn't always so great about reporting errors. If one occurs
in the verification info callback, it should be logged and the
connection should be shut down (if possible, anyway; the app_data could
be clobbered but there's no point testing for that). | test_surpriseFromInfoCallback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def negotiateProtocol(serverProtocols,
clientProtocols,
clientOptions=None):
"""
Create the TLS connection and negotiate a next protocol.
@param serverProtocols: The protocols the server is willing to negotiate.
@param clientProtocols: The protocols the client is willing to negotiate.
@param clientOptions: The type of C{OpenSSLCertificateOptions} class to
use for the client. Defaults to C{OpenSSLCertificateOptions}.
@return: A L{tuple} of the negotiated protocol and the reason the
connection was lost.
"""
caCertificate, serverCertificate = certificatesForAuthorityAndServer()
trustRoot = sslverify.OpenSSLCertificateAuthorities([
caCertificate.original,
])
sProto, cProto, sWrapped, cWrapped, pump = loopbackTLSConnectionInMemory(
trustRoot=trustRoot,
privateKey=serverCertificate.privateKey.original,
serverCertificate=serverCertificate.original,
clientProtocols=clientProtocols,
serverProtocols=serverProtocols,
clientOptions=clientOptions,
)
pump.flush()
return (cProto.negotiatedProtocol, cWrapped.lostReason) | Create the TLS connection and negotiate a next protocol.
@param serverProtocols: The protocols the server is willing to negotiate.
@param clientProtocols: The protocols the client is willing to negotiate.
@param clientOptions: The type of C{OpenSSLCertificateOptions} class to
use for the client. Defaults to C{OpenSSLCertificateOptions}.
@return: A L{tuple} of the negotiated protocol and the reason the
connection was lost. | negotiateProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_nextProtocolMechanismsNPNIsSupported(self):
"""
When at least NPN is available on the platform, NPN is in the set of
supported negotiation protocols.
"""
supportedProtocols = sslverify.protocolNegotiationMechanisms()
self.assertTrue(
sslverify.ProtocolNegotiationSupport.NPN in supportedProtocols
) | When at least NPN is available on the platform, NPN is in the set of
supported negotiation protocols. | test_nextProtocolMechanismsNPNIsSupported | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NPNAndALPNSuccess(self):
"""
When both ALPN and NPN are used, and both the client and server have
overlapping protocol choices, a protocol is successfully negotiated.
Further, the negotiated protocol is the first one in the list.
"""
protocols = [b'h2', b'http/1.1']
negotiatedProtocol, lostReason = negotiateProtocol(
clientProtocols=protocols,
serverProtocols=protocols,
)
self.assertEqual(negotiatedProtocol, b'h2')
self.assertIsNone(lostReason) | When both ALPN and NPN are used, and both the client and server have
overlapping protocol choices, a protocol is successfully negotiated.
Further, the negotiated protocol is the first one in the list. | test_NPNAndALPNSuccess | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NPNAndALPNDifferent(self):
"""
Client and server have different protocol lists: only the common
element is chosen.
"""
serverProtocols = [b'h2', b'http/1.1', b'spdy/2']
clientProtocols = [b'spdy/3', b'http/1.1']
negotiatedProtocol, lostReason = negotiateProtocol(
clientProtocols=clientProtocols,
serverProtocols=serverProtocols,
)
self.assertEqual(negotiatedProtocol, b'http/1.1')
self.assertIsNone(lostReason) | Client and server have different protocol lists: only the common
element is chosen. | test_NPNAndALPNDifferent | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NPNAndALPNNoAdvertise(self):
"""
When one peer does not advertise any protocols, the connection is set
up with no next protocol.
"""
protocols = [b'h2', b'http/1.1']
negotiatedProtocol, lostReason = negotiateProtocol(
clientProtocols=protocols,
serverProtocols=[],
)
self.assertIsNone(negotiatedProtocol)
self.assertIsNone(lostReason) | When one peer does not advertise any protocols, the connection is set
up with no next protocol. | test_NPNAndALPNNoAdvertise | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NPNAndALPNNoOverlap(self):
"""
When the client and server have no overlap of protocols, the connection
fails.
"""
clientProtocols = [b'h2', b'http/1.1']
serverProtocols = [b'spdy/3']
negotiatedProtocol, lostReason = negotiateProtocol(
serverProtocols=clientProtocols,
clientProtocols=serverProtocols,
)
self.assertIsNone(negotiatedProtocol)
self.assertEqual(lostReason.type, SSL.Error) | When the client and server have no overlap of protocols, the connection
fails. | test_NPNAndALPNNoOverlap | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_nextProtocolMechanismsALPNIsSupported(self):
"""
When ALPN is available on a platform, protocolNegotiationMechanisms
includes ALPN in the suported protocols.
"""
supportedProtocols = sslverify.protocolNegotiationMechanisms()
self.assertTrue(
sslverify.ProtocolNegotiationSupport.ALPN in
supportedProtocols
) | When ALPN is available on a platform, protocolNegotiationMechanisms
includes ALPN in the suported protocols. | test_nextProtocolMechanismsALPNIsSupported | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_nextProtocolMechanismsNoNegotiationSupported(self):
"""
When neither NPN or ALPN are available on a platform, there are no
supported negotiation protocols.
"""
supportedProtocols = sslverify.protocolNegotiationMechanisms()
self.assertFalse(supportedProtocols) | When neither NPN or ALPN are available on a platform, there are no
supported negotiation protocols. | test_nextProtocolMechanismsNoNegotiationSupported | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NPNAndALPNNotImplemented(self):
"""
A NotImplementedError is raised when using acceptableProtocols on a
platform that does not support either NPN or ALPN.
"""
protocols = [b'h2', b'http/1.1']
self.assertRaises(
NotImplementedError,
negotiateProtocol,
serverProtocols=protocols,
clientProtocols=protocols,
) | A NotImplementedError is raised when using acceptableProtocols on a
platform that does not support either NPN or ALPN. | test_NPNAndALPNNotImplemented | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_NegotiatedProtocolReturnsNone(self):
"""
negotiatedProtocol return L{None} even when NPN/ALPN aren't supported.
This works because, as neither are supported, negotiation isn't even
attempted.
"""
serverProtocols = None
clientProtocols = None
negotiatedProtocol, lostReason = negotiateProtocol(
clientProtocols=clientProtocols,
serverProtocols=serverProtocols,
)
self.assertIsNone(negotiatedProtocol)
self.assertIsNone(lostReason) | negotiatedProtocol return L{None} even when NPN/ALPN aren't supported.
This works because, as neither are supported, negotiation isn't even
attempted. | test_NegotiatedProtocolReturnsNone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_peerFromNonSSLTransport(self):
"""
Verify that peerFromTransport raises an exception if the transport
passed is not actually an SSL transport.
"""
x = self.assertRaises(CertificateError,
sslverify.Certificate.peerFromTransport,
_NotSSLTransport())
self.assertTrue(str(x).startswith("non-TLS")) | Verify that peerFromTransport raises an exception if the transport
passed is not actually an SSL transport. | test_peerFromNonSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_peerFromBlankSSLTransport(self):
"""
Verify that peerFromTransport raises an exception if the transport
passed is an SSL transport, but doesn't have a peer certificate.
"""
x = self.assertRaises(CertificateError,
sslverify.Certificate.peerFromTransport,
_MaybeSSLTransport())
self.assertTrue(str(x).startswith("TLS")) | Verify that peerFromTransport raises an exception if the transport
passed is an SSL transport, but doesn't have a peer certificate. | test_peerFromBlankSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_hostFromNonSSLTransport(self):
"""
Verify that hostFromTransport raises an exception if the transport
passed is not actually an SSL transport.
"""
x = self.assertRaises(CertificateError,
sslverify.Certificate.hostFromTransport,
_NotSSLTransport())
self.assertTrue(str(x).startswith("non-TLS")) | Verify that hostFromTransport raises an exception if the transport
passed is not actually an SSL transport. | test_hostFromNonSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_hostFromBlankSSLTransport(self):
"""
Verify that hostFromTransport raises an exception if the transport
passed is an SSL transport, but doesn't have a host certificate.
"""
x = self.assertRaises(CertificateError,
sslverify.Certificate.hostFromTransport,
_MaybeSSLTransport())
self.assertTrue(str(x).startswith("TLS")) | Verify that hostFromTransport raises an exception if the transport
passed is an SSL transport, but doesn't have a host certificate. | test_hostFromBlankSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_hostFromSSLTransport(self):
"""
Verify that hostFromTransport successfully creates the correct
certificate if passed a valid SSL transport.
"""
self.assertEqual(
sslverify.Certificate.hostFromTransport(
_ActualSSLTransport()).serialNumber(),
12345) | Verify that hostFromTransport successfully creates the correct
certificate if passed a valid SSL transport. | test_hostFromSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_peerFromSSLTransport(self):
"""
Verify that peerFromTransport successfully creates the correct
certificate if passed a valid SSL transport.
"""
self.assertEqual(
sslverify.Certificate.peerFromTransport(
_ActualSSLTransport()).serialNumber(),
12346) | Verify that peerFromTransport successfully creates the correct
certificate if passed a valid SSL transport. | test_peerFromSSLTransport | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_trustRootFromCertificatesPrivatePublic(self):
"""
L{trustRootFromCertificates} accepts either a L{sslverify.Certificate}
or a L{sslverify.PrivateCertificate} instance.
"""
privateCert = sslverify.PrivateCertificate.loadPEM(A_KEYPAIR)
cert = sslverify.Certificate.loadPEM(A_HOST_CERTIFICATE_PEM)
mt = sslverify.trustRootFromCertificates([privateCert, cert])
# Verify that the returned object acts correctly when used as a
# trustRoot= param to optionsForClientTLS.
sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
trustRoot=mt,
privateKey=privateCert.privateKey.original,
serverCertificate=privateCert.original,
)
# This connection should succeed
self.assertEqual(cWrap.data, b'greetings!')
self.assertIsNone(cWrap.lostReason) | L{trustRootFromCertificates} accepts either a L{sslverify.Certificate}
or a L{sslverify.PrivateCertificate} instance. | test_trustRootFromCertificatesPrivatePublic | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_trustRootSelfSignedServerCertificate(self):
"""
L{trustRootFromCertificates} called with a single self-signed
certificate will cause L{optionsForClientTLS} to accept client
connections to a server with that certificate.
"""
key, cert = makeCertificate(O=b"Server Test Certificate", CN=b"server")
selfSigned = sslverify.PrivateCertificate.fromCertificateAndKeyPair(
sslverify.Certificate(cert),
sslverify.KeyPair(key),
)
trust = sslverify.trustRootFromCertificates([selfSigned])
# Since we trust this exact certificate, connections to this server
# should succeed.
sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
trustRoot=trust,
privateKey=selfSigned.privateKey.original,
serverCertificate=selfSigned.original,
)
self.assertEqual(cWrap.data, b'greetings!')
self.assertIsNone(cWrap.lostReason) | L{trustRootFromCertificates} called with a single self-signed
certificate will cause L{optionsForClientTLS} to accept client
connections to a server with that certificate. | test_trustRootSelfSignedServerCertificate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_trustRootCertificateAuthorityTrustsConnection(self):
"""
L{trustRootFromCertificates} called with certificate A will cause
L{optionsForClientTLS} to accept client connections to a server with
certificate B where B is signed by A.
"""
caCert, serverCert = certificatesForAuthorityAndServer()
trust = sslverify.trustRootFromCertificates([caCert])
# Since we've listed the CA's certificate as a trusted cert, a
# connection to the server certificate it signed should succeed.
sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
trustRoot=trust,
privateKey=serverCert.privateKey.original,
serverCertificate=serverCert.original,
)
self.assertEqual(cWrap.data, b'greetings!')
self.assertIsNone(cWrap.lostReason) | L{trustRootFromCertificates} called with certificate A will cause
L{optionsForClientTLS} to accept client connections to a server with
certificate B where B is signed by A. | test_trustRootCertificateAuthorityTrustsConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_trustRootFromCertificatesUntrusted(self):
"""
L{trustRootFromCertificates} called with certificate A will cause
L{optionsForClientTLS} to disallow any connections to a server with
certificate B where B is not signed by A.
"""
key, cert = makeCertificate(O=b"Server Test Certificate", CN=b"server")
serverCert = sslverify.PrivateCertificate.fromCertificateAndKeyPair(
sslverify.Certificate(cert),
sslverify.KeyPair(key),
)
untrustedCert = sslverify.Certificate(
makeCertificate(O=b"CA Test Certificate", CN=b"unknown CA")[1]
)
trust = sslverify.trustRootFromCertificates([untrustedCert])
# Since we only trust 'untrustedCert' which has not signed our
# server's cert, we should reject this connection
sProto, cProto, sWrap, cWrap, pump = loopbackTLSConnectionInMemory(
trustRoot=trust,
privateKey=serverCert.privateKey.original,
serverCertificate=serverCert.original,
)
# This connection should fail, so no data was received.
self.assertEqual(cWrap.data, b'')
# It was an L{SSL.Error}.
self.assertEqual(cWrap.lostReason.type, SSL.Error)
# Some combination of OpenSSL and PyOpenSSL is bad at reporting errors.
err = cWrap.lostReason.value
self.assertEqual(err.args[0][0][2], 'tlsv1 alert unknown ca') | L{trustRootFromCertificates} called with certificate A will cause
L{optionsForClientTLS} to disallow any connections to a server with
certificate B where B is not signed by A. | test_trustRootFromCertificatesUntrusted | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_trustRootFromCertificatesOpenSSLObjects(self):
"""
L{trustRootFromCertificates} rejects any L{OpenSSL.crypto.X509}
instances in the list passed to it.
"""
private = sslverify.PrivateCertificate.loadPEM(A_KEYPAIR)
certX509 = private.original
exception = self.assertRaises(
TypeError,
sslverify.trustRootFromCertificates, [certX509],
)
self.assertEqual(
"certificates items must be twisted.internet.ssl.CertBase "
"instances",
exception.args[0],
) | L{trustRootFromCertificates} rejects any L{OpenSSL.crypto.X509}
instances in the list passed to it. | test_trustRootFromCertificatesOpenSSLObjects | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_constructorSetsFullName(self):
"""
The first argument passed to the constructor becomes the full name.
"""
self.assertEqual(
self.cipherName,
sslverify.OpenSSLCipher(self.cipherName).fullName
) | The first argument passed to the constructor becomes the full name. | test_constructorSetsFullName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_repr(self):
"""
C{repr(cipher)} returns a valid constructor call.
"""
cipher = sslverify.OpenSSLCipher(self.cipherName)
self.assertEqual(
cipher,
eval(repr(cipher), {'OpenSSLCipher': sslverify.OpenSSLCipher})
) | C{repr(cipher)} returns a valid constructor call. | test_repr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_eqSameClass(self):
"""
Equal type and C{fullName} means that the objects are equal.
"""
cipher1 = sslverify.OpenSSLCipher(self.cipherName)
cipher2 = sslverify.OpenSSLCipher(self.cipherName)
self.assertEqual(cipher1, cipher2) | Equal type and C{fullName} means that the objects are equal. | test_eqSameClass | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_eqSameNameDifferentType(self):
"""
If ciphers have the same name but different types, they're still
different.
"""
class DifferentCipher(object):
fullName = self.cipherName
self.assertNotEqual(
sslverify.OpenSSLCipher(self.cipherName),
DifferentCipher(),
) | If ciphers have the same name but different types, they're still
different. | test_eqSameNameDifferentType | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_doesNotStumbleOverEmptyList(self):
"""
If the expanded cipher list is empty, an empty L{list} is returned.
"""
self.assertEqual(
[],
sslverify._expandCipherString(u'', SSL.SSLv23_METHOD, 0)
) | If the expanded cipher list is empty, an empty L{list} is returned. | test_doesNotStumbleOverEmptyList | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_doesNotSwallowOtherSSLErrors(self):
"""
Only no cipher matches get swallowed, every other SSL error gets
propagated.
"""
def raiser(_):
# Unfortunately, there seems to be no way to trigger a real SSL
# error artificially.
raise SSL.Error([['', '', '']])
ctx = FakeContext(SSL.SSLv23_METHOD)
ctx.set_cipher_list = raiser
self.patch(sslverify.SSL, 'Context', lambda _: ctx)
self.assertRaises(
SSL.Error,
sslverify._expandCipherString, u'ALL', SSL.SSLv23_METHOD, 0
) | Only no cipher matches get swallowed, every other SSL error gets
propagated. | test_doesNotSwallowOtherSSLErrors | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_returnsListOfICiphers(self):
"""
L{sslverify._expandCipherString} always returns a L{list} of
L{interfaces.ICipher}.
"""
ciphers = sslverify._expandCipherString(u'ALL', SSL.SSLv23_METHOD, 0)
self.assertIsInstance(ciphers, list)
bogus = []
for c in ciphers:
if not interfaces.ICipher.providedBy(c):
bogus.append(c)
self.assertEqual([], bogus) | L{sslverify._expandCipherString} always returns a L{list} of
L{interfaces.ICipher}. | test_returnsListOfICiphers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_selectOnEmptyListReturnsEmptyList(self):
"""
If no ciphers are available, nothing can be selected.
"""
ac = sslverify.OpenSSLAcceptableCiphers([])
self.assertEqual([], ac.selectCiphers([])) | If no ciphers are available, nothing can be selected. | test_selectOnEmptyListReturnsEmptyList | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_selectReturnsOnlyFromAvailable(self):
"""
Select only returns a cross section of what is available and what is
desirable.
"""
ac = sslverify.OpenSSLAcceptableCiphers([
sslverify.OpenSSLCipher('A'),
sslverify.OpenSSLCipher('B'),
])
self.assertEqual([sslverify.OpenSSLCipher('B')],
ac.selectCiphers([sslverify.OpenSSLCipher('B'),
sslverify.OpenSSLCipher('C')])) | Select only returns a cross section of what is available and what is
desirable. | test_selectReturnsOnlyFromAvailable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_fromOpenSSLCipherStringExpandsToListOfCiphers(self):
"""
If L{sslverify.OpenSSLAcceptableCiphers.fromOpenSSLCipherString} is
called it expands the string to a list of ciphers.
"""
ac = sslverify.OpenSSLAcceptableCiphers.fromOpenSSLCipherString('ALL')
self.assertIsInstance(ac._ciphers, list)
self.assertTrue(all(sslverify.ICipher.providedBy(c)
for c in ac._ciphers)) | If L{sslverify.OpenSSLAcceptableCiphers.fromOpenSSLCipherString} is
called it expands the string to a list of ciphers. | test_fromOpenSSLCipherStringExpandsToListOfCiphers | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_fromFile(self):
"""
Calling C{fromFile} with a filename returns an instance with that file
name saved.
"""
params = sslverify.OpenSSLDiffieHellmanParameters.fromFile(
self.filePath
)
self.assertEqual(self.filePath, params._dhFile) | Calling C{fromFile} with a filename returns an instance with that file
name saved. | test_fromFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def SSL_CTX_set_ecdh_auto(self, ctx, value):
"""
Record the context and value under in the C{_state} instance
variable.
@see: L{FakeLibState}
@param ctx: An SSL context.
@type ctx: L{OpenSSL.SSL.Context}
@param value: A boolean value
@type value: L{bool}
"""
self._state.ecdhContexts.append(ctx)
self._state.ecdhValues.append(value)
if self._state.setECDHAutoRaises is not None:
raise self._state.setECDHAutoRaises | Record the context and value under in the C{_state} instance
variable.
@see: L{FakeLibState}
@param ctx: An SSL context.
@type ctx: L{OpenSSL.SSL.Context}
@param value: A boolean value
@type value: L{bool} | SSL_CTX_set_ecdh_auto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_SSL_CTX_set_ecdh_auto(self):
"""
L{FakeLib.SSL_CTX_set_ecdh_auto} records context and value it
was called with.
"""
state = FakeLibState(setECDHAutoRaises=None)
lib = FakeLib(state)
self.assertNot(state.ecdhContexts)
self.assertNot(state.ecdhValues)
context, value = "CONTEXT", True
lib.SSL_CTX_set_ecdh_auto(context, value)
self.assertEqual(state.ecdhContexts, [context])
self.assertEqual(state.ecdhValues, [True]) | L{FakeLib.SSL_CTX_set_ecdh_auto} records context and value it
was called with. | test_SSL_CTX_set_ecdh_auto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_SSL_CTX_set_ecdh_autoRaises(self):
"""
L{FakeLib.SSL_CTX_set_ecdh_auto} raises the exception provided
by its state, while still recording its arguments.
"""
state = FakeLibState(setECDHAutoRaises=ValueError)
lib = FakeLib(state)
self.assertNot(state.ecdhContexts)
self.assertNot(state.ecdhValues)
context, value = "CONTEXT", True
self.assertRaises(
ValueError, lib.SSL_CTX_set_ecdh_auto, context, value
)
self.assertEqual(state.ecdhContexts, [context])
self.assertEqual(state.ecdhValues, [True]) | L{FakeLib.SSL_CTX_set_ecdh_auto} raises the exception provided
by its state, while still recording its arguments. | test_SSL_CTX_set_ecdh_autoRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def get_elliptic_curve(self, curve):
"""
A fake that records the curve with which it was called.
@param curve: see L{crypto.get_elliptic_curve}
@return: see L{FakeCryptoState.getEllipticCurveReturns}
@raises: see L{FakeCryptoState.getEllipticCurveRaises}
"""
self._state.getEllipticCurveCalls.append(curve)
if self._state.getEllipticCurveRaises is not None:
raise self._state.getEllipticCurveRaises
return self._state.getEllipticCurveReturns | A fake that records the curve with which it was called.
@param curve: see L{crypto.get_elliptic_curve}
@return: see L{FakeCryptoState.getEllipticCurveReturns}
@raises: see L{FakeCryptoState.getEllipticCurveRaises} | get_elliptic_curve | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_get_elliptic_curveRecordsArgument(self):
"""
L{FakeCrypto.test_get_elliptic_curve} records the curve with
which it was called.
"""
state = FakeCryptoState(
getEllipticCurveRaises=None,
getEllipticCurveReturns=None,
)
crypto = FakeCrypto(state)
crypto.get_elliptic_curve("a curve name")
self.assertEqual(state.getEllipticCurveCalls, ["a curve name"]) | L{FakeCrypto.test_get_elliptic_curve} records the curve with
which it was called. | test_get_elliptic_curveRecordsArgument | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_get_elliptic_curveReturns(self):
"""
L{FakeCrypto.test_get_elliptic_curve} returns the value
specified by its state object and records what it was called
with.
"""
returnValue = "object"
state = FakeCryptoState(
getEllipticCurveRaises=None,
getEllipticCurveReturns=returnValue,
)
crypto = FakeCrypto(state)
self.assertIs(
crypto.get_elliptic_curve("another curve name"),
returnValue,
)
self.assertEqual(
state.getEllipticCurveCalls,
["another curve name"]
) | L{FakeCrypto.test_get_elliptic_curve} returns the value
specified by its state object and records what it was called
with. | test_get_elliptic_curveReturns | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_get_elliptic_curveRaises(self):
"""
L{FakeCrypto.test_get_elliptic_curve} raises the exception
specified by its state object.
"""
state = FakeCryptoState(
getEllipticCurveRaises=ValueError,
getEllipticCurveReturns=None
)
crypto = FakeCrypto(state)
self.assertRaises(
ValueError,
crypto.get_elliptic_curve, "yet another curve name",
)
self.assertEqual(
state.getEllipticCurveCalls,
["yet another curve name"],
) | L{FakeCrypto.test_get_elliptic_curve} raises the exception
specified by its state object. | test_get_elliptic_curveRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL110(self):
"""
No configuration of contexts occurs under OpenSSL 1.1.0 and
later, because they create contexts with secure ECDH curves.
@see: U{http://twistedmatrix.com/trac/ticket/9210}
"""
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_110,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(self.context)
self.assertFalse(self.libState.ecdhContexts)
self.assertFalse(self.libState.ecdhValues)
self.assertFalse(self.cryptoState.getEllipticCurveCalls)
self.assertIsNone(self.context._ecCurve) | No configuration of contexts occurs under OpenSSL 1.1.0 and
later, because they create contexts with secure ECDH curves.
@see: U{http://twistedmatrix.com/trac/ticket/9210} | test_openSSL110 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL102(self):
"""
OpenSSL 1.0.2 does not set ECDH curves by default, but
C{SSL_CTX_set_ecdh_auto} requests that a context choose a
secure set curves automatically.
"""
context = SSL.Context(SSL.SSLv23_METHOD)
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_102,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(context)
self.assertEqual(self.libState.ecdhContexts, [context._context])
self.assertEqual(self.libState.ecdhValues, [True])
self.assertFalse(self.cryptoState.getEllipticCurveCalls)
self.assertIsNone(self.context._ecCurve) | OpenSSL 1.0.2 does not set ECDH curves by default, but
C{SSL_CTX_set_ecdh_auto} requests that a context choose a
secure set curves automatically. | test_openSSL102 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL102SetECDHAutoRaises(self):
"""
An exception raised by C{SSL_CTX_set_ecdh_auto} under OpenSSL
1.0.2 is suppressed because ECDH is best-effort.
"""
self.libState.setECDHAutoRaises = BaseException
context = SSL.Context(SSL.SSLv23_METHOD)
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_102,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(context)
self.assertEqual(self.libState.ecdhContexts, [context._context])
self.assertEqual(self.libState.ecdhValues, [True])
self.assertFalse(self.cryptoState.getEllipticCurveCalls) | An exception raised by C{SSL_CTX_set_ecdh_auto} under OpenSSL
1.0.2 is suppressed because ECDH is best-effort. | test_openSSL102SetECDHAutoRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL101(self):
"""
OpenSSL 1.0.1 does not set ECDH curves by default, nor does
it expose L{SSL_CTX_set_ecdh_auto}. Instead, a single ECDH
curve can be set with L{OpenSSL.SSL.Context.set_tmp_ecdh}.
"""
self.cryptoState.getEllipticCurveReturns = curve = "curve object"
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_101,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(self.context)
self.assertFalse(self.libState.ecdhContexts)
self.assertFalse(self.libState.ecdhValues)
self.assertEqual(
self.cryptoState.getEllipticCurveCalls,
[sslverify._defaultCurveName],
)
self.assertIs(self.context._ecCurve, curve) | OpenSSL 1.0.1 does not set ECDH curves by default, nor does
it expose L{SSL_CTX_set_ecdh_auto}. Instead, a single ECDH
curve can be set with L{OpenSSL.SSL.Context.set_tmp_ecdh}. | test_openSSL101 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL101SetECDHRaises(self):
"""
An exception raised by L{OpenSSL.SSL.Context.set_tmp_ecdh}
under OpenSSL 1.0.1 is suppressed because ECHDE is best-effort.
"""
def set_tmp_ecdh(ctx):
raise BaseException
self.context.set_tmp_ecdh = set_tmp_ecdh
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_101,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(self.context)
self.assertFalse(self.libState.ecdhContexts)
self.assertFalse(self.libState.ecdhValues)
self.assertEqual(
self.cryptoState.getEllipticCurveCalls,
[sslverify._defaultCurveName],
) | An exception raised by L{OpenSSL.SSL.Context.set_tmp_ecdh}
under OpenSSL 1.0.1 is suppressed because ECHDE is best-effort. | test_openSSL101SetECDHRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_openSSL101NoECC(self):
"""
Contexts created under an OpenSSL 1.0.1 that doesn't support
ECC have no configuration applied.
"""
self.cryptoState.getEllipticCurveRaises = ValueError
chooser = sslverify._ChooseDiffieHellmanEllipticCurve(
self.OPENSSL_101,
openSSLlib=self.lib,
openSSLcrypto=self.crypto,
)
chooser.configureECDHCurve(self.context)
self.assertFalse(self.libState.ecdhContexts)
self.assertFalse(self.libState.ecdhValues)
self.assertIsNone(self.context._ecCurve) | Contexts created under an OpenSSL 1.0.1 that doesn't support
ECC have no configuration applied. | test_openSSL101NoECC | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def setUp(self):
"""
Create test certificate.
"""
self.sKey = makeCertificate(
O=b"Server Test Certificate",
CN=b"server")[0] | Create test certificate. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_getstateDeprecation(self):
"""
L{sslverify.KeyPair.__getstate__} is deprecated.
"""
self.callDeprecated(
(Version("Twisted", 15, 0, 0), "a real persistence system"),
sslverify.KeyPair(self.sKey).__getstate__) | L{sslverify.KeyPair.__getstate__} is deprecated. | test_getstateDeprecation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_setstateDeprecation(self):
"""
{sslverify.KeyPair.__setstate__} is deprecated.
"""
state = sslverify.KeyPair(self.sKey).dump()
self.callDeprecated(
(Version("Twisted", 15, 0, 0), "a real persistence system"),
sslverify.KeyPair(self.sKey).__setstate__, state) | {sslverify.KeyPair.__setstate__} is deprecated. | test_setstateDeprecation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_dependencyMissing(self):
"""
If I{service_identity} cannot be imported then
L{_selectVerifyImplementation} returns L{simpleVerifyHostname} and
L{SimpleVerificationError}.
"""
with SetAsideModule("service_identity"):
sys.modules["service_identity"] = None
result = sslverify._selectVerifyImplementation()
expected = (
sslverify.simpleVerifyHostname,
sslverify.simpleVerifyIPAddress,
sslverify.SimpleVerificationError)
self.assertEqual(expected, result) | If I{service_identity} cannot be imported then
L{_selectVerifyImplementation} returns L{simpleVerifyHostname} and
L{SimpleVerificationError}. | test_dependencyMissing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_dependencyMissingWarning(self):
"""
If I{service_identity} cannot be imported then
L{_selectVerifyImplementation} emits a L{UserWarning} advising the user
of the exact error.
"""
with SetAsideModule("service_identity"):
sys.modules["service_identity"] = None
sslverify._selectVerifyImplementation()
[warning] = list(
warning
for warning
in self.flushWarnings()
if warning["category"] == UserWarning)
importErrors = [
# Python 3.6.3
"'import of service_identity halted; None in sys.modules'",
# Python 3
"'import of 'service_identity' halted; None in sys.modules'",
# Python 2
"'No module named service_identity'"
]
expectedMessages = []
for importError in importErrors:
expectedMessages.append(
"You do not have a working installation of the "
"service_identity module: {message}. Please install it from "
"<https://pypi.python.org/pypi/service_identity> "
"and make sure all of its dependencies are satisfied. "
"Without the service_identity module, Twisted can perform only"
" rudimentary TLS client hostname verification. Many valid "
"certificate/hostname mappings may be rejected.".format(
message=importError))
self.assertIn(warning["message"], expectedMessages)
# Make sure we're abusing the warning system to a sufficient
# degree: there is no filename or line number that makes sense for
# this warning to "blame" for the problem. It is a system
# misconfiguration. So the location information should be blank
# (or as blank as we can make it).
self.assertEqual(warning["filename"], "")
self.assertEqual(warning["lineno"], 0) | If I{service_identity} cannot be imported then
L{_selectVerifyImplementation} emits a L{UserWarning} advising the user
of the exact error. | test_dependencyMissingWarning | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_sslverify.py | MIT |
def test_connectionSerial(self):
"""
Each L{FakeTransport} receives a serial number that uniquely identifies
it.
"""
a = FakeTransport(object(), True)
b = FakeTransport(object(), False)
self.assertIsInstance(a.serial, int)
self.assertIsInstance(b.serial, int)
self.assertNotEqual(a.serial, b.serial) | Each L{FakeTransport} receives a serial number that uniquely identifies
it. | test_connectionSerial | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_writeSequence(self):
"""
L{FakeTransport.writeSequence} will write a sequence of L{bytes} to the
transport.
"""
a = FakeTransport(object(), False)
a.write(b"a")
a.writeSequence([b"b", b"c", b"d"])
self.assertEqual(b"".join(a.stream), b"abcd") | L{FakeTransport.writeSequence} will write a sequence of L{bytes} to the
transport. | test_writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_writeAfterClose(self):
"""
L{FakeTransport.write} will accept writes after transport was closed,
but the data will be silently discarded.
"""
a = FakeTransport(object(), False)
a.write(b"before")
a.loseConnection()
a.write(b"after")
self.assertEqual(b"".join(a.stream), b"before") | L{FakeTransport.write} will accept writes after transport was closed,
but the data will be silently discarded. | test_writeAfterClose | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def _initial(self):
"""
@return: A new L{StrictPushProducer} which has not been through any state
changes.
"""
return StrictPushProducer() | @return: A new L{StrictPushProducer} which has not been through any state
changes. | _initial | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def _stopped(self):
"""
@return: A new, stopped L{StrictPushProducer}.
"""
producer = StrictPushProducer()
producer.stopProducing()
return producer | @return: A new, stopped L{StrictPushProducer}. | _stopped | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def _paused(self):
"""
@return: A new, paused L{StrictPushProducer}.
"""
producer = StrictPushProducer()
producer.pauseProducing()
return producer | @return: A new, paused L{StrictPushProducer}. | _paused | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def _resumed(self):
"""
@return: A new L{StrictPushProducer} which has been paused and resumed.
"""
producer = StrictPushProducer()
producer.pauseProducing()
producer.resumeProducing()
return producer | @return: A new L{StrictPushProducer} which has been paused and resumed. | _resumed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def assertStopped(self, producer):
"""
Assert that the given producer is in the stopped state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer}
"""
self.assertEqual(producer._state, u"stopped") | Assert that the given producer is in the stopped state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer} | assertStopped | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def assertPaused(self, producer):
"""
Assert that the given producer is in the paused state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer}
"""
self.assertEqual(producer._state, u"paused") | Assert that the given producer is in the paused state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer} | assertPaused | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def assertRunning(self, producer):
"""
Assert that the given producer is in the running state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer}
"""
self.assertEqual(producer._state, u"running") | Assert that the given producer is in the running state.
@param producer: The producer to verify.
@type producer: L{StrictPushProducer} | assertRunning | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_stopThenStop(self):
"""
L{StrictPushProducer.stopProducing} raises L{ValueError} if called when
the producer is stopped.
"""
self.assertRaises(ValueError, self._stopped().stopProducing) | L{StrictPushProducer.stopProducing} raises L{ValueError} if called when
the producer is stopped. | test_stopThenStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_stopThenPause(self):
"""
L{StrictPushProducer.pauseProducing} raises L{ValueError} if called when
the producer is stopped.
"""
self.assertRaises(ValueError, self._stopped().pauseProducing) | L{StrictPushProducer.pauseProducing} raises L{ValueError} if called when
the producer is stopped. | test_stopThenPause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_stopThenResume(self):
"""
L{StrictPushProducer.resumeProducing} raises L{ValueError} if called when
the producer is stopped.
"""
self.assertRaises(ValueError, self._stopped().resumeProducing) | L{StrictPushProducer.resumeProducing} raises L{ValueError} if called when
the producer is stopped. | test_stopThenResume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_pauseThenStop(self):
"""
L{StrictPushProducer} is stopped if C{stopProducing} is called on a paused
producer.
"""
producer = self._paused()
producer.stopProducing()
self.assertStopped(producer) | L{StrictPushProducer} is stopped if C{stopProducing} is called on a paused
producer. | test_pauseThenStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_pauseThenPause(self):
"""
L{StrictPushProducer.pauseProducing} raises L{ValueError} if called on a
paused producer.
"""
producer = self._paused()
self.assertRaises(ValueError, producer.pauseProducing) | L{StrictPushProducer.pauseProducing} raises L{ValueError} if called on a
paused producer. | test_pauseThenPause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_pauseThenResume(self):
"""
L{StrictPushProducer} is resumed if C{resumeProducing} is called on a
paused producer.
"""
producer = self._paused()
producer.resumeProducing()
self.assertRunning(producer) | L{StrictPushProducer} is resumed if C{resumeProducing} is called on a
paused producer. | test_pauseThenResume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_resumeThenStop(self):
"""
L{StrictPushProducer} is stopped if C{stopProducing} is called on a
resumed producer.
"""
producer = self._resumed()
producer.stopProducing()
self.assertStopped(producer) | L{StrictPushProducer} is stopped if C{stopProducing} is called on a
resumed producer. | test_resumeThenStop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_resumeThenPause(self):
"""
L{StrictPushProducer} is paused if C{pauseProducing} is called on a
resumed producer.
"""
producer = self._resumed()
producer.pauseProducing()
self.assertPaused(producer) | L{StrictPushProducer} is paused if C{pauseProducing} is called on a
resumed producer. | test_resumeThenPause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_resumeThenResume(self):
"""
L{StrictPushProducer.resumeProducing} raises L{ValueError} if called on a
resumed producer.
"""
producer = self._resumed()
self.assertRaises(ValueError, producer.resumeProducing) | L{StrictPushProducer.resumeProducing} raises L{ValueError} if called on a
resumed producer. | test_resumeThenResume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_stop(self):
"""
L{StrictPushProducer} is stopped if C{stopProducing} is called in the
initial state.
"""
producer = self._initial()
producer.stopProducing()
self.assertStopped(producer) | L{StrictPushProducer} is stopped if C{stopProducing} is called in the
initial state. | test_stop | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_pause(self):
"""
L{StrictPushProducer} is paused if C{pauseProducing} is called in the
initial state.
"""
producer = self._initial()
producer.pauseProducing()
self.assertPaused(producer) | L{StrictPushProducer} is paused if C{pauseProducing} is called in the
initial state. | test_pause | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_resume(self):
"""
L{StrictPushProducer} raises L{ValueError} if C{resumeProducing} is called
in the initial state.
"""
producer = self._initial()
self.assertRaises(ValueError, producer.resumeProducing) | L{StrictPushProducer} raises L{ValueError} if C{resumeProducing} is called
in the initial state. | test_resume | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def _testStreamingProducer(self, mode):
"""
Connect a couple protocol/transport pairs to an L{IOPump} and then pump
it. Verify that a streaming producer registered with one of the
transports does not receive invalid L{IPushProducer} method calls and
ends in the right state.
@param mode: C{u"server"} to test a producer registered with the
server transport. C{u"client"} to test a producer registered with
the client transport.
"""
serverProto = Protocol()
serverTransport = FakeTransport(serverProto, isServer=True)
clientProto = Protocol()
clientTransport = FakeTransport(clientProto, isServer=False)
pump = connect(
serverProto, serverTransport,
clientProto, clientTransport,
greet=False,
)
producer = StrictPushProducer()
victim = {
u"server": serverTransport,
u"client": clientTransport,
}[mode]
victim.registerProducer(producer, streaming=True)
pump.pump()
self.assertEqual(u"running", producer._state) | Connect a couple protocol/transport pairs to an L{IOPump} and then pump
it. Verify that a streaming producer registered with one of the
transports does not receive invalid L{IPushProducer} method calls and
ends in the right state.
@param mode: C{u"server"} to test a producer registered with the
server transport. C{u"client"} to test a producer registered with
the client transport. | _testStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_serverStreamingProducer(self):
"""
L{IOPump.pump} does not call C{resumeProducing} on a L{IPushProducer}
(stream producer) registered with the server transport.
"""
self._testStreamingProducer(mode=u"server") | L{IOPump.pump} does not call C{resumeProducing} on a L{IPushProducer}
(stream producer) registered with the server transport. | test_serverStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def test_clientStreamingProducer(self):
"""
L{IOPump.pump} does not call C{resumeProducing} on a L{IPushProducer}
(stream producer) registered with the client transport.
"""
self._testStreamingProducer(mode=u"client") | L{IOPump.pump} does not call C{resumeProducing} on a L{IPushProducer}
(stream producer) registered with the client transport. | test_clientStreamingProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_iosim.py | MIT |
def findByIteration(self, modname, where=modules, importPackages=False):
"""
You don't ever actually want to do this, so it's not in the public
API, but sometimes we want to compare the result of an iterative call
with a lookup call and make sure they're the same for test purposes.
"""
for modinfo in where.walkModules(importPackages=importPackages):
if modinfo.name == modname:
return modinfo
self.fail("Unable to find module %r through iteration." % (modname,)) | You don't ever actually want to do this, so it's not in the public
API, but sometimes we want to compare the result of an iterative call
with a lookup call and make sure they're the same for test purposes. | findByIteration | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_namespacedPackages(self):
"""
Duplicate packages are not yielded when iterating over namespace
packages.
"""
# Force pkgutil to be loaded already, since the probe package being
# created depends on it, and the replaceSysPath call below will make
# pretty much everything unimportable.
__import__('pkgutil')
namespaceBoilerplate = (
b'import pkgutil; '
b'__path__ = pkgutil.extend_path(__path__, __name__)')
# Create two temporary directories with packages:
#
# entry:
# test_package/
# __init__.py
# nested_package/
# __init__.py
# module.py
#
# anotherEntry:
# test_package/
# __init__.py
# nested_package/
# __init__.py
# module2.py
#
# test_package and test_package.nested_package are namespace packages,
# and when both of these are in sys.path, test_package.nested_package
# should become a virtual package containing both "module" and
# "module2"
entry = self.pathEntryWithOnePackage()
testPackagePath = entry.child('test_package')
testPackagePath.child('__init__.py').setContent(namespaceBoilerplate)
nestedEntry = testPackagePath.child('nested_package')
nestedEntry.makedirs()
nestedEntry.child('__init__.py').setContent(namespaceBoilerplate)
nestedEntry.child('module.py').setContent(b'')
anotherEntry = self.pathEntryWithOnePackage()
anotherPackagePath = anotherEntry.child('test_package')
anotherPackagePath.child('__init__.py').setContent(namespaceBoilerplate)
anotherNestedEntry = anotherPackagePath.child('nested_package')
anotherNestedEntry.makedirs()
anotherNestedEntry.child('__init__.py').setContent(namespaceBoilerplate)
anotherNestedEntry.child('module2.py').setContent(b'')
self.replaceSysPath([entry.path, anotherEntry.path])
module = modules.getModule('test_package')
# We have to use importPackages=True in order to resolve the namespace
# packages, so we remove the imported packages from sys.modules after
# walking
try:
walkedNames = [
mod.name for mod in module.walkModules(importPackages=True)]
finally:
for module in list(sys.modules.keys()):
if module.startswith('test_package'):
del sys.modules[module]
expected = [
'test_package',
'test_package.nested_package',
'test_package.nested_package.module',
'test_package.nested_package.module2',
]
self.assertEqual(walkedNames, expected) | Duplicate packages are not yielded when iterating over namespace
packages. | test_namespacedPackages | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_unimportablePackageGetItem(self):
"""
If a package has been explicitly forbidden from importing by setting a
L{None} key in sys.modules under its name,
L{modules.PythonPath.__getitem__} should still be able to retrieve an
unloaded L{modules.PythonModule} for that package.
"""
shouldNotLoad = []
path = modules.PythonPath(sysPath=[self.pathEntryWithOnePackage().path],
moduleLoader=shouldNotLoad.append,
importerCache={},
sysPathHooks={},
moduleDict={'test_package': None})
self.assertEqual(shouldNotLoad, [])
self.assertFalse(path['test_package'].isLoaded()) | If a package has been explicitly forbidden from importing by setting a
L{None} key in sys.modules under its name,
L{modules.PythonPath.__getitem__} should still be able to retrieve an
unloaded L{modules.PythonModule} for that package. | test_unimportablePackageGetItem | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_unimportablePackageWalkModules(self):
"""
If a package has been explicitly forbidden from importing by setting a
L{None} key in sys.modules under its name, L{modules.walkModules} should
still be able to retrieve an unloaded L{modules.PythonModule} for that
package.
"""
existentPath = self.pathEntryWithOnePackage()
self.replaceSysPath([existentPath.path])
self.replaceSysModules({"test_package": None})
walked = list(modules.walkModules())
self.assertEqual([m.name for m in walked],
["test_package"])
self.assertFalse(walked[0].isLoaded()) | If a package has been explicitly forbidden from importing by setting a
L{None} key in sys.modules under its name, L{modules.walkModules} should
still be able to retrieve an unloaded L{modules.PythonModule} for that
package. | test_unimportablePackageWalkModules | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_nonexistentPaths(self):
"""
Verify that L{modules.walkModules} ignores entries in sys.path which
do not exist in the filesystem.
"""
existentPath = self.pathEntryWithOnePackage()
nonexistentPath = FilePath(self.mktemp())
self.assertFalse(nonexistentPath.exists())
self.replaceSysPath([existentPath.path])
expected = [modules.getModule("test_package")]
beforeModules = list(modules.walkModules())
sys.path.append(nonexistentPath.path)
afterModules = list(modules.walkModules())
self.assertEqual(beforeModules, expected)
self.assertEqual(afterModules, expected) | Verify that L{modules.walkModules} ignores entries in sys.path which
do not exist in the filesystem. | test_nonexistentPaths | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_nonDirectoryPaths(self):
"""
Verify that L{modules.walkModules} ignores entries in sys.path which
refer to regular files in the filesystem.
"""
existentPath = self.pathEntryWithOnePackage()
nonDirectoryPath = FilePath(self.mktemp())
self.assertFalse(nonDirectoryPath.exists())
nonDirectoryPath.setContent(b"zip file or whatever\n")
self.replaceSysPath([existentPath.path])
beforeModules = list(modules.walkModules())
sys.path.append(nonDirectoryPath.path)
afterModules = list(modules.walkModules())
self.assertEqual(beforeModules, afterModules) | Verify that L{modules.walkModules} ignores entries in sys.path which
refer to regular files in the filesystem. | test_nonDirectoryPaths | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_twistedShowsUp(self):
"""
Scrounge around in the top-level module namespace and make sure that
Twisted shows up, and that the module thusly obtained is the same as
the module that we find when we look for it explicitly by name.
"""
self.assertEqual(modules.getModule('twisted'),
self.findByIteration("twisted")) | Scrounge around in the top-level module namespace and make sure that
Twisted shows up, and that the module thusly obtained is the same as
the module that we find when we look for it explicitly by name. | test_twistedShowsUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_dottedNames(self):
"""
Verify that the walkModules APIs will give us back subpackages, not just
subpackages.
"""
self.assertEqual(
modules.getModule('twisted.python'),
self.findByIteration("twisted.python",
where=modules.getModule('twisted'))) | Verify that the walkModules APIs will give us back subpackages, not just
subpackages. | test_dottedNames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_onlyTopModules(self):
"""
Verify that the iterModules API will only return top-level modules and
packages, not submodules or subpackages.
"""
for module in modules.iterModules():
self.assertFalse(
'.' in module.name,
"no nested modules should be returned from iterModules: %r"
% (module.filePath)) | Verify that the iterModules API will only return top-level modules and
packages, not submodules or subpackages. | test_onlyTopModules | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_loadPackagesAndModules(self):
"""
Verify that we can locate and load packages, modules, submodules, and
subpackages.
"""
for n in ['os',
'twisted',
'twisted.python',
'twisted.python.reflect']:
m = namedAny(n)
self.failUnlessIdentical(
modules.getModule(n).load(),
m)
self.failUnlessIdentical(
self.findByIteration(n).load(),
m) | Verify that we can locate and load packages, modules, submodules, and
subpackages. | test_loadPackagesAndModules | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_pathEntriesOnPath(self):
"""
Verify that path entries discovered via module loading are, in fact, on
sys.path somewhere.
"""
for n in ['os',
'twisted',
'twisted.python',
'twisted.python.reflect']:
self.failUnlessIn(
modules.getModule(n).pathEntry.filePath.path,
sys.path) | Verify that path entries discovered via module loading are, in fact, on
sys.path somewhere. | test_pathEntriesOnPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_alwaysPreferPy(self):
"""
Verify that .py files will always be preferred to .pyc files, regardless of
directory listing order.
"""
mypath = FilePath(self.mktemp())
mypath.createDirectory()
pp = modules.PythonPath(sysPath=[mypath.path])
originalSmartPath = pp._smartPath
def _evilSmartPath(pathName):
o = originalSmartPath(pathName)
originalChildren = o.children
def evilChildren():
# normally this order is random; let's make sure it always
# comes up .pyc-first.
x = list(originalChildren())
x.sort()
x.reverse()
return x
o.children = evilChildren
return o
mypath.child("abcd.py").setContent(b'\n')
compileall.compile_dir(mypath.path, quiet=True)
# sanity check
self.assertEqual(len(list(mypath.children())), 2)
pp._smartPath = _evilSmartPath
self.assertEqual(pp['abcd'].filePath,
mypath.child('abcd.py')) | Verify that .py files will always be preferred to .pyc files, regardless of
directory listing order. | test_alwaysPreferPy | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_packageMissingPath(self):
"""
A package can delete its __path__ for some reasons,
C{modules.PythonPath} should be able to deal with it.
"""
mypath = FilePath(self.mktemp())
mypath.createDirectory()
pp = modules.PythonPath(sysPath=[mypath.path])
subpath = mypath.child("abcd")
subpath.createDirectory()
subpath.child("__init__.py").setContent(b'del __path__\n')
sys.path.append(mypath.path)
__import__("abcd")
try:
l = list(pp.walkModules())
self.assertEqual(len(l), 1)
self.assertEqual(l[0].name, 'abcd')
finally:
del sys.modules['abcd']
sys.path.remove(mypath.path) | A package can delete its __path__ for some reasons,
C{modules.PythonPath} should be able to deal with it. | test_packageMissingPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_underUnderPathAlreadyImported(self):
"""
Verify that iterModules will honor the __path__ of already-loaded packages.
"""
self._underUnderPathTest() | Verify that iterModules will honor the __path__ of already-loaded packages. | test_underUnderPathAlreadyImported | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_listingModules(self):
"""
Make sure the module list comes back as we expect from iterModules on a
package, whether zipped or not.
"""
self._setupSysPath()
self._listModules() | Make sure the module list comes back as we expect from iterModules on a
package, whether zipped or not. | test_listingModules | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_listingModulesAlreadyImported(self):
"""
Make sure the module list comes back as we expect from iterModules on a
package, whether zipped or not, even if the package has already been
imported.
"""
self._setupSysPath()
namedAny(self.packageName)
self._listModules() | Make sure the module list comes back as we expect from iterModules on a
package, whether zipped or not, even if the package has already been
imported. | test_listingModulesAlreadyImported | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def tearDown(self):
"""
Clean up sys.path by re-binding our original object.
"""
if self.pathSetUp:
sys.path = self.savedSysPath | Clean up sys.path by re-binding our original object. | tearDown | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_unhandledImporter(self):
"""
Make sure that the behavior when encountering an unknown importer
type is not catastrophic failure.
"""
class SecretImporter(object):
pass
def hook(name):
return SecretImporter()
syspath = ['example/path']
sysmodules = {}
syshooks = [hook]
syscache = {}
def sysloader(name):
return None
space = modules.PythonPath(
syspath, sysmodules, syshooks, syscache, sysloader)
entries = list(space.iterEntries())
self.assertEqual(len(entries), 1)
self.assertRaises(KeyError, lambda: entries[0]['module']) | Make sure that the behavior when encountering an unknown importer
type is not catastrophic failure. | test_unhandledImporter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
def test_inconsistentImporterCache(self):
"""
If the path a module loaded with L{PythonPath.__getitem__} is not
present in the path importer cache, a warning is emitted, but the
L{PythonModule} is returned as usual.
"""
space = modules.PythonPath([], sys.modules, [], {})
thisModule = space[__name__]
warnings = self.flushWarnings([self.test_inconsistentImporterCache])
self.assertEqual(warnings[0]['category'], UserWarning)
self.assertEqual(
warnings[0]['message'],
FilePath(twisted.__file__).parent().dirname() +
" (for module " + __name__ + ") not in path importer cache "
"(PEP 302 violation - check your local configuration).")
self.assertEqual(len(warnings), 1)
self.assertEqual(thisModule.name, __name__) | If the path a module loaded with L{PythonPath.__getitem__} is not
present in the path importer cache, a warning is emitted, but the
L{PythonModule} is returned as usual. | test_inconsistentImporterCache | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_modules.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.