def test_encode_time(self): self.assertEqual('"08:12:25.012"', json_encode(time(8, 12, 25, 12345), use_utc=False)) self.assertEqual( '"08:12:25.012Z"', json_encode(time(8, 12, 25, 12345, tzinfo=timezone.utc), use_utc=False)) # "normalize" pytz timezone information to get "05:00" and not "04:56" # see https://stackoverflow.com/questions/26264897/time-zone-field-in-isoformat tzinfo = get_timezone('US/Eastern').localize( datetime(2018, 1, 12, 8, 12, 25, 12345), ).tzinfo self.assertEqual( '"08:12:25.012-05:00"', json_encode(time(8, 12, 25, 12345, tzinfo=tzinfo), use_utc=False)) # "normalize" pytz timezone information to get "08:00" and not "08:06" # see https://stackoverflow.com/questions/26264897/time-zone-field-in-isoformat tzinfo = get_timezone('Asia/Shanghai').localize( datetime(2018, 1, 12, 8, 12, 25, 12345), ).tzinfo self.assertEqual( '"08:12:25.012+08:00"', json_encode(time(8, 12, 25, 12345, tzinfo=tzinfo), use_utc=False))
def test_encode_datetime(self): self.assertEqual( '"2018-01-12T08:12:25.012"', json_encode(datetime(2018, 1, 12, 8, 12, 25, 12345), use_utc=False), ) self.assertEqual( '"2018-01-12T08:12:25.012Z"', json_encode( datetime(2018, 1, 12, 8, 12, 25, 12345, tzinfo=timezone.utc), use_utc=False, ), ) self.assertEqual( '"2018-01-12T08:12:25.012-05:00"', json_encode( get_timezone('US/Eastern').localize( datetime(2018, 1, 12, 8, 12, 25, 12345)), use_utc=False, ), ) self.assertEqual( '"2018-01-12T08:12:25.012+08:00"', json_encode( get_timezone('Asia/Shanghai').localize( datetime(2018, 1, 12, 8, 12, 25, 12345)), use_utc=False, ), )
def test_brick_action_extra_data(self): icon = self.get_icon('add', 'brick-action') self.assertBrickActionHTML( "{% brick_action 'add' label='Add something' confirm=True " "__name1='value1' __name2=2 %}", '''<a href="" title="{label}" class="brick-action action-type-add " data-action="add"> <script class="brick-action-data" type="application/json"> <!-- {json_data} --> </script> <img src="{icon_url}" class="brick-action-icon" title="{label}" alt="{label}" width="{icon_size}px"/> </a>'''.format( label='Add something', # icon_url=self._get_icon('add', 'brick-action').url, icon_url=icon.url, # icon_size=get_icon_size_px(get_current_theme(), 'brick-action'), icon_size=icon.size, json_data=json_encode({ 'options': { 'confirm': True }, 'data': { 'name1': 'value1', 'name2': 2 }, }), ))
def poll_stats_chart(node): try: if node.type == PollLineType.BOOL: chartpath = 'polls/templatetags/plots/boolean.html' data = [[[percent, 1, f'{answer} − {percent} %']] for answer, _stat, percent in node.answer_stats] else: chartpath = 'polls/templatetags/plots/number.html' data = [ [[percent, str(answer)] for answer, _stat, percent in node.answer_stats], ] context = { 'node': node, 'data': mark_safe(json_encode( data)), # TODO: use the template-filter 'jsonify' ? 'count': len(node.answer_stats), } return template.loader.render_to_string(chartpath, context) except Exception: logger.exception('An error occurred in {% poll_stats_chart %}') return _('[An error occurred]')
def refresh_job(self, job, data): # TODO: factorise logger.info('Job manager queue: request REFRESH "%s" (data=%s)', job, data) # self._redis.lpush(self.JOBS_COMMANDS_KEY, '{}-{}-{}'.format(CMD_REFRESH, job.id, json_dump(data))) self._redis.lpush( self.JOBS_COMMANDS_KEY, '{}-{}-{}'.format(CMD_REFRESH, job.id, json_encode(data)))
def test_encode_datetime__use_utc(self): self.assertEqual('"2018-01-12T08:12:25.012"', json_encode(datetime(2018, 1, 12, 8, 12, 25, 12345))) self.assertEqual( '"2018-01-12T08:12:25.012Z"', json_encode( datetime(2018, 1, 12, 8, 12, 25, 12345, tzinfo=timezone.utc))) self.assertEqual( '"2018-01-12T13:12:25.012Z"', json_encode( get_timezone('US/Eastern').localize( datetime(2018, 1, 12, 8, 12, 25, 12345)))) self.assertEqual( '"2018-01-12T00:12:25.012Z"', json_encode( get_timezone('Asia/Shanghai').localize( datetime(2018, 1, 12, 8, 12, 25, 12345))))
def test_brick_action_confirm(self): self.assertBrickActionHTML( "{% brick_action 'add' label='Add something' confirm=True %}", '''<a href="" title="{label}" class="brick-action action-type-add " data-action="add"> <script class="brick-action-data" type="application/json"><!-- {json_data} --></script> <img src="{icon_url}" class="brick-action-icon" title="{label}" alt="{label}" width="{icon_size}px"/> </a>'''.format( label='Add something', icon_url=self._get_icon('add', 'brick-action').url, icon_size=get_icon_size_px(get_current_theme(), 'brick-action'), json_data=json_encode({ 'options': { 'confirm': True }, 'data': {}, }), )) self.assertBrickActionHTML( "{% brick_action 'add' label='Add something' confirm='Are you sure ?' %}", '''<a href="" title="{label}" class="brick-action action-type-add " data-action="add"> <script class="brick-action-data" type="application/json"><!-- {json_data} --></script> <img src="{icon_url}" class="brick-action-icon" title="{label}" alt="{label}" width="{icon_size}px"/> </a>'''.format( label='Add something', icon_url=self._get_icon('add', 'brick-action').url, icon_size=get_icon_size_px(get_current_theme(), 'brick-action'), json_data=json_encode({ 'options': { 'confirm': 'Are you sure ?' }, 'data': {}, }), ))
def page_builder_for_flowpaginator(self, paginator): state = self.state page_str = self.arguments.get(self.page_arg) or str(state.page) try: page_info = json_load(page_str) except ValueError: page_info = None else: if not isinstance(page_info, dict): page_info = None page_obj = paginator.get_page(page_info) state.page = json_encode(page_obj.info()) return page_obj
def _uninstall_user_setting_values(sender, **kwargs): prefix = sender.label + '-' for user in get_user_model().objects.all(): d = json_load(user.json_settings) new_d = {} save = False for k, v in d.items(): if k.startswith(prefix): save = True else: new_d[k] = v if save: user.json_settings = json_encode(new_d) user.save()
def test_encode_generator(self): self.assertEqual('[0,1,2]', json_encode(x for x in range(3))) self.assertEqual('[2,4,6]', json_encode(x * 2 for x in [1, 2, 3]))
def encode_answer(self, raw_answer): # return json_dump(self._cast_answer_4_encoding(raw_answer)) if raw_answer is not None else None return json_encode(self._cast_answer_4_encoding( raw_answer)) if raw_answer is not None else None
def cleaned_serialized_args(self): "Return a cleaned copy of the args (to be used in Replies)." args = self._cleaned_args() # return json_dump(args) if args else None return json_encode(args) if args else None
def test_encode_none(self): self.assertEqual('null', json_encode(None)) # TODO: uncomment when order is guaranteed (Python 3.8?) # self.assertEqual('{"a":null,"b":12}', json_encode({'a': None, 'b': 12})) self.assertEqual('{"a":null}', json_encode({'a': None}))
def encode_condition(self, cond_answer): # TODO: cond_answer as list of choice (later with better operators) # return json_dump([cond_answer]) return json_encode([cond_answer])
def encode_condition(self, cond_answer): # NB: we use a (json) list, in order to encode complexier conditions later, # eg: [0, 'My user string'] # return json_dump([cond_answer]) return json_encode([cond_answer])
def serialized_args(self): args = self._args # return json_dump(args) if args else None return json_encode(args) if args else None
def encode_condition(self, cond_answer): """@param cond_answer Value of answer in condition.""" # return json_dump(cond_answer) return json_encode(cond_answer)
def test_encode_lazy(self): self.assertEqual('"{}"'.format(gettext('User')), json_encode(gettext_lazy('User')))
def test_encode_decimal(self): self.assertEqual("12.47", json_encode(Decimal("12.47"))) self.assertEqual("5.0", json_encode(Decimal("5")))
def test_encode_date(self): self.assertEqual('"2018-01-12"', json_encode(date(2018, 1, 12)))