示例#1
0
    def test_process_request_calls_invalid_request_event_for_invalid_requests(self):
        from sijax.helper import json

        # An invalid request is a request for a function that's not registered,
        # meaning the request is invalid as far as sijax is concerned
        inst = Sijax()
        cls = inst.__class__
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '["arg1", 12]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1", 12], inst.request_args)

        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON generated!")
        else:
            self.assertTrue(isinstance(commands, list))

            # we expect the default "Invalid request" alert
            self.assertEqual(1, len(commands))
            command_data = commands.pop(0)
            self.assertTrue("type" in command_data)
            self.assertEqual("alert", command_data["type"])
示例#2
0
    def test_process_request_calls_invalid_request_event_for_invalid_requests(
            self):
        from sijax.helper import json

        # An invalid request is a request for a function that's not registered,
        # meaning the request is invalid as far as sijax is concerned
        inst = Sijax()
        cls = inst.__class__
        inst.set_data({
            cls.PARAM_REQUEST: "my_func",
            cls.PARAM_ARGS: '["arg1", 12]'
        })
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1", 12], inst.request_args)

        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON generated!")
        else:
            self.assertTrue(isinstance(commands, list))

            # we expect the default "Invalid request" alert
            self.assertEqual(1, len(commands))
            command_data = commands.pop(0)
            self.assertTrue("type" in command_data)
            self.assertEqual("alert", command_data["type"])
示例#3
0
    def test_register_callback_works(self):
        from sijax.helper import json

        call_history = []

        def callback(obj_response):
            call_history.append('callback')
            obj_response.alert('test')


        app = flask.Flask(__name__)
        helper = flask_sijax.Sijax(app)

        with app.test_request_context():
            app.preprocess_request()

            helper.register_callback('test', callback)

            # no data, cannot determine request as a sijax request
            self.assertFalse(helper.is_sijax_request)

            cls_sijax = helper._sijax.__class__
            helper._sijax.set_data({cls_sijax.PARAM_REQUEST: 'test', cls_sijax.PARAM_ARGS: '[]'})

            self.assertTrue(helper.is_sijax_request)
            response = helper.process_request()
            self.assertEqual(['callback'], call_history)

            try:
                obj = json.loads(response.get_data(True))
            except:
                self.fail('Cannot decode JSON!')
    def test_executing_regular_callbacks_works(self):
        from types import StringType

        calls_history = []
        call_args_history = []

        def event_before(obj_response):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            calls_history.append("before")

            obj_response.script("javascript here..")

        def event_after(obj_response):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            calls_history.append("after")

            obj_response.css("#element", "backgroundColor", "red")

        def callback_main(obj_response, arg1, arg2):
            self.assertTrue(isinstance(obj_response, BaseResponse))

            calls_history.append("main")
            call_args_history.append(arg1)
            call_args_history.append(arg2)

            obj_response.alert("alert from main")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_BEFORE_PROCESSING, event_before)
        inst.register_event(cls.EVENT_AFTER_PROCESSING, event_after)

        call_args = ["arg1", 15]
        response = inst.execute_callback(call_args, callback=callback_main)

        self.assertEqual(["before", "main", "after"], calls_history)
        self.assertEqual(call_args, call_args_history)

        # the response should be a string for regular functions
        # streaming functions return generators instead..
        self.assertTrue(isinstance(response, StringType))

        from sijax.helper import json
        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON response!")
        else:
            self.assertTrue(isinstance(commands, list))

            commands_history = []
            for cmd_params in commands:
                self.assertTrue(isinstance(cmd_params, dict))
                self.assertTrue("type" in cmd_params, "Unknown command type!")
                commands_history.append(cmd_params["type"])

        self.assertEqual(["script", "alert", "css"], commands_history)
示例#5
0
    def test_executing_regular_callbacks_works(self):

        calls_history = []
        call_args_history = []

        def event_before(obj_response):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            calls_history.append("before")

            obj_response.script("javascript here..")

        def event_after(obj_response):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            calls_history.append("after")

            obj_response.css("#element", "backgroundColor", "red")

        def callback_main(obj_response, arg1, arg2):
            self.assertTrue(isinstance(obj_response, BaseResponse))

            calls_history.append("main")
            call_args_history.append(arg1)
            call_args_history.append(arg2)

            obj_response.alert("alert from main")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_BEFORE_PROCESSING, event_before)
        inst.register_event(cls.EVENT_AFTER_PROCESSING, event_after)

        call_args = ["arg1", 15]
        response = inst.execute_callback(call_args, callback=callback_main)

        self.assertEqual(["before", "main", "after"], calls_history)
        self.assertEqual(call_args, call_args_history)

        # the response should be a string for regular functions
        # streaming functions return generators instead..
        self.assertTrue(isinstance(response, string_types))

        from sijax.helper import json
        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON response!")
        else:
            self.assertTrue(isinstance(commands, list))

            commands_history = []
            for cmd_params in commands:
                self.assertTrue(isinstance(cmd_params, dict))
                self.assertTrue("type" in cmd_params, "Unknown command type!")
                commands_history.append(cmd_params["type"])

        self.assertEqual(["script", "alert", "css"], commands_history)
示例#6
0
def _assert_response_json(context, string):
    from sijax.helper import json
    try:
        obj = json.loads(string)
    except:
        context.fail('Cannot decode JSON!')
    else:
        context.assertTrue(isinstance(obj, list))
        for item in obj:
            context.assertTrue(isinstance(item, dict))
            context.assertTrue('type' in item)
示例#7
0
def _assert_response_json(context, string):
    from sijax.helper import json
    try:
        obj = json.loads(string)
    except:
        context.fail('Cannot decode JSON!')
    else:
        context.assertTrue(isinstance(obj, list))
        for item in obj:
            context.assertTrue(isinstance(item, dict))
            context.assertTrue('type' in item)
示例#8
0
    def test_process_request_calls_invalid_call_event_for_invalid_calls(self):
        from types import FunctionType
        from sijax.helper import json

        # An invalid call is a call to a function that appears valid.
        # The function is registered (known), but calling fails, because
        # the function expects another number of arguments

        call_history = []

        def my_callback(obj_response, arg1, arg2):
            call_history.append("call ok")

        def my_callback_with_defaults(obj_response, arg1=138, arg2=15):
            call_history.append("defaults ok")

        def my_callback_raising_TypeError(obj_response):
            raise TypeError('this should be re-raised by Sijax')

        def my_callback_raising_TypeError2(obj_response):
            def inner():
                raise TypeError('this should be re-raised by Sijax')

            inner()

        def invalid_call(obj_response, failed_callback):
            self.assertTrue(isinstance(failed_callback, FunctionType))
            call_history.append("invalid %s" % failed_callback.__name__)

        inst = Sijax()
        cls = inst.__class__
        inst.register_callback("my_func", my_callback)

        # Make a valid call that would succeed
        inst.set_data({
            cls.PARAM_REQUEST: "my_func",
            cls.PARAM_ARGS: '["arg1", 12]'
        })
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1", 12], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        # Make a call with a wrong number of arguments, and a default
        # event handler for invalid calls
        inst.set_data({
            cls.PARAM_REQUEST: "my_func",
            cls.PARAM_ARGS: '["arg1"]'
        })
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1"], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))
        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON generated!")
        else:
            self.assertTrue(isinstance(commands, list))
            # we expect the default "Action performed in a wrong way" alert
            self.assertEqual(1, len(commands))
            command_data = commands.pop(0)
            self.assertTrue("type" in command_data)
            self.assertEqual("alert", command_data["type"])

        # Make an invalid call with a custom event handler function
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual([], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        # let's see if calling works with default arguments
        inst.register_callback("my_func", my_callback_with_defaults)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        # let's ensure that raising a TypeError from within a handler,
        # is not mistaken for an invalid call (EVENT_INVALID_CALL),
        # and re-raises the exception
        inst.register_callback("my_func", my_callback_raising_TypeError)
        try:
            inst.process_request()
        except TypeError:
            call_history.append('TypeError')

        inst.register_callback("my_func", my_callback_raising_TypeError2)
        try:
            inst.process_request()
        except TypeError:
            call_history.append('TypeError2')

        expected = [
            'call ok', 'invalid my_callback', 'defaults ok', 'TypeError',
            'TypeError2'
        ]
        self.assertEqual(expected, call_history)
示例#9
0
    def test_process_request_calls_invalid_call_event_for_invalid_calls(self):
        from types import FunctionType
        from sijax.helper import json

        # An invalid call is a call to a function that appears valid.
        # The function is registered (known), but calling fails, because
        # the function expects another number of arguments

        call_history = []

        def my_callback(obj_response, arg1, arg2):
            call_history.append("call ok")

        def my_callback_with_defaults(obj_response, arg1=138, arg2=15):
            call_history.append("defaults ok")

        def my_callback_raising_TypeError(obj_response):
            raise TypeError('this should be re-raised by Sijax')

        def my_callback_raising_TypeError2(obj_response):
            def inner():
                raise TypeError('this should be re-raised by Sijax')
            inner()

        def invalid_call(obj_response, failed_callback):
            self.assertTrue(isinstance(failed_callback, FunctionType))
            call_history.append("invalid %s" % failed_callback.__name__)

        inst = Sijax()
        cls = inst.__class__
        inst.register_callback("my_func", my_callback)

        # Make a valid call that would succeed
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '["arg1", 12]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1", 12], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))


        # Make a call with a wrong number of arguments, and a default
        # event handler for invalid calls
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '["arg1"]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual(["arg1"], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))
        try:
            commands = json.loads(response)
        except:
            self.fail("Invalid JSON generated!")
        else:
            self.assertTrue(isinstance(commands, list))
            # we expect the default "Action performed in a wrong way" alert
            self.assertEqual(1, len(commands))
            command_data = commands.pop(0)
            self.assertTrue("type" in command_data)
            self.assertEqual("alert", command_data["type"])

        # Make an invalid call with a custom event handler function
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertEqual("my_func", inst.requested_function)
        self.assertEqual([], inst.request_args)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        # let's see if calling works with default arguments
        inst.register_callback("my_func", my_callback_with_defaults)
        response = inst.process_request()
        self.assertTrue(isinstance(response, string_types))

        # let's ensure that raising a TypeError from within a handler,
        # is not mistaken for an invalid call (EVENT_INVALID_CALL),
        # and re-raises the exception
        inst.register_callback("my_func", my_callback_raising_TypeError)
        try:
            inst.process_request()
        except TypeError:
            call_history.append('TypeError')

        inst.register_callback("my_func", my_callback_raising_TypeError2)
        try:
            inst.process_request()
        except TypeError:
            call_history.append('TypeError2')

        expected = ['call ok', 'invalid my_callback', 'defaults ok',
                    'TypeError', 'TypeError2']
        self.assertEqual(expected, call_history)