Move package into src

Prevents accidental imports when running tests.
diff --git a/tests/README b/tests/README
new file mode 100644
index 0000000..8b3b3ff
--- /dev/null
+++ b/tests/README
@@ -0,0 +1,8 @@
+These tests are meant to be run using twisted's "trial" command.
+
+See http://twistedmatrix.com/trac/wiki/TwistedTrial
+
+For example...
+
+$ sudo python ./setup install
+$ trial OpenSSL
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..9b08060
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (C) Jean-Paul Calderone
+# See LICENSE for details.
+
+"""
+Package containing unit tests for :py:mod:`OpenSSL`.
+"""
diff --git a/tests/memdbg.py b/tests/memdbg.py
new file mode 100644
index 0000000..324d0fd
--- /dev/null
+++ b/tests/memdbg.py
@@ -0,0 +1,82 @@
+import sys
+sys.modules['ssl'] = None
+sys.modules['_hashlib'] = None
+
+
+import traceback
+
+from cffi import api as _api
+_ffi = _api.FFI()
+_ffi.cdef(
+    """
+    void *malloc(size_t size);
+    void free(void *ptr);
+    void *realloc(void *ptr, size_t size);
+
+    int  CRYPTO_set_mem_functions(void *(*m)(size_t),void *(*r)(void *,size_t), void (*f)(void *));
+
+    int backtrace(void **buffer, int size);
+    char **backtrace_symbols(void *const *buffer, int size);
+    void backtrace_symbols_fd(void *const *buffer, int size, int fd);
+    """)
+_api = _ffi.verify(
+    """
+    #include <openssl/crypto.h>
+    #include <stdlib.h>
+    #include <execinfo.h>
+    """, libraries=["crypto"])
+C = _ffi.dlopen(None)
+
+verbose = False
+
+def log(s):
+    if verbose:
+        print(s)
+
+def _backtrace():
+    buf = _ffi.new("void*[]", 64)
+    result = _api.backtrace(buf, len(buf))
+    strings = _api.backtrace_symbols(buf, result)
+    stack = [_ffi.string(strings[i]) for i in range(result)]
+    C.free(strings)
+    return stack
+
+
+@_ffi.callback("void*(*)(size_t)")
+def malloc(n):
+    memory = C.malloc(n)
+    python_stack = traceback.extract_stack(limit=3)
+    c_stack = _backtrace()
+    heap[memory] = [(n, python_stack, c_stack)]
+    log("malloc(%d) -> %s" % (n, memory))
+    return memory
+
+
+@_ffi.callback("void*(*)(void*, size_t)")
+def realloc(p, n):
+    memory = C.realloc(p, n)
+    old = heap.pop(p)
+
+    python_stack = traceback.extract_stack(limit=3)
+    c_stack = _backtrace()
+
+    old.append((n, python_stack, c_stack))
+    heap[memory] = old
+    log("realloc(0x%x, %d) -> %s" % (int(_ffi.cast("int", p)), n, memory))
+    return memory
+
+
+@_ffi.callback("void(*)(void*)")
+def free(p):
+    if p != _ffi.NULL:
+        C.free(p)
+        del heap[p]
+        log("free(0x%x)" % (int(_ffi.cast("int", p)),))
+
+
+if _api.CRYPTO_set_mem_functions(malloc, realloc, free):
+    log('Enabled memory debugging')
+    heap = {}
+else:
+    log('Failed to enable memory debugging')
+    heap = None
diff --git a/tests/test_crypto.py b/tests/test_crypto.py
new file mode 100644
index 0000000..196e490
--- /dev/null
+++ b/tests/test_crypto.py
@@ -0,0 +1,3557 @@
+# Copyright (c) Jean-Paul Calderone
+# See LICENSE file for details.
+
+"""
+Unit tests for :py:mod:`OpenSSL.crypto`.
+"""
+
+from unittest import main
+from warnings import catch_warnings, simplefilter
+
+import base64
+import os
+import re
+from subprocess import PIPE, Popen
+from datetime import datetime, timedelta
+
+import pytest
+
+from six import u, b, binary_type
+
+from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
+from OpenSSL.crypto import X509, X509Type, X509Name, X509NameType
+from OpenSSL.crypto import (
+    X509Store, X509StoreType, X509StoreContext, X509StoreContextError
+)
+from OpenSSL.crypto import X509Req, X509ReqType
+from OpenSSL.crypto import X509Extension, X509ExtensionType
+from OpenSSL.crypto import load_certificate, load_privatekey
+from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
+from OpenSSL.crypto import dump_certificate, load_certificate_request
+from OpenSSL.crypto import dump_certificate_request, dump_privatekey
+from OpenSSL.crypto import PKCS7Type, load_pkcs7_data
+from OpenSSL.crypto import PKCS12, PKCS12Type, load_pkcs12
+from OpenSSL.crypto import CRL, Revoked, load_crl
+from OpenSSL.crypto import NetscapeSPKI, NetscapeSPKIType
+from OpenSSL.crypto import (
+    sign, verify, get_elliptic_curve, get_elliptic_curves)
+from OpenSSL._util import native, lib
+
+from .util import (
+    EqualityTestsMixin, TestCase, WARNING_TYPE_EXPECTED
+)
+
+
+def normalize_certificate_pem(pem):
+    return dump_certificate(FILETYPE_PEM, load_certificate(FILETYPE_PEM, pem))
+
+
+def normalize_privatekey_pem(pem):
+    return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
+
+
+GOOD_CIPHER = "blowfish"
+BAD_CIPHER = "zippers"
+
+GOOD_DIGEST = "MD5"
+BAD_DIGEST = "monkeys"
+
+root_cert_pem = b("""-----BEGIN CERTIFICATE-----
+MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
+BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
+ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
+NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
+MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
+ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
+urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
+2xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
+1dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
+FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
+VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
+BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
+b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
+AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
+hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
+w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
+-----END CERTIFICATE-----
+""")
+
+root_key_pem = b("""-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
+jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
+3claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
+AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
+yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
+6JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
+BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
+u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
+PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
+I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
+ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
+6AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
+cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
+-----END RSA PRIVATE KEY-----
+""")
+
+intermediate_cert_pem = b("""-----BEGIN CERTIFICATE-----
+MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
+WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
+DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
+ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
+dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
+MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
+AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
+FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
+21H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
+AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
+QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
+9n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
+9mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
+-----END CERTIFICATE-----
+""")
+
+intermediate_key_pem = b("""-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
+ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
+qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
+AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
+rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
+147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
++kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
+wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
+sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
+52vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
+DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
+/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
+NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
+-----END RSA PRIVATE KEY-----
+""")
+
+server_cert_pem = b("""-----BEGIN CERTIFICATE-----
+MIICKDCCAZGgAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UEBxMHQ2hpY2FnbzEQMA4GA1UEChMH
+VGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBSb290IENBMCIYDzIwMDkwMzI1MTIz
+NzUzWhgPMjAxNzA2MTExMjM3NTNaMBgxFjAUBgNVBAMTDWxvdmVseSBzZXJ2ZXIw
+gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAL6m+G653V0tpBC/OKl22VxOi2Cv
+lK4TYu9LHSDP9uDVTe7V5D5Tl6qzFoRRx5pfmnkqT5B+W9byp2NU3FC5hLm5zSAr
+b45meUhjEJ/ifkZgbNUjHdBIGP9MAQUHZa5WKdkGIJvGAvs8UzUqlr4TBWQIB24+
+lJ+Ukk/CRgasrYwdAgMBAAGjNjA0MB0GA1UdDgQWBBS4kC7Ij0W1TZXZqXQFAM2e
+gKEG2DATBgNVHSUEDDAKBggrBgEFBQcDATANBgkqhkiG9w0BAQUFAAOBgQBh30Li
+dJ+NlxIOx5343WqIBka3UbsOb2kxWrbkVCrvRapCMLCASO4FqiKWM+L0VDBprqIp
+2mgpFQ6FHpoIENGvJhdEKpptQ5i7KaGhnDNTfdy3x1+h852G99f1iyj0RmbuFcM8
+uzujnS8YXWvM7DM1Ilozk4MzPug8jzFp5uhKCQ==
+-----END CERTIFICATE-----
+""")
+
+server_key_pem = normalize_privatekey_pem(b("""-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
+U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
+SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
+AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
+j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
+j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
+Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
+msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
+FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
+4e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
+1sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
+NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
+r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
+-----END RSA PRIVATE KEY-----
+"""))
+
+intermediate_server_cert_pem = b("""-----BEGIN CERTIFICATE-----
+MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
+ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
+CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
+biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
+BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
+CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
+biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
+iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
++kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
+biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
+UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
+3bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
+x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
+-----END CERTIFICATE-----
+""")
+
+intermediate_server_key_pem = b("""-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
+SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
+8Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
+AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
+5ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
+d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
+z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
+dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
+EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
+X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
+9UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
+ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
+nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
+-----END RSA PRIVATE KEY-----
+""")
+
+client_cert_pem = b("""-----BEGIN CERTIFICATE-----
+MIICJjCCAY+gAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
+BAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UEBxMHQ2hpY2FnbzEQMA4GA1UEChMH
+VGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBSb290IENBMCIYDzIwMDkwMzI1MTIz
+ODA1WhgPMjAxNzA2MTExMjM4MDVaMBYxFDASBgNVBAMTC3VnbHkgY2xpZW50MIGf
+MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2
+rn+GrRHRiZ+xkCw/CGNhbtPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xK
+iku4G/KvnnmWdeJHqsiXeUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7Dtb
+oCRajYyHfluARQIDAQABozYwNDAdBgNVHQ4EFgQUNQB+qkaOaEVecf1J3TTUtAff
+0fAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADgYEAyv/Jh7gM
+Q3OHvmsFEEvRI+hsW8y66zK4K5de239Y44iZrFYkt7Q5nBPMEWDj4F2hLYWL/qtI
+9Zdr0U4UDCU9SmmGYh4o7R4TZ5pGFvBYvjhHbkSFYFQXZxKUi+WUxplP6I0wr2KJ
+PSTJCjJOn3xo2NTKRgV1gaoTf2EhL+RG8TQ=
+-----END CERTIFICATE-----
+""")
+
+client_key_pem = normalize_privatekey_pem(b("""-----BEGIN RSA PRIVATE KEY-----
+MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
+btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
+eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
+AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
+zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
+h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
+V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
+TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
+dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
+D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
+si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
+JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
+f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
+-----END RSA PRIVATE KEY-----
+"""))
+
+cleartextCertificatePEM = b("""-----BEGIN CERTIFICATE-----
+MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
+BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
+ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
+NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
+MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
+ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
+urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
+2xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
+1dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
+FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
+VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
+BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
+b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
+AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
+hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
+w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
+-----END CERTIFICATE-----
+""")
+
+cleartextPrivateKeyPEM = normalize_privatekey_pem(b("""\
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
+jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
+3claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
+AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
+yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
+6JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
+BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
+u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
+PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
+I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
+ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
+6AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
+cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
+-----END RSA PRIVATE KEY-----
+"""))
+
+cleartextCertificateRequestPEM = b("""-----BEGIN CERTIFICATE REQUEST-----
+MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
+EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
+ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
+BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
+E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
+xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
+gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
+Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
+oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
+-----END CERTIFICATE REQUEST-----
+""")
+
+encryptedPrivateKeyPEM = b("""-----BEGIN RSA PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: DES-EDE3-CBC,9573604A18579E9E
+
+SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
+a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
+8+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
+mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
++00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
+fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
+tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
+rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
+gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
+o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
+7SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
+MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
+11n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
+-----END RSA PRIVATE KEY-----
+""")
+
+encryptedPrivateKeyPEMPassphrase = b("foobar")
+
+# Some PKCS#7 stuff.  Generated with the openssl command line:
+#
+#    openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
+#
+# with a certificate and key (but the key should be irrelevant) in s.pem
+pkcs7Data = b("""\
+-----BEGIN PKCS7-----
+MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
+BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
+A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
+MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
+cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
+A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
+HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
+SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
+zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
+LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
+A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
+65w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
+Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
+Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
+bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
+VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
+/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
+Ho4EzbYCOaEAMQA=
+-----END PKCS7-----
+""")
+
+pkcs7DataASN1 = base64.b64decode(b"""
+MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
+BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
+A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
+MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
+cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
+A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
+HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
+SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
+zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
+LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
+A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
+65w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
+Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
+Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
+bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
+VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
+/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
+Ho4EzbYCOaEAMQA=
+""")
+
+crlData = b("""\
+-----BEGIN X509 CRL-----
+MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
+SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
+D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
+MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
+MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
+4dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
+0yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
+vrzEeLDRiiPl92dyyWmu
+-----END X509 CRL-----
+""")
+
+
+# A broken RSA private key which can be used to test the error path through
+# PKey.check.
+inconsistentPrivateKeyPEM = b("""-----BEGIN RSA PRIVATE KEY-----
+MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
+5kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
+OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
+zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
+nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
+HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
+oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
+-----END RSA PRIVATE KEY-----
+""")
+
+# certificate with NULL bytes in subjectAltName and common name
+
+nulbyteSubjectAltNamePEM = b("""-----BEGIN CERTIFICATE-----
+MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
+DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
+eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
+RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
+ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
+NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
+DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
+ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
+ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
+hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
+BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
+pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
+vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
+KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
+oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
+08LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
+HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
+BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
+Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
+bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
+AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
+i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
+HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
+kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
+VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
+RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
+-----END CERTIFICATE-----""")
+
+
+class X509ExtTests(TestCase):
+    """
+    Tests for :py:class:`OpenSSL.crypto.X509Extension`.
+    """
+
+    def setUp(self):
+        """
+        Create a new private key and start a certificate request (for a test
+        method to finish in one way or another).
+        """
+        super(X509ExtTests, self).setUp()
+        # Basic setup stuff to generate a certificate
+        self.pkey = PKey()
+        self.pkey.generate_key(TYPE_RSA, 384)
+        self.req = X509Req()
+        self.req.set_pubkey(self.pkey)
+        # Authority good you have.
+        self.req.get_subject().commonName = "Yoda root CA"
+        self.x509 = X509()
+        self.subject = self.x509.get_subject()
+        self.subject.commonName = self.req.get_subject().commonName
+        self.x509.set_issuer(self.subject)
+        self.x509.set_pubkey(self.pkey)
+        now = datetime.now()
+        expire = datetime.now() + timedelta(days=100)
+        self.x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
+        self.x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
+
+    def tearDown(self):
+        """
+        Forget all of the pyOpenSSL objects so they can be garbage collected,
+        their memory released, and not interfere with the leak detection code.
+        """
+        self.pkey = self.req = self.x509 = self.subject = None
+        super(X509ExtTests, self).tearDown()
+
+    def test_str(self):
+        """
+        The string representation of :py:class:`X509Extension` instances as
+        returned by :py:data:`str` includes stuff.
+        """
+        # This isn't necessarily the best string representation.  Perhaps it
+        # will be changed/improved in the future.
+        self.assertEquals(
+            str(X509Extension(b('basicConstraints'), True, b('CA:false'))),
+            'CA:FALSE')
+
+    def test_type(self):
+        """
+        :py:class:`X509Extension` and :py:class:`X509ExtensionType` refer to
+        the same type object and can be used to create instances of that type.
+        """
+        self.assertIdentical(X509Extension, X509ExtensionType)
+        self.assertConsistentType(
+            X509Extension,
+            'X509Extension', b('basicConstraints'), True, b('CA:true'))
+
+    def test_construction(self):
+        """
+        :py:class:`X509Extension` accepts an extension type name, a critical
+        flag, and an extension value and returns an
+        :py:class:`X509ExtensionType` instance.
+        """
+        basic = X509Extension(b('basicConstraints'), True, b('CA:true'))
+        self.assertTrue(
+            isinstance(basic, X509ExtensionType),
+            "%r is of type %r, should be %r" % (
+                basic, type(basic), X509ExtensionType))
+
+        comment = X509Extension(
+            b('nsComment'), False, b('pyOpenSSL unit test'))
+        self.assertTrue(
+            isinstance(comment, X509ExtensionType),
+            "%r is of type %r, should be %r" % (
+                comment, type(comment), X509ExtensionType))
+
+    def test_invalid_extension(self):
+        """
+        :py:class:`X509Extension` raises something if it is passed a bad
+        extension name or value.
+        """
+        self.assertRaises(
+            Error, X509Extension, b('thisIsMadeUp'), False, b('hi'))
+        self.assertRaises(
+            Error, X509Extension, b('basicConstraints'), False, b('blah blah'))
+
+        # Exercise a weird one (an extension which uses the r2i method).  This
+        # exercises the codepath that requires a non-NULL ctx to be passed to
+        # X509V3_EXT_nconf.  It can't work now because we provide no
+        # configuration database.  It might be made to work in the future.
+        self.assertRaises(
+            Error, X509Extension, b('proxyCertInfo'), True,
+            b('language:id-ppl-anyLanguage,pathlen:1,policy:text:AB'))
+
+    def test_get_critical(self):
+        """
+        :py:meth:`X509ExtensionType.get_critical` returns the value of the
+        extension's critical flag.
+        """
+        ext = X509Extension(b('basicConstraints'), True, b('CA:true'))
+        self.assertTrue(ext.get_critical())
+        ext = X509Extension(b('basicConstraints'), False, b('CA:true'))
+        self.assertFalse(ext.get_critical())
+
+    def test_get_short_name(self):
+        """
+        :py:meth:`X509ExtensionType.get_short_name` returns a string giving the
+        short type name of the extension.
+        """
+        ext = X509Extension(b('basicConstraints'), True, b('CA:true'))
+        self.assertEqual(ext.get_short_name(), b('basicConstraints'))
+        ext = X509Extension(b('nsComment'), True, b('foo bar'))
+        self.assertEqual(ext.get_short_name(), b('nsComment'))
+
+    def test_get_data(self):
+        """
+        :py:meth:`X509Extension.get_data` returns a string giving the data of
+        the extension.
+        """
+        ext = X509Extension(b('basicConstraints'), True, b('CA:true'))
+        # Expect to get back the DER encoded form of CA:true.
+        self.assertEqual(ext.get_data(), b('0\x03\x01\x01\xff'))
+
+    def test_get_data_wrong_args(self):
+        """
+        :py:meth:`X509Extension.get_data` raises :py:exc:`TypeError` if passed
+        any arguments.
+        """
+        ext = X509Extension(b('basicConstraints'), True, b('CA:true'))
+        self.assertRaises(TypeError, ext.get_data, None)
+        self.assertRaises(TypeError, ext.get_data, "foo")
+        self.assertRaises(TypeError, ext.get_data, 7)
+
+    def test_unused_subject(self):
+        """
+        The :py:data:`subject` parameter to :py:class:`X509Extension` may be
+        provided for an extension which does not use it and is ignored in this
+        case.
+        """
+        ext1 = X509Extension(
+            b('basicConstraints'), False, b('CA:TRUE'), subject=self.x509)
+        self.x509.add_extensions([ext1])
+        self.x509.sign(self.pkey, 'sha1')
+        # This is a little lame.  Can we think of a better way?
+        text = dump_certificate(FILETYPE_TEXT, self.x509)
+        self.assertTrue(b('X509v3 Basic Constraints:') in text)
+        self.assertTrue(b('CA:TRUE') in text)
+
+    def test_subject(self):
+        """
+        If an extension requires a subject, the :py:data:`subject` parameter to
+        :py:class:`X509Extension` provides its value.
+        """
+        ext3 = X509Extension(
+            b('subjectKeyIdentifier'), False, b('hash'), subject=self.x509)
+        self.x509.add_extensions([ext3])
+        self.x509.sign(self.pkey, 'sha1')
+        text = dump_certificate(FILETYPE_TEXT, self.x509)
+        self.assertTrue(b('X509v3 Subject Key Identifier:') in text)
+
+    def test_missing_subject(self):
+        """
+        If an extension requires a subject and the :py:data:`subject` parameter
+        is given no value, something happens.
+        """
+        self.assertRaises(
+            Error, X509Extension, b('subjectKeyIdentifier'), False, b('hash'))
+
+    def test_invalid_subject(self):
+        """
+        If the :py:data:`subject` parameter is given a value which is not an
+        :py:class:`X509` instance, :py:exc:`TypeError` is raised.
+        """
+        for badObj in [True, object(), "hello", [], self]:
+            self.assertRaises(
+                TypeError,
+                X509Extension,
+                'basicConstraints', False, 'CA:TRUE', subject=badObj)
+
+    def test_unused_issuer(self):
+        """
+        The :py:data:`issuer` parameter to :py:class:`X509Extension` may be
+        provided for an extension which does not use it and is ignored in this
+        case.
+        """
+        ext1 = X509Extension(
+            b('basicConstraints'), False, b('CA:TRUE'), issuer=self.x509)
+        self.x509.add_extensions([ext1])
+        self.x509.sign(self.pkey, 'sha1')
+        text = dump_certificate(FILETYPE_TEXT, self.x509)
+        self.assertTrue(b('X509v3 Basic Constraints:') in text)
+        self.assertTrue(b('CA:TRUE') in text)
+
+    def test_issuer(self):
+        """
+        If an extension requires an issuer, the :py:data:`issuer` parameter to
+        :py:class:`X509Extension` provides its value.
+        """
+        ext2 = X509Extension(
+            b('authorityKeyIdentifier'), False, b('issuer:always'),
+            issuer=self.x509)
+        self.x509.add_extensions([ext2])
+        self.x509.sign(self.pkey, 'sha1')
+        text = dump_certificate(FILETYPE_TEXT, self.x509)
+        self.assertTrue(b('X509v3 Authority Key Identifier:') in text)
+        self.assertTrue(b('DirName:/CN=Yoda root CA') in text)
+
+    def test_missing_issuer(self):
+        """
+        If an extension requires an issue and the :py:data:`issuer` parameter
+        is given no value, something happens.
+        """
+        self.assertRaises(
+            Error,
+            X509Extension,
+            b('authorityKeyIdentifier'), False,
+            b('keyid:always,issuer:always'))
+
+    def test_invalid_issuer(self):
+        """
+        If the :py:data:`issuer` parameter is given a value which is not an
+        :py:class:`X509` instance, :py:exc:`TypeError` is raised.
+        """
+        for badObj in [True, object(), "hello", [], self]:
+            self.assertRaises(
+                TypeError,
+                X509Extension,
+                'authorityKeyIdentifier', False, 'keyid:always,issuer:always',
+                issuer=badObj)
+
+
+class PKeyTests(TestCase):
+    """
+    Unit tests for :py:class:`OpenSSL.crypto.PKey`.
+    """
+
+    def test_type(self):
+        """
+        :py:class:`PKey` and :py:class:`PKeyType` refer to the same type object
+        and can be used to create instances of that type.
+        """
+        self.assertIdentical(PKey, PKeyType)
+        self.assertConsistentType(PKey, 'PKey')
+
+    def test_construction(self):
+        """
+        :py:class:`PKey` takes no arguments and returns a new :py:class:`PKey`
+        instance.
+        """
+        self.assertRaises(TypeError, PKey, None)
+        key = PKey()
+        self.assertTrue(
+            isinstance(key, PKeyType),
+            "%r is of type %r, should be %r" % (key, type(key), PKeyType))
+
+    def test_pregeneration(self):
+        """
+        :py:attr:`PKeyType.bits` and :py:attr:`PKeyType.type` return
+        :py:data:`0` before the key is generated.  :py:attr:`PKeyType.check`
+        raises :py:exc:`TypeError` before the key is generated.
+        """
+        key = PKey()
+        self.assertEqual(key.type(), 0)
+        self.assertEqual(key.bits(), 0)
+        self.assertRaises(TypeError, key.check)
+
+    def test_failedGeneration(self):
+        """
+        :py:meth:`PKeyType.generate_key` takes two arguments, the first giving
+        the key type as one of :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA` and
+        the second giving the number of bits to generate.  If an invalid type
+        is specified or generation fails, :py:exc:`Error` is raised.  If an
+        invalid number of bits is specified, :py:exc:`ValueError` or
+        :py:exc:`Error` is raised.
+        """
+        key = PKey()
+        self.assertRaises(TypeError, key.generate_key)
+        self.assertRaises(TypeError, key.generate_key, 1, 2, 3)
+        self.assertRaises(TypeError, key.generate_key, "foo", "bar")
+        self.assertRaises(Error, key.generate_key, -1, 0)
+
+        self.assertRaises(ValueError, key.generate_key, TYPE_RSA, -1)
+        self.assertRaises(ValueError, key.generate_key, TYPE_RSA, 0)
+
+        # XXX RSA generation for small values of bits is fairly buggy in a wide
+        # range of OpenSSL versions.  I need to figure out what the safe lower
+        # bound for a reasonable number of OpenSSL versions is and explicitly
+        # check for that in the wrapper.  The failure behavior is typically an
+        # infinite loop inside OpenSSL.
+
+        # self.assertRaises(Error, key.generate_key, TYPE_RSA, 2)
+
+        # XXX DSA generation seems happy with any number of bits.  The DSS
+        # says bits must be between 512 and 1024 inclusive.  OpenSSL's DSA
+        # generator doesn't seem to care about the upper limit at all.  For
+        # the lower limit, it uses 512 if anything smaller is specified.
+        # So, it doesn't seem possible to make generate_key fail for
+        # TYPE_DSA with a bits argument which is at least an int.
+
+        # self.assertRaises(Error, key.generate_key, TYPE_DSA, -7)
+
+    def test_rsaGeneration(self):
+        """
+        :py:meth:`PKeyType.generate_key` generates an RSA key when passed
+        :py:data:`TYPE_RSA` as a type and a reasonable number of bits.
+        """
+        bits = 128
+        key = PKey()
+        key.generate_key(TYPE_RSA, bits)
+        self.assertEqual(key.type(), TYPE_RSA)
+        self.assertEqual(key.bits(), bits)
+        self.assertTrue(key.check())
+
+    def test_dsaGeneration(self):
+        """
+        :py:meth:`PKeyType.generate_key` generates a DSA key when passed
+        :py:data:`TYPE_DSA` as a type and a reasonable number of bits.
+        """
+        # 512 is a magic number.  The DSS (Digital Signature Standard)
+        # allows a minimum of 512 bits for DSA.  DSA_generate_parameters
+        # will silently promote any value below 512 to 512.
+        bits = 512
+        key = PKey()
+        key.generate_key(TYPE_DSA, bits)
+        # self.assertEqual(key.type(), TYPE_DSA)
+        # self.assertEqual(key.bits(), bits)
+        # self.assertRaises(TypeError, key.check)
+
+    def test_regeneration(self):
+        """
+        :py:meth:`PKeyType.generate_key` can be called multiple times on the
+        same key to generate new keys.
+        """
+        key = PKey()
+        for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
+            key.generate_key(type, bits)
+            self.assertEqual(key.type(), type)
+            self.assertEqual(key.bits(), bits)
+
+    def test_inconsistentKey(self):
+        """
+        :py:`PKeyType.check` returns :py:exc:`Error` if the key is not
+        consistent.
+        """
+        key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
+        self.assertRaises(Error, key.check)
+
+    def test_check_wrong_args(self):
+        """
+        :py:meth:`PKeyType.check` raises :py:exc:`TypeError` if called with any
+        arguments.
+        """
+        self.assertRaises(TypeError, PKey().check, None)
+        self.assertRaises(TypeError, PKey().check, object())
+        self.assertRaises(TypeError, PKey().check, 1)
+
+    def test_check_public_key(self):
+        """
+        :py:meth:`PKeyType.check` raises :py:exc:`TypeError` if only the public
+        part of the key is available.
+        """
+        # A trick to get a public-only key
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        cert = X509()
+        cert.set_pubkey(key)
+        pub = cert.get_pubkey()
+        self.assertRaises(TypeError, pub.check)
+
+
+class X509NameTests(TestCase):
+    """
+    Unit tests for :py:class:`OpenSSL.crypto.X509Name`.
+    """
+
+    def _x509name(self, **attrs):
+        # XXX There's no other way to get a new X509Name yet.
+        name = X509().get_subject()
+        attrs = list(attrs.items())
+
+        # Make the order stable - order matters!
+        def key(attr):
+            return attr[1]
+        attrs.sort(key=key)
+        for k, v in attrs:
+            setattr(name, k, v)
+        return name
+
+    def test_type(self):
+        """
+        The type of X509Name objects is :py:class:`X509NameType`.
+        """
+        self.assertIdentical(X509Name, X509NameType)
+        self.assertEqual(X509NameType.__name__, 'X509Name')
+        self.assertTrue(isinstance(X509NameType, type))
+
+        name = self._x509name()
+        self.assertTrue(
+            isinstance(name, X509NameType),
+            "%r is of type %r, should be %r" % (
+                name, type(name), X509NameType))
+
+    def test_onlyStringAttributes(self):
+        """
+        Attempting to set a non-:py:data:`str` attribute name on an
+        :py:class:`X509NameType` instance causes :py:exc:`TypeError` to be
+        raised.
+        """
+        name = self._x509name()
+        # Beyond these cases, you may also think that unicode should be
+        # rejected.  Sorry, you're wrong.  unicode is automatically converted
+        # to str outside of the control of X509Name, so there's no way to
+        # reject it.
+
+        # Also, this used to test str subclasses, but that test is less
+        # relevant now that the implementation is in Python instead of C.  Also
+        # PyPy automatically converts str subclasses to str when they are
+        # passed to setattr, so we can't test it on PyPy.  Apparently CPython
+        # does this sometimes as well.
+        self.assertRaises(TypeError, setattr, name, None, "hello")
+        self.assertRaises(TypeError, setattr, name, 30, "hello")
+
+    def test_setInvalidAttribute(self):
+        """
+        Attempting to set any attribute name on an :py:class:`X509NameType`
+        instance for which no corresponding NID is defined causes
+        :py:exc:`AttributeError` to be raised.
+        """
+        name = self._x509name()
+        self.assertRaises(AttributeError, setattr, name, "no such thing", None)
+
+    def test_attributes(self):
+        """
+        :py:class:`X509NameType` instances have attributes for each standard
+        (?) X509Name field.
+        """
+        name = self._x509name()
+        name.commonName = "foo"
+        self.assertEqual(name.commonName, "foo")
+        self.assertEqual(name.CN, "foo")
+        name.CN = "baz"
+        self.assertEqual(name.commonName, "baz")
+        self.assertEqual(name.CN, "baz")
+        name.commonName = "bar"
+        self.assertEqual(name.commonName, "bar")
+        self.assertEqual(name.CN, "bar")
+        name.CN = "quux"
+        self.assertEqual(name.commonName, "quux")
+        self.assertEqual(name.CN, "quux")
+
+    def test_copy(self):
+        """
+        :py:class:`X509Name` creates a new :py:class:`X509NameType` instance
+        with all the same attributes as an existing :py:class:`X509NameType`
+        instance when called with one.
+        """
+        name = self._x509name(commonName="foo", emailAddress="bar@example.com")
+
+        copy = X509Name(name)
+        self.assertEqual(copy.commonName, "foo")
+        self.assertEqual(copy.emailAddress, "bar@example.com")
+
+        # Mutate the copy and ensure the original is unmodified.
+        copy.commonName = "baz"
+        self.assertEqual(name.commonName, "foo")
+
+        # Mutate the original and ensure the copy is unmodified.
+        name.emailAddress = "quux@example.com"
+        self.assertEqual(copy.emailAddress, "bar@example.com")
+
+    def test_repr(self):
+        """
+        :py:func:`repr` passed an :py:class:`X509NameType` instance should
+        return a string containing a description of the type and the NIDs which
+        have been set on it.
+        """
+        name = self._x509name(commonName="foo", emailAddress="bar")
+        self.assertEqual(
+            repr(name),
+            "<X509Name object '/emailAddress=bar/CN=foo'>")
+
+    def test_comparison(self):
+        """
+        :py:class:`X509NameType` instances should compare based on their NIDs.
+        """
+        def _equality(a, b, assertTrue, assertFalse):
+            assertTrue(a == b, "(%r == %r) --> False" % (a, b))
+            assertFalse(a != b)
+            assertTrue(b == a)
+            assertFalse(b != a)
+
+        def assertEqual(a, b):
+            _equality(a, b, self.assertTrue, self.assertFalse)
+
+        # Instances compare equal to themselves.
+        name = self._x509name()
+        assertEqual(name, name)
+
+        # Empty instances should compare equal to each other.
+        assertEqual(self._x509name(), self._x509name())
+
+        # Instances with equal NIDs should compare equal to each other.
+        assertEqual(self._x509name(commonName="foo"),
+                    self._x509name(commonName="foo"))
+
+        # Instance with equal NIDs set using different aliases should compare
+        # equal to each other.
+        assertEqual(self._x509name(commonName="foo"),
+                    self._x509name(CN="foo"))
+
+        # Instances with more than one NID with the same values should compare
+        # equal to each other.
+        assertEqual(self._x509name(CN="foo", organizationalUnitName="bar"),
+                    self._x509name(commonName="foo", OU="bar"))
+
+        def assertNotEqual(a, b):
+            _equality(a, b, self.assertFalse, self.assertTrue)
+
+        # Instances with different values for the same NID should not compare
+        # equal to each other.
+        assertNotEqual(self._x509name(CN="foo"),
+                       self._x509name(CN="bar"))
+
+        # Instances with different NIDs should not compare equal to each other.
+        assertNotEqual(self._x509name(CN="foo"),
+                       self._x509name(OU="foo"))
+
+        def _inequality(a, b, assertTrue, assertFalse):
+            assertTrue(a < b)
+            assertTrue(a <= b)
+            assertTrue(b > a)
+            assertTrue(b >= a)
+            assertFalse(a > b)
+            assertFalse(a >= b)
+            assertFalse(b < a)
+            assertFalse(b <= a)
+
+        def assertLessThan(a, b):
+            _inequality(a, b, self.assertTrue, self.assertFalse)
+
+        # An X509Name with a NID with a value which sorts less than the value
+        # of the same NID on another X509Name compares less than the other
+        # X509Name.
+        assertLessThan(self._x509name(CN="abc"),
+                       self._x509name(CN="def"))
+
+        def assertGreaterThan(a, b):
+            _inequality(a, b, self.assertFalse, self.assertTrue)
+
+        # An X509Name with a NID with a value which sorts greater than the
+        # value of the same NID on another X509Name compares greater than the
+        # other X509Name.
+        assertGreaterThan(self._x509name(CN="def"),
+                          self._x509name(CN="abc"))
+
+    def test_hash(self):
+        """
+        :py:meth:`X509Name.hash` returns an integer hash based on the value of
+        the name.
+        """
+        a = self._x509name(CN="foo")
+        b = self._x509name(CN="foo")
+        self.assertEqual(a.hash(), b.hash())
+        a.CN = "bar"
+        self.assertNotEqual(a.hash(), b.hash())
+
+    def test_der(self):
+        """
+        :py:meth:`X509Name.der` returns the DER encoded form of the name.
+        """
+        a = self._x509name(CN="foo", C="US")
+        self.assertEqual(
+            a.der(),
+            b('0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
+              '1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo'))
+
+    def test_get_components(self):
+        """
+        :py:meth:`X509Name.get_components` returns a :py:data:`list` of
+        two-tuples of :py:data:`str`
+        giving the NIDs and associated values which make up the name.
+        """
+        a = self._x509name()
+        self.assertEqual(a.get_components(), [])
+        a.CN = "foo"
+        self.assertEqual(a.get_components(), [(b("CN"), b("foo"))])
+        a.organizationalUnitName = "bar"
+        self.assertEqual(
+            a.get_components(),
+            [(b("CN"), b("foo")), (b("OU"), b("bar"))])
+
+    def test_load_nul_byte_attribute(self):
+        """
+        An :py:class:`OpenSSL.crypto.X509Name` from an
+        :py:class:`OpenSSL.crypto.X509` instance loaded from a file can have a
+        NUL byte in the value of one of its attributes.
+        """
+        cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
+        subject = cert.get_subject()
+        self.assertEqual(
+            "null.python.org\x00example.org", subject.commonName)
+
+    def test_setAttributeFailure(self):
+        """
+        If the value of an attribute cannot be set for some reason then
+        :py:class:`OpenSSL.crypto.Error` is raised.
+        """
+        name = self._x509name()
+        # This value is too long
+        self.assertRaises(Error, setattr, name, "O", b"x" * 512)
+
+
+class _PKeyInteractionTestsMixin:
+    """
+    Tests which involve another thing and a PKey.
+    """
+
+    def signable(self):
+        """
+        Return something with a :py:meth:`set_pubkey`, :py:meth:`set_pubkey`,
+        and :py:meth:`sign` method.
+        """
+        raise NotImplementedError()
+
+    def test_signWithUngenerated(self):
+        """
+        :py:meth:`X509Req.sign` raises :py:exc:`ValueError` when pass a
+        :py:class:`PKey` with no parts.
+        """
+        request = self.signable()
+        key = PKey()
+        self.assertRaises(ValueError, request.sign, key, GOOD_DIGEST)
+
+    def test_signWithPublicKey(self):
+        """
+        :py:meth:`X509Req.sign` raises :py:exc:`ValueError` when pass a
+        :py:class:`PKey` with no private part as the signing key.
+        """
+        request = self.signable()
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        request.set_pubkey(key)
+        pub = request.get_pubkey()
+        self.assertRaises(ValueError, request.sign, pub, GOOD_DIGEST)
+
+    def test_signWithUnknownDigest(self):
+        """
+        :py:meth:`X509Req.sign` raises :py:exc:`ValueError` when passed a
+        digest name which is not known.
+        """
+        request = self.signable()
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        self.assertRaises(ValueError, request.sign, key, BAD_DIGEST)
+
+    def test_sign(self):
+        """
+        :py:meth:`X509Req.sign` succeeds when passed a private key object and a
+        valid digest function. :py:meth:`X509Req.verify` can be used to check
+        the signature.
+        """
+        request = self.signable()
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        request.set_pubkey(key)
+        request.sign(key, GOOD_DIGEST)
+        # If the type has a verify method, cover that too.
+        if getattr(request, 'verify', None) is not None:
+            pub = request.get_pubkey()
+            self.assertTrue(request.verify(pub))
+            # Make another key that won't verify.
+            key = PKey()
+            key.generate_key(TYPE_RSA, 512)
+            self.assertRaises(Error, request.verify, key)
+
+
+class X509ReqTests(TestCase, _PKeyInteractionTestsMixin):
+    """
+    Tests for :py:class:`OpenSSL.crypto.X509Req`.
+    """
+
+    def signable(self):
+        """
+        Create and return a new :py:class:`X509Req`.
+        """
+        return X509Req()
+
+    def test_type(self):
+        """
+        :py:obj:`X509Req` and :py:obj:`X509ReqType` refer to the same type
+        object and can be used to create instances of that type.
+        """
+        self.assertIdentical(X509Req, X509ReqType)
+        self.assertConsistentType(X509Req, 'X509Req')
+
+    def test_construction(self):
+        """
+        :py:obj:`X509Req` takes no arguments and returns an
+        :py:obj:`X509ReqType` instance.
+        """
+        request = X509Req()
+        assert isinstance(request, X509ReqType)
+
+    def test_version(self):
+        """
+        :py:obj:`X509ReqType.set_version` sets the X.509 version of the
+        certificate request. :py:obj:`X509ReqType.get_version` returns the
+        X.509 version of the certificate request. The initial value of the
+        version is 0.
+        """
+        request = X509Req()
+        self.assertEqual(request.get_version(), 0)
+        request.set_version(1)
+        self.assertEqual(request.get_version(), 1)
+        request.set_version(3)
+        self.assertEqual(request.get_version(), 3)
+
+    def test_version_wrong_args(self):
+        """
+        :py:obj:`X509ReqType.set_version` raises :py:obj:`TypeError` if called
+        with the wrong number of arguments or with a non-:py:obj:`int`
+        argument. :py:obj:`X509ReqType.get_version` raises :py:obj:`TypeError`
+        if called with any arguments.
+        """
+        request = X509Req()
+        self.assertRaises(TypeError, request.set_version)
+        self.assertRaises(TypeError, request.set_version, "foo")
+        self.assertRaises(TypeError, request.set_version, 1, 2)
+        self.assertRaises(TypeError, request.get_version, None)
+
+    def test_get_subject(self):
+        """
+        :py:obj:`X509ReqType.get_subject` returns an :py:obj:`X509Name` for the
+        subject of the request and which is valid even after the request object
+        is otherwise dead.
+        """
+        request = X509Req()
+        subject = request.get_subject()
+        assert isinstance(subject, X509NameType)
+        subject.commonName = "foo"
+        self.assertEqual(request.get_subject().commonName, "foo")
+        del request
+        subject.commonName = "bar"
+        self.assertEqual(subject.commonName, "bar")
+
+    def test_get_subject_wrong_args(self):
+        """
+        :py:obj:`X509ReqType.get_subject` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        request = X509Req()
+        self.assertRaises(TypeError, request.get_subject, None)
+
+    def test_add_extensions(self):
+        """
+        :py:obj:`X509Req.add_extensions` accepts a :py:obj:`list` of
+        :py:obj:`X509Extension` instances and adds them to the X509 request.
+        """
+        request = X509Req()
+        request.add_extensions([
+            X509Extension(b('basicConstraints'), True, b('CA:false'))])
+        exts = request.get_extensions()
+        self.assertEqual(len(exts), 1)
+        self.assertEqual(exts[0].get_short_name(), b('basicConstraints'))
+        self.assertEqual(exts[0].get_critical(), 1)
+        self.assertEqual(exts[0].get_data(), b('0\x00'))
+
+    def test_get_extensions(self):
+        """
+        :py:obj:`X509Req.get_extensions` returns a :py:obj:`list` of
+        extensions added to this X509 request.
+        """
+        request = X509Req()
+        exts = request.get_extensions()
+        self.assertEqual(exts, [])
+        request.add_extensions([
+            X509Extension(b('basicConstraints'), True, b('CA:true')),
+            X509Extension(b('keyUsage'), False, b('digitalSignature'))])
+        exts = request.get_extensions()
+        self.assertEqual(len(exts), 2)
+        self.assertEqual(exts[0].get_short_name(), b('basicConstraints'))
+        self.assertEqual(exts[0].get_critical(), 1)
+        self.assertEqual(exts[0].get_data(), b('0\x03\x01\x01\xff'))
+        self.assertEqual(exts[1].get_short_name(), b('keyUsage'))
+        self.assertEqual(exts[1].get_critical(), 0)
+        self.assertEqual(exts[1].get_data(), b('\x03\x02\x07\x80'))
+
+    def test_add_extensions_wrong_args(self):
+        """
+        :py:obj:`X509Req.add_extensions` raises :py:obj:`TypeError` if called
+        with the wrong number of arguments or with a non-:py:obj:`list`.  Or it
+        raises :py:obj:`ValueError` if called with a :py:obj:`list` containing
+        objects other than :py:obj:`X509Extension` instances.
+        """
+        request = X509Req()
+        self.assertRaises(TypeError, request.add_extensions)
+        self.assertRaises(TypeError, request.add_extensions, object())
+        self.assertRaises(ValueError, request.add_extensions, [object()])
+        self.assertRaises(TypeError, request.add_extensions, [], None)
+
+    def test_verify_wrong_args(self):
+        """
+        :py:obj:`X509Req.verify` raises :py:obj:`TypeError` if called with zero
+        arguments or more than one argument or if passed anything other than a
+        :py:obj:`PKey` instance as its single argument.
+        """
+        request = X509Req()
+        self.assertRaises(TypeError, request.verify)
+        self.assertRaises(TypeError, request.verify, object())
+        self.assertRaises(TypeError, request.verify, PKey(), object())
+
+    def test_verify_uninitialized_key(self):
+        """
+        :py:obj:`X509Req.verify` raises :py:obj:`OpenSSL.crypto.Error` if
+        called with a :py:obj:`OpenSSL.crypto.PKey` which contains no key data.
+        """
+        request = X509Req()
+        pkey = PKey()
+        self.assertRaises(Error, request.verify, pkey)
+
+    def test_verify_wrong_key(self):
+        """
+        :py:obj:`X509Req.verify` raises :py:obj:`OpenSSL.crypto.Error` if
+        called with a :py:obj:`OpenSSL.crypto.PKey` which does not represent
+        the public part of the key which signed the request.
+        """
+        request = X509Req()
+        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        request.sign(pkey, GOOD_DIGEST)
+        another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
+        self.assertRaises(Error, request.verify, another_pkey)
+
+    def test_verify_success(self):
+        """
+        :py:obj:`X509Req.verify` returns :py:obj:`True` if called with a
+        :py:obj:`OpenSSL.crypto.PKey` which represents the public part of the
+        key which signed the request.
+        """
+        request = X509Req()
+        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        request.sign(pkey, GOOD_DIGEST)
+        self.assertEqual(True, request.verify(pkey))
+
+
+class X509Tests(TestCase, _PKeyInteractionTestsMixin):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.X509`.
+    """
+    pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
+
+    extpem = """
+-----BEGIN CERTIFICATE-----
+MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
+BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
+eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
+MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
+aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
+hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
+Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
+zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
+hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
+TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
+03HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
+MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
+b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
+MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
+uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
+WpOdIpB8KksUTCzV591Nr1wd
+-----END CERTIFICATE-----
+    """
+
+    def signable(self):
+        """
+        Create and return a new :py:obj:`X509`.
+        """
+        return X509()
+
+    def test_type(self):
+        """
+        :py:obj:`X509` and :py:obj:`X509Type` refer to the same type object and
+        can be used to create instances of that type.
+        """
+        self.assertIdentical(X509, X509Type)
+        self.assertConsistentType(X509, 'X509')
+
+    def test_construction(self):
+        """
+        :py:obj:`X509` takes no arguments and returns an instance of
+        :py:obj:`X509Type`.
+        """
+        certificate = X509()
+        self.assertTrue(
+            isinstance(certificate, X509Type),
+            "%r is of type %r, should be %r" % (certificate,
+                                                type(certificate),
+                                                X509Type))
+        self.assertEqual(type(X509Type).__name__, 'type')
+        self.assertEqual(type(certificate).__name__, 'X509')
+        self.assertEqual(type(certificate), X509Type)
+        self.assertEqual(type(certificate), X509)
+
+    def test_get_version_wrong_args(self):
+        """
+        :py:obj:`X509.get_version` raises :py:obj:`TypeError` if invoked with
+        any arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.get_version, None)
+
+    def test_set_version_wrong_args(self):
+        """
+        :py:obj:`X509.set_version` raises :py:obj:`TypeError` if invoked with
+        the wrong number of arguments or an argument not of type :py:obj:`int`.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.set_version)
+        self.assertRaises(TypeError, cert.set_version, None)
+        self.assertRaises(TypeError, cert.set_version, 1, None)
+
+    def test_version(self):
+        """
+        :py:obj:`X509.set_version` sets the certificate version number.
+        :py:obj:`X509.get_version` retrieves it.
+        """
+        cert = X509()
+        cert.set_version(1234)
+        self.assertEquals(cert.get_version(), 1234)
+
+    def test_get_serial_number_wrong_args(self):
+        """
+        :py:obj:`X509.get_serial_number` raises :py:obj:`TypeError` if invoked
+        with any arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.get_serial_number, None)
+
+    def test_serial_number(self):
+        """
+        The serial number of an :py:obj:`X509Type` can be retrieved and
+        modified with :py:obj:`X509Type.get_serial_number` and
+        :py:obj:`X509Type.set_serial_number`.
+        """
+        certificate = X509()
+        self.assertRaises(TypeError, certificate.set_serial_number)
+        self.assertRaises(TypeError, certificate.set_serial_number, 1, 2)
+        self.assertRaises(TypeError, certificate.set_serial_number, "1")
+        self.assertRaises(TypeError, certificate.set_serial_number, 5.5)
+        self.assertEqual(certificate.get_serial_number(), 0)
+        certificate.set_serial_number(1)
+        self.assertEqual(certificate.get_serial_number(), 1)
+        certificate.set_serial_number(2 ** 32 + 1)
+        self.assertEqual(certificate.get_serial_number(), 2 ** 32 + 1)
+        certificate.set_serial_number(2 ** 64 + 1)
+        self.assertEqual(certificate.get_serial_number(), 2 ** 64 + 1)
+        certificate.set_serial_number(2 ** 128 + 1)
+        self.assertEqual(certificate.get_serial_number(), 2 ** 128 + 1)
+
+    def _setBoundTest(self, which):
+        """
+        :py:obj:`X509Type.set_notBefore` takes a string in the format of an
+        ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
+        validity period to it.
+        """
+        certificate = X509()
+        set = getattr(certificate, 'set_not' + which)
+        get = getattr(certificate, 'get_not' + which)
+
+        # Starts with no value.
+        self.assertEqual(get(), None)
+
+        # GMT (Or is it UTC?) -exarkun
+        when = b("20040203040506Z")
+        set(when)
+        self.assertEqual(get(), when)
+
+        # A plus two hours and thirty minutes offset
+        when = b("20040203040506+0530")
+        set(when)
+        self.assertEqual(get(), when)
+
+        # A minus one hour fifteen minutes offset
+        when = b("20040203040506-0115")
+        set(when)
+        self.assertEqual(get(), when)
+
+        # An invalid string results in a ValueError
+        self.assertRaises(ValueError, set, b("foo bar"))
+
+        # The wrong number of arguments results in a TypeError.
+        self.assertRaises(TypeError, set)
+        with pytest.raises(TypeError):
+            set(b"20040203040506Z", b"20040203040506Z")
+        self.assertRaises(TypeError, get, b("foo bar"))
+
+    # XXX ASN1_TIME (not GENERALIZEDTIME)
+
+    def test_set_notBefore(self):
+        """
+        :py:obj:`X509Type.set_notBefore` takes a string in the format of an
+        ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
+        validity period to it.
+        """
+        self._setBoundTest("Before")
+
+    def test_set_notAfter(self):
+        """
+        :py:obj:`X509Type.set_notAfter` takes a string in the format of an ASN1
+        GENERALIZEDTIME and sets the end of the certificate's validity period
+        to it.
+        """
+        self._setBoundTest("After")
+
+    def test_get_notBefore(self):
+        """
+        :py:obj:`X509Type.get_notBefore` returns a string in the format of an
+        ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
+        internally.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        self.assertEqual(cert.get_notBefore(), b("20090325123658Z"))
+
+    def test_get_notAfter(self):
+        """
+        :py:obj:`X509Type.get_notAfter` returns a string in the format of an
+        ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
+        internally.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        self.assertEqual(cert.get_notAfter(), b("20170611123658Z"))
+
+    def test_gmtime_adj_notBefore_wrong_args(self):
+        """
+        :py:obj:`X509Type.gmtime_adj_notBefore` raises :py:obj:`TypeError` if
+        called with the wrong number of arguments or a non-:py:obj:`int`
+        argument.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.gmtime_adj_notBefore)
+        self.assertRaises(TypeError, cert.gmtime_adj_notBefore, None)
+        self.assertRaises(TypeError, cert.gmtime_adj_notBefore, 123, None)
+
+    def test_gmtime_adj_notBefore(self):
+        """
+        :py:obj:`X509Type.gmtime_adj_notBefore` changes the not-before
+        timestamp to be the current time plus the number of seconds passed in.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        not_before_min = (
+            datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
+        )
+        cert.gmtime_adj_notBefore(100)
+        not_before = datetime.strptime(
+            cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
+        )
+        not_before_max = datetime.utcnow() + timedelta(seconds=100)
+        self.assertTrue(not_before_min <= not_before <= not_before_max)
+
+    def test_gmtime_adj_notAfter_wrong_args(self):
+        """
+        :py:obj:`X509Type.gmtime_adj_notAfter` raises :py:obj:`TypeError` if
+        called with the wrong number of arguments or a non-:py:obj:`int`
+        argument.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.gmtime_adj_notAfter)
+        self.assertRaises(TypeError, cert.gmtime_adj_notAfter, None)
+        self.assertRaises(TypeError, cert.gmtime_adj_notAfter, 123, None)
+
+    def test_gmtime_adj_notAfter(self):
+        """
+        :py:obj:`X509Type.gmtime_adj_notAfter` changes the not-after timestamp
+        to be the current time plus the number of seconds passed in.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        not_after_min = (
+            datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
+        )
+        cert.gmtime_adj_notAfter(100)
+        not_after = datetime.strptime(
+            cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
+        )
+        not_after_max = datetime.utcnow() + timedelta(seconds=100)
+        self.assertTrue(not_after_min <= not_after <= not_after_max)
+
+    def test_has_expired_wrong_args(self):
+        """
+        :py:obj:`X509Type.has_expired` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.has_expired, None)
+
+    def test_has_expired(self):
+        """
+        :py:obj:`X509Type.has_expired` returns :py:obj:`True` if the
+        certificate's not-after time is in the past.
+        """
+        cert = X509()
+        cert.gmtime_adj_notAfter(-1)
+        self.assertTrue(cert.has_expired())
+
+    def test_has_not_expired(self):
+        """
+        :py:obj:`X509Type.has_expired` returns :py:obj:`False` if the
+        certificate's not-after time is in the future.
+        """
+        cert = X509()
+        cert.gmtime_adj_notAfter(2)
+        self.assertFalse(cert.has_expired())
+
+    def test_root_has_not_expired(self):
+        """
+        :py:obj:`X509Type.has_expired` returns :py:obj:`False` if the
+        certificate's not-after time is in the future.
+        """
+        cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        self.assertFalse(cert.has_expired())
+
+    def test_digest(self):
+        """
+        :py:obj:`X509.digest` returns a string giving ":"-separated hex-encoded
+        words of the digest of the certificate.
+        """
+        cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        self.assertEqual(
+            # This is MD5 instead of GOOD_DIGEST because the digest algorithm
+            # actually matters to the assertion (ie, another arbitrary, good
+            # digest will not product the same digest).
+            # Digest verified with the command:
+            # openssl x509 -in root_cert.pem -noout -fingerprint -md5
+            cert.digest("MD5"),
+            b("19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75"))
+
+    def _extcert(self, pkey, extensions):
+        cert = X509()
+        cert.set_pubkey(pkey)
+        cert.get_subject().commonName = "Unit Tests"
+        cert.get_issuer().commonName = "Unit Tests"
+        when = b(datetime.now().strftime("%Y%m%d%H%M%SZ"))
+        cert.set_notBefore(when)
+        cert.set_notAfter(when)
+
+        cert.add_extensions(extensions)
+        cert.sign(pkey, 'sha1')
+        return load_certificate(
+            FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
+
+    def test_extension_count(self):
+        """
+        :py:obj:`X509.get_extension_count` returns the number of extensions
+        that are present in the certificate.
+        """
+        pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
+        ca = X509Extension(b('basicConstraints'), True, b('CA:FALSE'))
+        key = X509Extension(b('keyUsage'), True, b('digitalSignature'))
+        subjectAltName = X509Extension(
+            b('subjectAltName'), True, b('DNS:example.com'))
+
+        # Try a certificate with no extensions at all.
+        c = self._extcert(pkey, [])
+        self.assertEqual(c.get_extension_count(), 0)
+
+        # And a certificate with one
+        c = self._extcert(pkey, [ca])
+        self.assertEqual(c.get_extension_count(), 1)
+
+        # And a certificate with several
+        c = self._extcert(pkey, [ca, key, subjectAltName])
+        self.assertEqual(c.get_extension_count(), 3)
+
+    def test_get_extension(self):
+        """
+        :py:obj:`X509.get_extension` takes an integer and returns an
+        :py:obj:`X509Extension` corresponding to the extension at that index.
+        """
+        pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
+        ca = X509Extension(b('basicConstraints'), True, b('CA:FALSE'))
+        key = X509Extension(b('keyUsage'), True, b('digitalSignature'))
+        subjectAltName = X509Extension(
+            b('subjectAltName'), False, b('DNS:example.com'))
+
+        cert = self._extcert(pkey, [ca, key, subjectAltName])
+
+        ext = cert.get_extension(0)
+        self.assertTrue(isinstance(ext, X509Extension))
+        self.assertTrue(ext.get_critical())
+        self.assertEqual(ext.get_short_name(), b('basicConstraints'))
+
+        ext = cert.get_extension(1)
+        self.assertTrue(isinstance(ext, X509Extension))
+        self.assertTrue(ext.get_critical())
+        self.assertEqual(ext.get_short_name(), b('keyUsage'))
+
+        ext = cert.get_extension(2)
+        self.assertTrue(isinstance(ext, X509Extension))
+        self.assertFalse(ext.get_critical())
+        self.assertEqual(ext.get_short_name(), b('subjectAltName'))
+
+        self.assertRaises(IndexError, cert.get_extension, -1)
+        self.assertRaises(IndexError, cert.get_extension, 4)
+        self.assertRaises(TypeError, cert.get_extension, "hello")
+
+    def test_nullbyte_subjectAltName(self):
+        """
+        The fields of a `subjectAltName` extension on an X509 may contain NUL
+        bytes and this value is reflected in the string representation of the
+        extension object.
+        """
+        cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
+
+        ext = cert.get_extension(3)
+        self.assertEqual(ext.get_short_name(), b('subjectAltName'))
+        self.assertEqual(
+            b("DNS:altnull.python.org\x00example.com, "
+              "email:null@python.org\x00user@example.org, "
+              "URI:http://null.python.org\x00http://example.org, "
+              "IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n"),
+            b(str(ext)))
+
+    def test_invalid_digest_algorithm(self):
+        """
+        :py:obj:`X509.digest` raises :py:obj:`ValueError` if called with an
+        unrecognized hash algorithm.
+        """
+        cert = X509()
+        self.assertRaises(ValueError, cert.digest, BAD_DIGEST)
+
+    def test_get_subject_wrong_args(self):
+        """
+        :py:obj:`X509.get_subject` raises :py:obj:`TypeError` if called with
+        any arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.get_subject, None)
+
+    def test_get_subject(self):
+        """
+        :py:obj:`X509.get_subject` returns an :py:obj:`X509Name` instance.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        subj = cert.get_subject()
+        self.assertTrue(isinstance(subj, X509Name))
+        self.assertEquals(
+            subj.get_components(),
+            [(b('C'), b('US')), (b('ST'), b('IL')), (b('L'), b('Chicago')),
+             (b('O'), b('Testing')), (b('CN'), b('Testing Root CA'))])
+
+    def test_set_subject_wrong_args(self):
+        """
+        :py:obj:`X509.set_subject` raises a :py:obj:`TypeError` if called with
+        the wrong number of arguments or an argument not of type
+        :py:obj:`X509Name`.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.set_subject)
+        self.assertRaises(TypeError, cert.set_subject, None)
+        with pytest.raises(TypeError):
+            cert.set_subject(cert.get_subject(), None)
+
+    def test_set_subject(self):
+        """
+        :py:obj:`X509.set_subject` changes the subject of the certificate to
+        the one passed in.
+        """
+        cert = X509()
+        name = cert.get_subject()
+        name.C = 'AU'
+        name.O = 'Unit Tests'
+        cert.set_subject(name)
+        self.assertEquals(
+            cert.get_subject().get_components(),
+            [(b('C'), b('AU')), (b('O'), b('Unit Tests'))])
+
+    def test_get_issuer_wrong_args(self):
+        """
+        :py:obj:`X509.get_issuer` raises :py:obj:`TypeError` if called with any
+        arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.get_issuer, None)
+
+    def test_get_issuer(self):
+        """
+        :py:obj:`X509.get_issuer` returns an :py:obj:`X509Name` instance.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        subj = cert.get_issuer()
+        self.assertTrue(isinstance(subj, X509Name))
+        comp = subj.get_components()
+        self.assertEquals(
+            comp,
+            [(b('C'), b('US')), (b('ST'), b('IL')), (b('L'), b('Chicago')),
+             (b('O'), b('Testing')), (b('CN'), b('Testing Root CA'))])
+
+    def test_set_issuer_wrong_args(self):
+        """
+        :py:obj:`X509.set_issuer` raises a :py:obj:`TypeError` if called with
+        the wrong number of arguments or an argument not of type
+        :py:obj:`X509Name`.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.set_issuer)
+        self.assertRaises(TypeError, cert.set_issuer, None)
+        self.assertRaises(TypeError, cert.set_issuer, cert.get_issuer(), None)
+
+    def test_set_issuer(self):
+        """
+        :py:obj:`X509.set_issuer` changes the issuer of the certificate to the
+        one passed in.
+        """
+        cert = X509()
+        name = cert.get_issuer()
+        name.C = 'AU'
+        name.O = 'Unit Tests'
+        cert.set_issuer(name)
+        self.assertEquals(
+            cert.get_issuer().get_components(),
+            [(b('C'), b('AU')), (b('O'), b('Unit Tests'))])
+
+    def test_get_pubkey_uninitialized(self):
+        """
+        When called on a certificate with no public key,
+        :py:obj:`X509.get_pubkey` raises :py:obj:`OpenSSL.crypto.Error`.
+        """
+        cert = X509()
+        self.assertRaises(Error, cert.get_pubkey)
+
+    def test_subject_name_hash_wrong_args(self):
+        """
+        :py:obj:`X509.subject_name_hash` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        cert = X509()
+        self.assertRaises(TypeError, cert.subject_name_hash, None)
+
+    def test_subject_name_hash(self):
+        """
+        :py:obj:`X509.subject_name_hash` returns the hash of the certificate's
+        subject name.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        self.assertIn(
+            cert.subject_name_hash(),
+            [3350047874,  # OpenSSL 0.9.8, MD5
+             3278919224,  # OpenSSL 1.0.0, SHA1
+             ])
+
+    def test_get_signature_algorithm(self):
+        """
+        :py:obj:`X509Type.get_signature_algorithm` returns a string which means
+        the algorithm used to sign the certificate.
+        """
+        cert = load_certificate(FILETYPE_PEM, self.pemData)
+        self.assertEqual(
+            b("sha1WithRSAEncryption"), cert.get_signature_algorithm())
+
+    def test_get_undefined_signature_algorithm(self):
+        """
+        :py:obj:`X509Type.get_signature_algorithm` raises :py:obj:`ValueError`
+        if the signature algorithm is undefined or unknown.
+        """
+        # This certificate has been modified to indicate a bogus OID in the
+        # signature algorithm field so that OpenSSL does not recognize it.
+        certPEM = b("""\
+-----BEGIN CERTIFICATE-----
+MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
+EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
+cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
+MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
+EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
+CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
+AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
++fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
+hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
+BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
+FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
+dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
+aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
+MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
+jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
+PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
+tgI5
+-----END CERTIFICATE-----
+""")
+        cert = load_certificate(FILETYPE_PEM, certPEM)
+        self.assertRaises(ValueError, cert.get_signature_algorithm)
+
+
+class X509StoreTests(TestCase):
+    """
+    Test for :py:obj:`OpenSSL.crypto.X509Store`.
+    """
+
+    def test_type(self):
+        """
+        :py:obj:`X509StoreType` is a type object.
+        """
+        self.assertIdentical(X509Store, X509StoreType)
+        self.assertConsistentType(X509Store, 'X509Store')
+
+    def test_add_cert_wrong_args(self):
+        store = X509Store()
+        self.assertRaises(TypeError, store.add_cert)
+        self.assertRaises(TypeError, store.add_cert, object())
+        self.assertRaises(TypeError, store.add_cert, X509(), object())
+
+    def test_add_cert(self):
+        """
+        :py:obj:`X509Store.add_cert` adds a :py:obj:`X509` instance to the
+        certificate store.
+        """
+        cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
+        store = X509Store()
+        store.add_cert(cert)
+
+    def test_add_cert_rejects_duplicate(self):
+        """
+        :py:obj:`X509Store.add_cert` raises :py:obj:`OpenSSL.crypto.Error` if
+        an attempt is made to add the same certificate to the store more than
+        once.
+        """
+        cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
+        store = X509Store()
+        store.add_cert(cert)
+        self.assertRaises(Error, store.add_cert, cert)
+
+
+class PKCS12Tests(TestCase):
+    """
+    Test for :py:obj:`OpenSSL.crypto.PKCS12` and
+    :py:obj:`OpenSSL.crypto.load_pkcs12`.
+    """
+    pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
+
+    def test_type(self):
+        """
+        :py:obj:`PKCS12Type` is a type object.
+        """
+        self.assertIdentical(PKCS12, PKCS12Type)
+        self.assertConsistentType(PKCS12, 'PKCS12')
+
+    def test_empty_construction(self):
+        """
+        :py:obj:`PKCS12` returns a new instance of :py:obj:`PKCS12` with no
+        certificate, private key, CA certificates, or friendly name.
+        """
+        p12 = PKCS12()
+        self.assertEqual(None, p12.get_certificate())
+        self.assertEqual(None, p12.get_privatekey())
+        self.assertEqual(None, p12.get_ca_certificates())
+        self.assertEqual(None, p12.get_friendlyname())
+
+    def test_type_errors(self):
+        """
+        The :py:obj:`PKCS12` setter functions (:py:obj:`set_certificate`,
+        :py:obj:`set_privatekey`, :py:obj:`set_ca_certificates`, and
+        :py:obj:`set_friendlyname`) raise :py:obj:`TypeError` when passed
+        objects of types other than those expected.
+        """
+        p12 = PKCS12()
+        self.assertRaises(TypeError, p12.set_certificate, 3)
+        self.assertRaises(TypeError, p12.set_certificate, PKey())
+        self.assertRaises(TypeError, p12.set_certificate, X509)
+        self.assertRaises(TypeError, p12.set_privatekey, 3)
+        self.assertRaises(TypeError, p12.set_privatekey, 'legbone')
+        self.assertRaises(TypeError, p12.set_privatekey, X509())
+        self.assertRaises(TypeError, p12.set_ca_certificates, 3)
+        self.assertRaises(TypeError, p12.set_ca_certificates, X509())
+        self.assertRaises(TypeError, p12.set_ca_certificates, (3, 4))
+        self.assertRaises(TypeError, p12.set_ca_certificates, (PKey(),))
+        self.assertRaises(TypeError, p12.set_friendlyname, 6)
+        self.assertRaises(TypeError, p12.set_friendlyname, ('foo', 'bar'))
+
+    def test_key_only(self):
+        """
+        A :py:obj:`PKCS12` with only a private key can be exported using
+        :py:obj:`PKCS12.export` and loaded again using :py:obj:`load_pkcs12`.
+        """
+        passwd = b"blah"
+        p12 = PKCS12()
+        pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        p12.set_privatekey(pkey)
+        self.assertEqual(None, p12.get_certificate())
+        self.assertEqual(pkey, p12.get_privatekey())
+        try:
+            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
+        except Error:
+            # Some versions of OpenSSL will throw an exception
+            # for this nearly useless PKCS12 we tried to generate:
+            # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
+            return
+        p12 = load_pkcs12(dumped_p12, passwd)
+        self.assertEqual(None, p12.get_ca_certificates())
+        self.assertEqual(None, p12.get_certificate())
+
+        # OpenSSL fails to bring the key back to us.  So sad.  Perhaps in the
+        # future this will be improved.
+        self.assertTrue(isinstance(p12.get_privatekey(), (PKey, type(None))))
+
+    def test_cert_only(self):
+        """
+        A :py:obj:`PKCS12` with only a certificate can be exported using
+        :py:obj:`PKCS12.export` and loaded again using :py:obj:`load_pkcs12`.
+        """
+        passwd = b"blah"
+        p12 = PKCS12()
+        cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
+        p12.set_certificate(cert)
+        self.assertEqual(cert, p12.get_certificate())
+        self.assertEqual(None, p12.get_privatekey())
+        try:
+            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
+        except Error:
+            # Some versions of OpenSSL will throw an exception
+            # for this nearly useless PKCS12 we tried to generate:
+            # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
+            return
+        p12 = load_pkcs12(dumped_p12, passwd)
+        self.assertEqual(None, p12.get_privatekey())
+
+        # OpenSSL fails to bring the cert back to us.  Groany mcgroan.
+        self.assertTrue(isinstance(p12.get_certificate(), (X509, type(None))))
+
+        # Oh ho.  It puts the certificate into the ca certificates list, in
+        # fact.  Totally bogus, I would think.  Nevertheless, let's exploit
+        # that to check to see if it reconstructed the certificate we expected
+        # it to.  At some point, hopefully this will change so that
+        # p12.get_certificate() is actually what returns the loaded
+        # certificate.
+        self.assertEqual(
+            cleartextCertificatePEM,
+            dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
+
+    def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
+                   friendly_name=None):
+        """
+        Generate a PKCS12 object with components from PEM.  Verify that the set
+        functions return None.
+        """
+        p12 = PKCS12()
+        if cert_pem:
+            ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
+            self.assertEqual(ret, None)
+        if key_pem:
+            ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
+            self.assertEqual(ret, None)
+        if ca_pem:
+            ret = p12.set_ca_certificates(
+                (load_certificate(FILETYPE_PEM, ca_pem),)
+            )
+            self.assertEqual(ret, None)
+        if friendly_name:
+            ret = p12.set_friendlyname(friendly_name)
+            self.assertEqual(ret, None)
+        return p12
+
+    def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
+                       extra=()):
+        """
+        Use openssl program to confirm three components are recoverable from a
+        PKCS12 string.
+        """
+        if key:
+            recovered_key = _runopenssl(
+                p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
+                b"pass:" + passwd, *extra)
+            self.assertEqual(recovered_key[-len(key):], key)
+        if cert:
+            recovered_cert = _runopenssl(
+                p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
+                b"pass:" + passwd, b"-nokeys", *extra)
+            self.assertEqual(recovered_cert[-len(cert):], cert)
+        if ca:
+            recovered_cert = _runopenssl(
+                p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
+                b"pass:" + passwd, b"-nokeys", *extra)
+            self.assertEqual(recovered_cert[-len(ca):], ca)
+
+    def verify_pkcs12_container(self, p12):
+        """
+        Verify that the PKCS#12 container contains the correct client
+        certificate and private key.
+
+        :param p12: The PKCS12 instance to verify.
+        :type p12: :py:class:`PKCS12`
+        """
+        cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
+        key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
+        self.assertEqual(
+            (client_cert_pem, client_key_pem, None),
+            (cert_pem, key_pem, p12.get_ca_certificates()))
+
+    def test_load_pkcs12(self):
+        """
+        A PKCS12 string generated using the openssl command line can be loaded
+        with :py:obj:`load_pkcs12` and its components extracted and examined.
+        """
+        passwd = b"whatever"
+        pem = client_key_pem + client_cert_pem
+        p12_str = _runopenssl(
+            pem,
+            b"pkcs12",
+            b"-export",
+            b"-clcerts",
+            b"-passout",
+            b"pass:" + passwd
+        )
+        p12 = load_pkcs12(p12_str, passphrase=passwd)
+        self.verify_pkcs12_container(p12)
+
+    def test_load_pkcs12_text_passphrase(self):
+        """
+        A PKCS12 string generated using the openssl command line can be loaded
+        with :py:obj:`load_pkcs12` and its components extracted and examined.
+        Using text as passphrase instead of bytes. DeprecationWarning expected.
+        """
+        pem = client_key_pem + client_cert_pem
+        passwd = b"whatever"
+        p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
+                              b"-passout", b"pass:" + passwd)
+        with catch_warnings(record=True) as w:
+            simplefilter("always")
+            p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
+
+            self.assertEqual(
+                "{0} for passphrase is no longer accepted, use bytes".format(
+                    WARNING_TYPE_EXPECTED
+                ),
+                str(w[-1].message)
+            )
+            self.assertIs(w[-1].category, DeprecationWarning)
+
+        self.verify_pkcs12_container(p12)
+
+    def test_load_pkcs12_no_passphrase(self):
+        """
+        A PKCS12 string generated using openssl command line can be loaded with
+        :py:obj:`load_pkcs12` without a passphrase and its components extracted
+        and examined.
+        """
+        pem = client_key_pem + client_cert_pem
+        p12_str = _runopenssl(
+            pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
+        p12 = load_pkcs12(p12_str)
+        self.verify_pkcs12_container(p12)
+
+    def _dump_and_load(self, dump_passphrase, load_passphrase):
+        """
+        A helper method to dump and load a PKCS12 object.
+        """
+        p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
+        dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
+        return load_pkcs12(dumped_p12, passphrase=load_passphrase)
+
+    def test_load_pkcs12_null_passphrase_load_empty(self):
+        """
+        A PKCS12 string can be dumped with a null passphrase, loaded with an
+        empty passphrase with :py:obj:`load_pkcs12`, and its components
+        extracted and examined.
+        """
+        self.verify_pkcs12_container(
+            self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
+
+    def test_load_pkcs12_null_passphrase_load_null(self):
+        """
+        A PKCS12 string can be dumped with a null passphrase, loaded with a
+        null passphrase with :py:obj:`load_pkcs12`, and its components
+        extracted and examined.
+        """
+        self.verify_pkcs12_container(
+            self._dump_and_load(dump_passphrase=None, load_passphrase=None))
+
+    def test_load_pkcs12_empty_passphrase_load_empty(self):
+        """
+        A PKCS12 string can be dumped with an empty passphrase, loaded with an
+        empty passphrase with :py:obj:`load_pkcs12`, and its components
+        extracted and examined.
+        """
+        self.verify_pkcs12_container(
+            self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
+
+    def test_load_pkcs12_empty_passphrase_load_null(self):
+        """
+        A PKCS12 string can be dumped with an empty passphrase, loaded with a
+        null passphrase with :py:obj:`load_pkcs12`, and its components
+        extracted and examined.
+        """
+        self.verify_pkcs12_container(
+            self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
+
+    def test_load_pkcs12_garbage(self):
+        """
+        :py:obj:`load_pkcs12` raises :py:obj:`OpenSSL.crypto.Error` when passed
+        a string which is not a PKCS12 dump.
+        """
+        passwd = 'whatever'
+        e = self.assertRaises(Error, load_pkcs12, b'fruit loops', passwd)
+        self.assertEqual(e.args[0][0][0], 'asn1 encoding routines')
+        self.assertEqual(len(e.args[0][0]), 3)
+
+    def test_replace(self):
+        """
+        :py:obj:`PKCS12.set_certificate` replaces the certificate in a PKCS12
+        cluster. :py:obj:`PKCS12.set_privatekey` replaces the private key.
+        :py:obj:`PKCS12.set_ca_certificates` replaces the CA certificates.
+        """
+        p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
+        p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
+        p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
+        p12.set_ca_certificates([root_cert])  # not a tuple
+        self.assertEqual(1, len(p12.get_ca_certificates()))
+        self.assertEqual(root_cert, p12.get_ca_certificates()[0])
+        p12.set_ca_certificates([client_cert, root_cert])
+        self.assertEqual(2, len(p12.get_ca_certificates()))
+        self.assertEqual(client_cert, p12.get_ca_certificates()[0])
+        self.assertEqual(root_cert, p12.get_ca_certificates()[1])
+
+    def test_friendly_name(self):
+        """
+        The *friendlyName* of a PKCS12 can be set and retrieved via
+        :py:obj:`PKCS12.get_friendlyname` and
+        :py:obj:`PKCS12_set_friendlyname`, and a :py:obj:`PKCS12` with a
+        friendly name set can be dumped with :py:obj:`PKCS12.export`.
+        """
+        passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+        for friendly_name in [b('Serverlicious'), None, b('###')]:
+            p12.set_friendlyname(friendly_name)
+            self.assertEqual(p12.get_friendlyname(), friendly_name)
+            dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
+            reloaded_p12 = load_pkcs12(dumped_p12, passwd)
+            self.assertEqual(
+                p12.get_friendlyname(), reloaded_p12.get_friendlyname())
+            # We would use the openssl program to confirm the friendly
+            # name, but it is not possible.  The pkcs12 command
+            # does not store the friendly name in the cert's
+            # alias, which we could then extract.
+            self.check_recovery(
+                dumped_p12, key=server_key_pem, cert=server_cert_pem,
+                ca=root_cert_pem, passwd=passwd)
+
+    def test_various_empty_passphrases(self):
+        """
+        Test that missing, None, and '' passphrases are identical for PKCS12
+        export.
+        """
+        p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
+        passwd = b""
+        dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
+        dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
+        dumped_p12_nopw = p12.export(iter=9, maciter=4)
+        for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
+            self.check_recovery(
+                dumped_p12, key=client_key_pem, cert=client_cert_pem,
+                ca=root_cert_pem, passwd=passwd)
+
+    def test_removing_ca_cert(self):
+        """
+        Passing :py:obj:`None` to :py:obj:`PKCS12.set_ca_certificates` removes
+        all CA certificates.
+        """
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+        p12.set_ca_certificates(None)
+        self.assertEqual(None, p12.get_ca_certificates())
+
+    def test_export_without_mac(self):
+        """
+        Exporting a PKCS12 with a :py:obj:`maciter` of ``-1`` excludes the MAC
+        entirely.
+        """
+        passwd = b"Lake Michigan"
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+        dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
+        self.check_recovery(
+            dumped_p12, key=server_key_pem, cert=server_cert_pem,
+            passwd=passwd, extra=(b"-nomacver",))
+
+    def test_load_without_mac(self):
+        """
+        Loading a PKCS12 without a MAC does something other than crash.
+        """
+        passwd = b"Lake Michigan"
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+        dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
+        try:
+            recovered_p12 = load_pkcs12(dumped_p12, passwd)
+            # The person who generated this PCKS12 should be flogged,
+            # or better yet we should have a means to determine
+            # whether a PCKS12 had a MAC that was verified.
+            # Anyway, libopenssl chooses to allow it, so the
+            # pyopenssl binding does as well.
+            self.assertTrue(isinstance(recovered_p12, PKCS12))
+        except Error:
+            # Failing here with an exception is preferred as some openssl
+            # versions do.
+            pass
+
+    def test_zero_len_list_for_ca(self):
+        """
+        A PKCS12 with an empty CA certificates list can be exported.
+        """
+        passwd = b'Hobie 18'
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
+        p12.set_ca_certificates([])
+        self.assertEqual((), p12.get_ca_certificates())
+        dumped_p12 = p12.export(passphrase=passwd, iter=3)
+        self.check_recovery(
+            dumped_p12, key=server_key_pem, cert=server_cert_pem,
+            passwd=passwd)
+
+    def test_export_without_args(self):
+        """
+        All the arguments to :py:obj:`PKCS12.export` are optional.
+        """
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+        dumped_p12 = p12.export()  # no args
+        self.check_recovery(
+            dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
+
+    def test_export_without_bytes(self):
+        """
+        Test :py:obj:`PKCS12.export` with text not bytes as passphrase
+        """
+        p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
+
+        with catch_warnings(record=True) as w:
+            simplefilter("always")
+            dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
+            self.assertEqual(
+                "{0} for passphrase is no longer accepted, use bytes".format(
+                    WARNING_TYPE_EXPECTED
+                ),
+                str(w[-1].message)
+            )
+            self.assertIs(w[-1].category, DeprecationWarning)
+        self.check_recovery(
+            dumped_p12,
+            key=server_key_pem,
+            cert=server_cert_pem,
+            passwd=b"randomtext"
+        )
+
+    def test_key_cert_mismatch(self):
+        """
+        :py:obj:`PKCS12.export` raises an exception when a key and certificate
+        mismatch.
+        """
+        p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
+        self.assertRaises(Error, p12.export)
+
+
+# These quoting functions taken directly from Twisted's twisted.python.win32.
+_cmdLineQuoteRe = re.compile(br'(\\*)"')
+_cmdLineQuoteRe2 = re.compile(br'(\\+)\Z')
+
+
+def cmdLineQuote(s):
+    """
+    Internal method for quoting a single command-line argument.
+
+    See http://www.perlmonks.org/?node_id=764004
+
+    :type: :py:obj:`str`
+    :param s: A single unquoted string to quote for something that is expecting
+        cmd.exe-style quoting
+
+    :rtype: :py:obj:`str`
+    :return: A cmd.exe-style quoted string
+    """
+    s = _cmdLineQuoteRe2.sub(br"\1\1", _cmdLineQuoteRe.sub(br'\1\1\\"', s))
+    return b'"' + s + b'"'
+
+
+def quoteArguments(arguments):
+    """
+    Quote an iterable of command-line arguments for passing to CreateProcess or
+    a similar API.  This allows the list passed to
+    :py:obj:`reactor.spawnProcess` to match the child process's
+    :py:obj:`sys.argv` properly.
+
+    :type arguments: :py:obj:`iterable` of :py:obj:`str`
+    :param arguments: An iterable of unquoted arguments to quote
+
+    :rtype: :py:obj:`str`
+    :return: A space-delimited string containing quoted versions of
+        :py:obj:`arguments`
+    """
+    return b' '.join(map(cmdLineQuote, arguments))
+
+
+def _runopenssl(pem, *args):
+    """
+    Run the command line openssl tool with the given arguments and write
+    the given PEM to its stdin.  Not safe for quotes.
+    """
+    if os.name == 'posix':
+        command = b"openssl " + b" ".join([
+            (b"'" + arg.replace(b"'", b"'\\''") + b"'")
+            for arg in args
+        ])
+    else:
+        command = b"openssl " + quoteArguments(args)
+    proc = Popen(native(command), shell=True, stdin=PIPE, stdout=PIPE)
+    proc.stdin.write(pem)
+    proc.stdin.close()
+    output = proc.stdout.read()
+    proc.stdout.close()
+    proc.wait()
+    return output
+
+
+class FunctionTests(TestCase):
+    """
+    Tests for free-functions in the :py:obj:`OpenSSL.crypto` module.
+    """
+
+    def test_load_privatekey_invalid_format(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`ValueError` if passed an
+        unknown filetype.
+        """
+        self.assertRaises(ValueError, load_privatekey, 100, root_key_pem)
+
+    def test_load_privatekey_invalid_passphrase_type(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`TypeError` if passed a
+        passphrase that is neither a :py:obj:`str` nor a callable.
+        """
+        self.assertRaises(
+            TypeError,
+            load_privatekey,
+            FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
+
+    def test_load_privatekey_wrong_args(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`TypeError` if called with the
+        wrong number of arguments.
+        """
+        self.assertRaises(TypeError, load_privatekey)
+
+    def test_load_privatekey_wrongPassphrase(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`OpenSSL.crypto.Error` when it
+        is passed an encrypted PEM and an incorrect passphrase.
+        """
+        self.assertRaises(
+            Error,
+            load_privatekey, FILETYPE_PEM, encryptedPrivateKeyPEM, b("quack"))
+
+    def test_load_privatekey_passphraseWrongType(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`ValueError` when it is passed
+        a passphrase with a private key encoded in a format, that doesn't
+        support encryption.
+        """
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        blob = dump_privatekey(FILETYPE_ASN1, key)
+        self.assertRaises(ValueError,
+                          load_privatekey, FILETYPE_ASN1, blob, "secret")
+
+    def test_load_privatekey_passphrase(self):
+        """
+        :py:obj:`load_privatekey` can create a :py:obj:`PKey` object from an
+        encrypted PEM string if given the passphrase.
+        """
+        key = load_privatekey(
+            FILETYPE_PEM, encryptedPrivateKeyPEM,
+            encryptedPrivateKeyPEMPassphrase)
+        self.assertTrue(isinstance(key, PKeyType))
+
+    def test_load_privatekey_passphrase_exception(self):
+        """
+        If the passphrase callback raises an exception, that exception is
+        raised by :py:obj:`load_privatekey`.
+        """
+        def cb(ignored):
+            raise ArithmeticError
+
+        with pytest.raises(ArithmeticError):
+            load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
+
+    def test_load_privatekey_wrongPassphraseCallback(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`OpenSSL.crypto.Error` when it
+        is passed an encrypted PEM and a passphrase callback which returns an
+        incorrect passphrase.
+        """
+        called = []
+
+        def cb(*a):
+            called.append(None)
+            return b("quack")
+        self.assertRaises(
+            Error,
+            load_privatekey, FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
+        self.assertTrue(called)
+
+    def test_load_privatekey_passphraseCallback(self):
+        """
+        :py:obj:`load_privatekey` can create a :py:obj:`PKey` object from an
+        encrypted PEM string if given a passphrase callback which returns the
+        correct password.
+        """
+        called = []
+
+        def cb(writing):
+            called.append(writing)
+            return encryptedPrivateKeyPEMPassphrase
+        key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
+        self.assertTrue(isinstance(key, PKeyType))
+        self.assertEqual(called, [False])
+
+    def test_load_privatekey_passphrase_wrong_return_type(self):
+        """
+        :py:obj:`load_privatekey` raises :py:obj:`ValueError` if the passphrase
+        callback returns something other than a byte string.
+        """
+        self.assertRaises(
+            ValueError,
+            load_privatekey,
+            FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
+
+    def test_dump_privatekey_wrong_args(self):
+        """
+        :py:obj:`dump_privatekey` raises :py:obj:`TypeError` if called with the
+        wrong number of arguments.
+        """
+        self.assertRaises(TypeError, dump_privatekey)
+        # If cipher name is given, password is required.
+        self.assertRaises(
+            TypeError, dump_privatekey, FILETYPE_PEM, PKey(), GOOD_CIPHER)
+
+    def test_dump_privatekey_unknown_cipher(self):
+        """
+        :py:obj:`dump_privatekey` raises :py:obj:`ValueError` if called with an
+        unrecognized cipher name.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        self.assertRaises(
+            ValueError, dump_privatekey,
+            FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
+
+    def test_dump_privatekey_invalid_passphrase_type(self):
+        """
+        :py:obj:`dump_privatekey` raises :py:obj:`TypeError` if called with a
+        passphrase which is neither a :py:obj:`str` nor a callable.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        self.assertRaises(
+            TypeError,
+            dump_privatekey, FILETYPE_PEM, key, GOOD_CIPHER, object())
+
+    def test_dump_privatekey_invalid_filetype(self):
+        """
+        :py:obj:`dump_privatekey` raises :py:obj:`ValueError` if called with an
+        unrecognized filetype.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 512)
+        self.assertRaises(ValueError, dump_privatekey, 100, key)
+
+    def test_load_privatekey_passphraseCallbackLength(self):
+        """
+        :py:obj:`crypto.load_privatekey` should raise an error when the
+        passphrase provided by the callback is too long, not silently truncate
+        it.
+        """
+        def cb(ignored):
+            return "a" * 1025
+
+        with pytest.raises(ValueError):
+            load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
+
+    def test_dump_privatekey_passphrase(self):
+        """
+        :py:obj:`dump_privatekey` writes an encrypted PEM when given a
+        passphrase.
+        """
+        passphrase = b("foo")
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
+        self.assertTrue(isinstance(pem, binary_type))
+        loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
+        self.assertTrue(isinstance(loadedKey, PKeyType))
+        self.assertEqual(loadedKey.type(), key.type())
+        self.assertEqual(loadedKey.bits(), key.bits())
+
+    def test_dump_privatekey_passphraseWrongType(self):
+        """
+        :py:obj:`dump_privatekey` raises :py:obj:`ValueError` when it is passed
+        a passphrase with a private key encoded in a format, that doesn't
+        support encryption.
+        """
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        with pytest.raises(ValueError):
+            dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
+
+    def test_dump_certificate(self):
+        """
+        :py:obj:`dump_certificate` writes PEM, DER, and text.
+        """
+        pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
+        cert = load_certificate(FILETYPE_PEM, pemData)
+        dumped_pem = dump_certificate(FILETYPE_PEM, cert)
+        self.assertEqual(dumped_pem, cleartextCertificatePEM)
+        dumped_der = dump_certificate(FILETYPE_ASN1, cert)
+        good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
+        self.assertEqual(dumped_der, good_der)
+        cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
+        dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
+        self.assertEqual(dumped_pem2, cleartextCertificatePEM)
+        dumped_text = dump_certificate(FILETYPE_TEXT, cert)
+        good_text = _runopenssl(dumped_pem, b"x509", b"-noout", b"-text")
+        self.assertEqual(dumped_text, good_text)
+
+    def test_dump_privatekey_pem(self):
+        """
+        :py:obj:`dump_privatekey` writes a PEM
+        """
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        self.assertTrue(key.check())
+        dumped_pem = dump_privatekey(FILETYPE_PEM, key)
+        self.assertEqual(dumped_pem, cleartextPrivateKeyPEM)
+
+    def test_dump_privatekey_asn1(self):
+        """
+        :py:obj:`dump_privatekey` writes a DER
+        """
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        dumped_pem = dump_privatekey(FILETYPE_PEM, key)
+
+        dumped_der = dump_privatekey(FILETYPE_ASN1, key)
+        # XXX This OpenSSL call writes "writing RSA key" to standard out.  Sad.
+        good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
+        self.assertEqual(dumped_der, good_der)
+        key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
+        dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
+        self.assertEqual(dumped_pem2, cleartextPrivateKeyPEM)
+
+    def test_dump_privatekey_text(self):
+        """
+        :py:obj:`dump_privatekey` writes a text
+        """
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        dumped_pem = dump_privatekey(FILETYPE_PEM, key)
+
+        dumped_text = dump_privatekey(FILETYPE_TEXT, key)
+        good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
+        self.assertEqual(dumped_text, good_text)
+
+    def test_dump_certificate_request(self):
+        """
+        :py:obj:`dump_certificate_request` writes a PEM, DER, and text.
+        """
+        req = load_certificate_request(
+            FILETYPE_PEM, cleartextCertificateRequestPEM)
+        dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
+        self.assertEqual(dumped_pem, cleartextCertificateRequestPEM)
+        dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
+        good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
+        self.assertEqual(dumped_der, good_der)
+        req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
+        dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
+        self.assertEqual(dumped_pem2, cleartextCertificateRequestPEM)
+        dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
+        good_text = _runopenssl(dumped_pem, b"req", b"-noout", b"-text")
+        self.assertEqual(dumped_text, good_text)
+        self.assertRaises(ValueError, dump_certificate_request, 100, req)
+
+    def test_dump_privatekey_passphraseCallback(self):
+        """
+        :py:obj:`dump_privatekey` writes an encrypted PEM when given a callback
+        which returns the correct passphrase.
+        """
+        passphrase = b("foo")
+        called = []
+
+        def cb(writing):
+            called.append(writing)
+            return passphrase
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
+        self.assertTrue(isinstance(pem, binary_type))
+        self.assertEqual(called, [True])
+        loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
+        self.assertTrue(isinstance(loadedKey, PKeyType))
+        self.assertEqual(loadedKey.type(), key.type())
+        self.assertEqual(loadedKey.bits(), key.bits())
+
+    def test_dump_privatekey_passphrase_exception(self):
+        """
+        :py:obj:`dump_privatekey` should not overwrite the exception raised
+        by the passphrase callback.
+        """
+        def cb(ignored):
+            raise ArithmeticError
+
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        with pytest.raises(ArithmeticError):
+            dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
+
+    def test_dump_privatekey_passphraseCallbackLength(self):
+        """
+        :py:obj:`crypto.dump_privatekey` should raise an error when the
+        passphrase provided by the callback is too long, not silently truncate
+        it.
+        """
+        def cb(ignored):
+            return "a" * 1025
+
+        key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+        with pytest.raises(ValueError):
+            dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
+
+    def test_load_pkcs7_data_pem(self):
+        """
+        :py:obj:`load_pkcs7_data` accepts a PKCS#7 string and returns an
+        instance of :py:obj:`PKCS7Type`.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertTrue(isinstance(pkcs7, PKCS7Type))
+
+    def test_load_pkcs7_data_asn1(self):
+        """
+        :py:obj:`load_pkcs7_data` accepts a bytes containing ASN1 data
+        representing PKCS#7 and returns an instance of :py:obj`PKCS7Type`.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
+        self.assertTrue(isinstance(pkcs7, PKCS7Type))
+
+    def test_load_pkcs7_data_invalid(self):
+        """
+        If the data passed to :py:obj:`load_pkcs7_data` is invalid,
+        :py:obj:`Error` is raised.
+        """
+        self.assertRaises(Error, load_pkcs7_data, FILETYPE_PEM, b"foo")
+
+
+class LoadCertificateTests(TestCase):
+    """
+    Tests for :py:obj:`load_certificate_request`.
+    """
+
+    def test_badFileType(self):
+        """
+        If the file type passed to :py:obj:`load_certificate_request` is
+        neither :py:obj:`FILETYPE_PEM` nor :py:obj:`FILETYPE_ASN1` then
+        :py:class:`ValueError` is raised.
+        """
+        self.assertRaises(ValueError, load_certificate_request, object(), b"")
+
+
+class PKCS7Tests(TestCase):
+    """
+    Tests for :py:obj:`PKCS7Type`.
+    """
+
+    def test_type(self):
+        """
+        :py:obj:`PKCS7Type` is a type object.
+        """
+        self.assertTrue(isinstance(PKCS7Type, type))
+        self.assertEqual(PKCS7Type.__name__, 'PKCS7')
+
+        # XXX This doesn't currently work.
+        # self.assertIdentical(PKCS7, PKCS7Type)
+
+    # XXX Opposite results for all these following methods
+
+    def test_type_is_signed_wrong_args(self):
+        """
+        :py:obj:`PKCS7Type.type_is_signed` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(TypeError, pkcs7.type_is_signed, None)
+
+    def test_type_is_signed(self):
+        """
+        :py:obj:`PKCS7Type.type_is_signed` returns :py:obj:`True` if the PKCS7
+        object is of the type *signed*.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertTrue(pkcs7.type_is_signed())
+
+    def test_type_is_enveloped_wrong_args(self):
+        """
+        :py:obj:`PKCS7Type.type_is_enveloped` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(TypeError, pkcs7.type_is_enveloped, None)
+
+    def test_type_is_enveloped(self):
+        """
+        :py:obj:`PKCS7Type.type_is_enveloped` returns :py:obj:`False` if the
+        PKCS7 object is not of the type *enveloped*.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertFalse(pkcs7.type_is_enveloped())
+
+    def test_type_is_signedAndEnveloped_wrong_args(self):
+        """
+        :py:obj:`PKCS7Type.type_is_signedAndEnveloped` raises
+        :py:obj:`TypeError` if called with any arguments.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(TypeError, pkcs7.type_is_signedAndEnveloped, None)
+
+    def test_type_is_signedAndEnveloped(self):
+        """
+        :py:obj:`PKCS7Type.type_is_signedAndEnveloped` returns :py:obj:`False`
+        if the PKCS7 object is not of the type *signed and enveloped*.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertFalse(pkcs7.type_is_signedAndEnveloped())
+
+    def test_type_is_data(self):
+        """
+        :py:obj:`PKCS7Type.type_is_data` returns :py:obj:`False` if the PKCS7
+        object is not of the type data.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertFalse(pkcs7.type_is_data())
+
+    def test_type_is_data_wrong_args(self):
+        """
+        :py:obj:`PKCS7Type.type_is_data` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(TypeError, pkcs7.type_is_data, None)
+
+    def test_get_type_name_wrong_args(self):
+        """
+        :py:obj:`PKCS7Type.get_type_name` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(TypeError, pkcs7.get_type_name, None)
+
+    def test_get_type_name(self):
+        """
+        :py:obj:`PKCS7Type.get_type_name` returns a :py:obj:`str` giving the
+        type name.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertEquals(pkcs7.get_type_name(), b('pkcs7-signedData'))
+
+    def test_attribute(self):
+        """
+        If an attribute other than one of the methods tested here is accessed
+        on an instance of :py:obj:`PKCS7Type`, :py:obj:`AttributeError` is
+        raised.
+        """
+        pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
+        self.assertRaises(AttributeError, getattr, pkcs7, "foo")
+
+
+class NetscapeSPKITests(TestCase, _PKeyInteractionTestsMixin):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.NetscapeSPKI`.
+    """
+
+    def signable(self):
+        """
+        Return a new :py:obj:`NetscapeSPKI` for use with signing tests.
+        """
+        return NetscapeSPKI()
+
+    def test_type(self):
+        """
+        :py:obj:`NetscapeSPKI` and :py:obj:`NetscapeSPKIType` refer to the same
+        type object and can be used to create instances of that type.
+        """
+        self.assertIdentical(NetscapeSPKI, NetscapeSPKIType)
+        self.assertConsistentType(NetscapeSPKI, 'NetscapeSPKI')
+
+    def test_construction(self):
+        """
+        :py:obj:`NetscapeSPKI` returns an instance of
+        :py:obj:`NetscapeSPKIType`.
+        """
+        nspki = NetscapeSPKI()
+        self.assertTrue(isinstance(nspki, NetscapeSPKIType))
+
+    def test_invalid_attribute(self):
+        """
+        Accessing a non-existent attribute of a :py:obj:`NetscapeSPKI` instance
+        causes an :py:obj:`AttributeError` to be raised.
+        """
+        nspki = NetscapeSPKI()
+        self.assertRaises(AttributeError, lambda: nspki.foo)
+
+    def test_b64_encode(self):
+        """
+        :py:obj:`NetscapeSPKI.b64_encode` encodes the certificate to a base64
+        blob.
+        """
+        nspki = NetscapeSPKI()
+        blob = nspki.b64_encode()
+        self.assertTrue(isinstance(blob, binary_type))
+
+
+class RevokedTests(TestCase):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.Revoked`
+    """
+
+    def test_construction(self):
+        """
+        Confirm we can create :py:obj:`OpenSSL.crypto.Revoked`.  Check
+        that it is empty.
+        """
+        revoked = Revoked()
+        self.assertTrue(isinstance(revoked, Revoked))
+        self.assertEquals(type(revoked), Revoked)
+        self.assertEquals(revoked.get_serial(), b('00'))
+        self.assertEquals(revoked.get_rev_date(), None)
+        self.assertEquals(revoked.get_reason(), None)
+
+    def test_construction_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.Revoked` with any arguments results
+        in a :py:obj:`TypeError` being raised.
+        """
+        self.assertRaises(TypeError, Revoked, None)
+        self.assertRaises(TypeError, Revoked, 1)
+        self.assertRaises(TypeError, Revoked, "foo")
+
+    def test_serial(self):
+        """
+        Confirm we can set and get serial numbers from
+        :py:obj:`OpenSSL.crypto.Revoked`.  Confirm errors are handled
+        with grace.
+        """
+        revoked = Revoked()
+        ret = revoked.set_serial(b('10b'))
+        self.assertEquals(ret, None)
+        ser = revoked.get_serial()
+        self.assertEquals(ser, b('010B'))
+
+        revoked.set_serial(b('31ppp'))  # a type error would be nice
+        ser = revoked.get_serial()
+        self.assertEquals(ser, b('31'))
+
+        self.assertRaises(ValueError, revoked.set_serial, b('pqrst'))
+        self.assertRaises(TypeError, revoked.set_serial, 100)
+        self.assertRaises(TypeError, revoked.get_serial, 1)
+        self.assertRaises(TypeError, revoked.get_serial, None)
+        self.assertRaises(TypeError, revoked.get_serial, "")
+
+    def test_date(self):
+        """
+        Confirm we can set and get revocation dates from
+        :py:obj:`OpenSSL.crypto.Revoked`.  Confirm errors are handled
+        with grace.
+        """
+        revoked = Revoked()
+        date = revoked.get_rev_date()
+        self.assertEquals(date, None)
+
+        now = b(datetime.now().strftime("%Y%m%d%H%M%SZ"))
+        ret = revoked.set_rev_date(now)
+        self.assertEqual(ret, None)
+        date = revoked.get_rev_date()
+        self.assertEqual(date, now)
+
+    def test_reason(self):
+        """
+        Confirm we can set and get revocation reasons from
+        :py:obj:`OpenSSL.crypto.Revoked`.  The "get" need to work
+        as "set".  Likewise, each reason of all_reasons() must work.
+        """
+        revoked = Revoked()
+        for r in revoked.all_reasons():
+            for x in range(2):
+                ret = revoked.set_reason(r)
+                self.assertEquals(ret, None)
+                reason = revoked.get_reason()
+                self.assertEquals(
+                    reason.lower().replace(b(' '), b('')),
+                    r.lower().replace(b(' '), b('')))
+                r = reason  # again with the resp of get
+
+        revoked.set_reason(None)
+        self.assertEqual(revoked.get_reason(), None)
+
+    def test_set_reason_wrong_arguments(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.Revoked.set_reason` with other than
+        one argument, or an argument which isn't a valid reason,
+        results in :py:obj:`TypeError` or :py:obj:`ValueError` being raised.
+        """
+        revoked = Revoked()
+        self.assertRaises(TypeError, revoked.set_reason, 100)
+        self.assertRaises(ValueError, revoked.set_reason, b('blue'))
+
+    def test_get_reason_wrong_arguments(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.Revoked.get_reason` with any
+        arguments results in :py:obj:`TypeError` being raised.
+        """
+        revoked = Revoked()
+        self.assertRaises(TypeError, revoked.get_reason, None)
+        self.assertRaises(TypeError, revoked.get_reason, 1)
+        self.assertRaises(TypeError, revoked.get_reason, "foo")
+
+
+class CRLTests(TestCase):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.CRL`
+    """
+    cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
+    pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
+
+    def test_construction(self):
+        """
+        Confirm we can create :py:obj:`OpenSSL.crypto.CRL`.  Check
+        that it is empty
+        """
+        crl = CRL()
+        self.assertTrue(isinstance(crl, CRL))
+        self.assertEqual(crl.get_revoked(), None)
+
+    def test_construction_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.CRL` with any number of arguments
+        results in a :py:obj:`TypeError` being raised.
+        """
+        self.assertRaises(TypeError, CRL, 1)
+        self.assertRaises(TypeError, CRL, "")
+        self.assertRaises(TypeError, CRL, None)
+
+    def _get_crl(self):
+        """
+        Get a new ``CRL`` with a revocation.
+        """
+        crl = CRL()
+        revoked = Revoked()
+        now = b(datetime.now().strftime("%Y%m%d%H%M%SZ"))
+        revoked.set_rev_date(now)
+        revoked.set_serial(b('3ab'))
+        revoked.set_reason(b('sUpErSeDEd'))
+        crl.add_revoked(revoked)
+        return crl
+
+    def test_export_pem(self):
+        """
+        If not passed a format, ``CRL.export`` returns a "PEM" format string
+        representing a serial number, a revoked reason, and certificate issuer
+        information.
+        """
+        crl = self._get_crl()
+        # PEM format
+        dumped_crl = crl.export(self.cert, self.pkey, days=20)
+        text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
+
+        # These magic values are based on the way the CRL above was constructed
+        # and with what certificate it was exported.
+        text.index(b('Serial Number: 03AB'))
+        text.index(b('Superseded'))
+        text.index(
+            b('Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA')
+        )
+
+    def test_export_der(self):
+        """
+        If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
+        "DER" format string representing a serial number, a revoked reason, and
+        certificate issuer information.
+        """
+        crl = self._get_crl()
+
+        # DER format
+        dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
+        text = _runopenssl(
+            dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
+        )
+        text.index(b('Serial Number: 03AB'))
+        text.index(b('Superseded'))
+        text.index(
+            b('Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA')
+        )
+
+    def test_export_text(self):
+        """
+        If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
+        text format string like the one produced by the openssl command line
+        tool.
+        """
+        crl = self._get_crl()
+
+        dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
+        text = _runopenssl(
+            dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
+        )
+
+        # text format
+        dumped_text = crl.export(self.cert, self.pkey, type=FILETYPE_TEXT)
+        self.assertEqual(text, dumped_text)
+
+    def test_export_custom_digest(self):
+        """
+        If passed the name of a digest function, ``CRL.export`` uses a
+        signature algorithm based on that digest function.
+        """
+        crl = self._get_crl()
+        dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
+        text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
+        text.index(b('Signature Algorithm: sha1'))
+
+    def test_export_md5_digest(self):
+        """
+        If passed md5 as the digest function, ``CRL.export`` uses md5 and does
+        not emit a deprecation warning.
+        """
+        crl = self._get_crl()
+        with catch_warnings(record=True) as catcher:
+            simplefilter("always")
+            self.assertEqual(0, len(catcher))
+        dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
+        text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
+        text.index(b('Signature Algorithm: md5'))
+
+    def test_export_default_digest(self):
+        """
+        If not passed the name of a digest function, ``CRL.export`` uses a
+        signature algorithm based on MD5 and emits a deprecation warning.
+        """
+        crl = self._get_crl()
+        with catch_warnings(record=True) as catcher:
+            simplefilter("always")
+            dumped_crl = crl.export(self.cert, self.pkey)
+            self.assertEqual(
+                "The default message digest (md5) is deprecated.  "
+                "Pass the name of a message digest explicitly.",
+                str(catcher[0].message),
+            )
+        text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
+        text.index(b('Signature Algorithm: md5'))
+
+    def test_export_invalid(self):
+        """
+        If :py:obj:`CRL.export` is used with an uninitialized :py:obj:`X509`
+        instance, :py:obj:`OpenSSL.crypto.Error` is raised.
+        """
+        crl = CRL()
+        self.assertRaises(Error, crl.export, X509(), PKey())
+
+    def test_add_revoked_keyword(self):
+        """
+        :py:obj:`OpenSSL.CRL.add_revoked` accepts its single argument as the
+        ``revoked`` keyword argument.
+        """
+        crl = CRL()
+        revoked = Revoked()
+        crl.add_revoked(revoked=revoked)
+        self.assertTrue(isinstance(crl.get_revoked()[0], Revoked))
+
+    def test_export_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.CRL.export` with fewer than two or more than
+        four arguments, or with arguments other than the certificate,
+        private key, integer file type, and integer number of days it
+        expects, results in a :py:obj:`TypeError` being raised.
+        """
+        crl = CRL()
+        self.assertRaises(TypeError, crl.export)
+        self.assertRaises(TypeError, crl.export, self.cert)
+        with pytest.raises(TypeError):
+            crl.export(self.cert, self.pkey, FILETYPE_PEM, 10, "md5", "foo")
+        with pytest.raises(TypeError):
+            crl.export(None, self.pkey, FILETYPE_PEM, 10)
+        with pytest.raises(TypeError):
+            crl.export(self.cert, None, FILETYPE_PEM, 10)
+        with pytest.raises(TypeError):
+            crl.export(self.cert, self.pkey, None, 10)
+        self.assertRaises(TypeError, crl.export, self.cert, FILETYPE_PEM, None)
+
+    def test_export_unknown_filetype(self):
+        """
+        Calling :py:obj:`OpenSSL.CRL.export` with a file type other than
+        :py:obj:`FILETYPE_PEM`, :py:obj:`FILETYPE_ASN1`, or
+        :py:obj:`FILETYPE_TEXT` results in a :py:obj:`ValueError` being raised.
+        """
+        crl = CRL()
+        with pytest.raises(ValueError):
+            crl.export(self.cert, self.pkey, 100, 10)
+
+    def test_export_unknown_digest(self):
+        """
+        Calling :py:obj:`OpenSSL.CRL.export` with an unsupported digest results
+        in a :py:obj:`ValueError` being raised.
+        """
+        crl = CRL()
+        self.assertRaises(
+            ValueError,
+            crl.export,
+            self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest"
+        )
+
+    def test_get_revoked(self):
+        """
+        Use python to create a simple CRL with two revocations.
+        Get back the :py:obj:`Revoked` using :py:obj:`OpenSSL.CRL.get_revoked`
+        and verify them.
+        """
+        crl = CRL()
+
+        revoked = Revoked()
+        now = b(datetime.now().strftime("%Y%m%d%H%M%SZ"))
+        revoked.set_rev_date(now)
+        revoked.set_serial(b('3ab'))
+        crl.add_revoked(revoked)
+        revoked.set_serial(b('100'))
+        revoked.set_reason(b('sUpErSeDEd'))
+        crl.add_revoked(revoked)
+
+        revs = crl.get_revoked()
+        self.assertEqual(len(revs), 2)
+        self.assertEqual(type(revs[0]), Revoked)
+        self.assertEqual(type(revs[1]), Revoked)
+        self.assertEqual(revs[0].get_serial(), b('03AB'))
+        self.assertEqual(revs[1].get_serial(), b('0100'))
+        self.assertEqual(revs[0].get_rev_date(), now)
+        self.assertEqual(revs[1].get_rev_date(), now)
+
+    def test_get_revoked_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.CRL.get_revoked` with any arguments results
+        in a :py:obj:`TypeError` being raised.
+        """
+        crl = CRL()
+        self.assertRaises(TypeError, crl.get_revoked, None)
+        self.assertRaises(TypeError, crl.get_revoked, 1)
+        self.assertRaises(TypeError, crl.get_revoked, "")
+        self.assertRaises(TypeError, crl.get_revoked, "", 1, None)
+
+    def test_add_revoked_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.CRL.add_revoked` with other than one
+        argument results in a :py:obj:`TypeError` being raised.
+        """
+        crl = CRL()
+        self.assertRaises(TypeError, crl.add_revoked)
+        self.assertRaises(TypeError, crl.add_revoked, 1, 2)
+        self.assertRaises(TypeError, crl.add_revoked, "foo", "bar")
+
+    def test_load_crl(self):
+        """
+        Load a known CRL and inspect its revocations.  Both
+        PEM and DER formats are loaded.
+        """
+        crl = load_crl(FILETYPE_PEM, crlData)
+        revs = crl.get_revoked()
+        self.assertEqual(len(revs), 2)
+        self.assertEqual(revs[0].get_serial(), b('03AB'))
+        self.assertEqual(revs[0].get_reason(), None)
+        self.assertEqual(revs[1].get_serial(), b('0100'))
+        self.assertEqual(revs[1].get_reason(), b('Superseded'))
+
+        der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
+        crl = load_crl(FILETYPE_ASN1, der)
+        revs = crl.get_revoked()
+        self.assertEqual(len(revs), 2)
+        self.assertEqual(revs[0].get_serial(), b('03AB'))
+        self.assertEqual(revs[0].get_reason(), None)
+        self.assertEqual(revs[1].get_serial(), b('0100'))
+        self.assertEqual(revs[1].get_reason(), b('Superseded'))
+
+    def test_load_crl_wrong_args(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.load_crl` with other than two
+        arguments results in a :py:obj:`TypeError` being raised.
+        """
+        self.assertRaises(TypeError, load_crl)
+        self.assertRaises(TypeError, load_crl, FILETYPE_PEM)
+        self.assertRaises(TypeError, load_crl, FILETYPE_PEM, crlData, None)
+
+    def test_load_crl_bad_filetype(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.load_crl` with an unknown file type
+        raises a :py:obj:`ValueError`.
+        """
+        self.assertRaises(ValueError, load_crl, 100, crlData)
+
+    def test_load_crl_bad_data(self):
+        """
+        Calling :py:obj:`OpenSSL.crypto.load_crl` with file data which can't
+        be loaded raises a :py:obj:`OpenSSL.crypto.Error`.
+        """
+        self.assertRaises(Error, load_crl, FILETYPE_PEM, b"hello, world")
+
+
+class X509StoreContextTests(TestCase):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.X509StoreContext`.
+    """
+    root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+    intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
+    intermediate_server_cert = load_certificate(
+        FILETYPE_PEM, intermediate_server_cert_pem)
+
+    def test_valid(self):
+        """
+        :py:obj:`verify_certificate` returns ``None`` when called with a
+        certificate and valid chain.
+        """
+        store = X509Store()
+        store.add_cert(self.root_cert)
+        store.add_cert(self.intermediate_cert)
+        store_ctx = X509StoreContext(store, self.intermediate_server_cert)
+        self.assertEqual(store_ctx.verify_certificate(), None)
+
+    def test_reuse(self):
+        """
+        :py:obj:`verify_certificate` can be called multiple times with the same
+        ``X509StoreContext`` instance to produce the same result.
+        """
+        store = X509Store()
+        store.add_cert(self.root_cert)
+        store.add_cert(self.intermediate_cert)
+        store_ctx = X509StoreContext(store, self.intermediate_server_cert)
+        self.assertEqual(store_ctx.verify_certificate(), None)
+        self.assertEqual(store_ctx.verify_certificate(), None)
+
+    def test_trusted_self_signed(self):
+        """
+        :py:obj:`verify_certificate` returns ``None`` when called with a
+        self-signed certificate and itself in the chain.
+        """
+        store = X509Store()
+        store.add_cert(self.root_cert)
+        store_ctx = X509StoreContext(store, self.root_cert)
+        self.assertEqual(store_ctx.verify_certificate(), None)
+
+    def test_untrusted_self_signed(self):
+        """
+        :py:obj:`verify_certificate` raises error when a self-signed
+        certificate is verified without itself in the chain.
+        """
+        store = X509Store()
+        store_ctx = X509StoreContext(store, self.root_cert)
+        with pytest.raises(X509StoreContextError) as exc:
+            store_ctx.verify_certificate()
+
+        assert exc.value.args[0][2] == 'self signed certificate'
+        assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
+
+    def test_invalid_chain_no_root(self):
+        """
+        :py:obj:`verify_certificate` raises error when a root certificate is
+        missing from the chain.
+        """
+        store = X509Store()
+        store.add_cert(self.intermediate_cert)
+        store_ctx = X509StoreContext(store, self.intermediate_server_cert)
+
+        with pytest.raises(X509StoreContextError) as exc:
+            store_ctx.verify_certificate()
+
+        assert exc.value.args[0][2] == 'unable to get issuer certificate'
+        assert exc.value.certificate.get_subject().CN == 'intermediate'
+
+    def test_invalid_chain_no_intermediate(self):
+        """
+        :py:obj:`verify_certificate` raises error when an intermediate
+        certificate is missing from the chain.
+        """
+        store = X509Store()
+        store.add_cert(self.root_cert)
+        store_ctx = X509StoreContext(store, self.intermediate_server_cert)
+
+        with pytest.raises(X509StoreContextError) as exc:
+            store_ctx.verify_certificate()
+
+        assert exc.value.args[0][2] == 'unable to get local issuer certificate'
+        assert exc.value.certificate.get_subject().CN == 'intermediate-service'
+
+    def test_modification_pre_verify(self):
+        """
+        :py:obj:`verify_certificate` can use a store context modified after
+        instantiation.
+        """
+        store_bad = X509Store()
+        store_bad.add_cert(self.intermediate_cert)
+        store_good = X509Store()
+        store_good.add_cert(self.root_cert)
+        store_good.add_cert(self.intermediate_cert)
+        store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
+
+        with pytest.raises(X509StoreContextError) as exc:
+            store_ctx.verify_certificate()
+
+        assert exc.value.args[0][2] == 'unable to get issuer certificate'
+        assert exc.value.certificate.get_subject().CN == 'intermediate'
+
+        store_ctx.set_store(store_good)
+        self.assertEqual(store_ctx.verify_certificate(), None)
+
+
+class SignVerifyTests(TestCase):
+    """
+    Tests for :py:obj:`OpenSSL.crypto.sign` and
+    :py:obj:`OpenSSL.crypto.verify`.
+    """
+
+    def test_sign_verify(self):
+        """
+        :py:obj:`sign` generates a cryptographic signature which
+        :py:obj:`verify` can check.
+        """
+        content = b(
+            "It was a bright cold day in April, and the clocks were striking "
+            "thirteen. Winston Smith, his chin nuzzled into his breast in an "
+            "effort to escape the vile wind, slipped quickly through the "
+            "glass doors of Victory Mansions, though not quickly enough to "
+            "prevent a swirl of gritty dust from entering along with him.")
+
+        # sign the content with this private key
+        priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
+        # verify the content with this cert
+        good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        # certificate unrelated to priv_key, used to trigger an error
+        bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        for digest in ['md5', 'sha1']:
+            sig = sign(priv_key, content, digest)
+
+            # Verify the signature of content, will throw an exception if
+            # error.
+            verify(good_cert, sig, content, digest)
+
+            # This should fail because the certificate doesn't match the
+            # private key that was used to sign the content.
+            self.assertRaises(Error, verify, bad_cert, sig, content, digest)
+
+            # This should fail because we've "tainted" the content after
+            # signing it.
+            self.assertRaises(
+                Error, verify,
+                good_cert, sig, content + b("tainted"), digest)
+
+        # test that unknown digest types fail
+        self.assertRaises(
+            ValueError, sign, priv_key, content, "strange-digest")
+        self.assertRaises(
+            ValueError, verify, good_cert, sig, content, "strange-digest")
+
+    def test_sign_verify_with_text(self):
+        """
+        :py:obj:`sign` generates a cryptographic signature which
+        :py:obj:`verify` can check. Deprecation warnings raised because using
+        text instead of bytes as content
+        """
+        content = (
+            b"It was a bright cold day in April, and the clocks were striking "
+            b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
+            b"effort to escape the vile wind, slipped quickly through the "
+            b"glass doors of Victory Mansions, though not quickly enough to "
+            b"prevent a swirl of gritty dust from entering along with him."
+        ).decode("ascii")
+
+        priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
+        cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        for digest in ['md5', 'sha1']:
+            with catch_warnings(record=True) as w:
+                simplefilter("always")
+                sig = sign(priv_key, content, digest)
+
+                self.assertEqual(
+                    "{0} for data is no longer accepted, use bytes".format(
+                        WARNING_TYPE_EXPECTED
+                    ),
+                    str(w[-1].message)
+                )
+                self.assertIs(w[-1].category, DeprecationWarning)
+
+            with catch_warnings(record=True) as w:
+                simplefilter("always")
+                verify(cert, sig, content, digest)
+
+                self.assertEqual(
+                    "{0} for data is no longer accepted, use bytes".format(
+                        WARNING_TYPE_EXPECTED
+                    ),
+                    str(w[-1].message)
+                )
+                self.assertIs(w[-1].category, DeprecationWarning)
+
+    def test_sign_nulls(self):
+        """
+        :py:obj:`sign` produces a signature for a string with embedded nulls.
+        """
+        content = b("Watch out!  \0  Did you see it?")
+        priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
+        good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        sig = sign(priv_key, content, "sha1")
+        verify(good_cert, sig, content, "sha1")
+
+
+class EllipticCurveTests(TestCase):
+    """
+    Tests for :py:class:`_EllipticCurve`, :py:obj:`get_elliptic_curve`, and
+    :py:obj:`get_elliptic_curves`.
+    """
+
+    def test_set(self):
+        """
+        :py:obj:`get_elliptic_curves` returns a :py:obj:`set`.
+        """
+        self.assertIsInstance(get_elliptic_curves(), set)
+
+    def test_some_curves(self):
+        """
+        If :py:mod:`cryptography` has elliptic curve support then the set
+        returned by :py:obj:`get_elliptic_curves` has some elliptic curves in
+        it.
+
+        There could be an OpenSSL that violates this assumption.  If so, this
+        test will fail and we'll find out.
+        """
+        curves = get_elliptic_curves()
+        if lib.Cryptography_HAS_EC:
+            self.assertTrue(curves)
+        else:
+            self.assertFalse(curves)
+
+    def test_a_curve(self):
+        """
+        :py:obj:`get_elliptic_curve` can be used to retrieve a particular
+        supported curve.
+        """
+        curves = get_elliptic_curves()
+        if curves:
+            curve = next(iter(curves))
+            self.assertEqual(curve.name, get_elliptic_curve(curve.name).name)
+        else:
+            self.assertRaises(ValueError, get_elliptic_curve, u("prime256v1"))
+
+    def test_not_a_curve(self):
+        """
+        :py:obj:`get_elliptic_curve` raises :py:class:`ValueError` if called
+        with a name which does not identify a supported curve.
+        """
+        self.assertRaises(
+            ValueError, get_elliptic_curve, u("this curve was just invented"))
+
+    def test_repr(self):
+        """
+        The string representation of a curve object includes simply states the
+        object is a curve and what its name is.
+        """
+        curves = get_elliptic_curves()
+        if curves:
+            curve = next(iter(curves))
+            self.assertEqual("<Curve %r>" % (curve.name,), repr(curve))
+
+    def test_to_EC_KEY(self):
+        """
+        The curve object can export a version of itself as an EC_KEY* via the
+        private :py:meth:`_EllipticCurve._to_EC_KEY`.
+        """
+        curves = get_elliptic_curves()
+        if curves:
+            curve = next(iter(curves))
+            # It's not easy to assert anything about this object.  However, see
+            # leakcheck/crypto.py for a test that demonstrates it at least does
+            # not leak memory.
+            curve._to_EC_KEY()
+
+
+class EllipticCurveFactory(object):
+    """
+    A helper to get the names of two curves.
+    """
+
+    def __init__(self):
+        curves = iter(get_elliptic_curves())
+        try:
+            self.curve_name = next(curves).name
+            self.another_curve_name = next(curves).name
+        except StopIteration:
+            self.curve_name = self.another_curve_name = None
+
+
+class EllipticCurveEqualityTests(TestCase, EqualityTestsMixin):
+    """
+    Tests :py:type:`_EllipticCurve`\ 's implementation of ``==`` and ``!=``.
+    """
+    curve_factory = EllipticCurveFactory()
+
+    if curve_factory.curve_name is None:
+        skip = "There are no curves available there can be no curve objects."
+
+    def anInstance(self):
+        """
+        Get the curve object for an arbitrary curve supported by the system.
+        """
+        return get_elliptic_curve(self.curve_factory.curve_name)
+
+    def anotherInstance(self):
+        """
+        Get the curve object for an arbitrary curve supported by the system -
+        but not the one returned by C{anInstance}.
+        """
+        return get_elliptic_curve(self.curve_factory.another_curve_name)
+
+
+class EllipticCurveHashTests(TestCase):
+    """
+    Tests for :py:type:`_EllipticCurve`\ 's implementation of hashing (thus use
+    as an item in a :py:type:`dict` or :py:type:`set`).
+    """
+    curve_factory = EllipticCurveFactory()
+
+    if curve_factory.curve_name is None:
+        skip = "There are no curves available there can be no curve objects."
+
+    def test_contains(self):
+        """
+        The ``in`` operator reports that a :py:type:`set` containing a curve
+        does contain that curve.
+        """
+        curve = get_elliptic_curve(self.curve_factory.curve_name)
+        curves = set([curve])
+        self.assertIn(curve, curves)
+
+    def test_does_not_contain(self):
+        """
+        The ``in`` operator reports that a :py:type:`set` not containing a
+        curve does not contain that curve.
+        """
+        curve = get_elliptic_curve(self.curve_factory.curve_name)
+        curves = set([
+            get_elliptic_curve(self.curve_factory.another_curve_name)
+        ])
+        self.assertNotIn(curve, curves)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/tests/test_rand.py b/tests/test_rand.py
new file mode 100644
index 0000000..8064011
--- /dev/null
+++ b/tests/test_rand.py
@@ -0,0 +1,212 @@
+# Copyright (c) Frederick Dean
+# See LICENSE for details.
+
+"""
+Unit tests for :py:obj:`OpenSSL.rand`.
+"""
+
+from unittest import main
+import os
+import stat
+import sys
+
+from OpenSSL import rand
+
+from .util import NON_ASCII, TestCase, b
+
+
+class RandTests(TestCase):
+    def test_bytes_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.bytes` raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or with a non-:py:obj:`int` argument.
+        """
+        self.assertRaises(TypeError, rand.bytes)
+        self.assertRaises(TypeError, rand.bytes, None)
+        self.assertRaises(TypeError, rand.bytes, 3, None)
+
+    def test_insufficientMemory(self):
+        """
+        :py:obj:`OpenSSL.rand.bytes` raises :py:obj:`MemoryError` if more bytes
+        are requested than will fit in memory.
+        """
+        self.assertRaises(MemoryError, rand.bytes, sys.maxsize)
+
+    def test_bytes(self):
+        """
+        Verify that we can obtain bytes from rand_bytes() and
+        that they are different each time.  Test the parameter
+        of rand_bytes() for bad values.
+        """
+        b1 = rand.bytes(50)
+        self.assertEqual(len(b1), 50)
+        b2 = rand.bytes(num_bytes=50)  # parameter by name
+        self.assertNotEqual(b1, b2)  # Hip, Hip, Horay! FIPS complaince
+        b3 = rand.bytes(num_bytes=0)
+        self.assertEqual(len(b3), 0)
+        exc = self.assertRaises(ValueError, rand.bytes, -1)
+        self.assertEqual(str(exc), "num_bytes must not be negative")
+
+    def test_add_wrong_args(self):
+        """
+        When called with the wrong number of arguments, or with arguments not
+        of type :py:obj:`str` and :py:obj:`int`, :py:obj:`OpenSSL.rand.add`
+        raises :py:obj:`TypeError`.
+        """
+        self.assertRaises(TypeError, rand.add)
+        self.assertRaises(TypeError, rand.add, b("foo"), None)
+        self.assertRaises(TypeError, rand.add, None, 3)
+        self.assertRaises(TypeError, rand.add, b("foo"), 3, None)
+
+    def test_add(self):
+        """
+        :py:obj:`OpenSSL.rand.add` adds entropy to the PRNG.
+        """
+        rand.add(b('hamburger'), 3)
+
+    def test_seed_wrong_args(self):
+        """
+        When called with the wrong number of arguments, or with
+        a non-:py:obj:`str` argument, :py:obj:`OpenSSL.rand.seed` raises
+        :py:obj:`TypeError`.
+        """
+        self.assertRaises(TypeError, rand.seed)
+        self.assertRaises(TypeError, rand.seed, None)
+        self.assertRaises(TypeError, rand.seed, b("foo"), None)
+
+    def test_seed(self):
+        """
+        :py:obj:`OpenSSL.rand.seed` adds entropy to the PRNG.
+        """
+        rand.seed(b('milk shake'))
+
+    def test_status_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.status` raises :py:obj:`TypeError` when called
+        with any arguments.
+        """
+        self.assertRaises(TypeError, rand.status, None)
+
+    def test_status(self):
+        """
+        :py:obj:`OpenSSL.rand.status` returns :py:obj:`True` if the PRNG has
+        sufficient entropy, :py:obj:`False` otherwise.
+        """
+        # It's hard to know what it is actually going to return.  Different
+        # OpenSSL random engines decide differently whether they have enough
+        # entropy or not.
+        self.assertTrue(rand.status() in (1, 2))
+
+    def test_egd_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.egd` raises :py:obj:`TypeError` when called with
+        the wrong number of arguments or with arguments not of type
+        :py:obj:`str` and :py:obj:`int`.
+        """
+        self.assertRaises(TypeError, rand.egd)
+        self.assertRaises(TypeError, rand.egd, None)
+        self.assertRaises(TypeError, rand.egd, "foo", None)
+        self.assertRaises(TypeError, rand.egd, None, 3)
+        self.assertRaises(TypeError, rand.egd, "foo", 3, None)
+
+    def test_egd_missing(self):
+        """
+        :py:obj:`OpenSSL.rand.egd` returns :py:obj:`0` or :py:obj:`-1` if the
+        EGD socket passed to it does not exist.
+        """
+        result = rand.egd(self.mktemp())
+        expected = (-1, 0)
+        self.assertTrue(
+            result in expected,
+            "%r not in %r" % (result, expected))
+
+    def test_egd_missing_and_bytes(self):
+        """
+        :py:obj:`OpenSSL.rand.egd` returns :py:obj:`0` or :py:obj:`-1` if the
+        EGD socket passed to it does not exist even if a size argument is
+        explicitly passed.
+        """
+        result = rand.egd(self.mktemp(), 1024)
+        expected = (-1, 0)
+        self.assertTrue(
+            result in expected,
+            "%r not in %r" % (result, expected))
+
+    def test_cleanup_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.cleanup` raises :py:obj:`TypeError` when called
+        with any arguments.
+        """
+        self.assertRaises(TypeError, rand.cleanup, None)
+
+    def test_cleanup(self):
+        """
+        :py:obj:`OpenSSL.rand.cleanup` releases the memory used by the PRNG and
+        returns :py:obj:`None`.
+        """
+        self.assertIdentical(rand.cleanup(), None)
+
+    def test_load_file_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.load_file` raises :py:obj:`TypeError` when called
+        the wrong number of arguments or arguments not of type :py:obj:`str`
+        and :py:obj:`int`.
+        """
+        self.assertRaises(TypeError, rand.load_file)
+        self.assertRaises(TypeError, rand.load_file, "foo", None)
+        self.assertRaises(TypeError, rand.load_file, None, 1)
+        self.assertRaises(TypeError, rand.load_file, "foo", 1, None)
+
+    def test_write_file_wrong_args(self):
+        """
+        :py:obj:`OpenSSL.rand.write_file` raises :py:obj:`TypeError` when
+        called with the wrong number of arguments or a non-:py:obj:`str`
+        argument.
+        """
+        self.assertRaises(TypeError, rand.write_file)
+        self.assertRaises(TypeError, rand.write_file, None)
+        self.assertRaises(TypeError, rand.write_file, "foo", None)
+
+    def _read_write_test(self, path):
+        """
+        Verify that ``rand.write_file`` and ``rand.load_file`` can be used.
+        """
+        # Create the file so cleanup is more straightforward
+        with open(path, "w"):
+            pass
+
+        try:
+            # Write random bytes to a file
+            rand.write_file(path)
+
+            # Verify length of written file
+            size = os.stat(path)[stat.ST_SIZE]
+            self.assertEqual(1024, size)
+
+            # Read random bytes from file
+            rand.load_file(path)
+            rand.load_file(path, 4)  # specify a length
+        finally:
+            # Cleanup
+            os.unlink(path)
+
+    def test_bytes_paths(self):
+        """
+        Random data can be saved and loaded to files with paths specified as
+        bytes.
+        """
+        path = self.mktemp()
+        path += NON_ASCII.encode(sys.getfilesystemencoding())
+        self._read_write_test(path)
+
+    def test_unicode_paths(self):
+        """
+        Random data can be saved and loaded to files with paths specified as
+        unicode.
+        """
+        path = self.mktemp().decode('utf-8') + NON_ASCII
+        self._read_write_test(path)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/tests/test_ssl.py b/tests/test_ssl.py
new file mode 100644
index 0000000..4aac429
--- /dev/null
+++ b/tests/test_ssl.py
@@ -0,0 +1,3773 @@
+# Copyright (C) Jean-Paul Calderone
+# See LICENSE for details.
+
+"""
+Unit tests for :py:obj:`OpenSSL.SSL`.
+"""
+
+from gc import collect, get_referrers
+from errno import ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN
+from sys import platform, getfilesystemencoding, version_info
+from socket import MSG_PEEK, SHUT_RDWR, error, socket
+from os import makedirs
+from os.path import join
+from unittest import main
+from weakref import ref
+from warnings import catch_warnings, simplefilter
+
+import pytest
+
+from six import PY3, text_type, u
+
+from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
+from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
+from OpenSSL.crypto import dump_privatekey, load_privatekey
+from OpenSSL.crypto import dump_certificate, load_certificate
+from OpenSSL.crypto import get_elliptic_curves
+
+from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
+from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
+from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
+from OpenSSL.SSL import (
+    SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
+    TLSv1_1_METHOD, TLSv1_2_METHOD)
+from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
+from OpenSSL.SSL import (
+    VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
+
+from OpenSSL.SSL import (
+    SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
+    SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
+    SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
+
+from OpenSSL.SSL import (
+    Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
+from OpenSSL.SSL import (
+    Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
+
+from OpenSSL._util import lib as _lib
+
+try:
+    from OpenSSL.SSL import OP_NO_QUERY_MTU
+except ImportError:
+    OP_NO_QUERY_MTU = None
+try:
+    from OpenSSL.SSL import OP_COOKIE_EXCHANGE
+except ImportError:
+    OP_COOKIE_EXCHANGE = None
+try:
+    from OpenSSL.SSL import OP_NO_TICKET
+except ImportError:
+    OP_NO_TICKET = None
+
+try:
+    from OpenSSL.SSL import OP_NO_COMPRESSION
+except ImportError:
+    OP_NO_COMPRESSION = None
+
+try:
+    from OpenSSL.SSL import MODE_RELEASE_BUFFERS
+except ImportError:
+    MODE_RELEASE_BUFFERS = None
+
+try:
+    from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
+except ImportError:
+    OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
+
+from OpenSSL.SSL import (
+    SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
+    SSL_ST_OK, SSL_ST_RENEGOTIATE,
+    SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
+    SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
+    SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
+    SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
+
+from .util import WARNING_TYPE_EXPECTED, NON_ASCII, TestCase, b
+from .test_crypto import (
+    cleartextCertificatePEM, cleartextPrivateKeyPEM,
+    client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
+    root_cert_pem)
+
+
+# openssl dhparam 128 -out dh-128.pem (note that 128 is a small number of bits
+# to use)
+dhparam = """\
+-----BEGIN DH PARAMETERS-----
+MBYCEQCobsg29c9WZP/54oAPcwiDAgEC
+-----END DH PARAMETERS-----
+"""
+
+
+skip_if_py3 = pytest.mark.skipif(PY3, reason="Python 2 only")
+skip_if_py26 = pytest.mark.skipif(
+    version_info[0:2] == (2, 6),
+    reason="Python 2.7 and later only"
+)
+
+
+def join_bytes_or_unicode(prefix, suffix):
+    """
+    Join two path components of either ``bytes`` or ``unicode``.
+
+    The return type is the same as the type of ``prefix``.
+    """
+    # If the types are the same, nothing special is necessary.
+    if type(prefix) == type(suffix):
+        return join(prefix, suffix)
+
+    # Otherwise, coerce suffix to the type of prefix.
+    if isinstance(prefix, text_type):
+        return join(prefix, suffix.decode(getfilesystemencoding()))
+    else:
+        return join(prefix, suffix.encode(getfilesystemencoding()))
+
+
+def verify_cb(conn, cert, errnum, depth, ok):
+    return ok
+
+
+def socket_pair():
+    """
+    Establish and return a pair of network sockets connected to each other.
+    """
+    # Connect a pair of sockets
+    port = socket()
+    port.bind(('', 0))
+    port.listen(1)
+    client = socket()
+    client.setblocking(False)
+    client.connect_ex(("127.0.0.1", port.getsockname()[1]))
+    client.setblocking(True)
+    server = port.accept()[0]
+
+    # Let's pass some unencrypted data to make sure our socket connection is
+    # fine.  Just one byte, so we don't have to worry about buffers getting
+    # filled up or fragmentation.
+    server.send(b("x"))
+    assert client.recv(1024) == b("x")
+    client.send(b("y"))
+    assert server.recv(1024) == b("y")
+
+    # Most of our callers want non-blocking sockets, make it easy for them.
+    server.setblocking(False)
+    client.setblocking(False)
+
+    return (server, client)
+
+
+def handshake(client, server):
+    conns = [client, server]
+    while conns:
+        for conn in conns:
+            try:
+                conn.do_handshake()
+            except WantReadError:
+                pass
+            else:
+                conns.remove(conn)
+
+
+def _create_certificate_chain():
+    """
+    Construct and return a chain of certificates.
+
+        1. A new self-signed certificate authority certificate (cacert)
+        2. A new intermediate certificate signed by cacert (icert)
+        3. A new server certificate signed by icert (scert)
+    """
+    caext = X509Extension(b('basicConstraints'), False, b('CA:true'))
+
+    # Step 1
+    cakey = PKey()
+    cakey.generate_key(TYPE_RSA, 512)
+    cacert = X509()
+    cacert.get_subject().commonName = "Authority Certificate"
+    cacert.set_issuer(cacert.get_subject())
+    cacert.set_pubkey(cakey)
+    cacert.set_notBefore(b("20000101000000Z"))
+    cacert.set_notAfter(b("20200101000000Z"))
+    cacert.add_extensions([caext])
+    cacert.set_serial_number(0)
+    cacert.sign(cakey, "sha1")
+
+    # Step 2
+    ikey = PKey()
+    ikey.generate_key(TYPE_RSA, 512)
+    icert = X509()
+    icert.get_subject().commonName = "Intermediate Certificate"
+    icert.set_issuer(cacert.get_subject())
+    icert.set_pubkey(ikey)
+    icert.set_notBefore(b("20000101000000Z"))
+    icert.set_notAfter(b("20200101000000Z"))
+    icert.add_extensions([caext])
+    icert.set_serial_number(0)
+    icert.sign(cakey, "sha1")
+
+    # Step 3
+    skey = PKey()
+    skey.generate_key(TYPE_RSA, 512)
+    scert = X509()
+    scert.get_subject().commonName = "Server Certificate"
+    scert.set_issuer(icert.get_subject())
+    scert.set_pubkey(skey)
+    scert.set_notBefore(b("20000101000000Z"))
+    scert.set_notAfter(b("20200101000000Z"))
+    scert.add_extensions([
+        X509Extension(b('basicConstraints'), True, b('CA:false'))])
+    scert.set_serial_number(0)
+    scert.sign(ikey, "sha1")
+
+    return [(cakey, cacert), (ikey, icert), (skey, scert)]
+
+
+class _LoopbackMixin:
+    """
+    Helper mixin which defines methods for creating a connected socket pair and
+    for forcing two connected SSL sockets to talk to each other via memory
+    BIOs.
+    """
+    def _loopbackClientFactory(self, socket):
+        client = Connection(Context(TLSv1_METHOD), socket)
+        client.set_connect_state()
+        return client
+
+    def _loopbackServerFactory(self, socket):
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
+        server = Connection(ctx, socket)
+        server.set_accept_state()
+        return server
+
+    def _loopback(self, serverFactory=None, clientFactory=None):
+        if serverFactory is None:
+            serverFactory = self._loopbackServerFactory
+        if clientFactory is None:
+            clientFactory = self._loopbackClientFactory
+
+        (server, client) = socket_pair()
+        server = serverFactory(server)
+        client = clientFactory(client)
+
+        handshake(client, server)
+
+        server.setblocking(True)
+        client.setblocking(True)
+        return server, client
+
+    def _interactInMemory(self, client_conn, server_conn):
+        """
+        Try to read application bytes from each of the two :py:obj:`Connection`
+        objects.  Copy bytes back and forth between their send/receive buffers
+        for as long as there is anything to copy.  When there is nothing more
+        to copy, return :py:obj:`None`.  If one of them actually manages to
+        deliver some application bytes, return a two-tuple of the connection
+        from which the bytes were read and the bytes themselves.
+        """
+        wrote = True
+        while wrote:
+            # Loop until neither side has anything to say
+            wrote = False
+
+            # Copy stuff from each side's send buffer to the other side's
+            # receive buffer.
+            for (read, write) in [(client_conn, server_conn),
+                                  (server_conn, client_conn)]:
+
+                # Give the side a chance to generate some more bytes, or
+                # succeed.
+                try:
+                    data = read.recv(2 ** 16)
+                except WantReadError:
+                    # It didn't succeed, so we'll hope it generated some
+                    # output.
+                    pass
+                else:
+                    # It did succeed, so we'll stop now and let the caller deal
+                    # with it.
+                    return (read, data)
+
+                while True:
+                    # Keep copying as long as there's more stuff there.
+                    try:
+                        dirty = read.bio_read(4096)
+                    except WantReadError:
+                        # Okay, nothing more waiting to be sent.  Stop
+                        # processing this send buffer.
+                        break
+                    else:
+                        # Keep track of the fact that someone generated some
+                        # output.
+                        wrote = True
+                        write.bio_write(dirty)
+
+    def _handshakeInMemory(self, client_conn, server_conn):
+        """
+        Perform the TLS handshake between two :py:class:`Connection` instances
+        connected to each other via memory BIOs.
+        """
+        client_conn.set_connect_state()
+        server_conn.set_accept_state()
+
+        for conn in [client_conn, server_conn]:
+            try:
+                conn.do_handshake()
+            except WantReadError:
+                pass
+
+        self._interactInMemory(client_conn, server_conn)
+
+
+class VersionTests(TestCase):
+    """
+    Tests for version information exposed by
+    :py:obj:`OpenSSL.SSL.SSLeay_version` and
+    :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
+    """
+    def test_OPENSSL_VERSION_NUMBER(self):
+        """
+        :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
+        byte and the patch, fix, minor, and major versions in the
+        nibbles above that.
+        """
+        self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
+
+    def test_SSLeay_version(self):
+        """
+        :py:obj:`SSLeay_version` takes a version type indicator and returns
+        one of a number of version strings based on that indicator.
+        """
+        versions = {}
+        for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
+                  SSLEAY_PLATFORM, SSLEAY_DIR]:
+            version = SSLeay_version(t)
+            versions[version] = t
+            self.assertTrue(isinstance(version, bytes))
+        self.assertEqual(len(versions), 5)
+
+
+class ContextTests(TestCase, _LoopbackMixin):
+    """
+    Unit tests for :py:obj:`OpenSSL.SSL.Context`.
+    """
+    def test_method(self):
+        """
+        :py:obj:`Context` can be instantiated with one of
+        :py:obj:`SSLv2_METHOD`, :py:obj:`SSLv3_METHOD`,
+        :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
+        :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
+        """
+        methods = [
+            SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]
+        for meth in methods:
+            Context(meth)
+
+        maybe = [SSLv2_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
+        for meth in maybe:
+            try:
+                Context(meth)
+            except (Error, ValueError):
+                # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
+                # don't.  Difficult to say in advance.
+                pass
+
+        self.assertRaises(TypeError, Context, "")
+        self.assertRaises(ValueError, Context, 10)
+
+    @skip_if_py3
+    def test_method_long(self):
+        """
+        On Python 2 :py:class:`Context` accepts values of type
+        :py:obj:`long` as well as :py:obj:`int`.
+        """
+        Context(long(TLSv1_METHOD))
+
+    def test_type(self):
+        """
+        :py:obj:`Context` and :py:obj:`ContextType` refer to the same type
+        object and can be used to create instances of that type.
+        """
+        self.assertIdentical(Context, ContextType)
+        self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
+
+    def test_use_privatekey(self):
+        """
+        :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey`
+        instance.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 128)
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(key)
+        self.assertRaises(TypeError, ctx.use_privatekey, "")
+
+    def test_use_privatekey_file_missing(self):
+        """
+        :py:obj:`Context.use_privatekey_file` raises
+        :py:obj:`OpenSSL.SSL.Error` when passed the name of a file which does
+        not exist.
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
+
+    def _use_privatekey_file_test(self, pemfile, filetype):
+        """
+        Verify that calling ``Context.use_privatekey_file`` with the given
+        arguments does not raise an exception.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 128)
+
+        with open(pemfile, "wt") as pem:
+            pem.write(
+                dump_privatekey(FILETYPE_PEM, key).decode("ascii")
+            )
+
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey_file(pemfile, filetype)
+
+    def test_use_privatekey_file_bytes(self):
+        """
+        A private key can be specified from a file by passing a ``bytes``
+        instance giving the file name to ``Context.use_privatekey_file``.
+        """
+        self._use_privatekey_file_test(
+            self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
+            FILETYPE_PEM,
+        )
+
+    def test_use_privatekey_file_unicode(self):
+        """
+        A private key can be specified from a file by passing a ``unicode``
+        instance giving the file name to ``Context.use_privatekey_file``.
+        """
+        self._use_privatekey_file_test(
+            self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
+            FILETYPE_PEM,
+        )
+
+    @skip_if_py3
+    def test_use_privatekey_file_long(self):
+        """
+        On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
+        filetype of type :py:obj:`long` as well as :py:obj:`int`.
+        """
+        self._use_privatekey_file_test(self.mktemp(), long(FILETYPE_PEM))
+
+    def test_use_certificate_wrong_args(self):
+        """
+        :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
+        when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as
+        an argument.
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, ctx.use_certificate)
+        self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
+        self.assertRaises(
+            TypeError, ctx.use_certificate, X509(), "hello, world"
+        )
+
+    def test_use_certificate_uninitialized(self):
+        """
+        :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
+        when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
+        initialized (ie, which does not actually have any certificate data).
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(Error, ctx.use_certificate, X509())
+
+    def test_use_certificate(self):
+        """
+        :py:obj:`Context.use_certificate` sets the certificate which will be
+        used to identify connections created using the context.
+        """
+        # TODO
+        # Hard to assert anything.  But we could set a privatekey then ask
+        # OpenSSL if the cert and key agree using check_privatekey.  Then as
+        # long as check_privatekey works right we're good...
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_certificate(
+            load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
+        )
+
+    def test_use_certificate_file_wrong_args(self):
+        """
+        :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
+        called with zero arguments or more than two arguments, or if the first
+        argument is not a byte string or the second argumnent is not an
+        integer.
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, ctx.use_certificate_file)
+        self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile",
+                          object())
+        self.assertRaises(
+            TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM,
+            object())
+        self.assertRaises(
+            TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
+        self.assertRaises(
+            TypeError, ctx.use_certificate_file, b"somefile", object())
+
+    def test_use_certificate_file_missing(self):
+        """
+        :py:obj:`Context.use_certificate_file` raises
+        `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does
+        not exist.
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
+
+    def _use_certificate_file_test(self, certificate_file):
+        """
+        Verify that calling ``Context.use_certificate_file`` with the given
+        filename doesn't raise an exception.
+        """
+        # TODO
+        # Hard to assert anything.  But we could set a privatekey then ask
+        # OpenSSL if the cert and key agree using check_privatekey.  Then as
+        # long as check_privatekey works right we're good...
+        with open(certificate_file, "wb") as pem_file:
+            pem_file.write(cleartextCertificatePEM)
+
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_certificate_file(certificate_file)
+
+    def test_use_certificate_file_bytes(self):
+        """
+        :py:obj:`Context.use_certificate_file` sets the certificate (given as a
+        ``bytes`` filename) which will be used to identify connections created
+        using the context.
+        """
+        filename = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
+        self._use_certificate_file_test(filename)
+
+    def test_use_certificate_file_unicode(self):
+        """
+        :py:obj:`Context.use_certificate_file` sets the certificate (given as a
+        ``bytes`` filename) which will be used to identify connections created
+        using the context.
+        """
+        filename = self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
+        self._use_certificate_file_test(filename)
+
+    @skip_if_py3
+    def test_use_certificate_file_long(self):
+        """
+        On Python 2 :py:obj:`Context.use_certificate_file` accepts a
+        filetype of type :py:obj:`long` as well as :py:obj:`int`.
+        """
+        pem_filename = self.mktemp()
+        with open(pem_filename, "wb") as pem_file:
+            pem_file.write(cleartextCertificatePEM)
+
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
+
+    def test_check_privatekey_valid(self):
+        """
+        :py:obj:`Context.check_privatekey` returns :py:obj:`None` if the
+        :py:obj:`Context` instance has been configured to use a matched key and
+        certificate pair.
+        """
+        key = load_privatekey(FILETYPE_PEM, client_key_pem)
+        cert = load_certificate(FILETYPE_PEM, client_cert_pem)
+        context = Context(TLSv1_METHOD)
+        context.use_privatekey(key)
+        context.use_certificate(cert)
+        self.assertIs(None, context.check_privatekey())
+
+    def test_check_privatekey_invalid(self):
+        """
+        :py:obj:`Context.check_privatekey` raises :py:obj:`Error` if the
+        :py:obj:`Context` instance has been configured to use a key and
+        certificate pair which don't relate to each other.
+        """
+        key = load_privatekey(FILETYPE_PEM, client_key_pem)
+        cert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        context = Context(TLSv1_METHOD)
+        context.use_privatekey(key)
+        context.use_certificate(cert)
+        self.assertRaises(Error, context.check_privatekey)
+
+    def test_check_privatekey_wrong_args(self):
+        """
+        :py:obj:`Context.check_privatekey` raises :py:obj:`TypeError` if called
+        with other than no arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.check_privatekey, object())
+
+    def test_set_app_data_wrong_args(self):
+        """
+        :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called
+        with other than one argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_app_data)
+        self.assertRaises(TypeError, context.set_app_data, None, None)
+
+    def test_get_app_data_wrong_args(self):
+        """
+        :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.get_app_data, None)
+
+    def test_app_data(self):
+        """
+        :py:obj:`Context.set_app_data` stores an object for later retrieval
+        using :py:obj:`Context.get_app_data`.
+        """
+        app_data = object()
+        context = Context(TLSv1_METHOD)
+        context.set_app_data(app_data)
+        self.assertIdentical(context.get_app_data(), app_data)
+
+    def test_set_options_wrong_args(self):
+        """
+        :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or a non-:py:obj:`int` argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_options)
+        self.assertRaises(TypeError, context.set_options, None)
+        self.assertRaises(TypeError, context.set_options, 1, None)
+
+    def test_set_options(self):
+        """
+        :py:obj:`Context.set_options` returns the new options value.
+        """
+        context = Context(TLSv1_METHOD)
+        options = context.set_options(OP_NO_SSLv2)
+        self.assertTrue(OP_NO_SSLv2 & options)
+
+    @skip_if_py3
+    def test_set_options_long(self):
+        """
+        On Python 2 :py:obj:`Context.set_options` accepts values of type
+        :py:obj:`long` as well as :py:obj:`int`.
+        """
+        context = Context(TLSv1_METHOD)
+        options = context.set_options(long(OP_NO_SSLv2))
+        self.assertTrue(OP_NO_SSLv2 & options)
+
+    def test_set_mode_wrong_args(self):
+        """
+        :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or a non-:py:obj:`int` argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_mode)
+        self.assertRaises(TypeError, context.set_mode, None)
+        self.assertRaises(TypeError, context.set_mode, 1, None)
+
+    if MODE_RELEASE_BUFFERS is not None:
+        def test_set_mode(self):
+            """
+            :py:obj:`Context.set_mode` accepts a mode bitvector and returns the
+            newly set mode.
+            """
+            context = Context(TLSv1_METHOD)
+            self.assertTrue(
+                MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
+
+        @skip_if_py3
+        def test_set_mode_long(self):
+            """
+            On Python 2 :py:obj:`Context.set_mode` accepts values of type
+            :py:obj:`long` as well as :py:obj:`int`.
+            """
+            context = Context(TLSv1_METHOD)
+            mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
+            self.assertTrue(MODE_RELEASE_BUFFERS & mode)
+    else:
+        "MODE_RELEASE_BUFFERS unavailable - OpenSSL version may be too old"
+
+    def test_set_timeout_wrong_args(self):
+        """
+        :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or a non-:py:obj:`int` argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_timeout)
+        self.assertRaises(TypeError, context.set_timeout, None)
+        self.assertRaises(TypeError, context.set_timeout, 1, None)
+
+    def test_get_timeout_wrong_args(self):
+        """
+        :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with
+        any arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.get_timeout, None)
+
+    def test_timeout(self):
+        """
+        :py:obj:`Context.set_timeout` sets the session timeout for all
+        connections created using the context object.
+        :py:obj:`Context.get_timeout` retrieves this value.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_timeout(1234)
+        self.assertEquals(context.get_timeout(), 1234)
+
+    @skip_if_py3
+    def test_timeout_long(self):
+        """
+        On Python 2 :py:obj:`Context.set_timeout` accepts values of type
+        `long` as well as int.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_timeout(long(1234))
+        self.assertEquals(context.get_timeout(), 1234)
+
+    def test_set_verify_depth_wrong_args(self):
+        """
+        :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called
+        with the wrong number of arguments or a non-:py:obj:`int` argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_verify_depth)
+        self.assertRaises(TypeError, context.set_verify_depth, None)
+        self.assertRaises(TypeError, context.set_verify_depth, 1, None)
+
+    def test_get_verify_depth_wrong_args(self):
+        """
+        :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.get_verify_depth, None)
+
+    def test_verify_depth(self):
+        """
+        :py:obj:`Context.set_verify_depth` sets the number of certificates in
+        a chain to follow before giving up.  The value can be retrieved with
+        :py:obj:`Context.get_verify_depth`.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_verify_depth(11)
+        self.assertEquals(context.get_verify_depth(), 11)
+
+    @skip_if_py3
+    def test_verify_depth_long(self):
+        """
+        On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
+        type `long` as well as int.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_verify_depth(long(11))
+        self.assertEquals(context.get_verify_depth(), 11)
+
+    def _write_encrypted_pem(self, passphrase):
+        """
+        Write a new private key out to a new file, encrypted using the given
+        passphrase.  Return the path to the new file.
+        """
+        key = PKey()
+        key.generate_key(TYPE_RSA, 128)
+        pemFile = self.mktemp()
+        fObj = open(pemFile, 'w')
+        pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
+        fObj.write(pem.decode('ascii'))
+        fObj.close()
+        return pemFile
+
+    def test_set_passwd_cb_wrong_args(self):
+        """
+        :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called
+        with the wrong arguments or with a non-callable first argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_passwd_cb)
+        self.assertRaises(TypeError, context.set_passwd_cb, None)
+        self.assertRaises(
+            TypeError, context.set_passwd_cb, lambda: None, None, None
+        )  # pragma: nocover
+
+    def test_set_passwd_cb(self):
+        """
+        :py:obj:`Context.set_passwd_cb` accepts a callable which will be
+        invoked when a private key is loaded from an encrypted PEM.
+        """
+        passphrase = b("foobar")
+        pemFile = self._write_encrypted_pem(passphrase)
+        calledWith = []
+
+        def passphraseCallback(maxlen, verify, extra):
+            calledWith.append((maxlen, verify, extra))
+            return passphrase
+        context = Context(TLSv1_METHOD)
+        context.set_passwd_cb(passphraseCallback)
+        context.use_privatekey_file(pemFile)
+        self.assertTrue(len(calledWith), 1)
+        self.assertTrue(isinstance(calledWith[0][0], int))
+        self.assertTrue(isinstance(calledWith[0][1], int))
+        self.assertEqual(calledWith[0][2], None)
+
+    def test_passwd_callback_exception(self):
+        """
+        :py:obj:`Context.use_privatekey_file` propagates any exception raised
+        by the passphrase callback.
+        """
+        pemFile = self._write_encrypted_pem(b("monkeys are nice"))
+
+        def passphraseCallback(maxlen, verify, extra):
+            raise RuntimeError("Sorry, I am a fail.")
+
+        context = Context(TLSv1_METHOD)
+        context.set_passwd_cb(passphraseCallback)
+        self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
+
+    def test_passwd_callback_false(self):
+        """
+        :py:obj:`Context.use_privatekey_file` raises
+        :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a false
+        value.
+        """
+        pemFile = self._write_encrypted_pem(b("monkeys are nice"))
+
+        def passphraseCallback(maxlen, verify, extra):
+            return b""
+
+        context = Context(TLSv1_METHOD)
+        context.set_passwd_cb(passphraseCallback)
+        self.assertRaises(Error, context.use_privatekey_file, pemFile)
+
+    def test_passwd_callback_non_string(self):
+        """
+        :py:obj:`Context.use_privatekey_file` raises
+        :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a true
+        non-string value.
+        """
+        pemFile = self._write_encrypted_pem(b("monkeys are nice"))
+
+        def passphraseCallback(maxlen, verify, extra):
+            return 10
+
+        context = Context(TLSv1_METHOD)
+        context.set_passwd_cb(passphraseCallback)
+        self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
+
+    def test_passwd_callback_too_long(self):
+        """
+        If the passphrase returned by the passphrase callback returns a string
+        longer than the indicated maximum length, it is truncated.
+        """
+        # A priori knowledge!
+        passphrase = b("x") * 1024
+        pemFile = self._write_encrypted_pem(passphrase)
+
+        def passphraseCallback(maxlen, verify, extra):
+            assert maxlen == 1024
+            return passphrase + b("y")
+
+        context = Context(TLSv1_METHOD)
+        context.set_passwd_cb(passphraseCallback)
+        # This shall succeed because the truncated result is the correct
+        # passphrase.
+        context.use_privatekey_file(pemFile)
+
+    def test_set_info_callback(self):
+        """
+        :py:obj:`Context.set_info_callback` accepts a callable which will be
+        invoked when certain information about an SSL connection is available.
+        """
+        (server, client) = socket_pair()
+
+        clientSSL = Connection(Context(TLSv1_METHOD), client)
+        clientSSL.set_connect_state()
+
+        called = []
+
+        def info(conn, where, ret):
+            called.append((conn, where, ret))
+        context = Context(TLSv1_METHOD)
+        context.set_info_callback(info)
+        context.use_certificate(
+            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
+        context.use_privatekey(
+            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
+
+        serverSSL = Connection(context, server)
+        serverSSL.set_accept_state()
+
+        handshake(clientSSL, serverSSL)
+
+        # The callback must always be called with a Connection instance as the
+        # first argument.  It would probably be better to split this into
+        # separate tests for client and server side info callbacks so we could
+        # assert it is called with the right Connection instance.  It would
+        # also be good to assert *something* about `where` and `ret`.
+        notConnections = [
+            conn for (conn, where, ret) in called
+            if not isinstance(conn, Connection)]
+        self.assertEqual(
+            [], notConnections,
+            "Some info callback arguments were not Connection instaces.")
+
+    def _load_verify_locations_test(self, *args):
+        """
+        Create a client context which will verify the peer certificate and call
+        its :py:obj:`load_verify_locations` method with the given arguments.
+        Then connect it to a server and ensure that the handshake succeeds.
+        """
+        (server, client) = socket_pair()
+
+        clientContext = Context(TLSv1_METHOD)
+        clientContext.load_verify_locations(*args)
+        # Require that the server certificate verify properly or the
+        # connection will fail.
+        clientContext.set_verify(
+            VERIFY_PEER,
+            lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
+
+        clientSSL = Connection(clientContext, client)
+        clientSSL.set_connect_state()
+
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_certificate(
+            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
+        serverContext.use_privatekey(
+            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
+
+        serverSSL = Connection(serverContext, server)
+        serverSSL.set_accept_state()
+
+        # Without load_verify_locations above, the handshake
+        # will fail:
+        # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
+        #          'certificate verify failed')]
+        handshake(clientSSL, serverSSL)
+
+        cert = clientSSL.get_peer_certificate()
+        self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
+
+    def _load_verify_cafile(self, cafile):
+        """
+        Verify that if path to a file containing a certificate is passed to
+        ``Context.load_verify_locations`` for the ``cafile`` parameter, that
+        certificate is used as a trust root for the purposes of verifying
+        connections created using that ``Context``.
+        """
+        fObj = open(cafile, 'w')
+        fObj.write(cleartextCertificatePEM.decode('ascii'))
+        fObj.close()
+
+        self._load_verify_locations_test(cafile)
+
+    def test_load_verify_bytes_cafile(self):
+        """
+        :py:obj:`Context.load_verify_locations` accepts a file name as a
+        ``bytes`` instance and uses the certificates within for verification
+        purposes.
+        """
+        cafile = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
+        self._load_verify_cafile(cafile)
+
+    def test_load_verify_unicode_cafile(self):
+        """
+        :py:obj:`Context.load_verify_locations` accepts a file name as a
+        ``unicode`` instance and uses the certificates within for verification
+        purposes.
+        """
+        self._load_verify_cafile(
+            self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
+        )
+
+    def test_load_verify_invalid_file(self):
+        """
+        :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when
+        passed a non-existent cafile.
+        """
+        clientContext = Context(TLSv1_METHOD)
+        self.assertRaises(
+            Error, clientContext.load_verify_locations, self.mktemp())
+
+    def _load_verify_directory_locations_capath(self, capath):
+        """
+        Verify that if path to a directory containing certificate files is
+        passed to ``Context.load_verify_locations`` for the ``capath``
+        parameter, those certificates are used as trust roots for the purposes
+        of verifying connections created using that ``Context``.
+        """
+        makedirs(capath)
+        # Hash values computed manually with c_rehash to avoid depending on
+        # c_rehash in the test suite.  One is from OpenSSL 0.9.8, the other
+        # from OpenSSL 1.0.0.
+        for name in [b'c7adac82.0', b'c3705638.0']:
+            cafile = join_bytes_or_unicode(capath, name)
+            with open(cafile, 'w') as fObj:
+                fObj.write(cleartextCertificatePEM.decode('ascii'))
+
+        self._load_verify_locations_test(None, capath)
+
+    def test_load_verify_directory_bytes_capath(self):
+        """
+        :py:obj:`Context.load_verify_locations` accepts a directory name as a
+        ``bytes`` instance and uses the certificates within for verification
+        purposes.
+        """
+        self._load_verify_directory_locations_capath(
+            self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
+        )
+
+    def test_load_verify_directory_unicode_capath(self):
+        """
+        :py:obj:`Context.load_verify_locations` accepts a directory name as a
+        ``unicode`` instance and uses the certificates within for verification
+        purposes.
+        """
+        self._load_verify_directory_locations_capath(
+            self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
+        )
+
+    def test_load_verify_locations_wrong_args(self):
+        """
+        :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if
+        called with the wrong number of arguments or with non-:py:obj:`str`
+        arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.load_verify_locations)
+        self.assertRaises(TypeError, context.load_verify_locations, object())
+        self.assertRaises(
+            TypeError, context.load_verify_locations, object(), object()
+        )
+        self.assertRaises(
+            TypeError, context.load_verify_locations, None, None, None
+        )
+
+    @pytest.mark.skipif(
+        platform == "win32",
+        reason="set_default_verify_paths appears not to work on Windows.  "
+        "See LP#404343 and LP#404344."
+    )
+    def test_set_default_verify_paths(self):
+        """
+        :py:obj:`Context.set_default_verify_paths` causes the
+        platform-specific CA certificate locations to be used for
+        verification purposes.
+        """
+        # Testing this requires a server with a certificate signed by one
+        # of the CAs in the platform CA location.  Getting one of those
+        # costs money.  Fortunately (or unfortunately, depending on your
+        # perspective), it's easy to think of a public server on the
+        # internet which has such a certificate.  Connecting to the network
+        # in a unit test is bad, but it's the only way I can think of to
+        # really test this. -exarkun
+
+        # Arg, verisign.com doesn't speak anything newer than TLS 1.0
+        context = Context(TLSv1_METHOD)
+        context.set_default_verify_paths()
+        context.set_verify(
+            VERIFY_PEER,
+            lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
+
+        client = socket()
+        client.connect(('verisign.com', 443))
+        clientSSL = Connection(context, client)
+        clientSSL.set_connect_state()
+        clientSSL.do_handshake()
+        clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
+        self.assertTrue(clientSSL.recv(1024))
+
+    def test_set_default_verify_paths_signature(self):
+        """
+        :py:obj:`Context.set_default_verify_paths` takes no arguments and
+        raises :py:obj:`TypeError` if given any.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_default_verify_paths, None)
+        self.assertRaises(TypeError, context.set_default_verify_paths, 1)
+        self.assertRaises(TypeError, context.set_default_verify_paths, "")
+
+    def test_add_extra_chain_cert_invalid_cert(self):
+        """
+        :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if
+        called with other than one argument or if called with an object which
+        is not an instance of :py:obj:`X509`.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.add_extra_chain_cert)
+        self.assertRaises(TypeError, context.add_extra_chain_cert, object())
+        self.assertRaises(
+            TypeError, context.add_extra_chain_cert, object(), object()
+        )
+
+    def _handshake_test(self, serverContext, clientContext):
+        """
+        Verify that a client and server created with the given contexts can
+        successfully handshake and communicate.
+        """
+        serverSocket, clientSocket = socket_pair()
+
+        server = Connection(serverContext, serverSocket)
+        server.set_accept_state()
+
+        client = Connection(clientContext, clientSocket)
+        client.set_connect_state()
+
+        # Make them talk to each other.
+        # self._interactInMemory(client, server)
+        for i in range(3):
+            for s in [client, server]:
+                try:
+                    s.do_handshake()
+                except WantReadError:
+                    pass
+
+    def test_set_verify_callback_connection_argument(self):
+        """
+        The first argument passed to the verify callback is the
+        :py:class:`Connection` instance for which verification is taking place.
+        """
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_privatekey(
+            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
+        serverContext.use_certificate(
+            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
+        serverConnection = Connection(serverContext, None)
+
+        class VerifyCallback(object):
+            def callback(self, connection, *args):
+                self.connection = connection
+                return 1
+
+        verify = VerifyCallback()
+        clientContext = Context(TLSv1_METHOD)
+        clientContext.set_verify(VERIFY_PEER, verify.callback)
+        clientConnection = Connection(clientContext, None)
+        clientConnection.set_connect_state()
+
+        self._handshakeInMemory(clientConnection, serverConnection)
+
+        self.assertIdentical(verify.connection, clientConnection)
+
+    def test_set_verify_callback_exception(self):
+        """
+        If the verify callback passed to :py:obj:`Context.set_verify` raises an
+        exception, verification fails and the exception is propagated to the
+        caller of :py:obj:`Connection.do_handshake`.
+        """
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_privatekey(
+            load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
+        serverContext.use_certificate(
+            load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
+
+        clientContext = Context(TLSv1_METHOD)
+
+        def verify_callback(*args):
+            raise Exception("silly verify failure")
+        clientContext.set_verify(VERIFY_PEER, verify_callback)
+
+        exc = self.assertRaises(
+            Exception, self._handshake_test, serverContext, clientContext)
+        self.assertEqual("silly verify failure", str(exc))
+
+    def test_add_extra_chain_cert(self):
+        """
+        :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509`
+        instance to add to the certificate chain.
+
+        See :py:obj:`_create_certificate_chain` for the details of the
+        certificate chain tested.
+
+        The chain is tested by starting a server with scert and connecting
+        to it with a client which trusts cacert and requires verification to
+        succeed.
+        """
+        chain = _create_certificate_chain()
+        [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
+
+        # Dump the CA certificate to a file because that's the only way to load
+        # it as a trusted CA in the client context.
+        for cert, name in [(cacert, 'ca.pem'),
+                           (icert, 'i.pem'),
+                           (scert, 's.pem')]:
+            with open(join(self.tmpdir, name), 'w') as f:
+                f.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
+
+        for key, name in [(cakey, 'ca.key'),
+                          (ikey, 'i.key'),
+                          (skey, 's.key')]:
+            with open(join(self.tmpdir, name), 'w') as f:
+                f.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
+
+        # Create the server context
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_privatekey(skey)
+        serverContext.use_certificate(scert)
+        # The client already has cacert, we only need to give them icert.
+        serverContext.add_extra_chain_cert(icert)
+
+        # Create the client
+        clientContext = Context(TLSv1_METHOD)
+        clientContext.set_verify(
+            VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
+        clientContext.load_verify_locations(join(self.tmpdir, "ca.pem"))
+
+        # Try it out.
+        self._handshake_test(serverContext, clientContext)
+
+    def _use_certificate_chain_file_test(self, certdir):
+        """
+        Verify that :py:obj:`Context.use_certificate_chain_file` reads a
+        certificate chain from a specified file.
+
+        The chain is tested by starting a server with scert and connecting to
+        it with a client which trusts cacert and requires verification to
+        succeed.
+        """
+        chain = _create_certificate_chain()
+        [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
+
+        makedirs(certdir)
+
+        chainFile = join_bytes_or_unicode(certdir, "chain.pem")
+        caFile = join_bytes_or_unicode(certdir, "ca.pem")
+
+        # Write out the chain file.
+        with open(chainFile, 'wb') as fObj:
+            # Most specific to least general.
+            fObj.write(dump_certificate(FILETYPE_PEM, scert))
+            fObj.write(dump_certificate(FILETYPE_PEM, icert))
+            fObj.write(dump_certificate(FILETYPE_PEM, cacert))
+
+        with open(caFile, 'w') as fObj:
+            fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
+
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_certificate_chain_file(chainFile)
+        serverContext.use_privatekey(skey)
+
+        clientContext = Context(TLSv1_METHOD)
+        clientContext.set_verify(
+            VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
+        clientContext.load_verify_locations(caFile)
+
+        self._handshake_test(serverContext, clientContext)
+
+    def test_use_certificate_chain_file_bytes(self):
+        """
+        ``Context.use_certificate_chain_file`` accepts the name of a file (as
+        an instance of ``bytes``) to specify additional certificates to use to
+        construct and verify a trust chain.
+        """
+        self._use_certificate_chain_file_test(
+            self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
+        )
+
+    def test_use_certificate_chain_file_unicode(self):
+        """
+        ``Context.use_certificate_chain_file`` accepts the name of a file (as
+        an instance of ``unicode``) to specify additional certificates to use
+        to construct and verify a trust chain.
+        """
+        self._use_certificate_chain_file_test(
+            self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
+        )
+
+    def test_use_certificate_chain_file_wrong_args(self):
+        """
+        :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
+        if passed zero or more than one argument or when passed a non-byte
+        string single argument.  It also raises :py:obj:`OpenSSL.SSL.Error`
+        when passed a bad chain file name (for example, the name of a file
+        which does not exist).
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.use_certificate_chain_file)
+        self.assertRaises(
+            TypeError, context.use_certificate_chain_file, object()
+        )
+        self.assertRaises(
+            TypeError, context.use_certificate_chain_file, b"foo", object()
+        )
+
+        self.assertRaises(
+            Error, context.use_certificate_chain_file, self.mktemp()
+        )
+
+    # XXX load_client_ca
+    # XXX set_session_id
+
+    def test_get_verify_mode_wrong_args(self):
+        """
+        :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.get_verify_mode, None)
+
+    def test_set_verify_mode(self):
+        """
+        :py:obj:`Context.get_verify_mode` returns the verify mode flags
+        previously passed to :py:obj:`Context.set_verify`.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertEquals(context.get_verify_mode(), 0)
+        context.set_verify(
+            VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
+        self.assertEquals(
+            context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
+
+    @skip_if_py3
+    def test_set_verify_mode_long(self):
+        """
+        On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
+        type :py:obj:`long` as well as :py:obj:`int`.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertEquals(context.get_verify_mode(), 0)
+        context.set_verify(
+            long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None
+        )  # pragma: nocover
+        self.assertEquals(
+            context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
+
+    def test_load_tmp_dh_wrong_args(self):
+        """
+        :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or with a non-:py:obj:`str` argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.load_tmp_dh)
+        self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
+        self.assertRaises(TypeError, context.load_tmp_dh, object())
+
+    def test_load_tmp_dh_missing_file(self):
+        """
+        :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the
+        specified file does not exist.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(Error, context.load_tmp_dh, b"hello")
+
+    def _load_tmp_dh_test(self, dhfilename):
+        """
+        Verify that calling ``Context.load_tmp_dh`` with the given filename
+        does not raise an exception.
+        """
+        context = Context(TLSv1_METHOD)
+        with open(dhfilename, "w") as dhfile:
+            dhfile.write(dhparam)
+
+        context.load_tmp_dh(dhfilename)
+        # XXX What should I assert here? -exarkun
+
+    def test_load_tmp_dh_bytes(self):
+        """
+        :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
+        specified file (given as ``bytes``).
+        """
+        self._load_tmp_dh_test(
+            self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
+        )
+
+    def test_load_tmp_dh_unicode(self):
+        """
+        :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
+        specified file (given as ``unicode``).
+        """
+        self._load_tmp_dh_test(
+            self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
+        )
+
+    def test_set_tmp_ecdh(self):
+        """
+        :py:obj:`Context.set_tmp_ecdh` sets the elliptic curve for
+        Diffie-Hellman to the specified curve.
+        """
+        context = Context(TLSv1_METHOD)
+        for curve in get_elliptic_curves():
+            if curve.name.startswith(u"Oakley-"):
+                # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
+                # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
+                # error queue on OpenSSL 1.0.2.
+                continue
+            # The only easily "assertable" thing is that it does not raise an
+            # exception.
+            context.set_tmp_ecdh(curve)
+
+    def test_set_cipher_list_bytes(self):
+        """
+        :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
+        ciphers which connections created with the context object will be able
+        to choose from.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_cipher_list(b"hello world:EXP-RC4-MD5")
+        conn = Connection(context, None)
+        self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
+
+    def test_set_cipher_list_text(self):
+        """
+        :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
+        the ciphers which connections created with the context object will be
+        able to choose from.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
+        conn = Connection(context, None)
+        self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
+
+    def test_set_cipher_list_wrong_args(self):
+        """
+        :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
+        passed zero arguments or more than one argument or when passed a
+        non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
+        passed an incorrect cipher list string.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_cipher_list)
+        self.assertRaises(TypeError, context.set_cipher_list, object())
+        self.assertRaises(
+            TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object()
+        )
+
+        self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
+
+    def test_set_session_cache_mode_wrong_args(self):
+        """
+        :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
+        called with other than one integer argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_session_cache_mode)
+        self.assertRaises(TypeError, context.set_session_cache_mode, object())
+
+    def test_get_session_cache_mode_wrong_args(self):
+        """
+        :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.get_session_cache_mode, 1)
+
+    def test_session_cache_mode(self):
+        """
+        :py:obj:`Context.set_session_cache_mode` specifies how sessions are
+        cached.  The setting can be retrieved via
+        :py:obj:`Context.get_session_cache_mode`.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_session_cache_mode(SESS_CACHE_OFF)
+        off = context.set_session_cache_mode(SESS_CACHE_BOTH)
+        self.assertEqual(SESS_CACHE_OFF, off)
+        self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
+
+    @skip_if_py3
+    def test_session_cache_mode_long(self):
+        """
+        On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
+        of type :py:obj:`long` as well as :py:obj:`int`.
+        """
+        context = Context(TLSv1_METHOD)
+        context.set_session_cache_mode(long(SESS_CACHE_BOTH))
+        self.assertEqual(
+            SESS_CACHE_BOTH, context.get_session_cache_mode())
+
+    def test_get_cert_store(self):
+        """
+        :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store`
+        instance.
+        """
+        context = Context(TLSv1_METHOD)
+        store = context.get_cert_store()
+        self.assertIsInstance(store, X509Store)
+
+
+class ServerNameCallbackTests(TestCase, _LoopbackMixin):
+    """
+    Tests for :py:obj:`Context.set_tlsext_servername_callback` and its
+    interaction with :py:obj:`Connection`.
+    """
+    def test_wrong_args(self):
+        """
+        :py:obj:`Context.set_tlsext_servername_callback` raises
+        :py:obj:`TypeError` if called with other than one argument.
+        """
+        context = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, context.set_tlsext_servername_callback)
+        self.assertRaises(
+            TypeError, context.set_tlsext_servername_callback, 1, 2)
+
+    def test_old_callback_forgotten(self):
+        """
+        If :py:obj:`Context.set_tlsext_servername_callback` is used to specify
+        a new callback, the one it replaces is dereferenced.
+        """
+        def callback(connection):
+            pass
+
+        def replacement(connection):
+            pass
+
+        context = Context(TLSv1_METHOD)
+        context.set_tlsext_servername_callback(callback)
+
+        tracker = ref(callback)
+        del callback
+
+        context.set_tlsext_servername_callback(replacement)
+
+        # One run of the garbage collector happens to work on CPython.  PyPy
+        # doesn't collect the underlying object until a second run for whatever
+        # reason.  That's fine, it still demonstrates our code has properly
+        # dropped the reference.
+        collect()
+        collect()
+
+        callback = tracker()
+        if callback is not None:
+            referrers = get_referrers(callback)
+            if len(referrers) > 1:
+                self.fail("Some references remain: %r" % (referrers,))
+
+    def test_no_servername(self):
+        """
+        When a client specifies no server name, the callback passed to
+        :py:obj:`Context.set_tlsext_servername_callback` is invoked and the
+        result of :py:obj:`Connection.get_servername` is :py:obj:`None`.
+        """
+        args = []
+
+        def servername(conn):
+            args.append((conn, conn.get_servername()))
+        context = Context(TLSv1_METHOD)
+        context.set_tlsext_servername_callback(servername)
+
+        # Lose our reference to it.  The Context is responsible for keeping it
+        # alive now.
+        del servername
+        collect()
+
+        # Necessary to actually accept the connection
+        context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        context.use_certificate(
+            load_certificate(FILETYPE_PEM, server_cert_pem))
+
+        # Do a little connection to trigger the logic
+        server = Connection(context, None)
+        server.set_accept_state()
+
+        client = Connection(Context(TLSv1_METHOD), None)
+        client.set_connect_state()
+
+        self._interactInMemory(server, client)
+
+        self.assertEqual([(server, None)], args)
+
+    def test_servername(self):
+        """
+        When a client specifies a server name in its hello message, the
+        callback passed to :py:obj:`Contexts.set_tlsext_servername_callback` is
+        invoked and the result of :py:obj:`Connection.get_servername` is that
+        server name.
+        """
+        args = []
+
+        def servername(conn):
+            args.append((conn, conn.get_servername()))
+        context = Context(TLSv1_METHOD)
+        context.set_tlsext_servername_callback(servername)
+
+        # Necessary to actually accept the connection
+        context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        context.use_certificate(
+            load_certificate(FILETYPE_PEM, server_cert_pem))
+
+        # Do a little connection to trigger the logic
+        server = Connection(context, None)
+        server.set_accept_state()
+
+        client = Connection(Context(TLSv1_METHOD), None)
+        client.set_connect_state()
+        client.set_tlsext_host_name(b("foo1.example.com"))
+
+        self._interactInMemory(server, client)
+
+        self.assertEqual([(server, b("foo1.example.com"))], args)
+
+
+class NextProtoNegotiationTests(TestCase, _LoopbackMixin):
+    """
+    Test for Next Protocol Negotiation in PyOpenSSL.
+    """
+    if _lib.Cryptography_HAS_NEXTPROTONEG:
+        def test_npn_success(self):
+            """
+            Tests that clients and servers that agree on the negotiated next
+            protocol can correct establish a connection, and that the agreed
+            protocol is reported by the connections.
+            """
+            advertise_args = []
+            select_args = []
+
+            def advertise(conn):
+                advertise_args.append((conn,))
+                return [b'http/1.1', b'spdy/2']
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                return b'spdy/2'
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_npn_advertise_callback(advertise)
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_npn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            self._interactInMemory(server, client)
+
+            self.assertEqual([(server,)], advertise_args)
+            self.assertEqual([(client, [b'http/1.1', b'spdy/2'])], select_args)
+
+            self.assertEqual(server.get_next_proto_negotiated(), b'spdy/2')
+            self.assertEqual(client.get_next_proto_negotiated(), b'spdy/2')
+
+        def test_npn_client_fail(self):
+            """
+            Tests that when clients and servers cannot agree on what protocol
+            to use next that the TLS connection does not get established.
+            """
+            advertise_args = []
+            select_args = []
+
+            def advertise(conn):
+                advertise_args.append((conn,))
+                return [b'http/1.1', b'spdy/2']
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                return b''
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_npn_advertise_callback(advertise)
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_npn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            # If the client doesn't return anything, the connection will fail.
+            self.assertRaises(Error, self._interactInMemory, server, client)
+
+            self.assertEqual([(server,)], advertise_args)
+            self.assertEqual([(client, [b'http/1.1', b'spdy/2'])], select_args)
+
+        def test_npn_select_error(self):
+            """
+            Test that we can handle exceptions in the select callback. If
+            select fails it should be fatal to the connection.
+            """
+            advertise_args = []
+
+            def advertise(conn):
+                advertise_args.append((conn,))
+                return [b'http/1.1', b'spdy/2']
+
+            def select(conn, options):
+                raise TypeError
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_npn_advertise_callback(advertise)
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_npn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            # If the callback throws an exception it should be raised here.
+            self.assertRaises(
+                TypeError, self._interactInMemory, server, client
+            )
+            self.assertEqual([(server,)], advertise_args)
+
+        def test_npn_advertise_error(self):
+            """
+            Test that we can handle exceptions in the advertise callback. If
+            advertise fails no NPN is advertised to the client.
+            """
+            select_args = []
+
+            def advertise(conn):
+                raise TypeError
+
+            def select(conn, options):  # pragma: nocover
+                """
+                Assert later that no args are actually appended.
+                """
+                select_args.append((conn, options))
+                return b''
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_npn_advertise_callback(advertise)
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_npn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            # If the client doesn't return anything, the connection will fail.
+            self.assertRaises(
+                TypeError, self._interactInMemory, server, client
+            )
+            self.assertEqual([], select_args)
+
+    else:
+        # No NPN.
+        def test_npn_not_implemented(self):
+            # Test the context methods first.
+            context = Context(TLSv1_METHOD)
+            fail_methods = [
+                context.set_npn_advertise_callback,
+                context.set_npn_select_callback,
+            ]
+            for method in fail_methods:
+                self.assertRaises(
+                    NotImplementedError, method, None
+                )
+
+            # Now test a connection.
+            conn = Connection(context)
+            fail_methods = [
+                conn.get_next_proto_negotiated,
+            ]
+            for method in fail_methods:
+                self.assertRaises(NotImplementedError, method)
+
+
+class ApplicationLayerProtoNegotiationTests(TestCase, _LoopbackMixin):
+    """
+    Tests for ALPN in PyOpenSSL.
+    """
+    # Skip tests on versions that don't support ALPN.
+    if _lib.Cryptography_HAS_ALPN:
+
+        def test_alpn_success(self):
+            """
+            Clients and servers that agree on the negotiated ALPN protocol can
+            correct establish a connection, and the agreed protocol is reported
+            by the connections.
+            """
+            select_args = []
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                return b'spdy/2'
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_alpn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            self._interactInMemory(server, client)
+
+            self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
+
+            self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
+            self.assertEqual(client.get_alpn_proto_negotiated(), b'spdy/2')
+
+        def test_alpn_set_on_connection(self):
+            """
+            The same as test_alpn_success, but setting the ALPN protocols on
+            the connection rather than the context.
+            """
+            select_args = []
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                return b'spdy/2'
+
+            # Setup the client context but don't set any ALPN protocols.
+            client_context = Context(TLSv1_METHOD)
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_alpn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            # Set the ALPN protocols on the client connection.
+            client = Connection(client_context, None)
+            client.set_alpn_protos([b'http/1.1', b'spdy/2'])
+            client.set_connect_state()
+
+            self._interactInMemory(server, client)
+
+            self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
+
+            self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
+            self.assertEqual(client.get_alpn_proto_negotiated(), b'spdy/2')
+
+        def test_alpn_server_fail(self):
+            """
+            When clients and servers cannot agree on what protocol to use next
+            the TLS connection does not get established.
+            """
+            select_args = []
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                return b''
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_alpn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            # If the client doesn't return anything, the connection will fail.
+            self.assertRaises(Error, self._interactInMemory, server, client)
+
+            self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
+
+        def test_alpn_no_server(self):
+            """
+            When clients and servers cannot agree on what protocol to use next
+            because the server doesn't offer ALPN, no protocol is negotiated.
+            """
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
+
+            server_context = Context(TLSv1_METHOD)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            # Do the dance.
+            self._interactInMemory(server, client)
+
+            self.assertEqual(client.get_alpn_proto_negotiated(), b'')
+
+        def test_alpn_callback_exception(self):
+            """
+            We can handle exceptions in the ALPN select callback.
+            """
+            select_args = []
+
+            def select(conn, options):
+                select_args.append((conn, options))
+                raise TypeError()
+
+            client_context = Context(TLSv1_METHOD)
+            client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
+
+            server_context = Context(TLSv1_METHOD)
+            server_context.set_alpn_select_callback(select)
+
+            # Necessary to actually accept the connection
+            server_context.use_privatekey(
+                load_privatekey(FILETYPE_PEM, server_key_pem))
+            server_context.use_certificate(
+                load_certificate(FILETYPE_PEM, server_cert_pem))
+
+            # Do a little connection to trigger the logic
+            server = Connection(server_context, None)
+            server.set_accept_state()
+
+            client = Connection(client_context, None)
+            client.set_connect_state()
+
+            self.assertRaises(
+                TypeError, self._interactInMemory, server, client
+            )
+            self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
+
+    else:
+        # No ALPN.
+        def test_alpn_not_implemented(self):
+            """
+            If ALPN is not in OpenSSL, we should raise NotImplementedError.
+            """
+            # Test the context methods first.
+            context = Context(TLSv1_METHOD)
+            self.assertRaises(
+                NotImplementedError, context.set_alpn_protos, None
+            )
+            self.assertRaises(
+                NotImplementedError, context.set_alpn_select_callback, None
+            )
+
+            # Now test a connection.
+            conn = Connection(context)
+            self.assertRaises(
+                NotImplementedError, conn.set_alpn_protos, None
+            )
+
+
+class SessionTests(TestCase):
+    """
+    Unit tests for :py:obj:`OpenSSL.SSL.Session`.
+    """
+    def test_construction(self):
+        """
+        :py:class:`Session` can be constructed with no arguments, creating
+        a new instance of that type.
+        """
+        new_session = Session()
+        self.assertTrue(isinstance(new_session, Session))
+
+    def test_construction_wrong_args(self):
+        """
+        If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
+        is raised.
+        """
+        self.assertRaises(TypeError, Session, 123)
+        self.assertRaises(TypeError, Session, "hello")
+        self.assertRaises(TypeError, Session, object())
+
+
+class ConnectionTests(TestCase, _LoopbackMixin):
+    """
+    Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
+    """
+    # XXX get_peer_certificate -> None
+    # XXX sock_shutdown
+    # XXX master_key -> TypeError
+    # XXX server_random -> TypeError
+    # XXX connect -> TypeError
+    # XXX connect_ex -> TypeError
+    # XXX set_connect_state -> TypeError
+    # XXX set_accept_state -> TypeError
+    # XXX renegotiate_pending
+    # XXX do_handshake -> TypeError
+    # XXX bio_read -> TypeError
+    # XXX recv -> TypeError
+    # XXX send -> TypeError
+    # XXX bio_write -> TypeError
+
+    def test_type(self):
+        """
+        :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same
+        type object and can be used to create instances of that type.
+        """
+        self.assertIdentical(Connection, ConnectionType)
+        ctx = Context(TLSv1_METHOD)
+        self.assertConsistentType(Connection, 'Connection', ctx, None)
+
+    def test_get_context(self):
+        """
+        :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance
+        used to construct the :py:obj:`Connection` instance.
+        """
+        context = Context(TLSv1_METHOD)
+        connection = Connection(context, None)
+        self.assertIdentical(connection.get_context(), context)
+
+    def test_get_context_wrong_args(self):
+        """
+        :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.get_context, None)
+
+    def test_set_context_wrong_args(self):
+        """
+        :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called
+        with a non-:py:obj:`Context` instance argument or with any number of
+        arguments other than 1.
+        """
+        ctx = Context(TLSv1_METHOD)
+        connection = Connection(ctx, None)
+        self.assertRaises(TypeError, connection.set_context)
+        self.assertRaises(TypeError, connection.set_context, object())
+        self.assertRaises(TypeError, connection.set_context, "hello")
+        self.assertRaises(TypeError, connection.set_context, 1)
+        self.assertRaises(TypeError, connection.set_context, 1, 2)
+        self.assertRaises(
+            TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
+        self.assertIdentical(ctx, connection.get_context())
+
+    def test_set_context(self):
+        """
+        :py:obj:`Connection.set_context` specifies a new :py:obj:`Context`
+        instance to be used for the connection.
+        """
+        original = Context(SSLv23_METHOD)
+        replacement = Context(TLSv1_METHOD)
+        connection = Connection(original, None)
+        connection.set_context(replacement)
+        self.assertIdentical(replacement, connection.get_context())
+        # Lose our references to the contexts, just in case the Connection
+        # isn't properly managing its own contributions to their reference
+        # counts.
+        del original, replacement
+        collect()
+
+    def test_set_tlsext_host_name_wrong_args(self):
+        """
+        If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte
+        string argument or a byte string with an embedded NUL or other than one
+        argument, :py:obj:`TypeError` is raised.
+        """
+        conn = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, conn.set_tlsext_host_name)
+        self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
+        self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
+        self.assertRaises(
+            TypeError, conn.set_tlsext_host_name, b("with\0null"))
+
+        if PY3:
+            # On Python 3.x, don't accidentally implicitly convert from text.
+            self.assertRaises(
+                TypeError,
+                conn.set_tlsext_host_name, b("example.com").decode("ascii"))
+
+    def test_get_servername_wrong_args(self):
+        """
+        :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.get_servername, object())
+        self.assertRaises(TypeError, connection.get_servername, 1)
+        self.assertRaises(TypeError, connection.get_servername, "hello")
+
+    def test_pending(self):
+        """
+        :py:obj:`Connection.pending` returns the number of bytes available for
+        immediate read.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertEquals(connection.pending(), 0)
+
+    def test_pending_wrong_args(self):
+        """
+        :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with
+        any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.pending, None)
+
+    def test_peek(self):
+        """
+        :py:obj:`Connection.recv` peeks into the connection if
+        :py:obj:`socket.MSG_PEEK` is passed.
+        """
+        server, client = self._loopback()
+        server.send(b('xy'))
+        self.assertEqual(client.recv(2, MSG_PEEK), b('xy'))
+        self.assertEqual(client.recv(2, MSG_PEEK), b('xy'))
+        self.assertEqual(client.recv(2), b('xy'))
+
+    def test_connect_wrong_args(self):
+        """
+        :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
+        a non-address argument or with the wrong number of arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), socket())
+        self.assertRaises(TypeError, connection.connect, None)
+        self.assertRaises(TypeError, connection.connect)
+        self.assertRaises(
+            TypeError, connection.connect, ("127.0.0.1", 1), None
+        )
+
+    def test_connection_undefined_attr(self):
+        """
+        :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
+        a non-address argument or with the wrong number of arguments.
+        """
+
+        def attr_access_test(connection):
+            return connection.an_attribute_which_is_not_defined
+
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(AttributeError, attr_access_test, connection)
+
+    def test_connect_refused(self):
+        """
+        :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the
+        underlying socket connect method raises it.
+        """
+        client = socket()
+        context = Context(TLSv1_METHOD)
+        clientSSL = Connection(context, client)
+        # pytest.raises here doesn't work because of a bug in py.test on Python
+        # 2.6: https://github.com/pytest-dev/pytest/issues/988
+        try:
+            clientSSL.connect(("127.0.0.1", 1))
+        except error as e:
+            exc = e
+        assert exc.args[0] == ECONNREFUSED
+
+    def test_connect(self):
+        """
+        :py:obj:`Connection.connect` establishes a connection to the specified
+        address.
+        """
+        port = socket()
+        port.bind(('', 0))
+        port.listen(3)
+
+        clientSSL = Connection(Context(TLSv1_METHOD), socket())
+        clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
+        # XXX An assertion?  Or something?
+
+    @pytest.mark.skipif(
+        platform == "darwin",
+        reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
+    )
+    def test_connect_ex(self):
+        """
+        If there is a connection error, :py:obj:`Connection.connect_ex`
+        returns the errno instead of raising an exception.
+        """
+        port = socket()
+        port.bind(('', 0))
+        port.listen(3)
+
+        clientSSL = Connection(Context(TLSv1_METHOD), socket())
+        clientSSL.setblocking(False)
+        result = clientSSL.connect_ex(port.getsockname())
+        expected = (EINPROGRESS, EWOULDBLOCK)
+        self.assertTrue(
+            result in expected, "%r not in %r" % (result, expected))
+
+    def test_accept_wrong_args(self):
+        """
+        :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with
+        any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), socket())
+        self.assertRaises(TypeError, connection.accept, None)
+
+    def test_accept(self):
+        """
+        :py:obj:`Connection.accept` accepts a pending connection attempt and
+        returns a tuple of a new :py:obj:`Connection` (the accepted client) and
+        the address the connection originated from.
+        """
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
+        port = socket()
+        portSSL = Connection(ctx, port)
+        portSSL.bind(('', 0))
+        portSSL.listen(3)
+
+        clientSSL = Connection(Context(TLSv1_METHOD), socket())
+
+        # Calling portSSL.getsockname() here to get the server IP address
+        # sounds great, but frequently fails on Windows.
+        clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
+
+        serverSSL, address = portSSL.accept()
+
+        self.assertTrue(isinstance(serverSSL, Connection))
+        self.assertIdentical(serverSSL.get_context(), ctx)
+        self.assertEquals(address, clientSSL.getsockname())
+
+    def test_shutdown_wrong_args(self):
+        """
+        :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with
+        the wrong number of arguments or with arguments other than integers.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.shutdown, None)
+        self.assertRaises(TypeError, connection.get_shutdown, None)
+        self.assertRaises(TypeError, connection.set_shutdown)
+        self.assertRaises(TypeError, connection.set_shutdown, None)
+        self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
+
+    def test_shutdown(self):
+        """
+        :py:obj:`Connection.shutdown` performs an SSL-level connection
+        shutdown.
+        """
+        server, client = self._loopback()
+        self.assertFalse(server.shutdown())
+        self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
+        self.assertRaises(ZeroReturnError, client.recv, 1024)
+        self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
+        client.shutdown()
+        self.assertEquals(
+            client.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
+        )
+        self.assertRaises(ZeroReturnError, server.recv, 1024)
+        self.assertEquals(
+            server.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
+        )
+
+    def test_shutdown_closed(self):
+        """
+        If the underlying socket is closed, :py:obj:`Connection.shutdown`
+        propagates the write error from the low level write call.
+        """
+        server, client = self._loopback()
+        server.sock_shutdown(2)
+        exc = self.assertRaises(SysCallError, server.shutdown)
+        if platform == "win32":
+            self.assertEqual(exc.args[0], ESHUTDOWN)
+        else:
+            self.assertEqual(exc.args[0], EPIPE)
+
+    def test_shutdown_truncated(self):
+        """
+        If the underlying connection is truncated, :obj:`Connection.shutdown`
+        raises an :obj:`Error`.
+        """
+        server_ctx = Context(TLSv1_METHOD)
+        client_ctx = Context(TLSv1_METHOD)
+        server_ctx.use_privatekey(
+            load_privatekey(FILETYPE_PEM, server_key_pem))
+        server_ctx.use_certificate(
+            load_certificate(FILETYPE_PEM, server_cert_pem))
+        server = Connection(server_ctx, None)
+        client = Connection(client_ctx, None)
+        self._handshakeInMemory(client, server)
+        self.assertEqual(server.shutdown(), False)
+        self.assertRaises(WantReadError, server.shutdown)
+        server.bio_shutdown()
+        self.assertRaises(Error, server.shutdown)
+
+    def test_set_shutdown(self):
+        """
+        :py:obj:`Connection.set_shutdown` sets the state of the SSL connection
+        shutdown process.
+        """
+        connection = Connection(Context(TLSv1_METHOD), socket())
+        connection.set_shutdown(RECEIVED_SHUTDOWN)
+        self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
+
+    @skip_if_py3
+    def test_set_shutdown_long(self):
+        """
+        On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
+        of type :py:obj:`long` as well as :py:obj:`int`.
+        """
+        connection = Connection(Context(TLSv1_METHOD), socket())
+        connection.set_shutdown(long(RECEIVED_SHUTDOWN))
+        self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
+
+    def test_state_string(self):
+        """
+        :meth:`Connection.state_string` verbosely describes the current
+        state of the :class:`Connection`.
+        """
+        server, client = socket_pair()
+        server = self._loopbackServerFactory(server)
+        client = self._loopbackClientFactory(client)
+
+        self.assertEqual('before/accept initialization',
+                         server.state_string().decode())
+        self.assertEqual('before/connect initialization',
+                         client.state_string().decode())
+
+        for conn in [server, client]:
+            try:
+                conn.do_handshake()
+            except WantReadError:
+                pass
+
+        self.assertEqual('SSLv3 read client hello B',
+                         server.state_string().decode())
+        self.assertEqual('SSLv3 read server hello A',
+                         client.state_string().decode())
+
+        for conn in [server, client]:
+            try:
+                conn.do_handshake()
+            except WantReadError:
+                pass
+
+        assert server.state_string().decode() in (
+            "SSLv3 read client certificate A",
+            "SSLv3 read client key exchange A",  # 1.0.2d+
+        )
+        self.assertEqual('SSLv3 read server session ticket A',
+                         client.state_string().decode())
+
+        for conn in [server, client]:
+            conn.do_handshake()
+
+        self.assertEqual('SSL negotiation finished successfully',
+                         server.state_string().decode())
+        self.assertEqual('SSL negotiation finished successfully',
+                         client.state_string().decode())
+
+    def test_app_data_wrong_args(self):
+        """
+        :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called
+        with other than one argument.  :py:obj:`Connection.get_app_data` raises
+        :py:obj:`TypeError` if called with any arguments.
+        """
+        conn = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, conn.get_app_data, None)
+        self.assertRaises(TypeError, conn.set_app_data)
+        self.assertRaises(TypeError, conn.set_app_data, None, None)
+
+    def test_app_data(self):
+        """
+        Any object can be set as app data by passing it to
+        :py:obj:`Connection.set_app_data` and later retrieved with
+        :py:obj:`Connection.get_app_data`.
+        """
+        conn = Connection(Context(TLSv1_METHOD), None)
+        app_data = object()
+        conn.set_app_data(app_data)
+        self.assertIdentical(conn.get_app_data(), app_data)
+
+    def test_makefile(self):
+        """
+        :py:obj:`Connection.makefile` is not implemented and calling that
+        method raises :py:obj:`NotImplementedError`.
+        """
+        conn = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(NotImplementedError, conn.makefile)
+
+    def test_get_peer_cert_chain_wrong_args(self):
+        """
+        :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        conn = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
+        self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
+        self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
+        self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
+
+    def test_get_peer_cert_chain(self):
+        """
+        :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates
+        which the connected server returned for the certification verification.
+        """
+        chain = _create_certificate_chain()
+        [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
+
+        serverContext = Context(TLSv1_METHOD)
+        serverContext.use_privatekey(skey)
+        serverContext.use_certificate(scert)
+        serverContext.add_extra_chain_cert(icert)
+        serverContext.add_extra_chain_cert(cacert)
+        server = Connection(serverContext, None)
+        server.set_accept_state()
+
+        # Create the client
+        clientContext = Context(TLSv1_METHOD)
+        clientContext.set_verify(VERIFY_NONE, verify_cb)
+        client = Connection(clientContext, None)
+        client.set_connect_state()
+
+        self._interactInMemory(client, server)
+
+        chain = client.get_peer_cert_chain()
+        self.assertEqual(len(chain), 3)
+        self.assertEqual(
+            "Server Certificate", chain[0].get_subject().CN)
+        self.assertEqual(
+            "Intermediate Certificate", chain[1].get_subject().CN)
+        self.assertEqual(
+            "Authority Certificate", chain[2].get_subject().CN)
+
+    def test_get_peer_cert_chain_none(self):
+        """
+        :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the
+        peer sends no certificate chain.
+        """
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
+        ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
+        server = Connection(ctx, None)
+        server.set_accept_state()
+        client = Connection(Context(TLSv1_METHOD), None)
+        client.set_connect_state()
+        self._interactInMemory(client, server)
+        self.assertIdentical(None, server.get_peer_cert_chain())
+
+    def test_get_session_wrong_args(self):
+        """
+        :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        ctx = Context(TLSv1_METHOD)
+        server = Connection(ctx, None)
+        self.assertRaises(TypeError, server.get_session, 123)
+        self.assertRaises(TypeError, server.get_session, "hello")
+        self.assertRaises(TypeError, server.get_session, object())
+
+    def test_get_session_unconnected(self):
+        """
+        :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
+        an object which has not been connected.
+        """
+        ctx = Context(TLSv1_METHOD)
+        server = Connection(ctx, None)
+        session = server.get_session()
+        self.assertIdentical(None, session)
+
+    def test_server_get_session(self):
+        """
+        On the server side of a connection, :py:obj:`Connection.get_session`
+        returns a :py:class:`Session` instance representing the SSL session for
+        that connection.
+        """
+        server, client = self._loopback()
+        session = server.get_session()
+        self.assertIsInstance(session, Session)
+
+    def test_client_get_session(self):
+        """
+        On the client side of a connection, :py:obj:`Connection.get_session`
+        returns a :py:class:`Session` instance representing the SSL session for
+        that connection.
+        """
+        server, client = self._loopback()
+        session = client.get_session()
+        self.assertIsInstance(session, Session)
+
+    def test_set_session_wrong_args(self):
+        """
+        If called with an object that is not an instance of
+        :py:class:`Session`, or with other than one argument,
+        :py:obj:`Connection.set_session` raises :py:obj:`TypeError`.
+        """
+        ctx = Context(TLSv1_METHOD)
+        connection = Connection(ctx, None)
+        self.assertRaises(TypeError, connection.set_session)
+        self.assertRaises(TypeError, connection.set_session, 123)
+        self.assertRaises(TypeError, connection.set_session, "hello")
+        self.assertRaises(TypeError, connection.set_session, object())
+        self.assertRaises(
+            TypeError, connection.set_session, Session(), Session())
+
+    def test_client_set_session(self):
+        """
+        :py:obj:`Connection.set_session`, when used prior to a connection being
+        established, accepts a :py:class:`Session` instance and causes an
+        attempt to re-use the session it represents when the SSL handshake is
+        performed.
+        """
+        key = load_privatekey(FILETYPE_PEM, server_key_pem)
+        cert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(key)
+        ctx.use_certificate(cert)
+        ctx.set_session_id("unity-test")
+
+        def makeServer(socket):
+            server = Connection(ctx, socket)
+            server.set_accept_state()
+            return server
+
+        originalServer, originalClient = self._loopback(
+            serverFactory=makeServer)
+        originalSession = originalClient.get_session()
+
+        def makeClient(socket):
+            client = self._loopbackClientFactory(socket)
+            client.set_session(originalSession)
+            return client
+        resumedServer, resumedClient = self._loopback(
+            serverFactory=makeServer,
+            clientFactory=makeClient)
+
+        # This is a proxy: in general, we have no access to any unique
+        # identifier for the session (new enough versions of OpenSSL expose
+        # a hash which could be usable, but "new enough" is very, very new).
+        # Instead, exploit the fact that the master key is re-used if the
+        # session is re-used.  As long as the master key for the two
+        # connections is the same, the session was re-used!
+        self.assertEqual(
+            originalServer.master_key(), resumedServer.master_key())
+
+    def test_set_session_wrong_method(self):
+        """
+        If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
+        instance associated with a context using a different SSL method than
+        the :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
+        raised.
+        """
+        key = load_privatekey(FILETYPE_PEM, server_key_pem)
+        cert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        ctx = Context(TLSv1_METHOD)
+        ctx.use_privatekey(key)
+        ctx.use_certificate(cert)
+        ctx.set_session_id("unity-test")
+
+        def makeServer(socket):
+            server = Connection(ctx, socket)
+            server.set_accept_state()
+            return server
+
+        originalServer, originalClient = self._loopback(
+            serverFactory=makeServer)
+        originalSession = originalClient.get_session()
+
+        def makeClient(socket):
+            # Intentionally use a different, incompatible method here.
+            client = Connection(Context(SSLv3_METHOD), socket)
+            client.set_connect_state()
+            client.set_session(originalSession)
+            return client
+
+        self.assertRaises(
+            Error,
+            self._loopback, clientFactory=makeClient, serverFactory=makeServer)
+
+    def test_wantWriteError(self):
+        """
+        :py:obj:`Connection` methods which generate output raise
+        :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
+        fail indicating a should-write state.
+        """
+        client_socket, server_socket = socket_pair()
+        # Fill up the client's send buffer so Connection won't be able to write
+        # anything.  Only write a single byte at a time so we can be sure we
+        # completely fill the buffer.  Even though the socket API is allowed to
+        # signal a short write via its return value it seems this doesn't
+        # always happen on all platforms (FreeBSD and OS X particular) for the
+        # very last bit of available buffer space.
+        msg = b"x"
+        for i in range(1024 * 1024 * 4):
+            try:
+                client_socket.send(msg)
+            except error as e:
+                if e.errno == EWOULDBLOCK:
+                    break
+                raise
+        else:
+            self.fail(
+                "Failed to fill socket buffer, cannot test BIO want write")
+
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, client_socket)
+        # Client's speak first, so make it an SSL client
+        conn.set_connect_state()
+        self.assertRaises(WantWriteError, conn.do_handshake)
+
+    # XXX want_read
+
+    def test_get_finished_before_connect(self):
+        """
+        :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
+        handshake is completed.
+        """
+        ctx = Context(TLSv1_METHOD)
+        connection = Connection(ctx, None)
+        self.assertEqual(connection.get_finished(), None)
+
+    def test_get_peer_finished_before_connect(self):
+        """
+        :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
+        TLS handshake is completed.
+        """
+        ctx = Context(TLSv1_METHOD)
+        connection = Connection(ctx, None)
+        self.assertEqual(connection.get_peer_finished(), None)
+
+    def test_get_finished(self):
+        """
+        :py:obj:`Connection.get_finished` method returns the TLS Finished
+        message send from client, or server. Finished messages are send during
+        TLS handshake.
+        """
+
+        server, client = self._loopback()
+
+        self.assertNotEqual(server.get_finished(), None)
+        self.assertTrue(len(server.get_finished()) > 0)
+
+    def test_get_peer_finished(self):
+        """
+        :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
+        message received from client, or server. Finished messages are send
+        during TLS handshake.
+        """
+        server, client = self._loopback()
+
+        self.assertNotEqual(server.get_peer_finished(), None)
+        self.assertTrue(len(server.get_peer_finished()) > 0)
+
+    def test_tls_finished_message_symmetry(self):
+        """
+        The TLS Finished message send by server must be the TLS Finished
+        message received by client.
+
+        The TLS Finished message send by client must be the TLS Finished
+        message received by server.
+        """
+        server, client = self._loopback()
+
+        self.assertEqual(server.get_finished(), client.get_peer_finished())
+        self.assertEqual(client.get_finished(), server.get_peer_finished())
+
+    def test_get_cipher_name_before_connect(self):
+        """
+        :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
+        connection has been established.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        self.assertIdentical(conn.get_cipher_name(), None)
+
+    def test_get_cipher_name(self):
+        """
+        :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
+        string giving the name of the currently used cipher.
+        """
+        server, client = self._loopback()
+        server_cipher_name, client_cipher_name = \
+            server.get_cipher_name(), client.get_cipher_name()
+
+        self.assertIsInstance(server_cipher_name, text_type)
+        self.assertIsInstance(client_cipher_name, text_type)
+
+        self.assertEqual(server_cipher_name, client_cipher_name)
+
+    def test_get_cipher_version_before_connect(self):
+        """
+        :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
+        connection has been established.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        self.assertIdentical(conn.get_cipher_version(), None)
+
+    def test_get_cipher_version(self):
+        """
+        :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
+        string giving the protocol name of the currently used cipher.
+        """
+        server, client = self._loopback()
+        server_cipher_version, client_cipher_version = \
+            server.get_cipher_version(), client.get_cipher_version()
+
+        self.assertIsInstance(server_cipher_version, text_type)
+        self.assertIsInstance(client_cipher_version, text_type)
+
+        self.assertEqual(server_cipher_version, client_cipher_version)
+
+    def test_get_cipher_bits_before_connect(self):
+        """
+        :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
+        connection has been established.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        self.assertIdentical(conn.get_cipher_bits(), None)
+
+    def test_get_cipher_bits(self):
+        """
+        :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
+        of the currently used cipher.
+        """
+        server, client = self._loopback()
+        server_cipher_bits, client_cipher_bits = \
+            server.get_cipher_bits(), client.get_cipher_bits()
+
+        self.assertIsInstance(server_cipher_bits, int)
+        self.assertIsInstance(client_cipher_bits, int)
+
+        self.assertEqual(server_cipher_bits, client_cipher_bits)
+
+    def test_get_protocol_version_name(self):
+        """
+        :py:obj:`Connection.get_protocol_version_name()` returns a string
+        giving the protocol version of the current connection.
+        """
+        server, client = self._loopback()
+        client_protocol_version_name = client.get_protocol_version_name()
+        server_protocol_version_name = server.get_protocol_version_name()
+
+        self.assertIsInstance(server_protocol_version_name, text_type)
+        self.assertIsInstance(client_protocol_version_name, text_type)
+
+        self.assertEqual(
+            server_protocol_version_name, client_protocol_version_name
+        )
+
+    def test_get_protocol_version(self):
+        """
+        :py:obj:`Connection.get_protocol_version()` returns an integer
+        giving the protocol version of the current connection.
+        """
+        server, client = self._loopback()
+        client_protocol_version = client.get_protocol_version()
+        server_protocol_version = server.get_protocol_version()
+
+        self.assertIsInstance(server_protocol_version, int)
+        self.assertIsInstance(client_protocol_version, int)
+
+        self.assertEqual(server_protocol_version, client_protocol_version)
+
+
+class ConnectionGetCipherListTests(TestCase):
+    """
+    Tests for :py:obj:`Connection.get_cipher_list`.
+    """
+    def test_wrong_args(self):
+        """
+        :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.get_cipher_list, None)
+
+    def test_result(self):
+        """
+        :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
+        :py:obj:`bytes` giving the names of the ciphers which might be used.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        ciphers = connection.get_cipher_list()
+        self.assertTrue(isinstance(ciphers, list))
+        for cipher in ciphers:
+            self.assertTrue(isinstance(cipher, str))
+
+
+class ConnectionSendTests(TestCase, _LoopbackMixin):
+    """
+    Tests for :py:obj:`Connection.send`
+    """
+    def test_wrong_args(self):
+        """
+        When called with arguments other than string argument for its first
+        parameter or more than two arguments, :py:obj:`Connection.send` raises
+        :py:obj:`TypeError`.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.send)
+        self.assertRaises(TypeError, connection.send, object())
+        self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
+
+    def test_short_bytes(self):
+        """
+        When passed a short byte string, :py:obj:`Connection.send` transmits
+        all of it and returns the number of bytes sent.
+        """
+        server, client = self._loopback()
+        count = server.send(b('xy'))
+        self.assertEquals(count, 2)
+        self.assertEquals(client.recv(2), b('xy'))
+
+    def test_text(self):
+        """
+        When passed a text, :py:obj:`Connection.send` transmits all of it and
+        returns the number of bytes sent. It also raises a DeprecationWarning.
+        """
+        server, client = self._loopback()
+        with catch_warnings(record=True) as w:
+            simplefilter("always")
+            count = server.send(b"xy".decode("ascii"))
+            self.assertEqual(
+                "{0} for buf is no longer accepted, use bytes".format(
+                    WARNING_TYPE_EXPECTED
+                ),
+                str(w[-1].message)
+            )
+            self.assertIs(w[-1].category, DeprecationWarning)
+        self.assertEquals(count, 2)
+        self.assertEquals(client.recv(2), b"xy")
+
+    @skip_if_py26
+    def test_short_memoryview(self):
+        """
+        When passed a memoryview onto a small number of bytes,
+        :py:obj:`Connection.send` transmits all of them and returns the number
+        of bytes sent.
+        """
+        server, client = self._loopback()
+        count = server.send(memoryview(b('xy')))
+        self.assertEquals(count, 2)
+        self.assertEquals(client.recv(2), b('xy'))
+
+    @skip_if_py3
+    def test_short_buffer(self):
+        """
+        When passed a buffer containing a small number of bytes,
+        :py:obj:`Connection.send` transmits all of them and returns the number
+        of bytes sent.
+        """
+        server, client = self._loopback()
+        count = server.send(buffer(b('xy')))
+        self.assertEquals(count, 2)
+        self.assertEquals(client.recv(2), b('xy'))
+
+
+def _make_memoryview(size):
+    """
+    Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
+    size.
+    """
+    return memoryview(bytearray(size))
+
+
+class ConnectionRecvIntoTests(TestCase, _LoopbackMixin):
+    """
+    Tests for :py:obj:`Connection.recv_into`
+    """
+    def _no_length_test(self, factory):
+        """
+        Assert that when the given buffer is passed to
+        ``Connection.recv_into``, whatever bytes are available to be received
+        that fit into that buffer are written into that buffer.
+        """
+        output_buffer = factory(5)
+
+        server, client = self._loopback()
+        server.send(b('xy'))
+
+        self.assertEqual(client.recv_into(output_buffer), 2)
+        self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
+
+    def test_bytearray_no_length(self):
+        """
+        :py:obj:`Connection.recv_into` can be passed a ``bytearray`` instance
+        and data in the receive buffer is written to it.
+        """
+        self._no_length_test(bytearray)
+
+    def _respects_length_test(self, factory):
+        """
+        Assert that when the given buffer is passed to ``Connection.recv_into``
+        along with a value for ``nbytes`` that is less than the size of that
+        buffer, only ``nbytes`` bytes are written into the buffer.
+        """
+        output_buffer = factory(10)
+
+        server, client = self._loopback()
+        server.send(b('abcdefghij'))
+
+        self.assertEqual(client.recv_into(output_buffer, 5), 5)
+        self.assertEqual(
+            output_buffer, bytearray(b('abcde\x00\x00\x00\x00\x00'))
+        )
+
+    def test_bytearray_respects_length(self):
+        """
+        When called with a ``bytearray`` instance,
+        :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter and
+        doesn't copy in more than that number of bytes.
+        """
+        self._respects_length_test(bytearray)
+
+    def _doesnt_overfill_test(self, factory):
+        """
+        Assert that if there are more bytes available to be read from the
+        receive buffer than would fit into the buffer passed to
+        :py:obj:`Connection.recv_into`, only as many as fit are written into
+        it.
+        """
+        output_buffer = factory(5)
+
+        server, client = self._loopback()
+        server.send(b('abcdefghij'))
+
+        self.assertEqual(client.recv_into(output_buffer), 5)
+        self.assertEqual(output_buffer, bytearray(b('abcde')))
+        rest = client.recv(5)
+        self.assertEqual(b('fghij'), rest)
+
+    def test_bytearray_doesnt_overfill(self):
+        """
+        When called with a ``bytearray`` instance,
+        :py:obj:`Connection.recv_into` respects the size of the array and
+        doesn't write more bytes into it than will fit.
+        """
+        self._doesnt_overfill_test(bytearray)
+
+    def _really_doesnt_overfill_test(self, factory):
+        """
+        Assert that if the value given by ``nbytes`` is greater than the actual
+        size of the output buffer passed to :py:obj:`Connection.recv_into`, the
+        behavior is as if no value was given for ``nbytes`` at all.
+        """
+        output_buffer = factory(5)
+
+        server, client = self._loopback()
+        server.send(b('abcdefghij'))
+
+        self.assertEqual(client.recv_into(output_buffer, 50), 5)
+        self.assertEqual(output_buffer, bytearray(b('abcde')))
+        rest = client.recv(5)
+        self.assertEqual(b('fghij'), rest)
+
+    def test_bytearray_really_doesnt_overfill(self):
+        """
+        When called with a ``bytearray`` instance and an ``nbytes`` value that
+        is too large, :py:obj:`Connection.recv_into` respects the size of the
+        array and not the ``nbytes`` value and doesn't write more bytes into
+        the buffer than will fit.
+        """
+        self._doesnt_overfill_test(bytearray)
+
+    def test_peek(self):
+
+        server, client = self._loopback()
+        server.send(b('xy'))
+
+        for _ in range(2):
+            output_buffer = bytearray(5)
+            self.assertEqual(
+                client.recv_into(output_buffer, flags=MSG_PEEK), 2)
+            self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
+
+    @skip_if_py26
+    def test_memoryview_no_length(self):
+        """
+        :py:obj:`Connection.recv_into` can be passed a ``memoryview``
+        instance and data in the receive buffer is written to it.
+        """
+        self._no_length_test(_make_memoryview)
+
+    @skip_if_py26
+    def test_memoryview_respects_length(self):
+        """
+        When called with a ``memoryview`` instance,
+        :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter
+        and doesn't copy more than that number of bytes in.
+        """
+        self._respects_length_test(_make_memoryview)
+
+    @skip_if_py26
+    def test_memoryview_doesnt_overfill(self):
+        """
+        When called with a ``memoryview`` instance,
+        :py:obj:`Connection.recv_into` respects the size of the array and
+        doesn't write more bytes into it than will fit.
+        """
+        self._doesnt_overfill_test(_make_memoryview)
+
+    @skip_if_py26
+    def test_memoryview_really_doesnt_overfill(self):
+        """
+        When called with a ``memoryview`` instance and an ``nbytes`` value
+        that is too large, :py:obj:`Connection.recv_into` respects the size
+        of the array and not the ``nbytes`` value and doesn't write more
+        bytes into the buffer than will fit.
+        """
+        self._doesnt_overfill_test(_make_memoryview)
+
+
+class ConnectionSendallTests(TestCase, _LoopbackMixin):
+    """
+    Tests for :py:obj:`Connection.sendall`.
+    """
+    def test_wrong_args(self):
+        """
+        When called with arguments other than a string argument for its first
+        parameter or with more than two arguments, :py:obj:`Connection.sendall`
+        raises :py:obj:`TypeError`.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.sendall)
+        self.assertRaises(TypeError, connection.sendall, object())
+        self.assertRaises(
+            TypeError, connection.sendall, "foo", object(), "bar")
+
+    def test_short(self):
+        """
+        :py:obj:`Connection.sendall` transmits all of the bytes in the string
+        passed to it.
+        """
+        server, client = self._loopback()
+        server.sendall(b('x'))
+        self.assertEquals(client.recv(1), b('x'))
+
+    def test_text(self):
+        """
+        :py:obj:`Connection.sendall` transmits all the content in the string
+        passed to it raising a DeprecationWarning in case of this being a text.
+        """
+        server, client = self._loopback()
+        with catch_warnings(record=True) as w:
+            simplefilter("always")
+            server.sendall(b"x".decode("ascii"))
+            self.assertEqual(
+                "{0} for buf is no longer accepted, use bytes".format(
+                    WARNING_TYPE_EXPECTED
+                ),
+                str(w[-1].message)
+            )
+            self.assertIs(w[-1].category, DeprecationWarning)
+        self.assertEquals(client.recv(1), b"x")
+
+    @skip_if_py26
+    def test_short_memoryview(self):
+        """
+        When passed a memoryview onto a small number of bytes,
+        :py:obj:`Connection.sendall` transmits all of them.
+        """
+        server, client = self._loopback()
+        server.sendall(memoryview(b('x')))
+        self.assertEquals(client.recv(1), b('x'))
+
+    @skip_if_py3
+    def test_short_buffers(self):
+        """
+        When passed a buffer containing a small number of bytes,
+        :py:obj:`Connection.sendall` transmits all of them.
+        """
+        server, client = self._loopback()
+        server.sendall(buffer(b('x')))
+        self.assertEquals(client.recv(1), b('x'))
+
+    def test_long(self):
+        """
+        :py:obj:`Connection.sendall` transmits all of the bytes in the string
+        passed to it even if this requires multiple calls of an underlying
+        write function.
+        """
+        server, client = self._loopback()
+        # Should be enough, underlying SSL_write should only do 16k at a time.
+        # On Windows, after 32k of bytes the write will block (forever
+        # - because no one is yet reading).
+        message = b('x') * (1024 * 32 - 1) + b('y')
+        server.sendall(message)
+        accum = []
+        received = 0
+        while received < len(message):
+            data = client.recv(1024)
+            accum.append(data)
+            received += len(data)
+        self.assertEquals(message, b('').join(accum))
+
+    def test_closed(self):
+        """
+        If the underlying socket is closed, :py:obj:`Connection.sendall`
+        propagates the write error from the low level write call.
+        """
+        server, client = self._loopback()
+        server.sock_shutdown(2)
+        exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
+        if platform == "win32":
+            self.assertEqual(exc.args[0], ESHUTDOWN)
+        else:
+            self.assertEqual(exc.args[0], EPIPE)
+
+
+class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
+    """
+    Tests for SSL renegotiation APIs.
+    """
+    def test_renegotiate_wrong_args(self):
+        """
+        :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called
+        with any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.renegotiate, None)
+
+    def test_total_renegotiations_wrong_args(self):
+        """
+        :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if
+        called with any arguments.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertRaises(TypeError, connection.total_renegotiations, None)
+
+    def test_total_renegotiations(self):
+        """
+        :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before
+        any renegotiations have happened.
+        """
+        connection = Connection(Context(TLSv1_METHOD), None)
+        self.assertEquals(connection.total_renegotiations(), 0)
+
+#     def test_renegotiate(self):
+#         """
+#         """
+#         server, client = self._loopback()
+
+#         server.send("hello world")
+#         self.assertEquals(client.recv(len("hello world")), "hello world")
+
+#         self.assertEquals(server.total_renegotiations(), 0)
+#         self.assertTrue(server.renegotiate())
+
+#         server.setblocking(False)
+#         client.setblocking(False)
+#         while server.renegotiate_pending():
+#             client.do_handshake()
+#             server.do_handshake()
+
+#         self.assertEquals(server.total_renegotiations(), 1)
+
+
+class ErrorTests(TestCase):
+    """
+    Unit tests for :py:obj:`OpenSSL.SSL.Error`.
+    """
+    def test_type(self):
+        """
+        :py:obj:`Error` is an exception type.
+        """
+        self.assertTrue(issubclass(Error, Exception))
+        self.assertEqual(Error.__name__, 'Error')
+
+
+class ConstantsTests(TestCase):
+    """
+    Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
+
+    These are values defined by OpenSSL intended only to be used as flags to
+    OpenSSL APIs.  The only assertions it seems can be made about them is
+    their values.
+    """
+    @pytest.mark.skipif(
+        OP_NO_QUERY_MTU is None,
+        reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
+    )
+    def test_op_no_query_mtu(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
+        of :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
+        """
+        self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
+
+    @pytest.mark.skipif(
+        OP_COOKIE_EXCHANGE is None,
+        reason="OP_COOKIE_EXCHANGE unavailable - "
+        "OpenSSL version may be too old"
+    )
+    def test_op_cookie_exchange(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
+        value of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by
+        :file:`openssl/ssl.h`.
+        """
+        self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
+
+    @pytest.mark.skipif(
+        OP_NO_TICKET is None,
+        reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
+    )
+    def test_op_no_ticket(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
+        :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
+        """
+        self.assertEqual(OP_NO_TICKET, 0x4000)
+
+    @pytest.mark.skipif(
+        OP_NO_COMPRESSION is None,
+        reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
+    )
+    def test_op_no_compression(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
+        value of :py:const:`SSL_OP_NO_COMPRESSION` defined by
+        :file:`openssl/ssl.h`.
+        """
+        self.assertEqual(OP_NO_COMPRESSION, 0x20000)
+
+    def test_sess_cache_off(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
+        :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x0, SESS_CACHE_OFF)
+
+    def test_sess_cache_client(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
+        :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x1, SESS_CACHE_CLIENT)
+
+    def test_sess_cache_server(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
+        :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x2, SESS_CACHE_SERVER)
+
+    def test_sess_cache_both(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
+        :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x3, SESS_CACHE_BOTH)
+
+    def test_sess_cache_no_auto_clear(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
+        value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
+        ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
+
+    def test_sess_cache_no_internal_lookup(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
+        the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
+        ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
+
+    def test_sess_cache_no_internal_store(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
+        the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
+        ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
+
+    def test_sess_cache_no_internal(self):
+        """
+        The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
+        value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
+        ``openssl/ssl.h``.
+        """
+        self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
+
+
+class MemoryBIOTests(TestCase, _LoopbackMixin):
+    """
+    Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
+    """
+    def _server(self, sock):
+        """
+        Create a new server-side SSL :py:obj:`Connection` object wrapped around
+        :py:obj:`sock`.
+        """
+        # Create the server side Connection.  This is mostly setup boilerplate
+        # - use TLSv1, use a particular certificate, etc.
+        server_ctx = Context(TLSv1_METHOD)
+        server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
+        server_ctx.set_verify(
+            VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
+            verify_cb
+        )
+        server_store = server_ctx.get_cert_store()
+        server_ctx.use_privatekey(
+            load_privatekey(FILETYPE_PEM, server_key_pem))
+        server_ctx.use_certificate(
+            load_certificate(FILETYPE_PEM, server_cert_pem))
+        server_ctx.check_privatekey()
+        server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
+        # Here the Connection is actually created.  If None is passed as the
+        # 2nd parameter, it indicates a memory BIO should be created.
+        server_conn = Connection(server_ctx, sock)
+        server_conn.set_accept_state()
+        return server_conn
+
+    def _client(self, sock):
+        """
+        Create a new client-side SSL :py:obj:`Connection` object wrapped around
+        :py:obj:`sock`.
+        """
+        # Now create the client side Connection.  Similar boilerplate to the
+        # above.
+        client_ctx = Context(TLSv1_METHOD)
+        client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
+        client_ctx.set_verify(
+            VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
+            verify_cb
+        )
+        client_store = client_ctx.get_cert_store()
+        client_ctx.use_privatekey(
+            load_privatekey(FILETYPE_PEM, client_key_pem))
+        client_ctx.use_certificate(
+            load_certificate(FILETYPE_PEM, client_cert_pem))
+        client_ctx.check_privatekey()
+        client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
+        client_conn = Connection(client_ctx, sock)
+        client_conn.set_connect_state()
+        return client_conn
+
+    def test_memoryConnect(self):
+        """
+        Two :py:obj:`Connection`s which use memory BIOs can be manually
+        connected by reading from the output of each and writing those bytes to
+        the input of the other and in this way establish a connection and
+        exchange application-level bytes with each other.
+        """
+        server_conn = self._server(None)
+        client_conn = self._client(None)
+
+        # There should be no key or nonces yet.
+        self.assertIdentical(server_conn.master_key(), None)
+        self.assertIdentical(server_conn.client_random(), None)
+        self.assertIdentical(server_conn.server_random(), None)
+
+        # First, the handshake needs to happen.  We'll deliver bytes back and
+        # forth between the client and server until neither of them feels like
+        # speaking any more.
+        self.assertIdentical(
+            self._interactInMemory(client_conn, server_conn), None)
+
+        # Now that the handshake is done, there should be a key and nonces.
+        self.assertNotIdentical(server_conn.master_key(), None)
+        self.assertNotIdentical(server_conn.client_random(), None)
+        self.assertNotIdentical(server_conn.server_random(), None)
+        self.assertEquals(
+            server_conn.client_random(), client_conn.client_random())
+        self.assertEquals(
+            server_conn.server_random(), client_conn.server_random())
+        self.assertNotEquals(
+            server_conn.client_random(), server_conn.server_random())
+        self.assertNotEquals(
+            client_conn.client_random(), client_conn.server_random())
+
+        # Here are the bytes we'll try to send.
+        important_message = b('One if by land, two if by sea.')
+
+        server_conn.write(important_message)
+        self.assertEquals(
+            self._interactInMemory(client_conn, server_conn),
+            (client_conn, important_message))
+
+        client_conn.write(important_message[::-1])
+        self.assertEquals(
+            self._interactInMemory(client_conn, server_conn),
+            (server_conn, important_message[::-1]))
+
+    def test_socketConnect(self):
+        """
+        Just like :py:obj:`test_memoryConnect` but with an actual socket.
+
+        This is primarily to rule out the memory BIO code as the source of any
+        problems encountered while passing data over a :py:obj:`Connection` (if
+        this test fails, there must be a problem outside the memory BIO code,
+        as no memory BIO is involved here).  Even though this isn't a memory
+        BIO test, it's convenient to have it here.
+        """
+        server_conn, client_conn = self._loopback()
+
+        important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
+        client_conn.send(important_message)
+        msg = server_conn.recv(1024)
+        self.assertEqual(msg, important_message)
+
+        # Again in the other direction, just for fun.
+        important_message = important_message[::-1]
+        server_conn.send(important_message)
+        msg = client_conn.recv(1024)
+        self.assertEqual(msg, important_message)
+
+    def test_socketOverridesMemory(self):
+        """
+        Test that :py:obj:`OpenSSL.SSL.bio_read` and
+        :py:obj:`OpenSSL.SSL.bio_write` don't work on
+        :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
+        """
+        context = Context(SSLv3_METHOD)
+        client = socket()
+        clientSSL = Connection(context, client)
+        self.assertRaises(TypeError, clientSSL.bio_read, 100)
+        self.assertRaises(TypeError, clientSSL.bio_write, "foo")
+        self.assertRaises(TypeError, clientSSL.bio_shutdown)
+
+    def test_outgoingOverflow(self):
+        """
+        If more bytes than can be written to the memory BIO are passed to
+        :py:obj:`Connection.send` at once, the number of bytes which were
+        written is returned and that many bytes from the beginning of the input
+        can be read from the other end of the connection.
+        """
+        server = self._server(None)
+        client = self._client(None)
+
+        self._interactInMemory(client, server)
+
+        size = 2 ** 15
+        sent = client.send(b"x" * size)
+        # Sanity check.  We're trying to test what happens when the entire
+        # input can't be sent.  If the entire input was sent, this test is
+        # meaningless.
+        self.assertTrue(sent < size)
+
+        receiver, received = self._interactInMemory(client, server)
+        self.assertIdentical(receiver, server)
+
+        # We can rely on all of these bytes being received at once because
+        # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
+        self.assertEquals(len(received), sent)
+
+    def test_shutdown(self):
+        """
+        :py:obj:`Connection.bio_shutdown` signals the end of the data stream
+        from which the :py:obj:`Connection` reads.
+        """
+        server = self._server(None)
+        server.bio_shutdown()
+        e = self.assertRaises(Error, server.recv, 1024)
+        # We don't want WantReadError or ZeroReturnError or anything - it's a
+        # handshake failure.
+        self.assertEquals(e.__class__, Error)
+
+    def test_unexpectedEndOfFile(self):
+        """
+        If the connection is lost before an orderly SSL shutdown occurs,
+        :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
+        "Unexpected EOF".
+        """
+        server_conn, client_conn = self._loopback()
+        client_conn.sock_shutdown(SHUT_RDWR)
+        exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
+        self.assertEqual(exc.args, (-1, "Unexpected EOF"))
+
+    def _check_client_ca_list(self, func):
+        """
+        Verify the return value of the :py:obj:`get_client_ca_list` method for
+        server and client connections.
+
+        :param func: A function which will be called with the server context
+            before the client and server are connected to each other.  This
+            function should specify a list of CAs for the server to send to the
+            client and return that same list.  The list will be used to verify
+            that :py:obj:`get_client_ca_list` returns the proper value at
+            various times.
+        """
+        server = self._server(None)
+        client = self._client(None)
+        self.assertEqual(client.get_client_ca_list(), [])
+        self.assertEqual(server.get_client_ca_list(), [])
+        ctx = server.get_context()
+        expected = func(ctx)
+        self.assertEqual(client.get_client_ca_list(), [])
+        self.assertEqual(server.get_client_ca_list(), expected)
+        self._interactInMemory(client, server)
+        self.assertEqual(client.get_client_ca_list(), expected)
+        self.assertEqual(server.get_client_ca_list(), expected)
+
+    def test_set_client_ca_list_errors(self):
+        """
+        :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if
+        called with a non-list or a list that contains objects other than
+        X509Names.
+        """
+        ctx = Context(TLSv1_METHOD)
+        self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
+        self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
+        self.assertIdentical(ctx.set_client_ca_list([]), None)
+
+    def test_set_empty_ca_list(self):
+        """
+        If passed an empty list, :py:obj:`Context.set_client_ca_list`
+        configures the context to send no CA names to the client and, on both
+        the server and client sides, :py:obj:`Connection.get_client_ca_list`
+        returns an empty list after the connection is set up.
+        """
+        def no_ca(ctx):
+            ctx.set_client_ca_list([])
+            return []
+        self._check_client_ca_list(no_ca)
+
+    def test_set_one_ca_list(self):
+        """
+        If passed a list containing a single X509Name,
+        :py:obj:`Context.set_client_ca_list` configures the context to send
+        that CA name to the client and, on both the server and client sides,
+        :py:obj:`Connection.get_client_ca_list` returns a list containing that
+        X509Name after the connection is set up.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        cadesc = cacert.get_subject()
+
+        def single_ca(ctx):
+            ctx.set_client_ca_list([cadesc])
+            return [cadesc]
+        self._check_client_ca_list(single_ca)
+
+    def test_set_multiple_ca_list(self):
+        """
+        If passed a list containing multiple X509Name objects,
+        :py:obj:`Context.set_client_ca_list` configures the context to send
+        those CA names to the client and, on both the server and client sides,
+        :py:obj:`Connection.get_client_ca_list` returns a list containing those
+        X509Names after the connection is set up.
+        """
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        sedesc = secert.get_subject()
+        cldesc = clcert.get_subject()
+
+        def multiple_ca(ctx):
+            L = [sedesc, cldesc]
+            ctx.set_client_ca_list(L)
+            return L
+        self._check_client_ca_list(multiple_ca)
+
+    def test_reset_ca_list(self):
+        """
+        If called multiple times, only the X509Names passed to the final call
+        of :py:obj:`Context.set_client_ca_list` are used to configure the CA
+        names sent to the client.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        cadesc = cacert.get_subject()
+        sedesc = secert.get_subject()
+        cldesc = clcert.get_subject()
+
+        def changed_ca(ctx):
+            ctx.set_client_ca_list([sedesc, cldesc])
+            ctx.set_client_ca_list([cadesc])
+            return [cadesc]
+        self._check_client_ca_list(changed_ca)
+
+    def test_mutated_ca_list(self):
+        """
+        If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
+        afterwards, this does not affect the list of CA names sent to the
+        client.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        cadesc = cacert.get_subject()
+        sedesc = secert.get_subject()
+
+        def mutated_ca(ctx):
+            L = [cadesc]
+            ctx.set_client_ca_list([cadesc])
+            L.append(sedesc)
+            return [cadesc]
+        self._check_client_ca_list(mutated_ca)
+
+    def test_add_client_ca_errors(self):
+        """
+        :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called
+        with a non-X509 object or with a number of arguments other than one.
+        """
+        ctx = Context(TLSv1_METHOD)
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        self.assertRaises(TypeError, ctx.add_client_ca)
+        self.assertRaises(TypeError, ctx.add_client_ca, "spam")
+        self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
+
+    def test_one_add_client_ca(self):
+        """
+        A certificate's subject can be added as a CA to be sent to the client
+        with :py:obj:`Context.add_client_ca`.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        cadesc = cacert.get_subject()
+
+        def single_ca(ctx):
+            ctx.add_client_ca(cacert)
+            return [cadesc]
+        self._check_client_ca_list(single_ca)
+
+    def test_multiple_add_client_ca(self):
+        """
+        Multiple CA names can be sent to the client by calling
+        :py:obj:`Context.add_client_ca` with multiple X509 objects.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        cadesc = cacert.get_subject()
+        sedesc = secert.get_subject()
+
+        def multiple_ca(ctx):
+            ctx.add_client_ca(cacert)
+            ctx.add_client_ca(secert)
+            return [cadesc, sedesc]
+        self._check_client_ca_list(multiple_ca)
+
+    def test_set_and_add_client_ca(self):
+        """
+        A call to :py:obj:`Context.set_client_ca_list` followed by a call to
+        :py:obj:`Context.add_client_ca` results in using the CA names from the
+        first call and the CA name from the second call.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        cadesc = cacert.get_subject()
+        sedesc = secert.get_subject()
+        cldesc = clcert.get_subject()
+
+        def mixed_set_add_ca(ctx):
+            ctx.set_client_ca_list([cadesc, sedesc])
+            ctx.add_client_ca(clcert)
+            return [cadesc, sedesc, cldesc]
+        self._check_client_ca_list(mixed_set_add_ca)
+
+    def test_set_after_add_client_ca(self):
+        """
+        A call to :py:obj:`Context.set_client_ca_list` after a call to
+        :py:obj:`Context.add_client_ca` replaces the CA name specified by the
+        former call with the names specified by the latter call.
+        """
+        cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
+        secert = load_certificate(FILETYPE_PEM, server_cert_pem)
+        clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
+
+        cadesc = cacert.get_subject()
+        sedesc = secert.get_subject()
+
+        def set_replaces_add_ca(ctx):
+            ctx.add_client_ca(clcert)
+            ctx.set_client_ca_list([cadesc])
+            ctx.add_client_ca(secert)
+            return [cadesc, sedesc]
+        self._check_client_ca_list(set_replaces_add_ca)
+
+
+class ConnectionBIOTests(TestCase):
+    """
+    Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
+    """
+    def test_wantReadError(self):
+        """
+        :py:obj:`Connection.bio_read` raises
+        :py:obj:`OpenSSL.SSL.WantReadError` if there are no bytes available to
+        be read from the BIO.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        self.assertRaises(WantReadError, conn.bio_read, 1024)
+
+    def test_buffer_size(self):
+        """
+        :py:obj:`Connection.bio_read` accepts an integer giving the maximum
+        number of bytes to read and return.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        conn.set_connect_state()
+        try:
+            conn.do_handshake()
+        except WantReadError:
+            pass
+        data = conn.bio_read(2)
+        self.assertEqual(2, len(data))
+
+    @skip_if_py3
+    def test_buffer_size_long(self):
+        """
+        On Python 2 :py:obj:`Connection.bio_read` accepts values of type
+        :py:obj:`long` as well as :py:obj:`int`.
+        """
+        ctx = Context(TLSv1_METHOD)
+        conn = Connection(ctx, None)
+        conn.set_connect_state()
+        try:
+            conn.do_handshake()
+        except WantReadError:
+            pass
+        data = conn.bio_read(long(2))
+        self.assertEqual(2, len(data))
+
+
+class InfoConstantTests(TestCase):
+    """
+    Tests for assorted constants exposed for use in info callbacks.
+    """
+    def test_integers(self):
+        """
+        All of the info constants are integers.
+
+        This is a very weak test.  It would be nice to have one that actually
+        verifies that as certain info events happen, the value passed to the
+        info callback matches up with the constant exposed by OpenSSL.SSL.
+        """
+        for const in [
+            SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
+            SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
+            SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
+            SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
+            SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
+            SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
+        ]:
+            self.assertTrue(isinstance(const, int))
+
+
+if __name__ == '__main__':
+    main()
diff --git a/tests/test_tsafe.py b/tests/test_tsafe.py
new file mode 100644
index 0000000..97045ce
--- /dev/null
+++ b/tests/test_tsafe.py
@@ -0,0 +1,25 @@
+# Copyright (C) Jean-Paul Calderone
+# See LICENSE for details.
+
+"""
+Unit tests for :py:obj:`OpenSSL.tsafe`.
+"""
+
+from OpenSSL.SSL import TLSv1_METHOD, Context
+from OpenSSL.tsafe import Connection
+
+from .util import TestCase
+
+
+class ConnectionTest(TestCase):
+    """
+    Tests for :py:obj:`OpenSSL.tsafe.Connection`.
+    """
+    def test_instantiation(self):
+        """
+        :py:obj:`OpenSSL.tsafe.Connection` can be instantiated.
+        """
+        # The following line should not throw an error.  This isn't an ideal
+        # test.  It would be great to refactor the other Connection tests so
+        # they could automatically be applied to this class too.
+        Connection(Context(TLSv1_METHOD), None)
diff --git a/tests/test_util.py b/tests/test_util.py
new file mode 100644
index 0000000..2aaded2
--- /dev/null
+++ b/tests/test_util.py
@@ -0,0 +1,19 @@
+from OpenSSL._util import exception_from_error_queue, lib
+
+from .util import TestCase
+
+
+class ErrorTests(TestCase):
+    """
+    Tests for handling of certain OpenSSL error cases.
+    """
+    def test_exception_from_error_queue_nonexistent_reason(self):
+        """
+        :py:func:`exception_from_error_queue` raises ``ValueError`` when it
+        encounters an OpenSSL error code which does not have a reason string.
+        """
+        lib.ERR_put_error(lib.ERR_LIB_EVP, 0, 1112, b"", 10)
+        exc = self.assertRaises(
+            ValueError, exception_from_error_queue, ValueError
+        )
+        self.assertEqual(exc.args[0][0][2], "")
diff --git a/tests/util.py b/tests/util.py
new file mode 100644
index 0000000..5b53dc2
--- /dev/null
+++ b/tests/util.py
@@ -0,0 +1,437 @@
+# Copyright (C) Jean-Paul Calderone
+# Copyright (C) Twisted Matrix Laboratories.
+# See LICENSE for details.
+
+"""
+Helpers for the OpenSSL test suite, largely copied from
+U{Twisted<http://twistedmatrix.com/>}.
+"""
+
+import shutil
+import sys
+import traceback
+
+from tempfile import mktemp, mkdtemp
+from unittest import TestCase
+
+import pytest
+
+from six import PY3
+
+from OpenSSL._util import exception_from_error_queue
+from OpenSSL.crypto import Error
+
+
+from . import memdbg
+
+from OpenSSL._util import ffi, lib, byte_string as b
+
+
+# This is the UTF-8 encoding of the SNOWMAN unicode code point.
+NON_ASCII = b("\xe2\x98\x83").decode("utf-8")
+
+
+class TestCase(TestCase):
+    """
+    :py:class:`TestCase` adds useful testing functionality beyond what is
+    available from the standard library :py:class:`unittest.TestCase`.
+    """
+
+    def run(self, result):
+        run = super(TestCase, self).run
+        if memdbg.heap is None:
+            return run(result)
+
+        # Run the test as usual
+        before = set(memdbg.heap)
+        run(result)
+
+        # Clean up some long-lived allocations so they won't be reported as
+        # memory leaks.
+        lib.CRYPTO_cleanup_all_ex_data()
+        lib.ERR_remove_thread_state(ffi.NULL)
+        after = set(memdbg.heap)
+
+        if not after - before:
+            # No leaks, fast succeed
+            return
+
+        if result.wasSuccessful():
+            # If it passed, run it again with memory debugging
+            before = set(memdbg.heap)
+            run(result)
+
+            # Clean up some long-lived allocations so they won't be reported as
+            # memory leaks.
+            lib.CRYPTO_cleanup_all_ex_data()
+            lib.ERR_remove_thread_state(ffi.NULL)
+
+            after = set(memdbg.heap)
+
+            self._reportLeaks(after - before, result)
+
+    def _reportLeaks(self, leaks, result):
+        def format_leak(p):
+            """
+            c_stack looks something like this (interesting parts indicated
+            with inserted arrows not part of the data):
+
+            cpython/2.7/python(PyCFunction_Call+0x8b) [0x56265a]
+            cpython/2.7/python() [0x4d5f52]
+            cpython/2.7/python(PyEval_EvalFrameEx+0x753b) [0x4d0e1e]
+            cpython/2.7/python() [0x4d6419]
+            cpython/2.7/python() [0x4d6129]
+            cpython/2.7/python(PyEval_EvalFrameEx+0x753b) [0x4d0e1e]
+            cpython/2.7/python(PyEval_EvalCodeEx+0x1043) [0x4d3726]
+            cpython/2.7/python() [0x55fd51]
+            cpython/2.7/python(PyObject_Call+0x7e) [0x420ee6]
+            cpython/2.7/python(PyEval_CallObjectWithKeywords+0x158) [0x4d56ec]
+            _cffi_backend.so(+0xe96e) [0x7fe2e38be96e]
+            libffi.so.6(ffi_closure_unix64_inner+0x1b9) [0x7fe2e36ad819]
+            libffi.so.6(ffi_closure_unix64+0x46) [0x7fe2e36adb7c]
+
+            |----- end interesting
+            v
+            libcrypto.so.1.0.0(CRYPTO_malloc+0x64) [0x7fe2e1cef784]
+            libcrypto.so.1.0.0(lh_insert+0x16b) [0x7fe2e1d6a24b]
+            libcrypto.so.1.0.0(+0x61c18) [0x7fe2e1cf0c18]
+            libcrypto.so.1.0.0(+0x625ec) [0x7fe2e1cf15ec]
+            libcrypto.so.1.0.0(DSA_new_method+0xe6) [0x7fe2e1d524d6]
+            libcrypto.so.1.0.0(DSA_generate_parameters+0x3a) [0x7fe2e1d5364a]
+            ^
+            |----- begin interesting
+
+            _cffi__x305d4698xb539baaa.so(+0x1f397) [0x7fe2df84d397]
+            cpython/2.7/python(PyCFunction_Call+0x8b) [0x56265a]
+            cpython/2.7/python() [0x4d5f52]
+            cpython/2.7/python(PyEval_EvalFrameEx+0x753b) [0x4d0e1e]
+            cpython/2.7/python() [0x4d6419]
+            ...
+
+            Notice the stack is upside down compared to a Python traceback.
+            Identify the start and end of interesting bits and stuff it into
+            the stack we report.
+            """
+            stacks = memdbg.heap[p]
+            # Eventually look at multiple stacks for the realloc() case.  For
+            # now just look at the original allocation location.
+            (size, python_stack, c_stack) = stacks[0]
+
+            stack = traceback.format_list(python_stack)[:-1]
+            saved = list(c_stack)
+
+            # Figure the first interesting frame will be after a the
+            # cffi-compiled module
+            while c_stack and '/__pycache__/_cffi__' not in c_stack[-1]:
+                c_stack.pop()
+
+            # Figure the last interesting frame will always be CRYPTO_malloc,
+            # since that's where we hooked in to things.
+            while (
+                c_stack and 'CRYPTO_malloc' not in c_stack[0] and
+                'CRYPTO_realloc' not in c_stack[0]
+            ):
+                c_stack.pop(0)
+
+            if c_stack:
+                c_stack.reverse()
+            else:
+                c_stack = saved[::-1]
+            stack.extend([frame + "\n" for frame in c_stack])
+
+            stack.insert(0, "Leaked (%s) at:\n")
+            return "".join(stack)
+
+        if leaks:
+            unique_leaks = {}
+            for p in leaks:
+                size = memdbg.heap[p][-1][0]
+                new_leak = format_leak(p)
+                if new_leak not in unique_leaks:
+                    unique_leaks[new_leak] = [(size, p)]
+                else:
+                    unique_leaks[new_leak].append((size, p))
+                memdbg.free(p)
+
+            for (stack, allocs) in unique_leaks.iteritems():
+                allocs_accum = []
+                for (size, pointer) in allocs:
+
+                    addr = int(ffi.cast('uintptr_t', pointer))
+                    allocs_accum.append("%d@0x%x" % (size, addr))
+                allocs_report = ", ".join(sorted(allocs_accum))
+
+                result.addError(
+                    self,
+                    (None, Exception(stack % (allocs_report,)), None))
+
+    _tmpdir = None
+
+    @property
+    def tmpdir(self):
+        """
+        On demand create a temporary directory.
+        """
+        if self._tmpdir is not None:
+            return self._tmpdir
+
+        self._tmpdir = mkdtemp(dir=".")
+        return self._tmpdir
+
+    def tearDown(self):
+        """
+        Clean up any files or directories created using
+        :py:meth:`TestCase.mktemp`.  Subclasses must invoke this method if they
+        override it or the cleanup will not occur.
+        """
+        if self._tmpdir is not None:
+            shutil.rmtree(self._tmpdir)
+
+        try:
+            exception_from_error_queue(Error)
+        except Error:
+            e = sys.exc_info()[1]
+            if e.args != ([],):
+                self.fail(
+                    "Left over errors in OpenSSL error queue: " + repr(e)
+                )
+
+    def assertIsInstance(self, instance, classOrTuple, message=None):
+        """
+        Fail if C{instance} is not an instance of the given class or of
+        one of the given classes.
+
+        @param instance: the object to test the type (first argument of the
+            C{isinstance} call).
+        @type instance: any.
+        @param classOrTuple: the class or classes to test against (second
+            argument of the C{isinstance} call).
+        @type classOrTuple: class, type, or tuple.
+
+        @param message: Custom text to include in the exception text if the
+            assertion fails.
+        """
+        assert isinstance(instance, classOrTuple)
+
+    def failUnlessIn(self, containee, container, msg=None):
+        """
+        Fail the test if :py:data:`containee` is not found in
+        :py:data:`container`.
+
+        :param containee: the value that should be in :py:class:`container`
+        :param container: a sequence type, or in the case of a mapping type,
+                          will follow semantics of 'if key in dict.keys()'
+        :param msg: if msg is None, then the failure message will be
+                    '%r not in %r' % (first, second)
+        """
+        assert containee in container
+    assertIn = failUnlessIn
+
+    def assertNotIn(self, containee, container, msg=None):
+        """
+        Fail the test if C{containee} is found in C{container}.
+
+        @param containee: the value that should not be in C{container}
+        @param container: a sequence type, or in the case of a mapping type,
+                          will follow semantics of 'if key in dict.keys()'
+        @param msg: if msg is None, then the failure message will be
+                    '%r in %r' % (first, second)
+        """
+        assert containee not in container
+    failIfIn = assertNotIn
+
+    def assertIs(self, first, second, msg=None):
+        """
+        Fail the test if :py:data:`first` is not :py:data:`second`.  This is an
+        obect-identity-equality test, not an object equality
+        (i.e. :py:func:`__eq__`) test.
+
+        :param msg: if msg is None, then the failure message will be
+        '%r is not %r' % (first, second)
+        """
+        assert first is second
+    assertIdentical = failUnlessIdentical = assertIs
+
+    def assertIsNot(self, first, second, msg=None):
+        """
+        Fail the test if :py:data:`first` is :py:data:`second`.  This is an
+        obect-identity-equality test, not an object equality
+        (i.e. :py:func:`__eq__`) test.
+
+        :param msg: if msg is None, then the failure message will be
+        '%r is %r' % (first, second)
+        """
+        assert first is not second
+    assertNotIdentical = failIfIdentical = assertIsNot
+
+    def failUnlessRaises(self, exception, f, *args, **kwargs):
+        """
+        Fail the test unless calling the function :py:data:`f` with the given
+        :py:data:`args` and :py:data:`kwargs` raises :py:data:`exception`. The
+        failure will report the traceback and call stack of the unexpected
+        exception.
+
+        :param exception: exception type that is to be expected
+        :param f: the function to call
+
+        :return: The raised exception instance, if it is of the given type.
+        :raise self.failureException: Raised if the function call does
+            not raise an exception or if it raises an exception of a
+            different type.
+        """
+        with pytest.raises(exception) as cm:
+            f(*args, **kwargs)
+        return cm.value
+    assertRaises = failUnlessRaises
+
+    def mktemp(self):
+        """
+        Return UTF-8-encoded bytes of a path to a tmp file.
+
+        The file will be cleaned up after the test run.
+        """
+        return mktemp(dir=self.tmpdir).encode("utf-8")
+
+    # Other stuff
+    def assertConsistentType(self, theType, name, *constructionArgs):
+        """
+        Perform various assertions about :py:data:`theType` to ensure that it
+        is a well-defined type.  This is useful for extension types, where it's
+        pretty easy to do something wacky.  If something about the type is
+        unusual, an exception will be raised.
+
+        :param theType: The type object about which to make assertions.
+        :param name: A string giving the name of the type.
+        :param constructionArgs: Positional arguments to use with
+            :py:data:`theType` to create an instance of it.
+        """
+        self.assertEqual(theType.__name__, name)
+        self.assertTrue(isinstance(theType, type))
+        instance = theType(*constructionArgs)
+        self.assertIdentical(type(instance), theType)
+
+
+class EqualityTestsMixin(object):
+    """
+    A mixin defining tests for the standard implementation of C{==} and C{!=}.
+    """
+
+    def anInstance(self):
+        """
+        Return an instance of the class under test.  Each call to this method
+        must return a different object.  All objects returned must be equal to
+        each other.
+        """
+        raise NotImplementedError()
+
+    def anotherInstance(self):
+        """
+        Return an instance of the class under test.  Each call to this method
+        must return a different object.  The objects must not be equal to the
+        objects returned by C{anInstance}.  They may or may not be equal to
+        each other (they will not be compared against each other).
+        """
+        raise NotImplementedError()
+
+    def test_identicalEq(self):
+        """
+        An object compares equal to itself using the C{==} operator.
+        """
+        o = self.anInstance()
+        self.assertTrue(o == o)
+
+    def test_identicalNe(self):
+        """
+        An object doesn't compare not equal to itself using the C{!=} operator.
+        """
+        o = self.anInstance()
+        self.assertFalse(o != o)
+
+    def test_sameEq(self):
+        """
+        Two objects that are equal to each other compare equal to each other
+        using the C{==} operator.
+        """
+        a = self.anInstance()
+        b = self.anInstance()
+        self.assertTrue(a == b)
+
+    def test_sameNe(self):
+        """
+        Two objects that are equal to each other do not compare not equal to
+        each other using the C{!=} operator.
+        """
+        a = self.anInstance()
+        b = self.anInstance()
+        self.assertFalse(a != b)
+
+    def test_differentEq(self):
+        """
+        Two objects that are not equal to each other do not compare equal to
+        each other using the C{==} operator.
+        """
+        a = self.anInstance()
+        b = self.anotherInstance()
+        self.assertFalse(a == b)
+
+    def test_differentNe(self):
+        """
+        Two objects that are not equal to each other compare not equal to each
+        other using the C{!=} operator.
+        """
+        a = self.anInstance()
+        b = self.anotherInstance()
+        self.assertTrue(a != b)
+
+    def test_anotherTypeEq(self):
+        """
+        The object does not compare equal to an object of an unrelated type
+        (which does not implement the comparison) using the C{==} operator.
+        """
+        a = self.anInstance()
+        b = object()
+        self.assertFalse(a == b)
+
+    def test_anotherTypeNe(self):
+        """
+        The object compares not equal to an object of an unrelated type (which
+        does not implement the comparison) using the C{!=} operator.
+        """
+        a = self.anInstance()
+        b = object()
+        self.assertTrue(a != b)
+
+    def test_delegatedEq(self):
+        """
+        The result of comparison using C{==} is delegated to the right-hand
+        operand if it is of an unrelated type.
+        """
+        class Delegate(object):
+            def __eq__(self, other):
+                # Do something crazy and obvious.
+                return [self]
+
+        a = self.anInstance()
+        b = Delegate()
+        self.assertEqual(a == b, [b])
+
+    def test_delegateNe(self):
+        """
+        The result of comparison using C{!=} is delegated to the right-hand
+        operand if it is of an unrelated type.
+        """
+        class Delegate(object):
+            def __ne__(self, other):
+                # Do something crazy and obvious.
+                return [self]
+
+        a = self.anInstance()
+        b = Delegate()
+        self.assertEqual(a != b, [b])
+
+
+# The type name expected in warnings about using the wrong string type.
+if PY3:
+    WARNING_TYPE_EXPECTED = "str"
+else:
+    WARNING_TYPE_EXPECTED = "unicode"