class HttpClientTest(SeecrTestCase):
    def setUp(self):
        super(HttpClientTest, self).setUp()
        self.port = randint(50000, 60000)
        self.server = MockServer(port=self.port)
        self.requests = []
        _buildResponse = self.server.buildResponse

        def buildResponse(**kwargs):
            self.requests.append(kwargs)
            return _buildResponse(**kwargs)

        self.server.buildResponse = buildResponse
        self.server.response = RESULT_HEADER + CRLF * 2 + RESULT_JSON
        self.server.start()

    def tearDown(self):
        self.server.halt = True
        super(HttpClientTest, self).tearDown()

    def testMockSetup(self):
        result = urlopen("http://localhost:%s/a/path" % self.port).read()
        self.assertEquals(RESULT_JSON, result)
        kwargs = self.requests[0]
        self.assertEquals("/a/path", kwargs["path"])

    def testExecuteQuery(self):
        result = asProcess(HttpClient(host="localhost", port=self.port).executeQuery("SPARQL"))
        self.assertEquals(PARSED_RESULT_JSON, result)

    def testExecuteQuerySynchronous(self):
        result = retval(HttpClient(host="localhost", port=self.port, synchronous=True).executeQuery("SPARQL"))
        self.assertEquals(PARSED_RESULT_JSON, result)
Example #2
0
    def testHangupConnectionTimeout(self):
        expectedException = IOError
        self.ms.socket.close()
        self.ms = MockServer(port=PortNumberGenerator.next(), hangupConnectionTimeout=0.1)
        self.ms.start()

        t0 = time()
        self.assertRaises(expectedException, lambda: urlopen(self.ms.myUrl).read())
        t1 = time()
        delta = t1 - t0
        self.assertTrue(0.09 < delta < 0.12, "Expected around 0.1, was %s" % delta)
        self.assertEqual(0, len(self.ms.requests))
Example #3
0
 def buildResponse(self, **kwargs):
     if kwargs['path'] in ["/api/service/v2/update", "/api/service/v2/list"]:
         while not self.configUpdate:
             sleep(0.25)
             if self.halt:
                 sys.stderr.write('%s halting while client still on the Phone!\n' % self.__class__.__name__)
                 sys.stderr.flush()
                 break
         if self.configUpdate:
             keys = set(k for k in kwargs.get('arguments', {}).get('keys', [''])[0].split(',') if k)
             for special_key in ['services', 'config']:
                 if '-'+special_key in keys:
                     keys.remove('-'+special_key)
                 else:
                     keys.add(special_key)
             identifier = self._findIdentifier(**kwargs)
             result = {}
             for key in keys:
                 try:
                     result[key] = self.configUpdate[key]
                 except KeyError:
                     pass
             if identifier:
                 service = result.get('services', {}).get(identifier, None)
                 if service:
                     result['this_service'] = dict(service)
                     result['this_service']['state'] = {'readable':service['readable'], 'writable':service['writable']}
             return Ok + CRLF + dumps(result)
     return MockServer.buildResponse(self, **kwargs)
Example #4
0
 def buildResponse(self, **kwargs):
     if kwargs["path"] in ["/api/service/v2/update", "/api/service/v2/list"]:
         while not self.configUpdate:
             sleep(0.25)
             if self.halt:
                 sys.stderr.write("%s halting while client still on the Phone!\n" % self.__class__.__name__)
                 sys.stderr.flush()
                 break
         if self.configUpdate:
             keys = set(k for k in kwargs.get("arguments", {}).get("keys", [""])[0].split(",") if k)
             for special_key in ["services", "config"]:
                 if "-" + special_key in keys:
                     keys.remove("-" + special_key)
                 else:
                     keys.add(special_key)
             identifier = self._findIdentifier(**kwargs)
             result = {}
             for key in keys:
                 try:
                     result[key] = self.configUpdate[key]
                 except KeyError:
                     pass
             if identifier:
                 service = result.get("services", {}).get(identifier, None)
                 if service:
                     result["this_service"] = dict(service)
                     result["this_service"]["state"] = {
                         "readable": service["readable"],
                         "writable": service["writable"],
                     }
             return Ok + CRLF + dumps(result)
     return MockServer.buildResponse(self, **kwargs)
Example #5
0
    def testHangupConnectionTimeout(self):
        expectedException = IOError if PY_VERSION == "2.7" else URLError
        self.ms = MockServer(port=PortNumberGenerator.next(), hangupConnectionTimeout=0.1)
        self.ms.start()

        t0 = time()
        self.assertRaises(expectedException, lambda: urlopen(self.ms.myUrl).read())
        t1 = time()
        delta = t1 - t0
        self.assertTrue(0.09 < delta < 0.12, "Expected around 0.1, was %s" % delta)
        self.assertEquals(0, len(self.ms.requests))
    def setUp(self):
        super(HttpClientTest, self).setUp()
        self.port = randint(50000, 60000)
        self.server = MockServer(port=self.port)
        self.requests = []
        _buildResponse = self.server.buildResponse

        def buildResponse(**kwargs):
            self.requests.append(kwargs)
            return _buildResponse(**kwargs)

        self.server.buildResponse = buildResponse
        self.server.response = RESULT_HEADER + CRLF * 2 + RESULT_JSON
        self.server.start()
Example #7
0
class MockServerTest(TestCase):
    def setUp(self):
        TestCase.setUp(self)
        self.ms = MockServer(port=PortNumberGenerator.next())

    def testResponse(self):
        self.ms.response = 'HTTP/1.0 200 OK\r\n\r\nRe-Sponsed.'
        self.ms.start()

        self.assertEqual([], self.ms.requests)
        self.assertEqual(b'Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEqual(b'Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEqual(2, len(self.ms.requests))
        self.assertTrue(b'User-Agent: Python-urllib' in self.ms.requests[0], self.ms.requests[0])
        self.assertTrue(b'GET / HTTP/1.1\r\n' in self.ms.requests[0], self.ms.requests[0])

    def testResponses(self):
        self.ms.responses = ['HTTP/1.0 200 OK\r\n\r\nRe-Sponsed.', 'HTTP/1.0 200 OK\r\n\r\nAnother-Sponsed.']
        self.ms.start()

        self.assertEqual(b'Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEqual(b'Another-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertRaises(HTTPError, lambda: urlopen(self.ms.myUrl).read())
        self.assertEqual(3, len(self.ms.requests))

    def testHangupConnectionTimeout(self):
        expectedException = IOError
        self.ms.socket.close()
        self.ms = MockServer(port=PortNumberGenerator.next(), hangupConnectionTimeout=0.1)
        self.ms.start()

        t0 = time()
        self.assertRaises(expectedException, lambda: urlopen(self.ms.myUrl).read())
        t1 = time()
        delta = t1 - t0
        self.assertTrue(0.09 < delta < 0.12, "Expected around 0.1, was %s" % delta)
        self.assertEqual(0, len(self.ms.requests))

    def tearDown(self):
        self.ms.halt = True
        TestCase.tearDown(self)
Example #8
0
class MockServerTest(TestCase):
    def setUp(self):
        TestCase.setUp(self)
        self.ms = MockServer(port=PortNumberGenerator.next())

    def testResponse(self):
        self.ms.response = 'HTTP/1.0 200 OK\r\n\r\nRe-Sponsed.'
        self.ms.start()

        self.assertEquals([], self.ms.requests)
        self.assertEquals('Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEquals('Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEquals(2, len(self.ms.requests))
        self.assertTrue('User-Agent: Python-urllib' in self.ms.requests[0], self.ms.requests[0])
        self.assertTrue('GET / HTTP/1.1\r\n' in self.ms.requests[0], self.ms.requests[0])

    def testResponses(self):
        self.ms.responses = ['HTTP/1.0 200 OK\r\n\r\nRe-Sponsed.', 'HTTP/1.0 200 OK\r\n\r\nAnother-Sponsed.']
        self.ms.start()

        self.assertEquals('Re-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertEquals('Another-Sponsed.', urlopen(self.ms.myUrl).read())
        self.assertRaises(HTTPError, lambda: urlopen(self.ms.myUrl).read())
        self.assertEquals(3, len(self.ms.requests))

    def testHangupConnectionTimeout(self):
        expectedException = IOError if PY_VERSION == "2.7" else URLError
        self.ms = MockServer(port=PortNumberGenerator.next(), hangupConnectionTimeout=0.1)
        self.ms.start()

        t0 = time()
        self.assertRaises(expectedException, lambda: urlopen(self.ms.myUrl).read())
        t1 = time()
        delta = t1 - t0
        self.assertTrue(0.09 < delta < 0.12, "Expected around 0.1, was %s" % delta)
        self.assertEquals(0, len(self.ms.requests))

    def tearDown(self):
        self.ms.halt = True
        TestCase.tearDown(self)
Example #9
0
 def __init__(self, port):
     MockServer.__init__(self, port)
     self.configUpdate = {}
Example #10
0
 def setUp(self):
     TestCase.setUp(self)
     self.ms = MockServer(port=PortNumberGenerator.next())
Example #11
0
 def setUp(self):
     TestCase.setUp(self)
     self.ms = MockServer(port=PortNumberGenerator.next())