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)
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)
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)
def test_process_request_throws_exception_when_called_for_non_sijax_requests(self): inst = Sijax() try: inst.process_request() self.fail("Process request got executed for a non-sijax request!") except SijaxError: pass
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)
def test_process_request_throws_exception_when_called_for_non_sijax_requests( self): inst = Sijax() try: inst.process_request() self.fail("Process request got executed for a non-sijax request!") except SijaxError: pass
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"])
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"])
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())
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)
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)
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)
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("")
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("")
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)
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)
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)
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)