예제 #1
0
class VerifyTest(TestCase):
    def setUp(self):
        self.server = StubServer(8998)

    def test_verify_checks_all_expectations(self):
        satisfied_expectation = self._MockExpectation(True)
        unsatisfied_expectation = self._MockExpectation(False)
        self.server._expectations = [
            satisfied_expectation, unsatisfied_expectation,
            satisfied_expectation
        ]

        self.assertRaises(Exception, self.server.verify)

    def test_verify_clears_all_expectations(self):
        satisfied_expectation = self._MockExpectation(True)
        self.server._expectations = [
            satisfied_expectation, satisfied_expectation, satisfied_expectation
        ]

        self.server.verify()

        self.assertEqual([], self.server._expectations)

    class _MockExpectation(object):
        def __init__(self, satisfied):
            self.satisfied = satisfied
예제 #2
0
class VerifyTest(TestCase):
    def setUp(self):
        self.server = StubServer(8998)

    def test_verify_checks_all_expectations(self):
        satisfied_expectation = self._MockExpectation(True)
        unsatisfied_expectation = self._MockExpectation(False)
        self.server._expectations = [
            satisfied_expectation,
            unsatisfied_expectation,
            satisfied_expectation
        ]

        self.assertRaises(Exception, self.server.verify)

    def test_verify_clears_all_expectations(self):
        satisfied_expectation = self._MockExpectation(True)
        self.server._expectations = [
            satisfied_expectation,
            satisfied_expectation,
            satisfied_expectation
        ]

        self.server.verify()

        self.assertEqual([], self.server._expectations)

    class _MockExpectation(object):
        def __init__(self, satisfied):
            self.satisfied = satisfied
예제 #3
0
class FunctionalTest(unittest.TestCase):
    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()
        
    def tearDown(self):
        self.server.stop()
        self.server.verify()
        
    def test_get_with_file_call(self):
        self.server.expect(method="GET", url="/address/\w+$").and_return(mime_type="text/xml", content="<address><number>12</number><street>Early Drive</street><city>Calgary</city></address>")
        address = Address.objects.get(city="Calgary")
        self.assertEquals("Early Drive", address.street)
예제 #4
0
class MyTestCase(unittest.TestCase):
    def setUp(self) -> None:
        SampleData.objects.create(id_name="id", mark_result=False).save()
        self.server = StubServer(8000)
        self.server.run()

    def tearDown(self) -> None:
        SampleData.objects.all().delete()
        self.server.stop()

    def test_mark_sample(self):
        request = HttpRequest()
        request.GET = QueryDict(query_string="sampleId=id", mutable=True)
        value = mark_sample(request)
        self.assertEqual(value.getvalue(),
                         b'{"id": "id", "mark_result": true}')

    @patch('domain.rootcause.algorithm.analysis')
    def test_mock_analysis(self, mock_analysis):
        self.server.expect(method="GET", url="/").and_return(content="id2")
        mock_analysis.return_value = True
        request = HttpRequest()
        request._body = '{"id": "id2"}'
        value = create_sample(request)
        self.assertEqual(value.getvalue(),
                         b'{"id": "id2", "mark_result": false}')
예제 #5
0
class FunctionalTest(unittest.TestCase):
    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()

    def tearDown(self):
        self.server.stop()
        self.server.verify()

    def test_get_with_file_call(self):
        self.server.expect(method="GET", url="/address/\w+$").and_return(
            mime_type="text/xml",
            content=
            "<address><number>12</number><street>Early Drive</street><city>Calgary</city></address>"
        )
        address = Address.objects.get(city="Calgary")
        self.assertEqual("Early Drive", address.street)
예제 #6
0
 def setUp(self):
     self.server = StubServer(8998)
예제 #7
0
class WebTest(TestCase):
    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()

    def tearDown(self):
        self.server.stop()
        self.server.verify()  # this is redundant because stop includes verify

    def _make_request(self, url, method="GET", payload=None, headers={}):
        self.opener = OpenerDirector()
        self.opener.add_handler(HTTPHandler())
        if payload is None:
            request = Request(url, headers=headers)
        else:
            request = Request(url, headers=headers, data=payload.encode('utf-8'))
        request.get_method = lambda: method
        response = self.opener.open(request)
        response_code = getattr(response, 'code', -1)
        return (response, response_code)

    def test_get_with_file_call(self):
        with open('data.txt', 'w') as f:
            f.write("test file")
        self.server.expect(method="GET", url="/address/\d+$").and_return(mime_type="text/xml", file_content="./data.txt")
        response, response_code = self._make_request("http://localhost:8998/address/25", method="GET")
        with open("./data.txt", "r") as f:
            expected = f.read().encode('utf-8')
        try:
            self.assertEqual(expected, response.read())
        finally:
            response.close()

    def test_put_with_capture(self):
        capture = {}
        self.server.expect(method="PUT", url="/address/\d+$", data_capture=capture).and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/address/45", method="PUT", payload=str({"hello": "world", "hi": "mum"}))
        try:
            self.assertEqual(b"", f.read())
            captured = eval(capture["body"])
            self.assertEqual("world", captured["hello"])
            self.assertEqual("mum", captured["hi"])
            self.assertEqual(201, reply_code)
        finally:
            f.close()

    def test_post_with_wrong_data(self):
        self.server.expect(method="POST", url="data/", data='Bob').and_return()
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='Chris')
        self.assertEqual(403, reply_code)
        self.assertRaises(Exception, self.server.stop)

    def test_post_with_multiple_expectations_wrong_data(self):
        self.server.expect(method="POST", url="data/", data='Bob').and_return(reply_code=201)
        self.server.expect(method="POST", url="data/", data='John').and_return(reply_code=202)
        self.server.expect(method="POST", url="data/", data='Dave').and_return(reply_code=203)
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='Dave')
        self.assertEqual(203, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='Bob')
        self.assertEqual(201, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='Chris')
        self.assertEqual(403, reply_code)
        self.assertRaises(Exception, self.server.stop)

    def test_post_with_mixed_expectations(self):
        self.server.expect(method="POST", url="data/").and_return(reply_code=202)
        self.server.expect(method="POST", url="data/", data='John').and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='John')
        self.assertEqual(201, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/", method="POST", payload='Dave')
        self.assertEqual(202, reply_code)

    def test_post_with_data_and_no_body_response(self):
        self.server.expect(method="POST", url="address/\d+/inhabitant", data='<inhabitant name="Chris"/>').and_return(reply_code=204)
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="POST", payload='<inhabitant name="Chris"/>')
        self.assertEqual(204, reply_code)

    def test_multiple_expectations_identifies_correct_unmatched_request(self):
        self.server.expect(method="POST", url="address/\d+/inhabitant", data='Twas brillig and the slithy toves').and_return(reply_code=204)
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="POST", payload='Twas brillig and the slithy toves')
        self.assertEqual(204, reply_code)
        self.server.expect(method="GET", url="/monitor/server_status$").and_return(content="Four score and seven years ago", mime_type="text/html")
        try:
            self.server.stop()
        except Exception as e:
            self.assertEqual(-1, str(e).find('brillig'), str(e))

    def test_get_with_data(self):
        self.server.expect(method="GET", url="/monitor/server_status$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/monitor/server_status", method="GET")
        try:
            self.assertTrue(b"Server is up" in f.read())
            self.assertEqual(200, reply_code)
        finally:
            f.close()

    def test_get_from_root(self):
        self.server.expect(method="GET", url="/$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/", method="GET")
        try:
            self.assertTrue(b"Server is up" in f.read())
            self.assertEqual(200, reply_code)
        finally:
            f.close()

    def test_put_when_post_expected(self):
        # set expectations
        self.server.expect(method="POST", url="address/\d+/inhabitant", data='<inhabitant name="Chris"/>').and_return(
            reply_code=204)

        # try a different method
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="PUT",
                                           payload='<inhabitant name="Chris"/>')

        # Validate the response
        self.assertEqual("Method not allowed", f.msg)
        self.assertEqual(405, reply_code)
        self.assertTrue(f.read().startswith(b"Method PUT not allowed."))

        # And we have an unmet expectation which needs to mention the POST that didn't happen
        try:
            self.server.stop()
        except Exception as e:
            self.assertTrue(str(e).find("POST") > 0, str(e))

    def test_unexpected_get(self):
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="GET")
        self.assertEqual(404, reply_code)
        self.server.stop()

    def test_repeated_get(self):
        self.server.expect(method="GET", url="counter$").and_return(content="1")
        self.server.expect(method="GET", url="counter$").and_return(content="2")
        self.server.expect(method="GET", url="counter$").and_return(content="3")

        for i in range(1, 4):
            f, reply_code = self._make_request("http://localhost:8998/counter", method="GET")
            self.assertEqual(200, reply_code)
            self.assertEqual(str(i).encode('utf-8'), f.read())

    def test_extra_get(self):
        self.server.expect(method="GET", url="counter$").and_return(content="1")
        f, reply_code = self._make_request("http://localhost:8998/counter", method="GET")
        self.assertEqual(200, reply_code)
        self.assertEqual(b"1", f.read())

        f, reply_code = self._make_request("http://localhost:8998/counter", method="GET")
        self.assertEqual(400, reply_code)
        self.assertEqual("Expectations exhausted",f.msg)
        self.assertTrue(f.read().startswith(b"Expectations at this URL have already been satisfied.\n"))

    def test_returns_additional_headers_for_expectation_without_data(self):
        self.server.expect(method="GET", url="/api/endpoint").and_return(
            headers=(("some_header", "foo"), ("some_other_header", "bar"),))

        r = requests.get("http://localhost:8998/api/endpoint")

        self.assertEqual(r.headers["some_header"], "foo")
        self.assertEqual(r.headers["some_other_header"], "bar")

    def test_returns_additional_headers_for_expectation_with_data(self):
        self.server.expect(method="POST", url="/api/endpoint", data="expected data").and_return(
            headers=(("some_header", "foo"), ("some_other_header", "bar"),))

        r = requests.post("http://localhost:8998/api/endpoint", data="expected data")

        self.assertEqual(r.headers["some_header"], "foo")
        self.assertEqual(r.headers["some_other_header"], "bar")
예제 #8
0
class WebTest(TestCase):
    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()

    def tearDown(self):
        self.server.stop()
        self.server.verify()

    def _make_request(self, url, method="GET", payload="", headers={}):
        self.opener = urllib2.OpenerDirector()
        self.opener.add_handler(urllib2.HTTPHandler())
        request = urllib2.Request(url, headers=headers, data=payload)
        request.get_method = lambda: method
        response = self.opener.open(request)
        response_code = getattr(response, 'code', -1)
        return (response, response_code)

    def test_get_with_file_call(self):
        f = open('data.txt', 'w')
        f.write("test file")
        f.close()
        self.server.expect(method="GET", url="/address/\d+$").and_return(mime_type="text/xml", file_content="./data.txt")
        response, response_code = self._make_request("http://localhost:8998/address/25", method="GET")
        expected = open("./data.txt", "r").read()
        try:
            self.assertEquals(expected, response.read())
        finally:
            response.close()

    def test_put_with_capture(self):
        capture = {}
        self.server.expect(method="PUT", url="/address/\d+$", data_capture=capture).and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/address/45", method="PUT", payload=str({"hello": "world", "hi": "mum"}))
        try:
            self.assertEquals("", f.read())
            captured = eval(capture["body"])
            self.assertEquals("world", captured["hello"])
            self.assertEquals("mum", captured["hi"])
            self.assertEquals(201, reply_code)
        finally:
            f.close()

    def test_post_with_data_and_no_body_response(self):
        self.server.expect(method="POST", url="address/\d+/inhabitant", data='<inhabitant name="Chris"/>').and_return(reply_code=204)
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="POST", payload='<inhabitant name="Chris"/>')
        self.assertEquals(204, reply_code)

    def test_get_with_data(self):
        self.server.expect(method="GET", url="/monitor/server_status$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/monitor/server_status", method="GET")
        try:
            self.assertTrue("Server is up" in f.read())
            self.assertEquals(200, reply_code)
        finally:
            f.close()

    def test_get_from_root(self):
        self.server.expect(method="GET", url="/$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/", method="GET")
        try:
            self.assertTrue("Server is up" in f.read())
            self.assertEquals(200, reply_code)
        finally:
            f.close()
예제 #9
0
 def setUp(self):
     self.server = StubServer(urlparse(test_url).port)
     self.server.run()
예제 #10
0
class FusionTest(TestCase):
    def setUp(self):
        self.server = StubServer(urlparse(test_url).port)
        self.server.run()

    def tearDown(self):
        self.server.stop()

    def test_ping_virgin(self):
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_virgin_response.json")
        f = Fusion(**fa)
        self.assertFalse(f.ping())

    def test_ping_established(self):
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_established_response.json")
        f = Fusion(**fa)
        self.assertTrue(f.ping())

    def test_set_admin_pw_bad_pw(self):
        #        HTTP/1.1 400 Bad Request
        #        {"code":"invalid-password"}
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='POST',
                           url='/api$',
                           data=json.dumps(
                               {"password": "******"})).and_return(
                                   reply_code=400,
                                   content='{"code":"invalid-password"}')

        f = Fusion(**fa)
        try:
            f.set_admin_password("top_secret")
            self.fail("Should have had an exception")
        except fusionpy.FusionError as fe:
            self.assertTrue(fe.response.status == 400)

    def test_Set_admin_pw_again(self):
        #          HTTP/1.1 409 Conflict
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='POST',
                           url='/api$',
                           data=json.dumps({"password": "******"
                                            })).and_return(reply_code=409)

        f = Fusion(**fa)
        try:
            f.set_admin_password()
            self.fail("Should have had an exception")
        except fusionpy.FusionError as fe:
            self.assertEqual(409, fe.response.status)

    def test_set_admin_pw(self):
        #        HTTP/1.1 201 Created
        #        (no content)
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='POST',
                           url='/api$',
                           data=json.dumps({"password": "******"
                                            })).and_return(reply_code=201)
        self.server.expect(method='GET', url='/api$').and_return(
            mime_type="application/json",
            file_content=test_path + "Fusion_ping_established_response.json")
        f = Fusion(**fa)
        f.set_admin_password()
        f.ping()

    def test_get_index_pipelines(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        for i in range(0, 2):
            self.server.expect(method='GET', url='/api/apollo/index-pipelines$'). \
                and_return(mime_type="application/json",
                           file_content=test_path + "some_index_pipelines.json")
        f = Fusion(**fa)
        pipelines = f.index_pipelines.get_pipelines(include_system=False)

        # This reference pipeline file may change, so this test could assert that certain pipelines are present
        # and even go so far as to dissect them, but this is not a test of json.loads().
        self.assertTrue(len(pipelines) > 8)
        pmap = {}
        for p in pipelines:
            pmap[p['id']] = p['stages']

        self.assertEqual(len(pipelines), len(pmap))

        allpipelines = f.index_pipelines.get_pipelines(include_system=True)

        self.assertTrue(len(allpipelines) > len(pipelines))

    def test_get_query_pipelines(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        for i in range(0, 2):
            self.server.expect(method='GET', url='/api/apollo/query-pipelines$'). \
                and_return(mime_type="application/json",
                           file_content=test_path + "some_query_pipelines.json")
        f = Fusion(**fa)
        pipelines = f.query_pipelines.get_pipelines(include_system=False)

        # This reference pipeline file may change, so this test could assert that certain pipelines are present
        # and even go so far as to dissect them, but this is not a test of json.loads().
        self.assertTrue(len(pipelines) > 7, len(pipelines))
        pmap = {}
        for p in pipelines:
            pmap[p['id']] = p['stages']

        self.assertEqual(len(pipelines), len(pmap))

        allpipelines = f.query_pipelines.get_pipelines(include_system=True)

        self.assertTrue(len(allpipelines) > len(pipelines))

    def test_get_collection_stats(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(
            method='GET', url='/api/apollo/collections/phi/stats$').and_return(
                file_content=test_path + "phi-stats.json")
        with open(test_path + "phi-stats.json") as f:
            json_stats = json.loads(f.read())

        self.assertEquals(json_stats, Fusion(**fa).get_collection().stats())

    def test_get_collections(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='GET', url='/api/apollo/collections/$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "list_of_collections.json")
        self.server.expect(method='GET', url='/api/apollo/collections/$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "list_of_collections.json")
        f = Fusion(**fa)
        c = f.get_collections()
        self.assertEquals(['solutiondupes'], c)

        c = f.get_collections(include_system=True)
        self.assertEquals([
            "system_metrics", "system_blobs", "solutiondupes",
            "system_messages", "logs", "audit_logs"
        ], c)

    def test_create_query_pipeline(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(
            method='POST', url='/api/apollo/query-pipelines/$').and_return(
                file_content=test_path + "create-pipeline-response.json")

        with open(test_path + "create-pipeline-response.json") as f:
            qp = json.loads(f.read())

        Fusion(**fa).query_pipelines.add_pipeline(qp)
예제 #11
0
 def setUp(self):
     self.server = StubServer(8998)
예제 #12
0
class WebTest(TestCase):
    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()

    def tearDown(self):
        self.server.stop()
        self.server.verify()  # this is redundant because stop includes verify

    def _make_request(self, url, method="GET", payload=None, headers={}):
        self.opener = OpenerDirector()
        self.opener.add_handler(HTTPHandler())
        if payload is None:
            request = Request(url, headers=headers)
        else:
            request = Request(url,
                              headers=headers,
                              data=payload.encode('utf-8'))
        request.get_method = lambda: method
        response = self.opener.open(request)
        response_code = getattr(response, 'code', -1)
        return (response, response_code)

    def test_get_with_file_call(self):
        with open('data.txt', 'w') as f:
            f.write("test file")
        self.server.expect(method="GET", url="/address/\d+$").and_return(
            mime_type="text/xml", file_content="./data.txt")
        response, response_code = self._make_request(
            "http://localhost:8998/address/25", method="GET")
        with open("./data.txt", "r") as f:
            expected = f.read().encode('utf-8')
        try:
            self.assertEqual(expected, response.read())
        finally:
            response.close()

    def test_put_with_capture(self):
        capture = {}
        self.server.expect(method="PUT",
                           url="/address/\d+$",
                           data_capture=capture).and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/address/45",
                                           method="PUT",
                                           payload=str({
                                               "hello": "world",
                                               "hi": "mum"
                                           }))
        try:
            self.assertEqual(b"", f.read())
            captured = eval(capture["body"])
            self.assertEqual("world", captured["hello"])
            self.assertEqual("mum", captured["hi"])
            self.assertEqual(201, reply_code)
        finally:
            f.close()

    def test_post_with_wrong_data(self):
        self.server.expect(method="POST", url="data/", data='Bob').and_return()
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='Chris')
        self.assertEqual(403, reply_code)
        self.assertRaises(Exception, self.server.stop)

    def test_post_with_multiple_expectations_wrong_data(self):
        self.server.expect(method="POST", url="data/",
                           data='Bob').and_return(reply_code=201)
        self.server.expect(method="POST", url="data/",
                           data='John').and_return(reply_code=202)
        self.server.expect(method="POST", url="data/",
                           data='Dave').and_return(reply_code=203)
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='Dave')
        self.assertEqual(203, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='Bob')
        self.assertEqual(201, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='Chris')
        self.assertEqual(403, reply_code)
        self.assertRaises(Exception, self.server.stop)

    def test_post_with_mixed_expectations(self):
        self.server.expect(method="POST",
                           url="data/").and_return(reply_code=202)
        self.server.expect(method="POST", url="data/",
                           data='John').and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='John')
        self.assertEqual(201, reply_code)
        f, reply_code = self._make_request("http://localhost:8998/data/",
                                           method="POST",
                                           payload='Dave')
        self.assertEqual(202, reply_code)

    def test_post_with_data_and_no_body_response(self):
        self.server.expect(
            method="POST",
            url="address/\d+/inhabitant",
            data='<inhabitant name="Chris"/>').and_return(reply_code=204)
        f, reply_code = self._make_request(
            "http://localhost:8998/address/45/inhabitant",
            method="POST",
            payload='<inhabitant name="Chris"/>')
        self.assertEqual(204, reply_code)

    def test_multiple_expectations_identifies_correct_unmatched_request(self):
        self.server.expect(
            method="POST",
            url="address/\d+/inhabitant",
            data='Twas brillig and the slithy toves').and_return(
                reply_code=204)
        f, reply_code = self._make_request(
            "http://localhost:8998/address/45/inhabitant",
            method="POST",
            payload='Twas brillig and the slithy toves')
        self.assertEqual(204, reply_code)
        self.server.expect(method="GET",
                           url="/monitor/server_status$").and_return(
                               content="Four score and seven years ago",
                               mime_type="text/html")
        try:
            self.server.stop()
        except Exception as e:
            self.assertEqual(-1, str(e).find('brillig'), str(e))

    def test_get_with_data(self):
        self.server.expect(
            method="GET", url="/monitor/server_status$").and_return(
                content="<html><body>Server is up</body></html>",
                mime_type="text/html")
        f, reply_code = self._make_request(
            "http://localhost:8998/monitor/server_status", method="GET")
        try:
            self.assertTrue(b"Server is up" in f.read())
            self.assertEqual(200, reply_code)
        finally:
            f.close()

    def test_get_from_root(self):
        self.server.expect(method="GET", url="/$").and_return(
            content="<html><body>Server is up</body></html>",
            mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/",
                                           method="GET")
        try:
            self.assertTrue(b"Server is up" in f.read())
            self.assertEqual(200, reply_code)
        finally:
            f.close()

    def test_put_when_post_expected(self):
        # set expectations
        self.server.expect(
            method="POST",
            url="address/\d+/inhabitant",
            data='<inhabitant name="Chris"/>').and_return(reply_code=204)

        # try a different method
        f, reply_code = self._make_request(
            "http://localhost:8998/address/45/inhabitant",
            method="PUT",
            payload='<inhabitant name="Chris"/>')

        # Validate the response
        self.assertEqual("Method not allowed", f.msg)
        self.assertEqual(405, reply_code)
        self.assertTrue(f.read().startswith(b"Method PUT not allowed."))

        # And we have an unmet expectation which needs to mention the POST that didn't happen
        try:
            self.server.stop()
        except Exception as e:
            self.assertTrue(str(e).find("POST") > 0, str(e))

    def test_unexpected_get(self):
        f, reply_code = self._make_request(
            "http://localhost:8998/address/45/inhabitant", method="GET")
        self.assertEqual(404, reply_code)
        self.server.stop()

    def test_repeated_get(self):
        self.server.expect(method="GET",
                           url="counter$").and_return(content="1")
        self.server.expect(method="GET",
                           url="counter$").and_return(content="2")
        self.server.expect(method="GET",
                           url="counter$").and_return(content="3")

        for i in range(1, 4):
            f, reply_code = self._make_request("http://localhost:8998/counter",
                                               method="GET")
            self.assertEqual(200, reply_code)
            self.assertEqual(str(i).encode('utf-8'), f.read())

    def test_extra_get(self):
        self.server.expect(method="GET",
                           url="counter$").and_return(content="1")
        f, reply_code = self._make_request("http://localhost:8998/counter",
                                           method="GET")
        self.assertEqual(200, reply_code)
        self.assertEqual(b"1", f.read())

        f, reply_code = self._make_request("http://localhost:8998/counter",
                                           method="GET")
        self.assertEqual(400, reply_code)
        self.assertEqual("Expectations exhausted", f.msg)
        self.assertTrue(f.read().startswith(
            b"Expectations at this URL have already been satisfied.\n"))
예제 #13
0
 def setUp(self) -> None:
     SampleData.objects.create(id_name="id", mark_result=False).save()
     self.server = StubServer(8000)
     self.server.run()
예제 #14
0
class WebTest(TestCase):

    def setUp(self):
        self.server = StubServer(8998)
        self.server.run()

    def tearDown(self):
        self.server.stop()
        self.server.verify()

    def _make_request(self, url, method="GET", payload="", headers={}):
        self.opener = urllib2.OpenerDirector()
        self.opener.add_handler(urllib2.HTTPHandler())
        request = urllib2.Request(url, headers=headers, data=payload)
        request.get_method = lambda: method
        response = self.opener.open(request)
        response_code = getattr(response, 'code', -1)
        return (response, response_code)

    def test_get_with_file_call(self):
        f = open('data.txt', 'w')
        f.write("test file")
        f.close()
        self.server.expect(method="GET", url="/address/\d+$").and_return(mime_type="text/xml", file_content="./data.txt")
        response, response_code = self._make_request("http://localhost:8998/address/25", method="GET")
        expected = open("./data.txt", "r").read()
        try:
            self.assertEquals(expected, response.read())
        finally:
            response.close()

    def test_put_with_capture(self):
        capture = {}
        self.server.expect(method="PUT", url="/address/\d+$", data_capture=capture).and_return(reply_code=201)
        f, reply_code = self._make_request("http://localhost:8998/address/45", method="PUT", payload=str({"hello": "world", "hi": "mum"}))
        try:
            self.assertEquals("", f.read())
            captured = eval(capture["body"])
            self.assertEquals("world", captured["hello"])
            self.assertEquals("mum", captured["hi"])
            self.assertEquals(201, reply_code)
        finally:
            f.close()

    def test_post_with_data_and_no_body_response(self):
        self.server.expect(method="POST", url="address/\d+/inhabitant", data='<inhabitant name="Chris"/>').and_return(reply_code=204)
        f, reply_code = self._make_request("http://localhost:8998/address/45/inhabitant", method="POST", payload='<inhabitant name="Chris"/>')
        self.assertEquals(204, reply_code)

    def test_get_with_data(self):
        self.server.expect(method="GET", url="/monitor/server_status$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/monitor/server_status", method="GET")
        try:
            self.assertTrue("Server is up" in f.read())
            self.assertEquals(200, reply_code)
        finally:
            f.close()
            
    def test_get_from_root(self):
        self.server.expect(method="GET", url="/$").and_return(content="<html><body>Server is up</body></html>", mime_type="text/html")
        f, reply_code = self._make_request("http://localhost:8998/", method="GET")
        try:
            self.assertTrue("Server is up" in f.read())
            self.assertEquals(200, reply_code)
        finally:
            f.close()
예제 #15
0
 def setUp(self):
     self.server = StubServer(urlparse(test_url).port)
     self.server.run()
예제 #16
0
class FusionTest(TestCase):
    def setUp(self):
        self.server = StubServer(urlparse(test_url).port)
        self.server.run()

    def tearDown(self):
        self.server.stop()

    def test_ping_virgin(self):
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_virgin_response.json")
        f = Fusion(**fa)
        self.assertFalse(f.ping())

    def test_ping_established(self):
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_established_response.json")
        f = Fusion(**fa)
        self.assertTrue(f.ping())

    def test_set_admin_pw_bad_pw(self):
        #        HTTP/1.1 400 Bad Request
        #        {"code":"invalid-password"}
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='POST', url='/api$', data=json.dumps({"password": "******"})).and_return(
            reply_code=400,
            content='{"code":"invalid-password"}')

        f = Fusion(**fa)
        try:
            f.set_admin_password("top_secret")
            self.fail("Should have had an exception")
        except fusionpy.FusionError as fe:
            self.assertTrue(fe.response.status == 400)

    def test_Set_admin_pw_again(self):
        #          HTTP/1.1 409 Conflict
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='POST', url='/api$', data=json.dumps({"password": "******"})).and_return(
            reply_code=409)

        f = Fusion(**fa)
        try:
            f.set_admin_password()
            self.fail("Should have had an exception")
        except fusionpy.FusionError as fe:
            self.assertEqual(409, fe.response.status)

    def test_set_admin_pw(self):
        #        HTTP/1.1 201 Created
        #        (no content)
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_virgin_response.json")
        self.server.expect(method='POST', url='/api$', data=json.dumps({"password": "******"})).and_return(
            reply_code=201)
        self.server.expect(method='GET', url='/api$').and_return(mime_type="application/json",
                                                                 file_content=test_path + "Fusion_ping_established_response.json")
        f = Fusion(**fa)
        f.set_admin_password()
        f.ping()

    def test_get_index_pipelines(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        for i in range(0, 2):
            self.server.expect(method='GET', url='/api/apollo/index-pipelines$'). \
                and_return(mime_type="application/json",
                           file_content=test_path + "some_index_pipelines.json")
        f = Fusion(**fa)
        pipelines = f.get_index_pipelines()

        # This reference pipeline file may change, so this test could assert that certain pipelines are present
        # and even go so far as to dissect them, but this is not a test of json.loads().
        self.assertTrue(len(pipelines) > 8)
        pmap = {}
        for p in pipelines:
            pmap[p['id']] = p['stages']

        self.assertEqual(len(pipelines), len(pmap))

        allpipelines = f.get_index_pipelines(include_system=True)

        self.assertTrue(len(allpipelines) > len(pipelines))

    def test_get_query_pipelines(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        for i in range(0, 2):
            self.server.expect(method='GET', url='/api/apollo/query-pipelines$'). \
                and_return(mime_type="application/json",
                           file_content=test_path + "some_query_pipelines.json")
        f = Fusion(**fa)
        pipelines = f.get_query_pipelines()

        # This reference pipeline file may change, so this test could assert that certain pipelines are present
        # and even go so far as to dissect them, but this is not a test of json.loads().
        self.assertTrue(len(pipelines) > 7, len(pipelines))
        pmap = {}
        for p in pipelines:
            pmap[p['id']] = p['stages']

        self.assertEqual(len(pipelines), len(pmap))

        allpipelines = f.get_query_pipelines(include_system=True)

        self.assertTrue(len(allpipelines) > len(pipelines))

    def test_get_collection_stats(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='GET', url='/api/apollo/collections/phi/stats$').and_return(
            file_content=test_path + "phi-stats.json")
        with open(test_path + "phi-stats.json") as f:
            json_stats = json.loads(f.read())

        self.assertEquals(json_stats, Fusion(**fa).get_collection().stats())

    def test_create_query_pipeline(self):
        self.server.expect(method='GET', url='/api$'). \
            and_return(mime_type="application/json",
                       file_content=test_path + "Fusion_ping_established_response.json")
        self.server.expect(method='POST', url='/api/apollo/query-pipelines/$').and_return(
            file_content=test_path + "create-pipeline-response.json")

        with open(test_path + "create-pipeline-response.json") as f:
            qp = json.loads(f.read())

        Fusion(**fa).add_query_pipeline(qp)