Exemplo n.º 1
0
    def test_args_extra_works_properly(self):
        call_history = []

        def callback(obj_response, arg1_custom, arg2_custom, arg_regular):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            call_history.append(arg1_custom)
            call_history.append(arg2_custom)
            call_history.append(arg_regular)

        def callback_basic(obj_response, arg_regular):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            call_history.append(arg_regular)

        inst = Sijax()
        cls = inst.__class__

        inst.register_callback("callback", callback, args_extra=("one", "two"))
        inst.set_data({cls.PARAM_REQUEST: "callback", cls.PARAM_ARGS: '["regular"]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.register_callback("callback", callback_basic)
        inst.set_data({cls.PARAM_REQUEST: "callback", cls.PARAM_ARGS: '["reg2"]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        call_history_expected = ["one", "two", "regular", "reg2"]
        self.assertEqual(call_history_expected, call_history)
Exemplo n.º 2
0
    def test_mass_registering_from_an_object_works(self):
        call_history = []

        class SijaxHandler(object):
            def callback_one(self, obj_response):
                call_history.append("one")

            def callback_two(self, obj_response):
                call_history.append("two")

        inst = Sijax()
        inst.register_object(SijaxHandler())
        cls = inst.__class__

        inst.set_data({
            cls.PARAM_REQUEST: "callback_one",
            cls.PARAM_ARGS: '[]'
        })
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.set_data({
            cls.PARAM_REQUEST: "callback_two",
            cls.PARAM_ARGS: '[]'
        })
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        self.assertEqual(["one", "two"], call_history)
Exemplo n.º 3
0
    def test_the_response_class_could_be_changed_during_registration(self):
        # Sometimes it may be convenient for the developer to be able to
        # change the class behind obj_response on a per-callback basis
        call_history = []

        class CustomResponse(BaseResponse): pass

        def my_callback(obj_response):
            call_history.append("regular")
            self.assertFalse(isinstance(obj_response, CustomResponse))
            self.assertTrue(isinstance(obj_response, BaseResponse))

        def my_custom_callback(obj_response):
            call_history.append("custom")
            self.assertTrue(isinstance(obj_response, CustomResponse))


        inst = Sijax()
        cls = inst.__class__

        inst.register_callback("my_func", my_callback)
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        inst.register_callback("my_func_custom", my_custom_callback, **params_custom)

        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.set_data({cls.PARAM_REQUEST: "my_func_custom", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        self.assertEqual(["regular", "custom"], call_history)
Exemplo n.º 4
0
    def test_args_extra_works_properly(self):
        call_history = []

        def callback(obj_response, arg1_custom, arg2_custom, arg_regular):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            call_history.append(arg1_custom)
            call_history.append(arg2_custom)
            call_history.append(arg_regular)

        def callback_basic(obj_response, arg_regular):
            self.assertTrue(isinstance(obj_response, BaseResponse))
            call_history.append(arg_regular)

        inst = Sijax()
        cls = inst.__class__

        inst.register_callback("callback", callback, args_extra=("one", "two"))
        inst.set_data({
            cls.PARAM_REQUEST: "callback",
            cls.PARAM_ARGS: '["regular"]'
        })
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.register_callback("callback", callback_basic)
        inst.set_data({
            cls.PARAM_REQUEST: "callback",
            cls.PARAM_ARGS: '["reg2"]'
        })
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        call_history_expected = ["one", "two", "regular", "reg2"]
        self.assertEqual(call_history_expected, call_history)
Exemplo n.º 5
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"])
Exemplo n.º 6
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"])
Exemplo n.º 7
0
    def test_registering_helper_works(self):
        from types import GeneratorType

        class CustomResponse(CometResponse): pass

        def process_request(inst):
            self.assertTrue(inst.is_sijax_request)
            response = inst.process_request()
            self.assertTrue(isinstance(response, GeneratorType))
            # something needs to "move the generator forward" if we want
            # to proceed in the call chain
            for string in response:
                pass

        call_history = []

        def invalid_call(obj_response, callback):
            self.fail("Invalid call handler triggered!")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})

        def my_callback(obj_response):
            self.assertTrue(isinstance(obj_response, CometResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("my_callback")
            call_history.append(type(obj_response).__name__)

        register_comet_callback(inst, "my_func", my_callback)
        process_request(inst)

        # let's see if we can override the default args and the response
        # class during callback registration
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        register_comet_callback(inst, "my_func", my_callback, **params_custom)
        process_request(inst)

        # Try mass registering now
        class SijaxHandler(object):
            @staticmethod
            def callback_one(obj_response, arg1):
                self.assertTrue(isinstance(obj_response, CustomResponse))
                call_history.append("callback_one")
                call_history.append(type(obj_response).__name__)
                call_history.append(arg1)

        register_comet_object(inst, SijaxHandler, **params_custom)
        inst.set_data({cls.PARAM_REQUEST: "callback_one", cls.PARAM_ARGS: '[45]'})
        process_request(inst)

        call_history_expected = [
            "my_callback", "CometResponse",
            "my_callback", "CustomResponse",
            "callback_one", "CustomResponse", 45
        ]
        self.assertEqual(call_history_expected, call_history)
def ajax_search(request, search_form, request_uri=None):

    request_uri_for_form = {
        FilterPlayersByVariantsForm:
        reverse('accounts:ajax-filter-players-by-variant'),
        SearchPlayersByKeywordsForm:
        reverse('accounts:ajax-search-players-by-kw'),
    }

    def search(obj_response, form_data):
        form = search_form(request, data=form_data)
        if form.is_valid():
            profiles_for_game = form.search()
            context = {
                'profiles_for_game':
                profiles_for_game,
                'MEDIA_URL':
                settings.MEDIA_URL,
                'STATIC_URL':
                settings.STATIC_URL,
                'request':
                request,
                'paginate_players_per_page':
                settings.ENDLESS_PAGINATE_PLAYERS_PER_PAGE,
            }
            players_count_str = "<h3>%s total players</h3>" % profiles_for_game.count(
            )
            obj_response.html("#id_players-count", players_count_str)
            players_tmpl = """
            {% load endless %}
            {% paginate paginate_players_per_page profiles_for_game as players %}
                {% include "accounts/_players_table.html" %}
            """
            t = Template(players_tmpl)
            players_table = t.render(Context(context))
            obj_response.html('#id_players-table', players_table)

            pag_tmpl = """
            {% load endless %}
            {% paginate paginate_players_per_page profiles_for_game %}
                {% include "accounts/_pagination.html" %}
            """
            t = Template(pag_tmpl)
            pagination = t.render(Context(context))
            obj_response.html('div#profile-pagination', pagination)
        else:
            log.debug('find players filter errors: %s', form.errors)

    instance = Sijax()
    instance.set_data(request.POST)
    instance.set_request_uri(request_uri_for_form.get(search_form, ''))
    instance.register_callback('search', search)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
Exemplo n.º 9
0
    def test_changing_incoming_data_works(self):
        inst = Sijax()
        self.assertTrue(inst.get_data() == {})

        data = {"key": "value"}
        inst.set_data(data)
        self.assertTrue(inst.get_data() == data)

        data = {"key": "value", "another": "one"}
        self.assertTrue(inst.get_data() == {"key": "value"})
        inst.set_data(data)
        self.assertTrue(inst.get_data() == data)
Exemplo n.º 10
0
    def test_changing_incoming_data_works(self):
        inst = Sijax()
        self.assertTrue(inst.get_data() == {})

        data = {"key": "value"}
        inst.set_data(data)
        self.assertTrue(inst.get_data() == data)

        data = {"key": "value", "another": "one"}
        self.assertTrue(inst.get_data() == {"key": "value"})
        inst.set_data(data)
        self.assertTrue(inst.get_data() == data)
Exemplo n.º 11
0
def ajax_load_games_by_city(request, for_city_id):
    def load_options(obj_response, for_city_id):
        #games_for_city = Instance.objects.filter(for_city__pk=for_city_id).language(get_language())
        games = Instance.objects.exclude(
            is_disabled=True).filter(for_city__pk=for_city_id).values_list(
                'pk', 'title').distinct().order_by('title')
        out = ""
        for id, title in games:
            out += '<option value="%s">%s</option>' % (id, title)
        obj_response.html('#id_0-instance', out)

    instance = Sijax()
    instance.set_data(request.POST)
    uri = reverse('instances:ajax-load-games-by-city', args=(for_city_id, ))
    instance.set_request_uri(uri)
    instance.register_callback('load_games_by_city', load_options)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
    return HttpResponse("")
Exemplo n.º 12
0
def ajax_load_languages_by_game(request, instance_id):
    def load_options(obj_response, instance_id):
        game = Instance.objects.get(pk=instance_id)
        langs = game.languages.values_list('pk',
                                           'name').distinct().order_by('code')
        out = ""
        for id, name in langs:
            out += '<option value="%s">%s</option>' % (id, name)
        obj_response.html('#id_0-preferred_language', out)

    instance = Sijax()
    instance.set_data(request.POST)
    uri = reverse('instances:ajax-load-languages-by-game',
                  args=(instance_id, ))
    instance.set_request_uri(uri)
    instance.register_callback('load_languages_by_game', load_options)
    if instance.is_sijax_request:
        return HttpResponse(instance.process_request())
    return HttpResponse("")
Exemplo n.º 13
0
    def test_new_callbacks_override_old_during_registering(self):
        call_history = []

        def callback_one(obj_response):
            call_history.append("one")

        def callback_two(obj_response):
            call_history.append("two")

        inst = Sijax()
        cls = inst.__class__
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)

        inst.register_callback("my_func", callback_one)
        inst.process_request()

        inst.register_callback("my_func", callback_two)
        inst.process_request()

        self.assertEqual(["one", "two"], call_history)
Exemplo n.º 14
0
    def test_new_callbacks_override_old_during_registering(self):
        call_history = []

        def callback_one(obj_response):
            call_history.append("one")

        def callback_two(obj_response):
            call_history.append("two")

        inst = Sijax()
        cls = inst.__class__
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)

        inst.register_callback("my_func", callback_one)
        inst.process_request()

        inst.register_callback("my_func", callback_two)
        inst.process_request()

        self.assertEqual(["one", "two"], call_history)
Exemplo n.º 15
0
    def test_mass_registering_from_a_class_works(self):
        call_history = []

        class SijaxHandler(object):
            @staticmethod
            def callback_one(obj_response):
                call_history.append("one")

            @staticmethod
            def callback_two(obj_response):
                call_history.append("two")

            @classmethod
            def callback_three(cls, obj_response):
                call_history.append("three")

        inst = Sijax()
        inst.register_object(SijaxHandler)
        cls = inst.__class__

        inst.set_data({cls.PARAM_REQUEST: "callback_one", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.set_data({cls.PARAM_REQUEST: "callback_two", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.set_data({cls.PARAM_REQUEST: "callback_three", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        self.assertEqual(["one", "two", "three"], call_history)
Exemplo n.º 16
0
    def test_the_response_class_could_be_changed_during_registration(self):
        # Sometimes it may be convenient for the developer to be able to
        # change the class behind obj_response on a per-callback basis
        call_history = []

        class CustomResponse(BaseResponse):
            pass

        def my_callback(obj_response):
            call_history.append("regular")
            self.assertFalse(isinstance(obj_response, CustomResponse))
            self.assertTrue(isinstance(obj_response, BaseResponse))

        def my_custom_callback(obj_response):
            call_history.append("custom")
            self.assertTrue(isinstance(obj_response, CustomResponse))

        inst = Sijax()
        cls = inst.__class__

        inst.register_callback("my_func", my_callback)
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        inst.register_callback("my_func_custom", my_custom_callback,
                               **params_custom)

        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        inst.set_data({
            cls.PARAM_REQUEST: "my_func_custom",
            cls.PARAM_ARGS: '[]'
        })
        self.assertTrue(inst.is_sijax_request)
        inst.process_request()

        self.assertEqual(["regular", "custom"], call_history)
Exemplo n.º 17
0
    def test_registering_helper_works(self):
        from types import GeneratorType

        from sijax.plugin.upload import func_name_by_form_id

        class CustomResponse(UploadResponse):
            pass

        def process_request(inst):
            self.assertTrue(inst.is_sijax_request)
            response = inst.process_request()
            self.assertTrue(isinstance(response, GeneratorType))
            # something needs to "move the generator forward" if we want
            # to proceed in the call chain
            for string in response:
                pass

        call_history = []

        def invalid_call(obj_response, callback):
            self.fail("Invalid call handler triggered!")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)

        def my_callback(obj_response, files, form_values):
            self.assertTrue(isinstance(obj_response, UploadResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("my_callback")
            call_history.append(obj_response.form_id)
            call_history.append(type(obj_response).__name__)
            call_history.append(files["file"])  # reaching into the file object

            # ensure that from all the post data, only the valid (non-system)
            # stuff made it through
            self.assertEqual({
                "form_key": "value",
                "form_key2": 15
            }, form_values)

        def my_callback2(obj_response, custom_arg1, custom_arg2, form_values):
            self.assertTrue(isinstance(obj_response, UploadResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("custom_callback")
            call_history.append(obj_response.form_id)
            call_history.append(type(obj_response).__name__)
            call_history.append(custom_arg1)
            call_history.append(custom_arg2)

            # ensure that from all the post data, only the valid (non-system)
            # stuff made it through
            self.assertEqual({
                "form_key": "value",
                "form_key2": 15
            }, form_values)

        form_id = "my_form"
        # the developer usually doesn't need to know the public system assigned
        # name of the callback function.. we'll need it though to fake the request
        public_callback_name = func_name_by_form_id(form_id)
        request_args_json = '["%s"]' % form_id
        post = {}
        post[cls.PARAM_REQUEST] = public_callback_name
        post[cls.PARAM_ARGS] = request_args_json
        post["form_key"] = "value"
        post["form_key2"] = 15
        inst.set_data(post)

        files = {"file": "object", "passed": "here"}
        register_upload_callback(inst,
                                 form_id,
                                 my_callback,
                                 args_extra=(files, ))
        process_request(inst)

        # let's see if we can override the default args and the response
        # class during callback registration
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        register_upload_callback(inst,
                                 form_id,
                                 my_callback2,
                                 args_extra=("custom1", "custom2"),
                                 **params_custom)
        process_request(inst)

        call_history_expected = [
            "my_callback", form_id, "UploadResponse", "object",
            "custom_callback", form_id, "CustomResponse", "custom1", "custom2"
        ]
        self.assertEqual(call_history_expected, call_history)
Exemplo n.º 18
0
    def test_registering_helper_works(self):
        from types import GeneratorType

        class CustomResponse(CometResponse):
            pass

        def process_request(inst):
            self.assertTrue(inst.is_sijax_request)
            response = inst.process_request()
            self.assertTrue(isinstance(response, GeneratorType))
            # something needs to "move the generator forward" if we want
            # to proceed in the call chain
            for string in response:
                pass

        call_history = []

        def invalid_call(obj_response, callback):
            self.fail("Invalid call handler triggered!")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.set_data({cls.PARAM_REQUEST: "my_func", cls.PARAM_ARGS: '[]'})

        def my_callback(obj_response):
            self.assertTrue(isinstance(obj_response, CometResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("my_callback")
            call_history.append(type(obj_response).__name__)

        register_comet_callback(inst, "my_func", my_callback)
        process_request(inst)

        # let's see if we can override the default args and the response
        # class during callback registration
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        register_comet_callback(inst, "my_func", my_callback, **params_custom)
        process_request(inst)

        # Try mass registering now
        class SijaxHandler(object):
            @staticmethod
            def callback_one(obj_response, arg1):
                self.assertTrue(isinstance(obj_response, CustomResponse))
                call_history.append("callback_one")
                call_history.append(type(obj_response).__name__)
                call_history.append(arg1)

        register_comet_object(inst, SijaxHandler, **params_custom)
        inst.set_data({
            cls.PARAM_REQUEST: "callback_one",
            cls.PARAM_ARGS: '[45]'
        })
        process_request(inst)

        call_history_expected = [
            "my_callback", "CometResponse", "my_callback", "CustomResponse",
            "callback_one", "CustomResponse", 45
        ]
        self.assertEqual(call_history_expected, call_history)
Exemplo n.º 19
0
    def test_invalid_call_event_works(self):
        from types import GeneratorType, FunctionType
        call_history = []

        def my_callback(obj_response, arg1, arg2):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("call ok")

        def my_callback_raising_TypeError(obj_response):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            raise TypeError('this should be re-raised by Sijax')

        def my_callback_raising_TypeError2(obj_response):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))

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

            inner()

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

        def exhaust_generator(gen):
            self.assertTrue(isinstance(gen, GeneratorType))
            try:
                while True:
                    next(gen)
            except StopIteration:
                pass

        inst = Sijax()
        cls = inst.__class__
        options = {cls.PARAM_RESPONSE_CLASS: StreamingIframeResponse}

        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.register_callback("my_func", my_callback, **options)

        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()
        exhaust_generator(response)

        # we should have succeeded until now..
        # let's try to make the call invalid and observe the failure
        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()
        exhaust_generator(response)

        # 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,
                               **options)
        try:
            response = inst.process_request()
            exhaust_generator(response)
        except TypeError:
            call_history.append('TypeError')

        inst.register_callback("my_func", my_callback_raising_TypeError2,
                               **options)
        try:
            response = inst.process_request()
            exhaust_generator(response)
        except TypeError:
            call_history.append('TypeError2')

        expected = [
            'call ok', 'invalid my_callback', 'TypeError', 'TypeError2'
        ]
        self.assertEqual(expected, call_history)
Exemplo n.º 20
0
    def test_detecting_sijax_requests_works(self):
        inst = Sijax()
        cls = inst.__class__

        # no POST data specified.. this surely is a GET request
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)

        # missing params that specify the function and args
        inst.set_data({"key": "value"})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)

        # missing args
        inst.set_data({cls.PARAM_REQUEST: "function"})
        self.assertFalse(inst.is_sijax_request)
        self.assertEqual(inst.requested_function, "function")

        # missing function name
        inst.set_data({cls.PARAM_ARGS: "[]"})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)
        self.assertEqual([], inst.request_args)

        inst.set_data({cls.PARAM_ARGS: '["invalid_json": here'})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)
        self.assertEqual([], inst.request_args)

        # this should be considered valid.. both params available
        # the arguments are json encoded
        inst.set_data({
            cls.PARAM_REQUEST: "function",
            cls.PARAM_ARGS: '["arg1", 5]'
        })
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("function", inst.requested_function)
        self.assertEqual(["arg1", 5], inst.request_args)

        inst.set_data({cls.PARAM_REQUEST: "func2", cls.PARAM_ARGS: '[28, 5]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("func2", inst.requested_function)
        self.assertEqual([28, 5], inst.request_args)
Exemplo n.º 21
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)
Exemplo n.º 22
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)
Exemplo n.º 23
0
    def test_detecting_sijax_requests_works(self):
        inst = Sijax()
        cls = inst.__class__

        # no POST data specified.. this surely is a GET request
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)

        # missing params that specify the function and args
        inst.set_data({"key": "value"})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)

        # missing args
        inst.set_data({cls.PARAM_REQUEST: "function"})
        self.assertFalse(inst.is_sijax_request)
        self.assertEqual(inst.requested_function, "function")

        # missing function name
        inst.set_data({cls.PARAM_ARGS: "[]"})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)
        self.assertEqual([], inst.request_args)

        inst.set_data({cls.PARAM_ARGS: '["invalid_json": here'})
        self.assertFalse(inst.is_sijax_request)
        self.assertTrue(inst.requested_function is None)
        self.assertEqual([], inst.request_args)

        # this should be considered valid.. both params available
        # the arguments are json encoded
        inst.set_data({cls.PARAM_REQUEST: "function", cls.PARAM_ARGS: '["arg1", 5]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("function", inst.requested_function)
        self.assertEqual(["arg1", 5], inst.request_args)

        inst.set_data({cls.PARAM_REQUEST: "func2", cls.PARAM_ARGS: '[28, 5]'})
        self.assertTrue(inst.is_sijax_request)
        self.assertEqual("func2", inst.requested_function)
        self.assertEqual([28, 5], inst.request_args)
Exemplo n.º 24
0
    def test_registering_helper_works(self):
        from types import GeneratorType

        from sijax.plugin.upload import func_name_by_form_id

        class CustomResponse(UploadResponse): pass

        def process_request(inst):
            self.assertTrue(inst.is_sijax_request)
            response = inst.process_request()
            self.assertTrue(isinstance(response, GeneratorType))
            # something needs to "move the generator forward" if we want
            # to proceed in the call chain
            for string in response:
                pass

        call_history = []

        def invalid_call(obj_response, callback):
            self.fail("Invalid call handler triggered!")

        inst = Sijax()
        cls = inst.__class__
        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)

        def my_callback(obj_response, files, form_values):
            self.assertTrue(isinstance(obj_response, UploadResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("my_callback")
            call_history.append(obj_response.form_id)
            call_history.append(type(obj_response).__name__)
            call_history.append(files["file"]) # reaching into the file object

            # ensure that from all the post data, only the valid (non-system)
            # stuff made it through
            self.assertEqual({"form_key": "value", "form_key2": 15}, form_values)

        def my_callback2(obj_response, custom_arg1, custom_arg2, form_values):
            self.assertTrue(isinstance(obj_response, UploadResponse))
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("custom_callback")
            call_history.append(obj_response.form_id)
            call_history.append(type(obj_response).__name__)
            call_history.append(custom_arg1)
            call_history.append(custom_arg2)

            # ensure that from all the post data, only the valid (non-system)
            # stuff made it through
            self.assertEqual({"form_key": "value", "form_key2": 15}, form_values)

        form_id = "my_form"
        # the developer usually doesn't need to know the public system assigned
        # name of the callback function.. we'll need it though to fake the request
        public_callback_name = func_name_by_form_id(form_id)
        request_args_json = '["%s"]' % form_id
        post = {}
        post[cls.PARAM_REQUEST] = public_callback_name
        post[cls.PARAM_ARGS] = request_args_json
        post["form_key"] = "value"
        post["form_key2"] = 15
        inst.set_data(post)

        files = {"file": "object", "passed": "here"}
        register_upload_callback(inst, form_id, my_callback, args_extra=(files,))
        process_request(inst)


        # let's see if we can override the default args and the response
        # class during callback registration
        params_custom = {cls.PARAM_RESPONSE_CLASS: CustomResponse}
        register_upload_callback(inst, form_id, my_callback2, args_extra=("custom1", "custom2"), **params_custom)
        process_request(inst)

        call_history_expected = [
            "my_callback", form_id, "UploadResponse", "object",
            "custom_callback", form_id, "CustomResponse", "custom1", "custom2"
        ]
        self.assertEqual(call_history_expected, call_history)
Exemplo n.º 25
0
    def test_invalid_call_event_works(self):
        from types import GeneratorType, FunctionType
        call_history = []

        def my_callback(obj_response, arg1, arg2):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            call_history.append("call ok")

        def my_callback_raising_TypeError(obj_response):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            raise TypeError('this should be re-raised by Sijax')

        def my_callback_raising_TypeError2(obj_response):
            self.assertTrue(isinstance(obj_response, StreamingIframeResponse))
            def inner():
                raise TypeError('this should be re-raised by Sijax')
            inner()

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

        def exhaust_generator(gen):
            self.assertTrue(isinstance(gen, GeneratorType))
            try:
                while True:
                    next(gen)
            except StopIteration:
                pass

        inst = Sijax()
        cls = inst.__class__
        options = {cls.PARAM_RESPONSE_CLASS: StreamingIframeResponse}

        inst.register_event(cls.EVENT_INVALID_CALL, invalid_call)
        inst.register_callback("my_func", my_callback, **options)

        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()
        exhaust_generator(response)

        # we should have succeeded until now..
        # let's try to make the call invalid and observe the failure
        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()
        exhaust_generator(response)

        # 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, **options)
        try:
            response = inst.process_request()
            exhaust_generator(response)
        except TypeError:
            call_history.append('TypeError')

        inst.register_callback("my_func", my_callback_raising_TypeError2, **options)
        try:
            response = inst.process_request()
            exhaust_generator(response)
        except TypeError:
            call_history.append('TypeError2')

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