Example #1
0
    def testNonBlockingRequestMultipart(self):
        """
        Test NonBlocking Http client
        """
        console.terse("{0}\n".format(
            self.testNonBlockingRequestMultipart.__doc__))

        console.reinit(verbosity=console.Wordage.profuse)

        wireLogBeta = nonblocking.WireLog(buffify=True)
        result = wireLogBeta.reopen()

        eha = ('127.0.0.1', 8080)
        beta = nonblocking.Outgoer(ha=eha, bufsize=131072)
        self.assertIs(beta.reopen(), True)
        self.assertIs(beta.accepted, False)
        self.assertIs(beta.cutoff, False)

        console.terse("Connecting beta to server ...\n")
        while True:
            beta.serviceConnect()
            #alpha.serviceAccepts()
            if beta.accepted:  # and beta.ca in alpha.ixes
                break
            time.sleep(0.05)

        self.assertIs(beta.accepted, True)
        self.assertIs(beta.cutoff, False)
        self.assertEqual(beta.ca, beta.cs.getsockname())
        self.assertEqual(beta.ha, beta.cs.getpeername())
        self.assertEqual(eha, beta.ha)

        console.terse("{0}\n".format("Building Request ...\n"))
        host = u'127.0.0.1'
        port = 8080
        method = u'POST'
        path = u'/echo'
        console.terse("{0} from  {1}:{2}{3} ...\n".format(
            method, host, port, path))
        headers = odict([(u'Accept', u'application/json'),
                         (u'Content-Type', u'multipart/form-data')])
        fargs = odict([("text", "This is the life,\nIt is the best.\n"),
                       ("html", "<html><body></body><html>")])
        request = httping.Requester(hostname=host,
                                    port=port,
                                    method=method,
                                    path=path,
                                    headers=headers)

        msgOut = request.rebuild(fargs=fargs)

        beta.tx(msgOut)
        while beta.txes or not beta.rxbs:
            beta.serviceTxes()
            beta.serviceReceives()
            time.sleep(0.05)
        beta.serviceReceives()

        msgIn, index = beta.tailRxbs(0)

        response = httping.Respondent(msg=beta.rxbs, method=method)

        while response.parser:
            response.parse()

        response.dictify()

        self.assertEqual(
            response.data, {
                'action':
                None,
                'content':
                None,
                'form': [['text', 'This is the life,\nIt is the best.\n'],
                         ['html', '<html><body></body><html>']],
                'query': {},
                'url':
                'http://127.0.0.1:8080/echo',
                'verb':
                'POST'
            })

        self.assertEqual(len(beta.rxbs), 0)

        #alpha.close()
        beta.close()

        wireLogBeta.close()
        console.reinit(verbosity=console.Wordage.concise)
Example #2
0
    def testNonBlockingRequestStreamFancyJson(self):
        """
        Test NonBlocking Http client
        """
        console.terse("{0}\n".format(
            self.testNonBlockingRequestStreamFancyJson.__doc__))

        console.reinit(verbosity=console.Wordage.profuse)

        wireLogBeta = nonblocking.WireLog(buffify=True)
        result = wireLogBeta.reopen()

        eha = ('127.0.0.1', 8080)
        beta = nonblocking.Outgoer(ha=eha, bufsize=131072, wlog=wireLogBeta)
        self.assertIs(beta.reopen(), True)
        self.assertIs(beta.accepted, False)
        self.assertIs(beta.cutoff, False)

        console.terse("Connecting beta to server ...\n")
        while True:
            beta.serviceConnect()
            #alpha.serviceAccepts()
            if beta.accepted:  # and beta.ca in alpha.ixes
                break
            time.sleep(0.05)

        self.assertIs(beta.accepted, True)
        self.assertIs(beta.cutoff, False)
        self.assertEqual(beta.ca, beta.cs.getsockname())
        self.assertEqual(beta.ha, beta.cs.getpeername())
        self.assertEqual(eha, beta.ha)

        console.terse("{0}\n".format("Building Request ...\n"))
        host = u'127.0.0.1'
        port = 8080
        method = u'GET'
        path = u'/fancy?idify=true;jsonify=true'
        console.terse("{0} from  {1}:{2}{3} ...\n".format(
            method, host, port, path))
        headers = odict([('Accept', 'application/json')])
        request = httping.Requester(hostname=host,
                                    port=port,
                                    method=method,
                                    path=path,
                                    headers=headers)
        msgOut = request.rebuild()
        lines = [
            b'GET /fancy?idify=true;jsonify=true HTTP/1.1',
            b'Host: 127.0.0.1:8080',
            b'Accept-Encoding: identity',
            b'Content-Length: 0',
            b'Accept: application/json',
            b'',
            b'',
        ]
        for i, line in enumerate(lines):
            self.assertEqual(line, request.lines[i])

        self.assertEqual(
            request.head,
            b'GET /fancy?idify=true;jsonify=true HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nAccept-Encoding: identity\r\nContent-Length: 0\r\nAccept: application/json\r\n\r\n'
        )
        self.assertEqual(msgOut, request.head)

        beta.tx(msgOut)
        while beta.txes or not beta.rxbs:
            beta.serviceTxes()
            beta.serviceReceives()
            time.sleep(0.05)
        beta.serviceReceives()

        msgIn, index = beta.tailRxbs(0)

        response = httping.Respondent(msg=beta.rxbs,
                                      method=method,
                                      path=path,
                                      reconnectable=True)

        timer = Timer(duration=3.0)
        while response.parser and not timer.expired:
            response.parse()
            beta.serviceReceives()
            time.sleep(0.01)

        if response.parser:
            response.parser.close()
            response.parser = None

        response.dictify()

        self.assertEqual(response.eventSource.retry, 1000)
        self.assertTrue(len(response.events) > 2)
        event = response.events.popleft()
        self.assertEqual(event, {
            'id': '0',
            'name': '',
            'data': 'START',
            'json': None
        })
        event = response.events.popleft()
        self.assertEqual(event, {
            'id': '1',
            'name': '',
            'data': None,
            'json': {
                'count': 1
            }
        })
        event = response.events.popleft()
        self.assertEqual(event, {
            'id': '2',
            'name': '',
            'data': None,
            'json': {
                'count': 2
            }
        })
        self.assertTrue(len(response.body) == 0)
        self.assertTrue(len(response.eventSource.raw) == 0)

        beta.close()

        wireLogBeta.close()
        console.reinit(verbosity=console.Wordage.concise)
    def testClientTLS(self):
        """
        Test OutgoerTLS class  NonBlocking TCP/IP with TLS client
        Wrapped with ssl context
        """
        try:
            import ssl
        except ImportError:
            return

        console.terse("{0}\n".format(self.testClientTLS.__doc__))
        console.reinit(verbosity=console.Wordage.profuse)

        wireLogBeta = nonblocking.WireLog(buffify=True, same=True)
        result = wireLogBeta.reopen()
        #serverHa = ("127.0.0.1", 8080)
        serverHa = ("localhost", 8080)
        #serverHa = ("google.com", 443)

        keypath = '/etc/pki/tls/certs/client_key.pem'  # local private key
        certpath = '/etc/pki/tls/certs/client_cert.pem'  # local public cert
        cafilepath = '/etc/pki/tls/certs/localhost.crt'  # remote public cert
        beta = nonblocking.OutgoerTls(ha=serverHa,
                                      bufsize=131072,
                                      wlog=wireLogBeta,
                                      context=None,
                                      version=ssl.PROTOCOL_TLSv1,
                                      certify=ssl.CERT_REQUIRED,
                                      keypath=keypath,
                                      certpath=certpath,
                                      cafilepath=cafilepath,
                                      hostify=True,
                                      certedhost="localhost")
        self.assertIs(beta.reopen(), True)
        self.assertIs(beta.accepted, False)
        self.assertIs(beta.cutoff, False)

        console.terse("Connecting beta\n")
        while True:
            beta.serviceConnect()
            if beta.accepted:
                break
            time.sleep(0.05)

        self.assertIs(beta.accepted, True)
        self.assertIs(beta.cutoff, False)
        self.assertEqual(beta.ca, beta.cs.getsockname())
        self.assertEqual(beta.ha, beta.cs.getpeername())
        #self.assertEqual(beta.ha, serverHa)

        console.terse("Handshaking beta\n")
        while True:
            beta.serviceConnect()
            if beta.connected:
                break
            time.sleep(0.01)

        self.assertIs(beta.connected, True)

        msgOut = b"GET /echo HTTP/1.0\r\n\r\n"
        beta.tx(msgOut)
        while beta.txes:
            beta.serviceTxes()
            time.sleep(0.05)
            beta.serviceReceives()
            time.sleep(0.05)
        msgIn = bytes(beta.rxbs)
        beta.clearRxbs()
        self.assertTrue(
            msgIn.startswith(b'HTTP/1.1 200 OK\r\nContent-Length: '))
        self.assertTrue(msgIn.endswith(b'/echo", "action": null}'))

        beta.close()

        # repeat but only call serviceConnect which calls connect
        self.assertIs(beta.reopen(), True)
        self.assertIs(beta.accepted, False)
        self.assertIs(beta.cutoff, False)

        console.terse("Connecting and Handshaking beta\n")
        while True:
            beta.serviceConnect()
            if beta.connected:
                break
            time.sleep(0.01)

        self.assertIs(beta.accepted, True)
        self.assertIs(beta.cutoff, False)
        self.assertEqual(beta.ca, beta.cs.getsockname())
        self.assertEqual(beta.ha, beta.cs.getpeername())
        self.assertIs(beta.connected, True)

        msgOut = b"GET /echo HTTP/1.0\r\n\r\n"
        beta.tx(msgOut)
        while beta.txes:
            beta.serviceTxes()
            time.sleep(0.05)
            beta.serviceReceives()
            time.sleep(0.05)
        msgIn = bytes(beta.rxbs)
        beta.clearRxbs()
        self.assertTrue(
            msgIn.startswith(b'HTTP/1.1 200 OK\r\nContent-Length: '))
        self.assertTrue(msgIn.endswith(b'/echo", "action": null}'))

        beta.close()

        wlBetaRx = wireLogBeta.getRx()
        wlBetaTx = wireLogBeta.getTx()
        self.assertEqual(wlBetaRx, wlBetaTx)  # since wlog is same

        wireLogBeta.close()
        console.reinit(verbosity=console.Wordage.concise)
Example #4
0
    def testNonBlockingRequestEcho(self):
        """
        Test NonBlocking Http client
        """
        console.terse("{0}\n".format(self.testNonBlockingRequestEcho.__doc__))

        console.reinit(verbosity=console.Wordage.profuse)

        wireLogBeta = nonblocking.WireLog(buffify=True)
        result = wireLogBeta.reopen()

        eha = ('127.0.0.1', 8080)
        beta = nonblocking.Outgoer(ha=eha, bufsize=131072)
        self.assertIs(beta.reopen(), True)
        self.assertIs(beta.accepted, False)
        self.assertIs(beta.cutoff, False)

        console.terse("Connecting beta to server ...\n")
        while True:
            beta.serviceConnect()
            #alpha.serviceAccepts()
            if beta.accepted:  # and beta.ca in alpha.ixes
                break
            time.sleep(0.05)

        self.assertIs(beta.accepted, True)
        self.assertIs(beta.cutoff, False)
        self.assertEqual(beta.ca, beta.cs.getsockname())
        self.assertEqual(beta.ha, beta.cs.getpeername())
        self.assertEqual(eha, beta.ha)

        console.terse("{0}\n".format("Building Request ...\n"))
        host = u'127.0.0.1'
        port = 8080
        method = u'GET'
        path = u'/echo?name=fame'
        console.terse("{0} from  {1}:{2}{3} ...\n".format(
            method, host, port, path))
        headers = odict([('Accept', 'application/json')])
        request = httping.Requester(hostname=host,
                                    port=port,
                                    method=method,
                                    path=path,
                                    headers=headers)
        msgOut = request.rebuild()
        lines = [
            b'GET /echo?name=fame HTTP/1.1',
            b'Host: 127.0.0.1:8080',
            b'Accept-Encoding: identity',
            b'Content-Length: 0',
            b'Accept: application/json',
            b'',
            b'',
        ]
        for i, line in enumerate(lines):
            self.assertEqual(line, request.lines[i])

        self.assertEqual(
            request.head,
            b'GET /echo?name=fame HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nAccept-Encoding: identity\r\nContent-Length: 0\r\nAccept: application/json\r\n\r\n'
        )
        self.assertEqual(
            msgOut,
            b'GET /echo?name=fame HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nAccept-Encoding: identity\r\nContent-Length: 0\r\nAccept: application/json\r\n\r\n'
        )

        beta.tx(msgOut)
        while beta.txes or not beta.rxbs:
            beta.serviceTxes()
            beta.serviceReceives()
            time.sleep(0.05)
        beta.serviceReceives()

        msgIn, index = beta.tailRxbs(0)
        self.assertTrue(
            msgIn.endswith(
                b'{"content": null, "query": {"name": "fame"}, "verb": "GET", "path": "http://127.0.0.1:8080/echo?name=fame", "action": null}'
            ))

        #response = httping.HttpResponseNb(msgIn, method=method, path=path)
        response = httping.Respondent(msg=beta.rxbs, method=method, path=path)

        while response.parser:
            response.parse()

        response.dictify()

        self.assertEqual(
            bytes(response.body),
            b'{"content": null, "query": {"name": "fame"}, "verb": "GET", "url": "http://127.0.0.1:8080/echo?name=fame", "action": null}'
        )

        self.assertEqual(len(beta.rxbs), 0)

        #alpha.close()
        beta.close()

        wireLogBeta.close()
        console.reinit(verbosity=console.Wordage.concise)
    def testClientServerTLSService(self):
        """
        Test Classes ServerTLS service methods
        """
        try:
            import ssl
        except ImportError:
            return

        console.terse("{0}\n".format(self.testClientServerTLSService.__doc__))
        console.reinit(verbosity=console.Wordage.profuse)

        wireLogAlpha = nonblocking.WireLog(buffify=True, same=True)
        result = wireLogAlpha.reopen()

        wireLogBeta = nonblocking.WireLog(buffify=True, same=True)
        result = wireLogBeta.reopen()

        serverKeypath = '/etc/pki/tls/certs/server_key.pem'  # local private key
        serverCertpath = '/etc/pki/tls/certs/server_cert.pem'  # local public cert
        clientCafilepath = '/etc/pki/tls/certs/client.pem'  # remote public cert

        alpha = nonblocking.ServerTls(
            host='localhost',
            port=6101,
            bufsize=131072,
            wlog=wireLogAlpha,
            certify=ssl.CERT_NONE,
            keypath=serverKeypath,
            certpath=serverCertpath,
            cafilepath=clientCafilepath,
        )
        self.assertIs(alpha.reopen(), True)
        self.assertEqual(alpha.ha, ('127.0.0.1', 6101))

        #beta = nonblocking.OutgoerTLS(ha=alpha.eha,
        #bufsize=131072,
        #wlog=wireLogBeta)
        #self.assertIs(beta.reopen(), True)
        #self.assertIs(beta.accepted, False)
        #self.assertIs(beta.cutoff, False)

        console.terse("Connecting beta to alpha\n")
        while True:
            #beta.serviceConnect()
            alpha.serviceConnects()
            #if beta.accepted and beta.ca in alpha.ixes:
            #break
            if len(alpha.ixes) == 1:
                break
            time.sleep(0.05)

        #self.assertIs(beta.accepted, True)
        #self.assertIs(beta.cutoff, False)
        #self.assertEqual(beta.ca, beta.cs.getsockname())
        #self.assertEqual(beta.ha, beta.cs.getpeername())
        #self.assertEqual(alpha.eha, beta.ha)
        #ixBeta = alpha.ixes[beta.ca]
        #self.assertIsNotNone(ixBeta.ca)
        #self.assertIsNotNone(ixBeta.cs)

        #self.assertEqual(ixBeta.cs.getsockname(), beta.cs.getpeername())
        #self.assertEqual(ixBeta.cs.getpeername(), beta.cs.getsockname())
        #self.assertEqual(ixBeta.ca, beta.ca)
        #self.assertEqual(ixBeta.ha, beta.ha)

        #msgOut = b"Beta sends to Alpha"
        #beta.transmit(msgOut)
        #while not ixBeta.rxbs and beta.txes:
        #beta.serviceTxes()
        #alpha.serviceAllRxAllIx()
        #time.sleep(0.05)
        #msgIn = bytes(ixBeta.rxbs)
        #self.assertEqual(msgIn, msgOut)
        #index = len(ixBeta.rxbs)

        ix = alpha.ixes.values()[0]
        while True:
            alpha.serviceReceivesAllIx()
            time.sleep(0.05)
            if ix.rxbs:
                break

        time.sleep(0.05)
        alpha.serviceReceivesAllIx()

        msgIn = bytes(ix.rxbs)
        #self.assertEqual(msgIn, msgOut)
        index = len(ix.rxbs)

        msgOut = b'Wait what?'
        ix.tx(msgOut)
        while ix.txes:
            alpha.serviceTxesAllIx()
            time.sleep(0.05)

        alpha.close()
        #beta.close()

        wireLogAlpha.close()
        #wireLogBeta.close()
        console.reinit(verbosity=console.Wordage.concise)