Example #1
1
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        view = flask_restful.Resource

        exception = Mock()
        exception.code = 404
        exception.data = {"status": 404, "message": "Not Found"}
        api.add_resource(view, "/foo", endpoint="bor")
        api.add_resource(view, "/fee", endpoint="bir")
        api.add_resource(view, "/fii", endpoint="ber")

        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(), dumps({"status": 404, "message": "Not Found"}))

        with app.test_request_context("/fOo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(
                resp.data.decode(),
                dumps(
                    {"status": 404, "message": "Not Found. You have requested this URI [/fOo] but did you mean /foo ?"}
                ),
            )

        with app.test_request_context("/fOo"):
            del exception.data["message"]
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(
                resp.data.decode(),
                dumps({"status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?"}),
            )
Example #2
1
    def test_handle_error_signal(self):
        if not signals_available:
            # This test requires the blinker lib to run.
            print("Can't test signals without signal support")
            return
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {"foo": "bar"}

        recorded = []

        def record(sender, exception):
            recorded.append(exception)

        got_request_exception.connect(record, app)
        try:
            with app.test_request_context("/foo"):
                api.handle_error(exception)
                self.assertEquals(len(recorded), 1)
                self.assertTrue(exception is recorded[0])
        finally:
            got_request_exception.disconnect(record, app)
Example #3
0
 def test_rpc_request(self):
     response = Mock()
     response.code = 200
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     result = yield self.client.foo()
     self.assertTrue(result)
Example #4
0
 def test_rpc_request_404(self):
     response = Mock()
     response.code = 404
     response.phrase = "Not found."
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     return self.assertFailure(self.client.foo(), HTTPError)
Example #5
0
    def setUp(self):
        self.vumi_helper = yield self.add_helper(VumiApiHelper())

        response = Mock()
        response.code = http.OK
        response.delivered_body = "javascript!"
        self.mocked_url_call = Mock(side_effect=[succeed(response), succeed(response)])

        self.patch(ConversationConfigResource, "load_source_from_url", self.mocked_url_call)

        self.config = self.vumi_helper.mk_config(
            {"worker_name": "conversation_api_worker", "web_path": "/foo/", "web_port": 0, "health_path": "/health/"}
        )
        self.worker = yield self.vumi_helper.get_worker_helper().get_worker(ConversationApiWorker, self.config)
        self.addr = self.worker.webserver.getHost()
        self.url = "http://%s:%s%s" % (self.addr.host, self.addr.port, self.config["web_path"])

        self.user_helper = yield self.vumi_helper.make_user(u"user")
        yield self.vumi_helper.setup_tagpool(u"pool", [u"tag1", u"tag2"])
        yield self.user_helper.add_tagpool_permission(u"pool")

        self.conversation = yield self.user_helper.create_conversation(
            u"jsbox",
            config={
                "jsbox_app_config": {"config": {"source_url": "http://configsourcecode/"}},
                "jsbox": {"source_url": "http://sourcecode/"},
                "http_api": {"api_tokens": ["token-1", "token-2", "token-3"], "metrics_store": "metrics_store"},
            },
        )

        self.auth_headers = {
            "Authorization": ["Basic " + base64.b64encode("%s:%s" % (self.user_helper.account_key, "token-1"))]
        }
Example #6
0
    def test_read_validate_params_token_expired(self):
        client_id = "abc"
        client_secret = "t%gH"
        code = "xyz"
        redirect_uri = "http://callback"

        auth_code_mock = Mock(AuthorizationCode)
        auth_code_mock.code = code
        auth_code_mock.redirect_uri = redirect_uri
        auth_code_mock.is_expired.return_value = True

        auth_code_store_mock = Mock(spec=AuthCodeStore)
        auth_code_store_mock.fetch_by_code.return_value = auth_code_mock

        client_mock = Mock(Client)
        client_mock.secret = client_secret
        client_mock.redirect_uris = [redirect_uri]

        client_store_mock = Mock(spec=ClientStore)
        client_store_mock.fetch_by_client_id.return_value = client_mock

        request_mock = Mock(spec=Request)
        request_mock.post_param.side_effect = [client_id, client_secret, code, redirect_uri]

        handler = AuthorizationCodeTokenHandler(
            Mock(spec=AccessTokenStore), auth_code_store_mock, client_store_mock, Mock()
        )

        with self.assertRaises(OAuthInvalidError) as expected:
            handler.read_validate_params(request_mock)

        error = expected.exception

        self.assertEqual(error.error, "invalid_grant")
        self.assertEqual(error.explanation, "Authorization code has expired")
Example #7
0
 def test_fetch_redirect_empty(self):
     client = HTTPClient("http://example.com")
     client.agent = Mock()
     client.followRedirect = True
     client.maxRedirects = 1
     _response1 = Mock()
     _response1.code = 302
     _response1.headers.getAllRawHeaders.return_value = {}
     _response1.deliverBody = lambda x: x.connectionLost(None)
     _response2 = Mock()
     _response2.code = 200
     _response2.headers.getAllRawHeaders.return_value = {}
     _response2.deliverBody = lambda x: x.connectionLost(None)
     client.agent.request.side_effect = [succeed(_response1), succeed(_response2)]
     response = yield client.fetch()
     self.assertEqual(response.body, "")
Example #8
0
def dummy_balance_code():
    m = Mock()
    m.pk = random.randint(1, 999)
    m.value = 100
    m.code = generate_balance_code()
    m.refill_series.pk = random.randint(1, 99)
    m.refill_series.least_valid_until = date.today()
    return m
Example #9
0
 def _create_mocked_response(self, code=200, notification="Received", subscription="Active", device="Connected"):
     response = Mock()
     response.code = code
     response.MOCKED_HEADERS = {
         "X-NotificationStatus": [notification],
         "X-SubscriptionStatus": [subscription],
         "X-DeviceConnectionStatus": [device],
     }
     response.headers.getRawHeaders = Mock(side_effect=lambda name: response.MOCKED_HEADERS.get(name))
     return response
Example #10
0
    def test_handle_error_401_sends_challege_default_realm(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        exception = Mock()
        exception.code = 401
        exception.data = {"foo": "bar"}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 401)
            self.assertEquals(resp.headers["WWW-Authenticate"], 'Basic realm="flask-restful"')
    def test_connect_while_connected(self, mock_endpoint):
        "should pass http request body to TwitterStreamingProtocol"
        mock_http_response = Mock()
        mock_http_response.code = 200
        mock_http_response.deliverBody = Mock()

        self._connect(mock_endpoint, mock_http_response)
        self.assertEquals(CONNECTED, self.stream.state)

        with self.assertRaises(ValueError):
            self.stream.track(TestReceiver(), ["track"])
Example #12
0
    def test_generate_key_module(self):
        """ Test that a key is generated for module functions """

        def test_func():
            pass

        stat = Mock()
        stat.code = test_func.__code__

        expected_key = "%s.%s" % (self.__module__, stat.code.co_name)
        key = linesman._generate_key(stat)
        assert_equals(key, expected_key)
    def test_successful_connection(self, mock_endpoint):
        "should pass http request body to TwitterStreamingProtocol"
        mock_http_response = Mock()
        mock_http_response.code = 200
        mock_http_response.deliverBody = Mock()

        d = self._connect(mock_endpoint, mock_http_response)

        self.assertEquals(CONNECTED, self.stream.state)
        self.assertTrue(mock_http_response.deliverBody.called)

        self.assertTrue(d.called)
Example #14
0
    def test_handle_error(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {"foo": "bar"}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 400)
            self.assertEquals(resp.data.decode(), dumps({"foo": "bar"}))
Example #15
0
    def test_generate_key_unknown(self):
        """ Test that unknown module functions return as strings """

        def test_func():
            pass

        stat = Mock()
        stat.code = test_func.__code__

        expected_key = "%s.%s" % (stat.code.co_filename, stat.code.co_name)
        key = linesman._generate_key(stat)
        assert_equals(key, expected_key)
Example #16
0
    def test_handle_auth(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 401
        exception.data = {"foo": "bar"}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 401)
            self.assertEquals(resp.data.decode(), dumps({"foo": "bar"}))

            self.assertTrue("WWW-Authenticate" in resp.headers)
Example #17
0
    def test_handle_produce_response_transport_error(self, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 599
        response.error = object()
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1

        self.producer._handle_produce_response("test_driver", response)

        self.client.mock_for("response_5xx").assert_called_once_with("test_driver", response)
        fake_retry.assert_has_calls([call("test_driver", m1), call("test_driver", m2)])
Example #18
0
    def test_handle_produce_response_on_200(self, fake_decode, fake_handle_success):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 200
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {"offsets": [{}, {}], "value_schema_id": 1, "key_schema_id": 2}
        fake_decode.return_value = body

        self.producer._handle_produce_response("test_driver", response)

        fake_handle_success.assert_called_once_with("test_driver", response, body)
Example #19
0
    def test_payment_multiple_fees(self, mock_get_organizer):
        mock_get_organizer.return_value = self.organizer
        m_currency = Mock()
        m_currency.code = "USD"
        amount = Decimal("100")

        ldgr_ids = user.payment_to_campaign(
            self.user,
            self.campaign,
            amount,
            self.currency,
            fees=(self.stripe_fee, self.poold_fee),
            full_name="Imalittle Teapot",
        )
        deposit_id, withdrawal_id = ldgr_ids

        user_txn = TransactionModel.query.filter_by(id=deposit_id).filter_by(balance_id=self.user_balance.id).first()
        dpt_ldgrs = (
            ExternalLedgerModel.query.filter_by(record_id=deposit_id)
            .filter_by(processor="stripe")
            .filter_by(fee_id=None)
            .first()
        )
        assert_equal(Decimal("100.0000"), user_txn.credit)
        assert_true(user_txn.debit is None)
        assert_equal(Decimal("106.3900"), dpt_ldgrs.credit)
        assert_true(dpt_ldgrs.debit is None)
        assert_equal("Imalittle Teapot", dpt_ldgrs.full_name)

        org_txn = (
            TransactionModel.query.filter_by(id=withdrawal_id).filter_by(balance_id=self.organizer_balance.id).first()
        )
        assert_equal(Decimal("100.0000"), org_txn.debit)
        assert_true(org_txn.credit is None)

        stripe_ldgr = (
            ExternalLedgerModel.query.filter_by(record_id=deposit_id).filter_by(fee_id=self.stripe_fee.id).first()
        )
        assert_equal(Decimal("3.3900"), stripe_ldgr.debit)
        assert_true(stripe_ldgr.credit is None)
        assert_true(stripe_ldgr.full_name is None)

        poold_ldgr = (
            ExternalLedgerModel.query.filter_by(record_id=deposit_id).filter_by(fee_id=self.poold_fee.id).first()
        )
        assert_equal(Decimal("3.0000"), poold_ldgr.debit)
        assert_true(poold_ldgr.credit is None)
        assert_true(poold_ldgr.full_name is None)
Example #20
0
    def test_fail_card(self, mock_get_organizer):
        exp = datetime.now() + timedelta(days=365)
        stripe_customer_id = _create_stripe_customer_for_card(
            self.FAIL_CARD_NUMBER, self.TEST_CARD_CVC, exp.month, exp.year, self.user
        )

        self.create_user_meta(self.user, stripe_customer_id=stripe_customer_id)

        mock_get_organizer.return_value = self.organizer
        m_currency = Mock()
        m_currency.code = "USD"
        m_campaign = Mock()
        m_campaign.id = randint(1, 999)
        amount = Decimal("100")

        user.payment_to_campaign(self.user, m_campaign, amount, m_currency, fees=(self.stripe_fee, self.poold_fee))
Example #21
0
 def make_response(self, response_attrs=None, request_attrs=None):
     response = Mock()
     request = Mock()
     response.code = 200
     response.error = None
     response.body = json.dumps({"offsets": [{}]})
     request._id = 1
     request._topic = "test_driver"
     request._batch = [Message("test_driver", self.test_value, None, None, 0, 1)]
     for k, v in (response_attrs or {}).items():
         if k == "body":
             v = json.dumps(v)
         setattr(response, k, v)
     for k, v in (request_attrs or {}).items():
         setattr(request, k, v)
     response.request = request
     return response
def test_handle_http_response():
    response = Mock(HTTPResponse)
    response.status = 200
    response.code = "OK"
    response.content_type = "text/html"
    response.content_length = 1234
    response.content = "<html><body>hi</body></html>"
    value = handle_http_response(response)

    content_array = [
        "HTTP/1.1 200 OK",
        "Content-Type: text/html",
        "Content-Length: 1234",
        "Server: Ocean/0.1.1",
        "",
        "<html><body>hi</body></html>",
    ]
    assert value == "\n".join(content_array)
Example #23
0
    def test_read_validate_params(self):
        client_id = "abc"
        client_secret = "t%gH"
        code = "defg"
        redirect_uri = "http://callback"
        scopes = ["scope"]

        auth_code = Mock(AuthorizationCode)
        auth_code.code = code
        auth_code.is_expired.return_value = False
        auth_code.redirect_uri = redirect_uri
        auth_code.scopes = scopes

        auth_code_store_mock = Mock(spec=AuthCodeStore)
        auth_code_store_mock.fetch_by_code.return_value = auth_code

        client_mock = Mock(Client)
        client_mock.secret = client_secret
        client_mock.redirect_uris = [redirect_uri]

        client_store_mock = Mock(spec=ClientStore)
        client_store_mock.fetch_by_client_id.return_value = client_mock

        request_mock = Mock(spec=Request)
        request_mock.post_param.side_effect = [client_id, client_secret, code, redirect_uri]

        handler = AuthorizationCodeTokenHandler(
            Mock(spec=AccessTokenStore), auth_code_store_mock, client_store_mock, Mock()
        )
        result = handler.read_validate_params(request_mock)

        request_mock.post_param.assert_has_calls(
            [call("client_id"), call("client_secret"), call("code"), call("redirect_uri")]
        )
        auth_code_store_mock.fetch_by_code.assert_called_with(code)
        self.assertEqual(handler.client_id, client_id)
        self.assertEqual(handler.client_secret, client_secret)
        self.assertEqual(handler.code, code)
        self.assertEqual(handler.redirect_uri, redirect_uri)
        self.assertEqual(handler.scopes, scopes)
        self.assertTrue(result)
Example #24
0
    def setUp(self):
        self.FORM_CODE = "QR1"
        self.VALUES = {"EID": "100", "Q1": "20"}

        self.dbm = Mock(spec=DatabaseManager)
        self.form_model_patcher = patch("mangrove.transport.submissions.get_form_model_by_code")
        self.form_submission_entity_patcher = patch("mangrove.form_model.form_model.entity")
        self.SubmissionLogger_class_patcher = patch("mangrove.transport.submissions.SubmissionLogger")

        self.get_form_model_mock = self.form_model_patcher.start()
        self.form_submission_entity_module = self.form_submission_entity_patcher.start()
        self.SubmissionLogger_mock_class = self.SubmissionLogger_class_patcher.start()
        self.submissionLogger = Mock(spec=SubmissionLogger)
        self.SubmissionLogger_mock_class.return_value = self.submissionLogger
        self.SUBMISSION_ID = "SUBMISSION_ID"
        self.submissionLogger.create_submission_log.return_value = self.SUBMISSION_ID

        self.form_model_mock = Mock(spec=FormModel)
        self.form_model_mock.is_registration_form.return_value = False
        self.form_model_mock.entity_defaults_to_reporter.return_value = False
        self.form_model_mock.is_inactive.return_value = False
        self.form_model_mock.is_in_test_mode.return_value = False
        self.ENTITY_TYPE = ["entity_type"]
        self.form_model_mock.entity_type = self.ENTITY_TYPE
        entity_question = Mock()
        entity_question.code = "eid"
        self.form_model_mock.entity_question = entity_question
        self.get_form_model_mock.return_value = self.form_model_mock
        self.sms = Channel.SMS

        reporter = Mock(spec=Entity)
        reporter.short_code.return_value = "REP1"
        self.submission_request = SubmissionRequest(
            form_code=self.FORM_CODE,
            submission=self.VALUES,
            transport=self.sms,
            source="1234",
            destination="5678",
            reporter=reporter,
        )
        self.submission_handler = SubmissionHandler(self.dbm)
Example #25
0
    def test_handle_produce_response_on_retriable(self, fake_decode, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 500
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {
            "offsets": [{}, {}],
            "value_schema_id": 1,
            "key_schema_id": 2,
            "error_code": 50001,
            "message": "Retriable",
        }
        fake_decode.return_value = body

        self.producer._handle_produce_response("test_driver", response)

        fake_retry.assert_has_calls([call("test_driver", m1), call("test_driver", m2)])
Example #26
0
    def test_route_to_busy_node_saves_looks_up_and_send_check_fails(self):
        import autopush.router.simple as simple

        response_mock = Mock()
        self.agent_mock.request.side_effect = MockAssist([response_mock, self._raise_connect_error])
        response_mock.code = 202
        self.storage_mock.save_notification.return_value = True
        router_data = dict(node_id="http://somewhere", uaid=dummy_uaid)
        self.router_mock.get_uaid.return_value = router_data

        d = self.router.route_notification(self.notif, router_data)

        def verify_deliver(result):
            ok_(isinstance(result, RouterResponse))
            eq_(result.status_code, 202)
            assert self.router_mock.clear_node.called
            nk = simple.node_key(router_data["node_id"])
            eq_(simple.dead_cache.get(nk), True)

        d.addBoth(verify_deliver)
        return d
Example #27
0
def get_team():
    team = Mock()
    team.code = get_string()
    team.name = get_string()
    return team
Example #28
0
def mock_resp(code=200, method="GET"):
    resp = Mock()
    resp.code = code
    resp.request.method = method
    return resp
Example #29
0
 def test_rpc_request_error1(self):
     response = Mock()
     response.code = 404
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = fail(HTTPError(404))
     return self.assertFailure(self.client.foo(), HTTPError)
Example #30
0
 def test_rpc_request_error_old(self):
     response = Mock()
     response.code = 200
     response.body = escape.json_encode({"error": "some error"})
     cyclone.httpclient.fetch.return_value = succeed(response)
     return self.assertFailure(self.client.foo(), Exception)