Python test.support.verbose() Examples

The following are 30 code examples of test.support.verbose(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module test.support , or try the search function .
Example #1
Source File: test_socketserver.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def make_server(self, addr, svrcls, hdlrbase):
        class MyServer(svrcls):
            def handle_error(self, request, client_address):
                self.close_request(request)
                self.server_close()
                raise

        class MyHandler(hdlrbase):
            def handle(self):
                line = self.rfile.readline()
                self.wfile.write(line)

        if verbose: print("creating server")
        server = MyServer(addr, MyHandler)
        self.assertEqual(server.server_address, server.socket.getsockname())
        return server 
Example #2
Source File: test_capi.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def pendingcalls_wait(self, l, n, context = None):
        #now, stick around until l[0] has grown to 10
        count = 0;
        while len(l) != n:
            #this busy loop is where we expect to be interrupted to
            #run our callbacks.  Note that callbacks are only run on the
            #main thread
            if False and support.verbose:
                print("(%i)"%(len(l),),)
            for i in range(1000):
                a = i*i
            if context and not context.event.is_set():
                continue
            count += 1
            self.assertTrue(count < 10000,
                "timeout waiting for %i callbacks, got %i"%(n, len(l)))
        if False and support.verbose:
            print("(%i)"%(len(l),)) 
Example #3
Source File: test_dummy_thread.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_uncond_acquire_blocking(self):
        #Make sure that unconditional acquiring of a locked lock blocks.
        def delay_unlock(to_unlock, delay):
            """Hold on to lock for a set amount of time before unlocking."""
            time.sleep(delay)
            to_unlock.release()

        self.lock.acquire()
        start_time = int(time.time())
        _thread.start_new_thread(delay_unlock,(self.lock, DELAY))
        if support.verbose:
            print()
            print("*** Waiting for thread to release the lock "\
            "(approx. %s sec.) ***" % DELAY)
        self.lock.acquire()
        end_time = int(time.time())
        if support.verbose:
            print("done")
        self.assertTrue((end_time - start_time) >= DELAY,
                        "Blocking by unconditional acquiring failed.") 
Example #4
Source File: test_pickle.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_reverse_import_mapping(self):
        for module2, module3 in IMPORT_MAPPING.items():
            with self.subTest((module2, module3)):
                try:
                    getmodule(module3)
                except ImportError as exc:
                    if support.verbose:
                        print(exc)
                if ((module2, module3) not in ALT_IMPORT_MAPPING and
                    REVERSE_IMPORT_MAPPING.get(module3, None) != module2):
                    for (m3, n3), (m2, n2) in REVERSE_NAME_MAPPING.items():
                        if (module3, module2) == (m3, m2):
                            break
                    else:
                        self.fail('No reverse mapping from %r to %r' %
                                  (module3, module2))
                module = REVERSE_IMPORT_MAPPING.get(module3, module3)
                module = IMPORT_MAPPING.get(module, module)
                self.assertEqual(module, module3) 
Example #5
Source File: test_parser.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_all_project_files(self):
        for filepath in support.all_project_files():
            with open(filepath, "rb") as fp:
                encoding = tokenize.detect_encoding(fp.readline)[0]
            self.assertIsNotNone(encoding,
                                 "can't detect encoding for %s" % filepath)
            with open(filepath, "r", encoding=encoding) as fp:
                source = fp.read()
            try:
                tree = driver.parse_string(source)
            except ParseError as err:
                if verbose > 0:
                    warnings.warn('ParseError on file %s (%s)' % (filepath, err))
                continue
            new = str(tree)
            x = diff(filepath, new)
            if x:
                self.fail("Idempotency failed: %s" % filepath) 
Example #6
Source File: test_cmd_line_script.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_issue8202(self):
        # Make sure package __init__ modules see "-m" in sys.argv0 while
        # searching for the module to execute
        with support.temp_dir() as script_dir:
            with support.change_cwd(path=script_dir):
                pkg_dir = os.path.join(script_dir, 'test_pkg')
                make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
                script_name = _make_test_script(pkg_dir, 'script')
                rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
                if verbose > 1:
                    print(repr(out))
                expected = "init_argv0==%r" % '-m'
                self.assertIn(expected.encode('utf-8'), out)
                self._check_output(script_name, rc, out,
                                   script_name, script_name, '', 'test_pkg',
                                   importlib.machinery.SourceFileLoader) 
Example #7
Source File: test_reprlib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _check_path_limitations(self, module_name):
        # base directory
        source_path_len = len(self.here)
        # a path separator + `longname` (twice)
        source_path_len += 2 * (len(self.longname) + 1)
        # a path separator + `module_name` + ".py"
        source_path_len += len(module_name) + 1 + len(".py")
        cached_path_len = (source_path_len +
            len(importlib.util.cache_from_source("x.py")) - len("x.py"))
        if os.name == 'nt' and cached_path_len >= 258:
            # Under Windows, the max path len is 260 including C's terminating
            # NUL character.
            # (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath)
            self.skipTest("test paths too long (%d characters) for Windows' 260 character limit"
                          % cached_path_len)
        elif os.name == 'nt' and verbose:
            print("cached_path_len =", cached_path_len) 
Example #8
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_socketserver(self):
            """Using a SocketServer to create and manage SSL connections."""
            server = make_https_server(self, certfile=CERTFILE)
            # try to connect
            if support.verbose:
                sys.stdout.write('\n')
            with open(CERTFILE, 'rb') as f:
                d1 = f.read()
            d2 = ''
            # now fetch the same data from the HTTPS server
            url = 'https://localhost:%d/%s' % (
                server.port, os.path.split(CERTFILE)[1])
            context = ssl.create_default_context(cafile=CERTFILE)
            f = urllib.request.urlopen(url, context=context)
            try:
                dlen = f.info().get("content-length")
                if dlen and (int(dlen) > 0):
                    d2 = f.read(int(dlen))
                    if support.verbose:
                        sys.stdout.write(
                            " client: read %d bytes from remote server '%s'\n"
                            % (len(d2), server))
            finally:
                f.close()
            self.assertEqual(d1, d2) 
Example #9
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_protocol_tlsv1_2(self):
            """Connecting to a TLSv1.2 server with various client options.
               Testing against older TLS versions."""
            if support.verbose:
                sys.stdout.write("\n")
            try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2',
                               server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,
                               client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,)
            if hasattr(ssl, 'PROTOCOL_SSLv2'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, False)
            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv23, False,
                               client_options=ssl.OP_NO_TLSv1_2)

            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2')
            try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) 
Example #10
Source File: test_strftime.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_strftime(self):
        now = time.time()
        self._update_variables(now)
        self.strftest1(now)
        self.strftest2(now)

        if support.verbose:
            print("Strftime test, platform: %s, Python version: %s" % \
                  (sys.platform, sys.version.split()[0]))

        for j in range(-5, 5):
            for i in range(25):
                arg = now + (i+j*100)*23*3603
                self._update_variables(arg)
                self.strftest1(arg)
                self.strftest2(arg) 
Example #11
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        delay = random.random() / 10000.0
        if verbose:
            print('task %s will run for %.1f usec' %
                  (self.name, delay * 1e6))

        with self.sema:
            with self.mutex:
                self.nrunning.inc()
                if verbose:
                    print(self.nrunning.get(), 'tasks are running')
                self.testcase.assertTrue(self.nrunning.get() <= 3)

            time.sleep(delay)
            if verbose:
                print('task', self.name, 'done')

            with self.mutex:
                self.nrunning.dec()
                self.testcase.assertTrue(self.nrunning.get() >= 0)
                if verbose:
                    print('%s is finished. %d tasks are running' %
                          (self.name, self.nrunning.get())) 
Example #12
Source File: regrtest.py    From jawfish with MIT License 6 votes vote down vote up
def __exit__(self, exc_type, exc_val, exc_tb):
        saved_values = self.saved_values
        del self.saved_values
        for name, get, restore in self.resource_info():
            current = get()
            original = saved_values.pop(name)
            # Check for changes to the resource's value
            if current != original:
                self.changed = True
                restore(original)
                if not self.quiet:
                    print("Warning -- {} was modified by {}".format(
                                                 name, self.testname),
                                                 file=sys.stderr)
                    if self.verbose > 1:
                        print("  Before: {}\n  After:  {} ".format(
                                                  original, current),
                                                  file=sys.stderr)
        return False 
Example #13
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_protocol_tlsv1_1(self):
            """Connecting to a TLSv1.1 server with various client options.
               Testing against older TLS versions."""
            if support.verbose:
                sys.stdout.write("\n")
            try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1')
            if hasattr(ssl, 'PROTOCOL_SSLv2'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, False)
            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv23, False,
                               client_options=ssl.OP_NO_TLSv1_1)

            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1')
            try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False) 
Example #14
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_protocol_sslv3(self):
            """Connecting to an SSLv3 server with various client options"""
            if support.verbose:
                sys.stdout.write("\n")
            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3')
            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL)
            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED)
            if hasattr(ssl, 'PROTOCOL_SSLv2'):
                try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False,
                               client_options=ssl.OP_NO_SSLv3)
            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
            if no_sslv2_implies_sslv3_hello():
                # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs
                try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23,
                                   False, client_options=ssl.OP_NO_SSLv2) 
Example #15
Source File: test_cmd_line_script.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _check_output(self, script_name, exit_code, data,
                             expected_file, expected_argv0,
                             expected_path0, expected_package,
                             expected_loader):
        if verbose > 1:
            print("Output from test script %r:" % script_name)
            print(repr(data))
        self.assertEqual(exit_code, 0)
        printed_loader = '__loader__==%a' % expected_loader
        printed_file = '__file__==%a' % expected_file
        printed_package = '__package__==%r' % expected_package
        printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
        printed_path0 = 'sys.path[0]==%a' % expected_path0
        printed_cwd = 'cwd==%a' % os.getcwd()
        if verbose > 1:
            print('Expected output:')
            print(printed_file)
            print(printed_package)
            print(printed_argv0)
            print(printed_cwd)
        self.assertIn(printed_loader.encode('utf-8'), data)
        self.assertIn(printed_file.encode('utf-8'), data)
        self.assertIn(printed_package.encode('utf-8'), data)
        self.assertIn(printed_argv0.encode('utf-8'), data)
        self.assertIn(printed_path0.encode('utf-8'), data)
        self.assertIn(printed_cwd.encode('utf-8'), data) 
Example #16
Source File: test_crypt.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_crypt(self):
        c = crypt.crypt('mypassword', 'ab')
        if support.verbose:
            print('Test encryption: ', c) 
Example #17
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_protocol_tlsv1(self):
            """Connecting to a TLSv1 server with various client options"""
            if support.verbose:
                sys.stdout.write("\n")
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1')
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)
            if hasattr(ssl, 'PROTOCOL_SSLv2'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False)
            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False,
                               client_options=ssl.OP_NO_TLSv1) 
Example #18
Source File: regrtest.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, testname, verbose=0, quiet=False):
        self.testname = testname
        self.verbose = verbose
        self.quiet = quiet

    # To add things to save and restore, add a name XXX to the resources list
    # and add corresponding get_XXX/restore_XXX functions.  get_XXX should
    # return the value to be saved and compared against a second call to the
    # get function when test execution completes.  restore_XXX should accept
    # the saved value and restore the resource using it.  It will be called if
    # and only if a change in the value is detected.
    #
    # Note: XXX will have any '.' replaced with '_' characters when determining
    # the corresponding method names. 
Example #19
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_protocol_sslv23(self):
            """Connecting to an SSLv23 server with various client options"""
            if support.verbose:
                sys.stdout.write("\n")
            if hasattr(ssl, 'PROTOCOL_SSLv2'):
                try:
                    try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True)
                except OSError as x:
                    # this fails on some older versions of OpenSSL (0.9.7l, for instance)
                    if support.verbose:
                        sys.stdout.write(
                            " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n"
                            % str(x))
            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1')

            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)

            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)

            # Server with specific SSL options
            if hasattr(ssl, 'PROTOCOL_SSLv3'):
                try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False,
                               server_options=ssl.OP_NO_SSLv3)
            # Will choose TLSv1
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True,
                               server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
            try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False,
                               server_options=ssl.OP_NO_TLSv1) 
Example #20
Source File: test_capi.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_subinterps(self):
        # This is just a "don't crash" test
        out, err = self.run_embedded_interpreter()
        if support.verbose:
            print()
            print(out)
            print(err) 
Example #21
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_check_hostname(self):
            if support.verbose:
                sys.stdout.write("\n")

            server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            server_context.load_cert_chain(SIGNED_CERTFILE)

            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            context.verify_mode = ssl.CERT_REQUIRED
            context.check_hostname = True
            context.load_verify_locations(SIGNING_CA)

            # correct hostname should verify
            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with context.wrap_socket(socket.socket(),
                                         server_hostname="localhost") as s:
                    s.connect((HOST, server.port))
                    cert = s.getpeercert()
                    self.assertTrue(cert, "Can't get peer certificate.")

            # incorrect hostname should raise an exception
            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with context.wrap_socket(socket.socket(),
                                         server_hostname="invalid") as s:
                    with self.assertRaisesRegex(ssl.CertificateError,
                                                "hostname 'invalid' doesn't match 'localhost'"):
                        s.connect((HOST, server.port))

            # missing server_hostname arg should cause an exception, too
            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with socket.socket() as s:
                    with self.assertRaisesRegex(ValueError,
                                                "check_hostname requires server_hostname"):
                        context.wrap_socket(s) 
Example #22
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_crl_check(self):
            if support.verbose:
                sys.stdout.write("\n")

            server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            server_context.load_cert_chain(SIGNED_CERTFILE)

            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            context.verify_mode = ssl.CERT_REQUIRED
            context.load_verify_locations(SIGNING_CA)
            tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
            self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf)

            # VERIFY_DEFAULT should pass
            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with context.wrap_socket(socket.socket()) as s:
                    s.connect((HOST, server.port))
                    cert = s.getpeercert()
                    self.assertTrue(cert, "Can't get peer certificate.")

            # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails
            context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF

            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with context.wrap_socket(socket.socket()) as s:
                    with self.assertRaisesRegex(ssl.SSLError,
                                                "certificate verify failed"):
                        s.connect((HOST, server.port))

            # now load a CRL file. The CRL file is signed by the CA.
            context.load_verify_locations(CRLFILE)

            server = ThreadedEchoServer(context=server_context, chatty=True)
            with server:
                with context.wrap_socket(socket.socket()) as s:
                    s.connect((HOST, server.port))
                    cert = s.getpeercert()
                    self.assertTrue(cert, "Can't get peer certificate.") 
Example #23
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_getpeercert(self):
            if support.verbose:
                sys.stdout.write("\n")
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_REQUIRED
            context.load_verify_locations(CERTFILE)
            context.load_cert_chain(CERTFILE)
            server = ThreadedEchoServer(context=context, chatty=False)
            with server:
                s = context.wrap_socket(socket.socket(),
                                        do_handshake_on_connect=False)
                s.connect((HOST, server.port))
                # getpeercert() raise ValueError while the handshake isn't
                # done.
                with self.assertRaises(ValueError):
                    s.getpeercert()
                s.do_handshake()
                cert = s.getpeercert()
                self.assertTrue(cert, "Can't get peer certificate.")
                cipher = s.cipher()
                if support.verbose:
                    sys.stdout.write(pprint.pformat(cert) + '\n')
                    sys.stdout.write("Connection cipher is " + str(cipher) + '.\n')
                if 'subject' not in cert:
                    self.fail("No subject field in certificate: %s." %
                              pprint.pformat(cert))
                if ((('organizationName', 'Python Software Foundation'),)
                    not in cert['subject']):
                    self.fail(
                        "Missing or invalid 'organizationName' field in certificate subject; "
                        "should be 'Python Software Foundation'.")
                self.assertIn('notBefore', cert)
                self.assertIn('notAfter', cert)
                before = ssl.cert_time_to_seconds(cert['notBefore'])
                after = ssl.cert_time_to_seconds(cert['notAfter'])
                self.assertLess(before, after)
                s.close() 
Example #24
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_echo(self):
            """Basic test of an SSL client connecting to a server"""
            if support.verbose:
                sys.stdout.write("\n")
            for protocol in PROTOCOLS:
                with self.subTest(protocol=ssl._PROTOCOL_NAMES[protocol]):
                    context = ssl.SSLContext(protocol)
                    context.load_cert_chain(CERTFILE)
                    server_params_test(context, context,
                                       chatty=True, connectionchatty=True) 
Example #25
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def bad_cert_test(certfile):
        """
        Launch a server with CERT_REQUIRED, and check that trying to
        connect to it with the given client certificate fails.
        """
        server = ThreadedEchoServer(CERTFILE,
                                    certreqs=ssl.CERT_REQUIRED,
                                    cacerts=CERTFILE, chatty=False,
                                    connectionchatty=False)
        with server:
            try:
                with socket.socket() as sock:
                    s = ssl.wrap_socket(sock,
                                        certfile=certfile,
                                        ssl_version=ssl.PROTOCOL_TLSv1)
                    s.connect((HOST, server.port))
            except ssl.SSLError as x:
                if support.verbose:
                    sys.stdout.write("\nSSLError is %s\n" % x.args[1])
            except OSError as x:
                if support.verbose:
                    sys.stdout.write("\nOSError is %s\n" % x.args[1])
            except OSError as x:
                if x.errno != errno.ENOENT:
                    raise
                if support.verbose:
                    sys.stdout.write("\OSError is %s\n" % str(x))
            else:
                raise AssertionError("Use of invalid cert should have failed!") 
Example #26
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(self, *args):
            if support.verbose:
                sys.stdout.write(" cleanup: stopping server.\n")
            self.stop()
            if support.verbose:
                sys.stdout.write(" cleanup: joining server thread.\n")
            self.join()
            if support.verbose:
                sys.stdout.write(" cleanup: successfully joined.\n") 
Example #27
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def handle_accepted(self, sock_obj, addr):
                if support.verbose:
                    sys.stdout.write(" server:  new connection from %s:%s\n" %addr)
                self.ConnectionHandler(sock_obj, self.certfile) 
Example #28
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def handle_close(self):
                    self.close()
                    if support.verbose:
                        sys.stdout.write(" server:  closed connection %s\n" % self.socket) 
Example #29
Source File: test_locale.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        oldlocale = locale.setlocale(self.locale_type)
        self.addCleanup(locale.setlocale, self.locale_type, oldlocale)
        locale.setlocale(self.locale_type, self.enUS_locale)
        if verbose:
            print("testing with %r..." % self.enUS_locale, end=' ', flush=True) 
Example #30
Source File: test_ssl.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def handle_read(self):
                    if self._ssl_accepting:
                        self._do_ssl_handshake()
                    else:
                        data = self.recv(1024)
                        if support.verbose:
                            sys.stdout.write(" server:  read %s from client\n" % repr(data))
                        if not data:
                            self.close()
                        else:
                            self.send(data.lower())