def item(request, pk): data = filter(lambda item: text(item['pk']) == text(pk), DATABASE) data = map(convert_data, data) data = list(data) logger.debug('3rd item search: `%s`', pk) if not data: raise Http404("Unknown item `{}`".format(pk)) result = {'data': data} response = json.dumps(result) logger.debug('response: `%s`', response) return HttpResponse(response)
def test_selected(self): instance = AutocompletePerson() result = instance.selected([]) self.assertEqual(result, []) result = instance.selected([1]) self.assertEqual(result, [(text('1'), text('Alice Iñtërnâtiônàlizætiøn'))]) result = instance.selected(['2']) self.assertEqual(result, [(text('2'), text('Alice Inchains'))]) result = instance.selected(['MEUH']) self.assertEqual(result, [])
def item(self, current_item): """ Return the current item. @param current_item: Current item @type param: django.models @return: Label of the current item @rtype : dict """ return {'value': text(current_item.pk), 'label': text(current_item)}
def test_selected(self): instance = AutocompleteUrlSimple() searched_id = 1 item_url = instance.get_item_url(searched_id) with mock.patch('demo.autocomplete.AutocompleteUrlSimple' '.get_item_url') as mock_auto: mock_auto.return_value = self.live_server_url + item_url result = instance.selected([]) self.assertEqual(result, []) result = instance.selected([searched_id]) self.assertEqual(result, [(text(searched_id), text('first person'))])
def test_selected(self): instance = AutocompletePerson() result = instance.selected([]) self.assertEqual(result, []) result = instance.selected([1]) self.assertEqual(result, [ (text('1'), text('Alice Iñtërnâtiônàlizætiøn'))] ) result = instance.selected(['2']) self.assertEqual(result, [(text('2'), text('Alice Inchains'))]) result = instance.selected(['MEUH']) self.assertEqual(result, [])
def selected(self, ids): """ Return the selected options as a list of tuples """ # cleanup the id list ids = filter(lambda x: "{}".format(x).isdigit(), copy(ids)) # Prepare the QS # TODO: not contextually filtered, check if it's possible at some point qs = self.get_model_queryset().filter(pk__in=ids) result = [] for item in qs: result.append((text(item.pk), text(item))) return result
def test_selected(self): instance = AutocompleteUrlSimple() searched_id = 1 item_url = instance.get_item_url(searched_id) with mock.patch('demo.autocomplete.AutocompleteUrlSimple' '.get_item_url') as mock_auto: mock_auto.return_value = self.live_server_url + item_url result = instance.selected([]) self.assertEqual(result, []) result = instance.selected([searched_id]) self.assertEqual(result, [ (text(searched_id), text('first person'))] )
def selected(self, ids): data = [] # Filter out "falsy IDs" (empty string, None, 0...) ids = filter(lambda x: x, ids) for _id in ids: if _id: # Call to the item URL result = self.http_call(url=self.get_item_url(pk=_id)) if self.data_key in result and len(result[self.data_key]): for item in result[self.data_key]: data.append((text(item[self.value_key]), text(item[self.label_key]))) return data
def test_autocomplete_person_queries(self): response = self.client.get( self.url, data={"q": "ali"} ) self.assertEqual(response.status_code, 200) data = get_json(response) # query, the dataset has 4 records self.assertTrue(data) self.assertEqual(len(data), 4) self.assertIn({ "value": text(self.alice1.pk), "label": text(self.alice1)}, data ) self.assertIn({ "value": text(self.alice2.pk), "label": text(self.alice2)}, data ) self.assertIn({ "value": text(self.alice3.pk), "label": text(self.alice3)}, data ) self.assertIn({ "value": text(self.alice4.pk), "label": text(self.alice4)}, data )
def item(self, current_item): """ Return the current item. @param current_item: Current item @type param: django.models @return: Label of the current item @rtype : dict """ return { 'value': text(current_item.pk), 'label': text(current_item) }
def selected(self, ids): """ Return the selected options as a list of tuples """ # cleanup the id list ids = filter(lambda x: "{}".format(x).isdigit(), copy(ids)) # Prepare the QS # TODO: not contextually filtered, check if it's possible at some point qs = self.get_model_queryset().filter(pk__in=ids) result = [] for item in qs: result.append( (text(item.pk), text(item)) ) return result
def get_error(exc): """ Return the appropriate HTTP status code according to the Exception/Error. """ if isinstance(exc, HTTPError): # Returning the HTTP Error code coming from requests module return exc.response.status_code, text(exc.response.content) if isinstance(exc, Timeout): # A timeout is a 408, and it's not a HTTPError (why? dunno). return 408, exc if isinstance(exc, Http404): # 404 is 404 return 404, exc if isinstance(exc, PermissionDenied): # Permission denied is 403 return 403, exc if isinstance(exc, SuspiciousOperation): # Shouldn't happen, but you never know return 400, exc # The default error code is 500 return 500, exc
def render_options(self, choices, selected_choices): selected_choices = set(text(v) for v in selected_choices) selected_choices_tuples = self.agnocomplete.selected(selected_choices) output = [] for option_value, option_label in selected_choices_tuples: output.append(self.render_option(selected_choices, option_value, option_label)) # noqa return '\n'.join(output)
def atomic_item(request, pk): """ Similar to `item` but does not return a list """ data = None for item in DATABASE: if text(item['pk']) == text(pk): data = convert_data(item) break if not data: raise Http404("Unknown item `{}`".format(pk)) logger.debug('3rd item search: `%s`', pk) result = {'data': data} response = json.dumps(result) logger.debug('response: `%s`', response) return HttpResponse(response)
def selected(self, ids): data = [] # Filter out "falsy IDs" (empty string, None, 0...) ids = filter(lambda x: x, ids) for _id in ids: if _id: # Call to the item URL result = self.http_call(url=self.get_item_url(pk=_id)) if self.data_key in result and len(result[self.data_key]): for item in result[self.data_key]: data.append( ( text(item[self.value_key]), text(item[self.label_key]) ) ) return data
def test_item(self): instance = AutocompletePersonLabel() qs = instance.get_queryset() condition = instance.get_queryset_filters(query="bob") items = qs.filter(condition) people = Person.objects.get(first_name='Bob') label = u'{item} {mail}'.format(item=text(people), mail=people.email) self.assertEqual(instance.item(items.first())['label'], label)
def render_options(self, choices, selected_choices): selected_choices = set(text(v) for v in selected_choices) selected_choices_tuples = self.agnocomplete.selected(selected_choices) output = [] for option_value, option_label in selected_choices_tuples: output.append( self.render_option(selected_choices, option_value, option_label)) # noqa return '\n'.join(output)
def label(self, current_item): """ Return a label for the current item. @param current_item: Current item @type param: django.models @return: Label of the current item @rtype : text """ return text(current_item)
def item(self, current_item): """ Return the current item. @param current_item: Current item @type param: django.models @return: Value and label of the current item @rtype : dict """ return { 'value': text(getattr(current_item, self.get_field_name())), 'label': self.label(current_item) }
def render_options(self, *args): # Django >= 1.10, only "selected_choices" in the arg list if len(args) == 1: selected_choices = args[0] else: # Django < 1.10 - selected_choices is the second arg. _, selected_choices = args selected_choices = set(text(v) for v in selected_choices) selected_choices_tuples = self.agnocomplete.selected( selected_choices) output = [] for option_value, option_label in selected_choices_tuples: output.append( self.render_option(selected_choices, option_value, option_label)) # noqa return '\n'.join(output)
def optgroups(self, name, value, attrs=None): selected_ids = set(text(v) for v in value) selected_choices = self.agnocomplete.selected(selected_ids) options = [] groups = [(None, options, 0) # single unnamed group ] for option_value, option_label in selected_choices: opt = self.create_option( name, option_value, option_label, True, 0, subindex=None, attrs=attrs, ) opt['attrs']['selected'] = True options.append(opt) return groups
def test_405(self): response = self.client.get( reverse('url-proxy:errors'), {'q': '405'}) self.assertEqual(response.status_code, 405) self.assertEqual(text(response.content), MESSAGE_405)
def test_500(self): response = self.client.get( reverse('url-proxy:errors'), {'q': 'whatever'}) self.assertEqual(response.status_code, 500) self.assertEqual(text(response.content), MESSAGE_500)
def item(self, current_item): return dict( value=text(current_item['pk']), label='{} {}'.format(current_item['first_name'], current_item['last_name']), )
def item(self, current_item): return dict( value=text(current_item[self.value_key]), label=text(current_item[self.label_key]), )
from requests.exceptions import HTTPError from ..autocomplete import ( AutocompleteUrlSimple, AutocompleteUrlConvert, AutocompleteUrlConvertSchema, AutocompleteUrlConvertSchemaList, AutocompleteUrlConvertComplex, AutocompleteUrlSimpleAuth, AutocompleteUrlHeadersAuth, AutocompleteUrlSimplePost, AutocompleteUrlSimpleWithExtra, ) from .. import DATABASE, GOODAUTHTOKEN RESULT_DICT = [{ 'value': text(item['pk']), 'label': text(item['name']) } for item in DATABASE] # noqa @override_settings(HTTP_HOST='') class AutocompleteUrlSimpleTest(LiveServerTestCase): def test_search(self): instance = AutocompleteUrlSimple() # "mock" Change URL by adding the host search_url = instance.search_url with mock.patch('demo.autocomplete.AutocompleteUrlSimple' '.get_search_url') as mock_auto: mock_auto.return_value = self.live_server_url + search_url self.assertEqual(list(instance.items()), []) # Limit is 2, a 1-char-long query should be empty
def label(self, current_item): return u'{item} {mail}'.format( item=text(current_item), mail=current_item.email)
def item(self, current_item): return dict( value=text(current_item['pk']), label='{} {}'.format( current_item['first_name'], current_item['last_name']), )
def test_500(self): response = self.client.get(reverse('url-proxy:errors'), {'q': 'whatever'}) self.assertEqual(response.status_code, 500) self.assertEqual(text(response.content), MESSAGE_500)
def test_405(self): response = self.client.get(reverse('url-proxy:errors'), {'q': '405'}) self.assertEqual(response.status_code, 405) self.assertEqual(text(response.content), MESSAGE_405)
from requests.exceptions import HTTPError from ..autocomplete import ( AutocompleteUrlSimple, AutocompleteUrlConvert, AutocompleteUrlConvertSchema, AutocompleteUrlConvertSchemaList, AutocompleteUrlConvertComplex, AutocompleteUrlSimpleAuth, AutocompleteUrlHeadersAuth, AutocompleteUrlSimplePost, AutocompleteUrlSimpleWithExtra, ) from .. import DATABASE, GOODAUTHTOKEN RESULT_DICT = [{'value': text(item['pk']), 'label': text(item['name'])} for item in DATABASE] # noqa @override_settings(HTTP_HOST='') class AutocompleteUrlSimpleTest(LiveServerTestCase): def test_search(self): instance = AutocompleteUrlSimple() # "mock" Change URL by adding the host search_url = instance.search_url with mock.patch('demo.autocomplete.AutocompleteUrlSimple' '.get_search_url') as mock_auto: mock_auto.return_value = self.live_server_url + search_url self.assertEqual(list(instance.items()), []) # Limit is 2, a 1-char-long query should be empty self.assertEqual(list(instance.items(query='p')), [])
def label(self, current_item): return '{item} {mail}'.format(item=text(current_item), mail=current_item.email)
from ..autocomplete import ( AutocompleteUrlSimple, AutocompleteUrlConvert, AutocompleteUrlConvertSchema, AutocompleteUrlConvertSchemaList, AutocompleteUrlConvertComplex, AutocompleteUrlSimpleAuth, AutocompleteUrlHeadersAuth, AutocompleteUrlSimplePost, AutocompleteUrlSimpleWithExtra, AutocompleteUrlSkipItem, ) from .. import DATABASE, GOODAUTHTOKEN RESULT_DICT = [{'value': text(item['pk']), 'label': text(item['name'])} for item in DATABASE] # noqa @override_settings(HTTP_HOST='') class AutocompleteUrlSimpleTest(LiveServerTestCase): def test_search(self): instance = AutocompleteUrlSimple() # "mock" Change URL by adding the host search_url = instance.search_url with mock.patch('demo.autocomplete.AutocompleteUrlSimple' '.get_search_url') as mock_auto: mock_auto.return_value = self.live_server_url + search_url self.assertEqual(list(instance.items()), []) # Limit is 2, a 1-char-long query should be empty self.assertEqual(list(instance.items(query='p')), [])