qpid-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From acon...@apache.org
Subject [2/2] qpid-proton git commit: PROTON-1476: c and c++ example tests running on python 2.6
Date Thu, 11 May 2017 16:54:16 GMT
PROTON-1476: c and c++ example tests running on python 2.6

Using common exampletest.py library


Project: http://git-wip-us.apache.org/repos/asf/qpid-proton/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-proton/commit/81ba5a3b
Tree: http://git-wip-us.apache.org/repos/asf/qpid-proton/tree/81ba5a3b
Diff: http://git-wip-us.apache.org/repos/asf/qpid-proton/diff/81ba5a3b

Branch: refs/heads/master
Commit: 81ba5a3b38e450c7159caed1ffa82313d0df8409
Parents: beb38d2
Author: Alan Conway <aconway@redhat.com>
Authored: Thu May 11 10:50:09 2017 -0400
Committer: Alan Conway <aconway@redhat.com>
Committed: Thu May 11 12:50:39 2017 -0400

----------------------------------------------------------------------
 examples/c/proactor/CMakeLists.txt  |   3 +-
 examples/c/proactor/example_test.py |  88 ++++++++++
 examples/c/proactor/test.py         |  87 ----------
 examples/cpp/CMakeLists.txt         |  13 +-
 examples/cpp/example_test.py        | 284 +++++++++----------------------
 examples/exampletest.py             |  78 ++++++---
 6 files changed, 226 insertions(+), 327 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/c/proactor/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/examples/c/proactor/CMakeLists.txt b/examples/c/proactor/CMakeLists.txt
index 11fb073..6ea8aaf 100644
--- a/examples/c/proactor/CMakeLists.txt
+++ b/examples/c/proactor/CMakeLists.txt
@@ -40,4 +40,5 @@ foreach(name broker send receive direct)
 endforeach()
 
 set(run_env ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/proton-c/env.py ${EXAMPLE_ENV} "PATH=${test_path}"
${VALGRIND_ENV})
-add_test(c-example-proactor ${run_env} -- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test.py
-v)
+
+add_test(c-example-proactor ${run_env} -- ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/example_test.py
-v)

http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/c/proactor/example_test.py
----------------------------------------------------------------------
diff --git a/examples/c/proactor/example_test.py b/examples/c/proactor/example_test.py
new file mode 100644
index 0000000..38f7fc8
--- /dev/null
+++ b/examples/c/proactor/example_test.py
@@ -0,0 +1,88 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License
+#
+
+# This is a test script to run the examples and verify that they behave as expected.
+
+import unittest, sys, time
+from exampletest import *
+
+def python_cmd(name):
+    dir = os.path.dirname(__file__)
+    return [sys.executable, os.path.join(dir, "..", "..", "python", name)]
+
+def receive_expect(n):
+    return ''.join('{"sequence"=%s}\n'%i for i in xrange(1, n+1)) + "%s messages received\n"%n
+
+class Broker(object):
+    def __init__(self, test):
+        self.test = test
+
+    def __enter__(self):
+        with TestPort() as tp:
+            self.port = tp.port
+            self.host = tp.host
+            self.addr = tp.addr
+            self.proc = self.test.proc(["broker", "", self.port])
+            self.proc.wait_re("listening")
+            return self
+
+    def __exit__(self, *args):
+        b = getattr(self, "proc")
+        if b:
+            if b.poll() !=  None: # Broker crashed
+                raise ProcError(b, "broker crash")
+            b.kill()
+
+class CExampleTest(ExampleTestCase):
+
+    def test_send_receive(self):
+        """Send first then receive"""
+        with Broker(self) as b:
+            s = self.proc(["send", "", b.port])
+            self.assertEqual("10 messages sent and acknowledged\n", s.wait_exit())
+            r = self.proc(["receive", "", b.port])
+            self.assertEqual(receive_expect(10), r.wait_exit())
+
+    def test_receive_send(self):
+        """Start receiving  first, then send."""
+        with Broker(self) as b:
+            r = self.proc(["receive", "", b.port]);
+            s = self.proc(["send", "", b.port]);
+            self.assertEqual("10 messages sent and acknowledged\n", s.wait_exit())
+            self.assertEqual(receive_expect(10), r.wait_exit())
+
+    def test_send_direct(self):
+        """Send to direct server"""
+        with TestPort() as tp:
+            d = self.proc(["direct", "", tp.port])
+            d.wait_re("listening")
+            self.assertEqual("10 messages sent and acknowledged\n", self.proc(["send", "",
tp.port]).wait_exit())
+            self.assertIn(receive_expect(10), d.wait_exit())
+
+    def test_receive_direct(self):
+        """Receive from direct server"""
+        with TestPort() as tp:
+            d = self.proc(["direct", "", tp.port])
+            d.wait_re("listening")
+            self.assertEqual(receive_expect(10), self.proc(["receive", "", tp.port]).wait_exit())
+            self.assertIn("10 messages sent and acknowledged\n", d.wait_exit())
+
+
+if __name__ == "__main__":
+    unittest.main()

http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/c/proactor/test.py
----------------------------------------------------------------------
diff --git a/examples/c/proactor/test.py b/examples/c/proactor/test.py
deleted file mode 100644
index f62ea4e..0000000
--- a/examples/c/proactor/test.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License
-#
-
-# This is a test script to run the examples and verify that they behave as expected.
-
-import unittest, sys, time
-from exampletest import *
-
-def python_cmd(name):
-    dir = os.path.dirname(__file__)
-    return [sys.executable, os.path.join(dir, "..", "..", "python", name)]
-
-def receive_expect(n):
-    return ''.join('{"sequence"=%s}\n'%i for i in xrange(1, n+1)) + "%s messages received\n"%n
-
-class Broker(object):
-    def __init__(self, test):
-        self.test = test
-
-    def __enter__(self):
-        with TestPort() as port:
-            self.port = port
-            self.proc = self.test.proc(["broker", "", self.port])
-            self.proc.wait_re("listening")
-            return self
-
-    def __exit__(self, *args):
-        b = getattr(self, "proc")
-        if b:
-            if b.poll() !=  None: # Broker crashed
-                raise ProcError(b, "broker crash")
-            b.kill()
-
-class CExampleTest(ExampleTestCase):
-
-    def test_send_receive(self):
-        """Send first then receive"""
-        with Broker(self) as b:
-            s = self.proc(["send", "", b.port])
-            self.assertEqual("10 messages sent and acknowledged\n", s.wait_out())
-            r = self.proc(["receive", "", b.port])
-            self.assertEqual(receive_expect(10), r.wait_out())
-
-    def test_receive_send(self):
-        """Start receiving  first, then send."""
-        with Broker(self) as b:
-            r = self.proc(["receive", "", b.port]);
-            s = self.proc(["send", "", b.port]);
-            self.assertEqual("10 messages sent and acknowledged\n", s.wait_out())
-            self.assertEqual(receive_expect(10), r.wait_out())
-
-    def test_send_direct(self):
-        """Send to direct server"""
-        with TestPort() as port:
-            d = self.proc(["direct", "", port])
-            d.wait_re("listening")
-            self.assertEqual("10 messages sent and acknowledged\n", self.proc(["send", "",
port]).wait_out())
-            self.assertIn(receive_expect(10), d.wait_out())
-
-    def test_receive_direct(self):
-        """Receive from direct server"""
-        with TestPort() as port:
-            addr = "127.0.0.1:%s" % port
-            d = self.proc(["direct", "", port])
-            d.wait_re("listening")
-            self.assertEqual(receive_expect(10), self.proc(["receive", "", port]).wait_out())
-            self.assertIn("10 messages sent and acknowledged\n", d.wait_out())
-
-
-if __name__ == "__main__":
-    unittest.main()

http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/cpp/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/examples/cpp/CMakeLists.txt b/examples/cpp/CMakeLists.txt
index 304d899..236aac7 100644
--- a/examples/cpp/CMakeLists.txt
+++ b/examples/cpp/CMakeLists.txt
@@ -30,7 +30,7 @@ macro(add_cpp_test name)
   else(WIN32)
     set(test_path "$<TARGET_FILE_DIR:broker>:$ENV{PATH}")
   endif(WIN32)
-  set(run_env ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/proton-c/env.py)
+  set(run_env ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/proton-c/env.py ${EXAMPLE_ENV})
   add_test(NAME ${name} COMMAND ${run_env} "PATH=${test_path}" ${VALGRIND_ENV} -- ${ARGN})
 endmacro()
 
@@ -64,17 +64,6 @@ if(HAS_CPP11)
       scheduled_send)
     add_executable(${example} ${example}.cpp)
   endforeach()
-
-  # Linux-only multi-threaded examples (TODO make these portable)
-#   if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
-#     set(container_src mt/epoll_container.cpp)
-#     foreach(example
-#         broker)
-#       add_executable(mt_${example} mt/${example}.cpp ${container_src})
-#       target_link_libraries(mt_${example} pthread)
-#     endforeach()
-#     add_cpp_test(cpp-example-mt ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/example_test.py
-v MtBrokerTest)
-#   endif()
 endif()
 
 add_cpp_test(cpp-example-container ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/example_test.py
-v ContainerExampleTest)

http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/cpp/example_test.py
----------------------------------------------------------------------
diff --git a/examples/cpp/example_test.py b/examples/cpp/example_test.py
index e2052dc..a80ee5c 100644
--- a/examples/cpp/example_test.py
+++ b/examples/cpp/example_test.py
@@ -21,6 +21,7 @@
 
 import unittest
 import os, sys, socket, time, re, inspect
+from exampletest import *
 from  random import randrange
 from subprocess import Popen, PIPE, STDOUT, call
 from copy import copy
@@ -80,148 +81,6 @@ def ensureCanTestExtendedSASL():
   if not createdSASLDb:
     raise Skipped("Can't Test Extended SASL: Couldn't create auth db")
 
-def pick_addr():
-    """Pick a new host:port address."""
-    # TODO Conway 2015-07-14: need a safer way to pick ports.
-    p =  randrange(10000, 20000)
-    return "127.0.0.1:%s" % p
-
-class ProcError(Exception):
-    """An exception that captures failed process output"""
-    def __init__(self, proc, what="non-0 exit"):
-        out = proc.out.strip()
-        if out:
-            out = "\nvvvvvvvvvvvvvvvv\n%s\n^^^^^^^^^^^^^^^^\n" % out
-        else:
-            out = ", no output)"
-        super(Exception, self, ).__init__(
-            "%s %s, code=%s%s" % (proc.args, what, proc.returncode, out))
-
-class Proc(Popen):
-    """A example process that stores its stdout and can scan it for a 'ready' pattern'"""
-
-    if "VALGRIND" in os.environ and os.environ["VALGRIND"]:
-        env_args = [os.environ["VALGRIND"], "--error-exitcode=42", "--quiet", "--leak-check=full"]
-    else:
-        env_args = []
-
-    def __init__(self, args, ready=None, timeout=30, skip_valgrind=False, **kwargs):
-        """Start an example process"""
-        args = list(args)
-        if platform.system() == "Windows":
-            args[0] += ".exe"
-        self.timeout = timeout
-        self.args = args
-        self.out = ""
-        if not skip_valgrind:
-            args = self.env_args + args
-        try:
-            Popen.__init__(self, args, stdout=PIPE, stderr=STDOUT,
-                           universal_newlines=True,  **kwargs)
-        except Exception as e:
-            raise ProcError(self, str(e))
-        # Start reader thread.
-        self.pattern = ready
-        self.ready = Event()
-        # Help with Python 2.5, 2.6, 2.7 changes to Event.wait(), Event.is_set
-        self.ready_set = False
-        self.error = None
-        self.thread = Thread(target=self.run_)
-        self.thread.daemon = True
-        self.thread.start()
-        if self.pattern:
-            self.wait_ready()
-
-    def run_(self):
-        try:
-            while True:
-                l = self.stdout.readline()
-                if not l: break
-                self.out += l
-                if self.pattern is not None:
-                    if re.search(self.pattern, l):
-                        self.ready_set = True
-                        self.ready.set()
-            if self.wait() != 0:
-                raise ProcError(self)
-        except Exception as e:
-            self.error = e
-        finally:
-            self.stdout.close()
-            self.ready_set = True
-            self.ready.set()
-
-    def safe_kill(self):
-        """Kill and clean up zombie but don't wait forever. No exceptions."""
-        try:
-            self.kill()
-            self.thread.join(self.timeout)
-        except: pass
-        return self.out
-
-    def check_(self):
-        if self.error:
-            raise self.error
-
-    def wait_ready(self):
-        """Wait for ready to appear in output"""
-        self.ready.wait(self.timeout)
-        if self.ready_set:
-            self.check_()
-            return self.out
-        else:
-            self.safe_kill()
-            raise ProcError(self, "timeout waiting for '%s'" % self.pattern)
-
-    def wait_exit(self):
-        """Wait for process to exit, return output. Raise ProcError on failure."""
-        self.thread.join(self.timeout)
-        if self.poll() is not None:
-            self.check_()
-            return self.out
-        else:
-            raise ProcError(self, "timeout waiting for exit")
-
-
-if hasattr(unittest.TestCase, 'setUpClass') and  hasattr(unittest.TestCase, 'tearDownClass'):
-    TestCase = unittest.TestCase
-else:
-    class TestCase(unittest.TestCase):
-        """
-        Roughly provides setUpClass and tearDownClass functionality for older python
-        versions in our test scenarios. If subclasses override setUp or tearDown
-        they *must* call the superclass.
-        """
-        def setUp(self):
-            if not hasattr(type(self), '_setup_class_count'):
-                type(self)._setup_class_count = len(
-                    inspect.getmembers(
-                        type(self),
-                        predicate=lambda m: inspect.ismethod(m) and m.__name__.startswith('test_')))
-                type(self).setUpClass()
-
-        def tearDown(self):
-            self.assertTrue(self._setup_class_count > 0)
-            self._setup_class_count -=  1
-            if self._setup_class_count == 0:
-                type(self).tearDownClass()
-
-
-class ExampleTestCase(TestCase):
-    """TestCase that manages started processes"""
-    def setUp(self):
-        super(ExampleTestCase, self).setUp()
-        self.procs = []
-
-    def tearDown(self):
-        for p in self.procs:
-            p.safe_kill()
-        super(ExampleTestCase, self).tearDown()
-
-    def proc(self, *args, **kwargs):
-        p = Proc(*args, **kwargs)
-        self.procs.append(p)
-        return p
 
 class BrokerTestCase(ExampleTestCase):
     """
@@ -231,14 +90,16 @@ class BrokerTestCase(ExampleTestCase):
 
     @classmethod
     def setUpClass(cls):
-        cls.addr = pick_addr() + "/examples"
         cls.broker = None       # In case Proc throws, create the attribute.
-        cls.broker = Proc([cls.broker_exe, "-a", cls.addr], ready="listening")
-        cls.broker.wait_ready()
+        with TestPort() as tp:
+            cls.addr = "%s:%s/example" % (tp.host, tp.port)
+            cls.broker = Proc([cls.broker_exe, "-a", tp.addr])
+            cls.broker.wait_re("listening")
 
     @classmethod
     def tearDownClass(cls):
-        if cls.broker: cls.broker.safe_kill()
+        if cls.broker:
+            cls.broker.kill()
 
     def tearDown(self):
         b = type(self).broker
@@ -267,7 +128,8 @@ class ContainerExampleTest(BrokerTestCase):
         self.assertEqual('Hello World!\n', self.proc(["helloworld", self.addr]).wait_exit())
 
     def test_helloworld_direct(self):
-        self.assertEqual('Hello World!\n', self.proc(["helloworld_direct", pick_addr()]).wait_exit())
+        with TestPort() as tp:
+            self.assertEqual('Hello World!\n', self.proc(["helloworld_direct", tp.addr]).wait_exit())
 
     def test_simple_send_recv(self):
         self.assertEqual("all messages confirmed\n",
@@ -283,21 +145,22 @@ class ContainerExampleTest(BrokerTestCase):
 
 
     def test_simple_send_direct_recv(self):
-        addr = pick_addr()
-        recv = self.proc(["direct_recv", "-a", addr], "listening")
-        self.assertEqual("all messages confirmed\n",
-                         self.proc(["simple_send", "-a", addr]).wait_exit())
-        self.assertEqual(recv_expect("direct_recv", addr), recv.wait_exit())
+        with TestPort() as tp:
+            addr = "%s/examples" % tp.addr
+            recv = self.proc(["direct_recv", "-a", addr], "listening")
+            self.assertEqual("all messages confirmed\n",
+                             self.proc(["simple_send", "-a", addr]).wait_exit())
+            self.assertEqual(recv_expect("direct_recv", addr), recv.wait_exit())
 
     def test_simple_recv_direct_send(self):
-        addr = pick_addr()
-        send = self.proc(["direct_send", "-a", addr], "listening")
-        self.assertEqual(recv_expect("simple_recv", addr),
-                         self.proc(["simple_recv", "-a", addr]).wait_exit())
-
-        self.assertEqual(
-            "direct_send listening on %s\nall messages confirmed\n" % addr,
-            send.wait_exit())
+        with TestPort() as tp:
+            addr = "%s/examples" % tp.addr
+            send = self.proc(["direct_send", "-a", addr], "listening")
+            self.assertEqual(recv_expect("simple_recv", addr),
+                             self.proc(["simple_recv", "-a", addr]).wait_exit())
+            self.assertEqual(
+                "direct_send listening on %s\nall messages confirmed\n" % addr,
+                send.wait_exit())
 
     def test_request_response(self):
         server = self.proc(["server", "-a", self.addr], "connected")
@@ -305,10 +168,11 @@ class ContainerExampleTest(BrokerTestCase):
                          self.proc(["client", "-a", self.addr]).wait_exit())
 
     def test_request_response_direct(self):
-        addr = pick_addr()
-        server = self.proc(["server_direct", "-a", addr+"/examples"], "listening")
-        self.assertEqual(CLIENT_EXPECT,
-                         self.proc(["client", "-a", addr+"/examples"]).wait_exit())
+        with TestPort() as tp:
+            addr = "%s/examples" % tp.addr
+            server = self.proc(["server_direct", "-a", addr], "listening")
+            self.assertEqual(CLIENT_EXPECT,
+                             self.proc(["client", "-a", addr]).wait_exit())
 
     def test_flow_control(self):
         want="""success: Example 1: simple credit
@@ -316,7 +180,8 @@ success: Example 2: basic drain
 success: Example 3: drain without credit
 success: Exmaple 4: high/low watermark
 """
-        self.assertEqual(want, self.proc(["flow_control", "--address", pick_addr(), "--quiet"]).wait_exit())
+        with TestPort() as tp:
+            self.assertEqual(want, self.proc(["flow_control", "--address", tp.addr, "--quiet"]).wait_exit())
 
     def test_encode_decode(self):
         want="""
@@ -345,6 +210,21 @@ map{string(k1):int(42), symbol(k2):boolean(0)}
         self.maxDiff = None
         self.assertEqual(want, self.proc(["encode_decode"]).wait_exit())
 
+
+class ContainerExampleSSLTest(BrokerTestCase):
+    """Run the SSL container examples, verify they behave as expected."""
+
+    broker_exe = "broker"
+
+    def setUp(self):
+        if not SSL.present:
+            self.skip("SSL not available")
+        self.vg_args = Proc.vg_args
+        Proc.vg_args = []       # Disable
+
+    def tearDown(self):
+        Proc.vg_args = self.vg_args
+
     def ssl_certs_dir(self):
         """Absolute path to the test SSL certificates"""
         pn_root = dirname(dirname(dirname(sys.argv[0])))
@@ -352,30 +232,33 @@ map{string(k1):int(42), symbol(k2):boolean(0)}
 
     def test_ssl(self):
         # SSL without SASL, VERIFY_PEER_NAME
-        addr = "amqps://" + pick_addr() + "/examples"
-        # Disable valgrind when using OpenSSL
-        out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir()], skip_valgrind=True).wait_exit()
-        expect = "Outgoing client connection connected via SSL.  Server certificate identity
CN=test_server\nHello World!"
-        expect_found = (out.find(expect) >= 0)
-        self.assertEqual(expect_found, True)
+        with TestPort() as tp:
+            addr = "amqps://%s/examples" % tp.addr
+            # Disable valgrind when using OpenSSL
+            out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir()], skip_valgrind=True).wait_exit()
+            expect = "Outgoing client connection connected via SSL.  Server certificate identity
CN=test_server\nHello World!"
+            expect_found = (out.find(expect) >= 0)
+            self.assertEqual(expect_found, True)
 
     def test_ssl_no_name(self):
         # VERIFY_PEER
-        addr = "amqps://" + pick_addr() + "/examples"
-        # Disable valgrind when using OpenSSL
-        out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir(), "-v", "noname"],
skip_valgrind=True).wait_exit()
-        expect = "Outgoing client connection connected via SSL.  Server certificate identity
CN=test_server\nHello World!"
-        expect_found = (out.find(expect) >= 0)
-        self.assertEqual(expect_found, True)
+        with TestPort() as tp:
+            addr = "amqps://%s/examples" % tp.addr
+            # Disable valgrind when using OpenSSL
+            out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir(), "-v", "noname"],
skip_valgrind=True).wait_exit()
+            expect = "Outgoing client connection connected via SSL.  Server certificate identity
CN=test_server\nHello World!"
+            expect_found = (out.find(expect) >= 0)
+            self.assertEqual(expect_found, True)
 
     def test_ssl_bad_name(self):
         # VERIFY_PEER
-        addr = "amqps://" + pick_addr() + "/examples"
-        # Disable valgrind when using OpenSSL
-        out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir(), "-v", "fail"], skip_valgrind=True).wait_exit()
-        expect = "Expected failure of connection with wrong peer name"
-        expect_found = (out.find(expect) >= 0)
-        self.assertEqual(expect_found, True)
+        with TestPort() as tp:
+            addr = "amqps://%s/examples" % tp.addr
+            # Disable valgrind when using OpenSSL
+            out = self.proc(["ssl", "-a", addr, "-c", self.ssl_certs_dir(), "-v", "fail"],
skip_valgrind=True).wait_exit()
+            expect = "Expected failure of connection with wrong peer name"
+            expect_found = (out.find(expect) >= 0)
+            self.assertEqual(expect_found, True)
 
     def test_ssl_client_cert(self):
         # SSL with SASL EXTERNAL
@@ -383,11 +266,12 @@ map{string(k1):int(42), symbol(k2):boolean(0)}
 Outgoing client connection connected via SSL.  Server certificate identity CN=test_server
 Hello World!
 """
-        addr = "amqps://" + pick_addr() + "/examples"
-        # Disable valgrind when using OpenSSL
-        out = self.proc(["ssl_client_cert", addr, self.ssl_certs_dir()], skip_valgrind=True).wait_exit()
-        expect_found = (out.find(expect) >= 0)
-        self.assertEqual(expect_found, True)
+        with TestPort() as tp:
+            addr = "amqps://%s/examples" % tp.addr
+            # Disable valgrind when using OpenSSL
+            out = self.proc(["ssl_client_cert", addr, self.ssl_certs_dir()], skip_valgrind=True).wait_exit()
+            expect_found = (out.find(expect) >= 0)
+            self.assertEqual(expect_found, True)
 
     def test_scheduled_send_03(self):
         # Output should be a bunch of "send" lines but can't guarantee exactly how many.
@@ -424,19 +308,21 @@ class EngineTestCase(BrokerTestCase):
 
 
     def test_simple_send_direct_recv(self):
-        addr = pick_addr()
-        recv = self.proc(["direct_recv", "-a", addr], "listening")
-        self.assertEqual("all messages confirmed\n",
-                         self.proc(["simple_send", "-a", addr]).wait_exit())
-        self.assertEqual(recv_expect("direct_recv", addr), recv.wait_exit())
+        with TestPort() as tp:
+            addr = "%s/examples" % tp.addr
+            recv = self.proc(["direct_recv", "-a", addr], "listening")
+            self.assertEqual("all messages confirmed\n",
+                             self.proc(["simple_send", "-a", addr]).wait_exit())
+            self.assertEqual(recv_expect("direct_recv", addr), recv.wait_exit())
 
     def test_simple_recv_direct_send(self):
-        addr = pick_addr()
-        send = self.proc(["direct_send", "-a", addr], "listening")
-        self.assertEqual(recv_expect("simple_recv", addr),
-                         self.proc(["simple_recv", "-a", addr]).wait_exit())
-        self.assertEqual("direct_send listening on %s\nall messages confirmed\n" % addr,
-                         send.wait_exit())
+        with TestPort() as tp:
+            addr = "%s/examples" % tp.addr
+            send = self.proc(["direct_send", "-a", tp.addr], "listening")
+            self.assertEqual(recv_expect("simple_recv", addr),
+                             self.proc(["simple_recv", "-a", addr]).wait_exit())
+            self.assertEqual("direct_send listening on %s\nall messages confirmed\n" % addr,
+                             send.wait_exit())
 
     def test_request_response(self):
         server = self.proc(["server", "-a", self.addr], "connected")

http://git-wip-us.apache.org/repos/asf/qpid-proton/blob/81ba5a3b/examples/exampletest.py
----------------------------------------------------------------------
diff --git a/examples/exampletest.py b/examples/exampletest.py
index 71aa463..bb055a1 100644
--- a/examples/exampletest.py
+++ b/examples/exampletest.py
@@ -36,11 +36,12 @@ class TestPort(object):
     def __init__(self):
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-        self.sock.bind(('', 0))
-        self.port = socket.getnameinfo(self.sock.getsockname(), 0)[1]
+        self.sock.bind(('127.0.0.1', 0)) # Testing exampless is local only
+        self.host, self.port = socket.getnameinfo(self.sock.getsockname(), 0)
+        self.addr = "%s:%s" % (self.host, self.port)
 
     def __enter__(self):
-        return self.port
+        return self
 
     def __exit__(self, *args):
         self.close()
@@ -57,32 +58,36 @@ class ProcError(Exception):
         else:
             out = ", no output)"
         super(Exception, self, ).__init__(
-            "%s %s, code=%s%s" % (proc.args, what, proc.returncode, out))
+            "%s %s, code=%s%s" % (proc.args, what, getattr(proc, 'returncode', 'noreturn'),
out))
 
 class NotFoundError(ProcError):
     pass
 
 class Proc(Popen):
-    """A example process that stores its output, optionally run with valgrind."""
+    """A example process that stores its stdout and can scan it for a 'ready' pattern'"""
 
     if "VALGRIND" in os.environ and os.environ["VALGRIND"]:
-        env_args = [os.environ["VALGRIND"], "--error-exitcode=42", "--quiet", "--leak-check=full"]
+        vg_args = [os.environ["VALGRIND"], "--error-exitcode=42", "--quiet", "--leak-check=full"]
     else:
-        env_args = []
+        vg_args = []
 
     @property
     def out(self):
         self._out.seek(0)
-        return self._out.read()
+        # Normalize line endings, os.tmpfile() opens in binary mode.
+        return self._out.read().replace('\r\n','\n').replace('\r','\n')
 
-    def __init__(self, args, **kwargs):
+    def __init__(self, args, skip_valgrind=False, **kwargs):
         """Start an example process"""
         args = list(args)
-        self.args = args
+        if skip_valgrind:
+            self.args = args
+        else:
+            self.args = self.vg_args + args
         self.kwargs = kwargs
         self._out = os.tmpfile()
         try:
-            Popen.__init__(self, self.env_args + self.args, stdout=self._out, stderr=STDOUT,
**kwargs)
+            Popen.__init__(self, self.args, stdout=self._out, stderr=STDOUT, **kwargs)
         except OSError, e:
             if e.errno == errno.ENOENT:
                 raise NotFoundError(self, str(e))
@@ -98,7 +103,7 @@ class Proc(Popen):
             pass                # Already exited.
         return self.out
 
-    def wait_out(self, timeout=DEFAULT_TIMEOUT, expect=0):
+    def wait_exit(self, timeout=DEFAULT_TIMEOUT, expect=0):
         """Wait for process to exit, return output. Raise ProcError  on failure."""
         t = threading.Thread(target=self.wait)
         t.start()
@@ -124,29 +129,46 @@ class Proc(Popen):
             time.sleep(0.01)    # Not very efficient
         raise ProcError(self, "gave up waiting for '%s' after %ss" % (regexp, timeout))
 
-# Work-around older python unittest that lacks setUpClass.
-if hasattr(unittest.TestCase, 'setUpClass') and  hasattr(unittest.TestCase, 'tearDownClass'):
-    TestCase = unittest.TestCase
-else:
-    class TestCase(unittest.TestCase):
-        """
-        Roughly provides setUpClass and tearDownClass functionality for older python
-        versions in our test scenarios. If subclasses override setUp or tearDown
-        they *must* call the superclass.
-        """
+def _tc_missing(attr):
+    return not hasattr(unittest.TestCase, attr)
+
+class TestCase(unittest.TestCase):
+    """
+    Roughly provides setUpClass() and tearDownClass() and other features missing
+    in python 2.6. If subclasses override setUp() or tearDown() they *must*
+    call the superclass.
+    """
+
+    if _tc_missing('setUpClass') and _tc_missing('tearDownClass'):
+
+        @classmethod
+        def setUpClass(cls):
+            pass
+
+        @classmethod
+        def tearDownClass(cls):
+            pass
+
         def setUp(self):
-            if not hasattr(type(self), '_setup_class_count'):
-                type(self)._setup_class_count = len(
-                    inspect.getmembers(
-                        type(self),
-                        predicate=lambda(m): inspect.ismethod(m) and m.__name__.startswith('test_')))
-                type(self).setUpClass()
+            super(TestCase, self).setUp()
+            cls = type(self)
+            if not hasattr(cls, '_setup_class_count'): # First time
+                def is_test(m):
+                    return inspect.ismethod(m) and m.__name__.startswith('test_')
+                cls._setup_class_count = len(inspect.getmembers(cls, predicate=is_test))
+                cls.setUpClass()
 
         def tearDown(self):
             self.assertTrue(self._setup_class_count > 0)
             self._setup_class_count -=  1
             if self._setup_class_count == 0:
                 type(self).tearDownClass()
+            super(TestCase, self).tearDown()
+
+    if _tc_missing('assertIn'):
+
+        def assertIn(self, a, b):
+            self.assertTrue(a in b, "%r not in %r" % (a, b))
 
 class ExampleTestCase(TestCase):
     """TestCase that manages started processes"""


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


Mime
View raw message