Example #1
0
    def test_process(self):
        access_token = "abcd"
        client_id = "efg"
        scopes = ["scope"]

        expected_body = {"access_token": access_token, "token_type": "Bearer"}

        access_token_store_mock = Mock(spec=AccessTokenStore)

        token_generator_mock = Mock(spec=["generate"])
        token_generator_mock.generate.return_value = access_token

        response_mock = Mock(spec=Response)
        response_mock.body = None
        response_mock.status_code = None

        handler = AuthorizationCodeTokenHandler(
            access_token_store_mock, Mock(spec=AuthCodeStore), Mock(spec=ClientStore), token_generator_mock
        )
        handler.client_id = client_id
        handler.scopes = scopes
        response = handler.process(Mock(spec=Request), response_mock, {})

        access_token, = access_token_store_mock.save_token.call_args[0]
        self.assertTrue(isinstance(access_token, AccessToken))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.body, json.dumps(expected_body))
        response_mock.add_header.assert_called_with("Content-type", "application/json")
Example #2
0
    def test_redirect_oauth_error(self):
        error_identifier = "eid"
        redirect_uri = "https://callback"

        expected_redirect = "%s?error=%s" % (redirect_uri, error_identifier)

        error_mock = Mock(spec=OAuthUserError)
        error_mock.error = error_identifier

        response_mock = Mock(spec=Response)

        handler = AuthorizationCodeAuthHandler(
            auth_token_store=Mock(),
            client_store=Mock(),
            scope_handler=Mock(),
            site_adapter=Mock(),
            token_generator=Mock(),
        )
        handler.redirect_uri = redirect_uri
        result = handler.redirect_oauth_error(error_mock, response_mock)

        response_mock.add_header.assert_called_with("Location", expected_redirect)
        response_mock.status_code = 302
        response_mock.body = ""
        self.assertEqual(result, response_mock)
    def test_respond_to_detection_response(self):
        sender = MagicMock()
        detect = MagicMock()
        detect.respond_to_detection_response = Mock(return_value="something_to_send")
        context = MagicMock()
        suggest = Mock()
        target = Target(sender, detect, context, suggest)
        target.json_decode = MagicMock(return_value="decode_detection_response")

        response = Mock()
        response.body = "response_body"

        handler = Mock()
        handler.context_id = "context_id_value"

        target.get_detect_callback(response, handler, "message_value")

        target.json_decode.assert_called_once_with("response_body")

        # context.post_context_message.assert_called_once_with("context_id_value", 1, "", dection="decode_detection_response")

        self.assertEqual(1, context.post_context_message.call_count)
        self.assertEqual("context_id_value", context.post_context_message.call_args_list[0][0][0])
        self.assertEqual(1, context.post_context_message.call_args_list[0][0][1])
        self.assertEqual("", context.post_context_message.call_args_list[0][0][2])
        self.assertEqual("decode_detection_response", context.post_context_message.call_args_list[0][1]["detection"])

        detect.respond_to_detection_response.assert_called_once_with(handler, "decode_detection_response")

        sender.write_jemboo_response_message.assert_called_once_with(handler, "something_to_send")
Example #4
0
    def test_call(self):
        body = "body"
        headers = {"header": "value"}
        path = "/authorize"
        status_code = 200
        http_code = "200 OK"

        environment = {"PATH_INFO": path, "myvar": "value"}

        request_mock = Mock(spec=Request)
        request_class_mock = Mock(return_value=request_mock)

        responseMock = Mock(spec=Response)
        responseMock.body = body
        responseMock.headers = headers
        responseMock.status_code = status_code

        server_mock = Mock(spec=Provider)
        server_mock.dispatch.return_value = responseMock

        start_response_mock = Mock()

        wsgi = Wsgi(server=server_mock, authorize_uri=path, request_class=request_class_mock, env_vars=["myvar"])
        result = wsgi(environment, start_response_mock)

        request_class_mock.assert_called_with(environment)
        server_mock.dispatch.assert_called_with(request_mock, {"myvar": "value"})
        start_response_mock.assert_called_with(http_code, headers.items())
        self.assertEqual(result, [body])
    def test_update_item_itemnotfound(self):
        """This test case covers scenario when we want to update an item which does not exist."""

        expected_body = {"name": "cool name", "description": "incredible simple description"}
        url = "/simple-resources"
        version = "1.0"
        resource_id = "12345"

        request = Mock()
        request.body = json.dumps(expected_body).encode()

        resource = Resource(name="Mock Simple Resource", url=url, version=float(version))
        resource(MockSimpleResourceRoa, self._resources_registry)

        pk_col = MockSimpleResourceRoa.id

        model = Mock()

        self._resources_registry.find_by_url = Mock(return_value=resource)
        self._json_serializer.deserialize = Mock(return_value=model)
        self._model_facade.find_by_pk = Mock(return_value=None)
        self._model_facade.model_pk_cols = [pk_col]

        response = self._controller.update_item(request, version, url, resource_id)

        self._assert_resource_error(response, 404, 10040, version, url)

        self._resources_registry.find_by_url.assert_called_once_with(url, float(version))
        self._model_facade.find_by_pk.assert_called_once_with({MockSimpleResourceRoa.id: resource_id})
        self._json_serializer_cls.assert_called_once_with(resource)
        self._json_serializer.deserialize.assert_called_once_with(json.dumps(expected_body))
    def test_regular(self):
        sender = MagicMock()
        detect = MagicMock()
        context = MagicMock()
        suggest = Mock()
        target = Target(sender, detect, context, suggest)
        target.json_decode = MagicMock(return_value={"_rev": "context_revision_value"})
        target.context_responder.unsupported_entities = MagicMock()

        response = Mock()
        response.body = "response_body_value"

        handler = MagicMock()
        handler.user_id = "user_id_value"
        handler.application_id = "application_id_value"
        handler.session_id = "session_id_value"
        handler.locale = "locale_value"

        target.get_context_callback(response, handler, "message_value")

        target.json_decode.assert_called_once_with("response_body_value")

        target.context_responder.unsupported_entities.assert_called_once_with(
            handler, {"_rev": "context_revision_value"}
        )

        self.assertEqual(1, suggest.post_suggest.call_count)
        self.assertEqual("user_id_value", suggest.post_suggest.call_args_list[0][0][0])
        self.assertEqual("application_id_value", suggest.post_suggest.call_args_list[0][0][1])
        self.assertEqual("session_id_value", suggest.post_suggest.call_args_list[0][0][2])
        self.assertEqual("locale_value", suggest.post_suggest.call_args_list[0][0][3])
        self.assertDictEqual({"_rev": "context_revision_value"}, suggest.post_suggest.call_args_list[0][0][4])
    def test_update_item_resource_invalid(self):
        """This test case ensures an item is not updated if it fails validation."""

        expected_body = {}

        url = "/simple-resources"
        version = "1.0"

        resource = Resource(
            name="Mock Simple Resource", url=url, version=float(version), validator=MockSimpleResourceValidator
        )
        resource(MockSimpleResourceRoa, self._resources_registry)

        resource_id = 1986

        request = Mock()
        request.body = json.dumps(expected_body).encode()

        self._resources_registry.find_by_url = Mock(return_value=resource)
        self._json_serializer.deserialize = Mock(return_value=MockSimpleResourceRoa())

        response = self._controller.update_item(request, version, url, resource_id)

        self._assert_resource_error(response, 400, 10010, version, url)

        self._resources_registry.find_by_url.assert_called_once_with(url, float(version))
        self._json_serializer.deserialize.assert_called_once_with(json.dumps(expected_body))
    def test_update_item_dbex(self):
        """This test case covers scenario when an item can not be updated because of a db exception."""

        expected_body = {"name": "cool name", "description": "incredible simple description"}
        url = "/simple-resources"
        version = "1.0"
        resource_id = "12345"

        request = Mock()
        request.body = json.dumps(expected_body).encode()

        resource = Resource(name="Mock Simple Resource", url=url, version=float(version))
        resource(MockSimpleResourceRoa, self._resources_registry)

        pk_col = Mock()
        pk_col.name = "id"

        model = Mock()

        self._resources_registry.find_by_url = Mock(return_value=resource)
        self._json_serializer.deserialize = Mock(return_value=model)
        self._model_facade.update = Mock(side_effect=FantasticoDbError("Unexpected exception"))
        self._model_facade.model_pk_cols = [pk_col]

        response = self._controller.update_item(request, version, url, resource_id)

        self._assert_resource_error(response, 400, 10030, version, url)

        self.assertEqual(resource_id, model.id)

        self._resources_registry.find_by_url.assert_called_once_with(url, float(version))
        self._json_serializer_cls.assert_called_once_with(resource)
        self._json_serializer.deserialize.assert_called_once_with(json.dumps(expected_body))
    def test_create_item_invalidresource(self):
        """This test case ensures an item can not be created if it's invalid."""

        resource = Resource(
            name="Mock Simple Resource",
            url="/mock-simple-resources",
            version=1.0,
            validator=MockSimpleResourceValidator,
        )
        resource(MockSimpleResourceRoa, self._resources_registry)

        request_body = {"description": "Simple resource description."}

        request = Mock()
        request.body = json.dumps(request_body).encode()

        self._resources_registry.find_by_url = Mock(return_value=resource)
        self._json_serializer.deserialize = Mock(
            return_value=MockSimpleResourceRoa(description=request_body.get("description"))
        )

        response = self._controller.create_item(request, version=str(resource.version), resource_url=resource.url)

        self._assert_resource_error(response, 400, 10010, str(resource.version), resource.url)

        self._resources_registry.find_by_url.assert_called_once_with(resource.url, resource.version)
        self._json_serializer.deserialize.assert_called_once_with(request.body.decode())
    def test_create_item_dbexception(self):
        """This test case ensures an error response is received if an unexpected db error occurs when creating the resource."""

        resource = Resource(name="Mock Simple Resource", url="/mock-simple-resources", version=1.0)
        resource(MockSimpleResourceRoa, self._resources_registry)

        request_body = {"name": "simple-resource1", "description": "Simple resource description."}

        expected_model = MockSimpleResourceRoa(
            name=request_body.get("name"), description=request_body.get("description")
        )

        request = Mock()
        request.body = json.dumps(request_body).encode()

        self._resources_registry.find_by_url = Mock(return_value=resource)
        self._json_serializer.deserialize = Mock(return_value=expected_model)
        self._model_facade.create = Mock(side_effect=FantasticoDbError("Unexpected db error."))

        response = self._controller.create_item_latest(request, resource.url)

        self._assert_resource_error(response, 400, 10030, str(resource.version), resource.url)

        self._resources_registry.find_by_url.assert_called_once_with(resource.url, "latest")
        self._json_serializer.deserialize.assert_called_once_with(request.body.decode())
        self._model_facade.create.assert_called_once_with(expected_model)
Example #11
0
    def get_signed_grade_mock_request_with_correct_signature(self):
        """
        Generate a proper LTI request object
        """
        mock_request = Mock()
        mock_request.headers = {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": (
                u'OAuth realm="https://testurl/", oauth_body_hash="wwzA3s8gScKD1VpJ7jMt9b%2BMj9Q%3D",'
                'oauth_nonce="18821463", oauth_timestamp="1409321145", '
                'oauth_consumer_key="__consumer_key__", oauth_signature_method="HMAC-SHA1", '
                'oauth_version="1.0", oauth_signature="fHsE1hhIz76/msUoMR3Lyb7Aou4%3D"'
            ),
        }
        mock_request.url = u"https://testurl"
        mock_request.http_method = u"POST"
        mock_request.method = mock_request.http_method

        mock_request.body = (
            "<?xml version='1.0' encoding='utf-8'?>\n"
            '<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">'
            "<imsx_POXHeader><imsx_POXRequestHeaderInfo><imsx_version>V1.0</imsx_version>"
            "<imsx_messageIdentifier>edX_fix</imsx_messageIdentifier></imsx_POXRequestHeaderInfo>"
            "</imsx_POXHeader><imsx_POXBody><replaceResultRequest><resultRecord><sourcedGUID>"
            "<sourcedId>MITxLTI/MITxLTI/201x:localhost%3A8000-i4x-MITxLTI-MITxLTI-lti-3751833a214a4f66a0d18f63234207f2:363979ef768ca171b50f9d1bfb322131</sourcedId>"  # pylint: disable=line-too-long
            "</sourcedGUID><result><resultScore><language>en</language><textString>0.32</textString></resultScore>"
            "</result></resultRecord></replaceResultRequest></imsx_POXBody></imsx_POXEnvelopeRequest>"
        )

        return mock_request
    def get_signed_grade_mock_request(self, namespace_lti_v1p1=True):
        """
        Example of signed request from LTI Provider.

        When `namespace_v1p0` is set to True then the default namespase from
        LTI 1.1 will be used. Otherwise fake namespace will be added to XML.
        """
        mock_request = Mock()
        mock_request.headers = {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": u'OAuth oauth_nonce="135685044251684026041377608307", \
                oauth_timestamp="1234567890", oauth_version="1.0", \
                oauth_signature_method="HMAC-SHA1", \
                oauth_consumer_key="test_client_key", \
                oauth_signature="my_signature%3D", \
                oauth_body_hash="JEpIArlNCeV4ceXxric8gJQCnBw="',
        }
        mock_request.url = u"http://testurl"
        mock_request.http_method = u"POST"

        params = {}
        if not namespace_lti_v1p1:
            params = {"namespace": "http://www.fakenamespace.com/fake"}
        mock_request.body = self.get_request_body(params)

        return mock_request
Example #13
0
 def get_signed_grade_mock_request(self):
     """
     Example of signed request from LTI Provider.
     """
     mock_request = Mock()
     mock_request.headers = {
         "X-Requested-With": "XMLHttpRequest",
         "Content-Type": "application/xml",
         "Authorization": u'OAuth oauth_nonce="135685044251684026041377608307", \
             oauth_timestamp="1234567890", oauth_version="1.0", \
             oauth_signature_method="HMAC-SHA1", \
             oauth_consumer_key="test_client_key", \
             oauth_signature="my_signature%3D", \
             oauth_body_hash="gz+PeJZuF2//n9hNUnDj2v5kN70="',
     }
     mock_request.url = u"http://testurl"
     mock_request.http_method = u"POST"
     mock_request.body = textwrap.dedent(
         """
         <?xml version = "1.0" encoding = "UTF-8"?>
             <imsx_POXEnvelopeRequest  xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
             </imsx_POXEnvelopeRequest>
     """
     )
     return mock_request
Example #14
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 #15
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)
    def test_payment_already_paid(self):
        payment = mommy.make(getpaid.models.Payment, id=90, amount=119000, paid_on=now())

        request = Mock()
        request.POST = {"TBK_MONTO": "11900000"}
        request.body = self.QUOTED_REQUEST_BODY

        self.assertFalse(PaymentProcessor.validate(payment, request))
 def test_no_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = -1
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.body = "a".encode("ascii") * 1000  # 1000 bytes?
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertTrue(request_model.raw_body)
Example #18
0
 def test_dump_body_buffer(self):
     msg = Mock()
     msg.body = "str"
     try:
         buf = buffer(msg.body)
     except NameError:
         raise SkipTest("buffer type not available")
     self.assertTrue(dump_body(msg, buf))
Example #19
0
 def test_plain(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "text/plain"}
     mock_request.body = "sdfsdf"
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertFalse(body)
     self.assertEqual(raw_body, mock_request.body)
Example #20
0
    def test_that_organiser_email_can_be_added_as_constituent(self, mock_client_func):
        mock_api_response = Mock()
        mock_client_func.return_value = mock_api_response
        mock_api_response.http_status = 200
        mock_api_response.body = '[{"cons_id"  : 34, "email_id" : 234}]'

        eq_(34, bsd.BSDClient.register_email_address_as_constituent("example@mozilla.org"))

        mock_client_func.assert_called_with("/cons/email_register", {"email": "example@mozilla.org", "format": "json"})
 def test_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = 10  # 10kb
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.body = "a".encode("ascii") * 1024 * 100  # 100kb
     mock_request.path = reverse("silk:requests")
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertFalse(request_model.raw_body)
Example #22
0
    def test_that_event_can_be_fetched_given_obfuscated_id(self, mock_client_func):
        mock_api_response = Mock()
        mock_client_func.return_value = mock_api_response
        mock_api_response.body = '{"event": "json"}'

        eq_(bsd.BSDClient.fetch_event("obf_id"), {"event": "json"})

        mock_client_func.assert_called_with(
            "/event/get_event_details", {"values": json.dumps({"event_id_obfuscated": "obf_id"})}
        )
Example #23
0
 def test_invalid_encoding_json(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=asdas-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d).encode("UTF-8")
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body, encoding="UTF-8"), d)
     self.assertEqual(raw_body, raw_body)
Example #24
0
 def test_utf_json_not_encoded(self):
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json; charset=UTF-8"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d)
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(raw_body, mock_request.body)
def test__get_question_top_answer_body__answers():
    Answer = namedtuple("Answer", ["id", "score"])
    answers = [Answer(1, 1), Answer(2, 2)]

    so = Mock()
    fetched_answer = Mock()
    fetched_answer.body = "foobar"
    so.answer.return_value = fetched_answer
    question = Mock()
    question.answers = answers
    assert get_question_top_answer_body(so, question) == "foobar"
Example #26
0
 def test_utf_json_encoded_no_charset(self):
     """default to UTF-8"""
     mock_request = Mock()
     mock_request.META = {DJANGO_META_CONTENT_TYPE: "application/json"}
     d = {"x": u"语"}
     mock_request.body = json.dumps(d).encode("UTF-8")
     mock_request.get = mock_request.META.get
     factory = RequestModelFactory(mock_request)
     body, raw_body = factory.body()
     self.assertDictEqual(json.loads(body), d)
     self.assertEqual(raw_body, mock_request.body.decode("UTF-8"))
Example #27
0
 def test_cleanup_should_not_delete_other_stacks_messages(self):
     message_body = (
         "{ "
         '"status": "UPDATE_COMPLETE", '
         '"timestamp": "2015-11-24T13:14:16.575Z", '
         '"stackName": "other-teststack", '
         '"message": "User Initiated", '
         '"emitter": "cloudformation", '
         '"resourceType": "AWS::CloudFormation::Stack"}'
     )
     message = Mock()
     message.body = message_body
     self.assertIsNone(cleanup_old_messages(datetime.now(), message, "my-teststack"))
Example #28
0
def test_get_ticket_from_issue(ticket):
    issue = Mock(["body", "number", "state", "title"])
    issue.body = "MockBody"
    issue.number = 123
    issue.state = "MockState"
    issue.title = "MockTitle"
    ret = get_ticket_from_issue(issue)
    assert_called_once(
        ticket,
        (),
        {"identifier": 123, "description": "MockBody", "title": "MockTitle", "owner": None, "state": "MockState"},
    )
    assert_equal(ticket.return_value, ret)
Example #29
0
    def test_that_constituent_email_can_be_queried_given_a_cons_id(
        self, mock_client_func, mock_charset_func, mock_email_extractor_func
    ):
        mock_response = Mock()
        mock_client_func.return_value = mock_response
        mock_charset_func.return_value = "utf-8"
        mock_response.body = "<xml>"
        mock_email_extractor_func.return_value = "example@mozilla.org"

        eq_("example@mozilla.org", bsd.BSDClient.constituent_email_for_constituent_id("abcd"))

        mock_client_func.assert_called_with(
            "/cons/get_constituents_by_id", {"cons_ids": "abcd", "bundles": "primary_cons_email"}
        )
        mock_charset_func.assert_called_with(mock_response)
        mock_email_extractor_func.assert_called_with("<xml>")
Example #30
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