def test_json_browser_collapse_all_from_start_line(self): """ test json browser collapse all nested nodes when press key. """ data = {"key": {"key": 'val'}} # grab JSONBrowser instance to test client = Mock() view = View(self.config, client) json_browser = view._frame._json_browser json_browser.set_top_node(data) size = (18, 5) for key in split(self.keymap.json_browser.collapse_all, self.keymap.global_command_key): json_browser.keypress(size, key) content = [[t[2] for t in row] for row in json_browser.render(size).content()] # verify expected = [[B("{\xe2\x80\xa6} ")], [B(" ")], [B(" ")], [B(" ")], [B(" ")]] self.assertEqual(expected, content)
def test1(self): self.cptest("none", "asdf", [], 0, 0, [[(None,None,B("asdf"))]]) self.cptest("left pad", "asdf", [], 2, 0, [[(None,None,B(" ")),(None,None,B("asdf"))]]) self.cptest("right pad", "asdf", [], 0, 2, [[(None,None,B("asdf")),(None,None,B(" "))]])
def test_simple_object(self): """ test rendering of a not-nested JSON object """ data = {"k1": "v1", "k2": "v2"} # act node = ObjectNode("", data, display_key=False) widget = node.get_widget() contents = [] while widget is not None: node = widget.get_node() if not node.is_expanded(): node.toggle_expanded() widget = node.get_widget() contents.append(widget.render((18, )).content()) widget = widget.next_inorder() texts = [[[t[2] for t in row] for row in content] for content in contents] # verify self.assertEqual(4, len(texts)) expected = [ [[B("{ ")]], [[B(" "), B("k1"), B(": "), B("v1 ")]], [[B(" "), B("k2"), B(": "), B("v2 ")]], [[B("} ")]], ] self.assertEqual(expected, texts)
def test_boolean_node(self): """ test JSON `boolean` rendering """ data = True # act node = self._node_factory.create_root_node(data) widget = node.get_widget() contents = [] while widget is not None: node = widget.get_node() if not node.is_expanded(): widget.keypress((18, ), 'enter') widget = node.get_widget() contents.append(widget.render((18, )).content()) widget = widget.next_inorder() texts = [[[t[2] for t in row] for row in content] for content in contents] # verify self.assertEqual(1, len(texts)) expected = [[[B('true'), B(' ')]]] self.assertEqual(expected, texts)
def test_object_with_list_child(self): """ test rendering of a JSON object with list child """ data = {"key": [1]} # act node = ObjectNode("", data, display_key=False) widget = node.get_widget() contents = [] while widget is not None: node = widget.get_node() if not node.is_expanded(): node.toggle_expanded() widget = node.get_widget() contents.append(widget.render((18, )).content()) widget = widget.next_inorder() texts = [[[t[2] for t in row] for row in content] for content in contents] # verify self.assertEqual(5, len(texts)) expected = [ [[B("{ ")]], [[B(" "), B("key"), B(": "), B("[ ")]], [[B(" "), B("1 ")]], [[B(" "), B("] ")]], [[B("} ")]], ] self.assertEqual(expected, texts)
def test_prev_order(self): data = {"k1": "v1", "k2": "v2"} node = ObjectNode("", data, display_key=False) # start from the end widget = node.get_end_node().get_widget() contents = [] while widget is not None: contents.append(widget.render((18, )).content()) widget = widget.prev_inorder() texts = [[[t[2] for t in row] for row in content] for content in contents] texts.reverse() # verify self.assertEqual(4, len(texts)) expected = [ [[B("{ ")]], [[B(" "), B("k1"), B(": "), B("v1 ")]], [[B(" "), B("k2"), B(": "), B("v2 ")]], [[B("} ")]], ] self.assertEqual(expected, texts)
class TagMarkupTest(unittest.TestCase): mytests = [ ("simple one", "simple one", []), (('blue', "john"), "john", [('blue', 4)]), (["a ", "litt", "le list"], "a little list", []), (["mix", ('high', [" it ", ('ital', "up a")]), " little"], "mix it up a little", [(None, 3), ('high', 4), ('ital', 4)]), ([u"ÂŁÂŁ", u"xÂŁÂŁ"], u"ÂŁÂŁxÂŁÂŁ", []), ([B("\xc2\x80"), B("\xc2\x80")], B("\xc2\x80\xc2\x80"), []), ] def test(self): for input, text, attr in self.mytests: restext, resattr = urwid.decompose_tagmarkup(input) assert restext == text, "got: %r expected: %r" % (restext, text) assert resattr == attr, "got: %r expected: %r" % (resattr, attr) def test_bad_tuple(self): self.assertRaises(urwid.TagMarkupException, lambda: urwid.decompose_tagmarkup((1, 2, 3))) def test_bad_type(self): self.assertRaises(urwid.TagMarkupException, lambda: urwid.decompose_tagmarkup(5))
def test_encoding_vt100_graphics(self): vterm.util._target_encoding = 'ascii' self.write('\e)0\e(0\x0fg\x0eg\e)Bn\e)0g\e)B\e(B\x0fn') self.expect([[(None, '0', B('g')), (None, '0', B('g')), (None, None, B('n')), (None, '0', B('g')), (None, None, B('n'))]], raw=True)
def parse_csi(self, char): """ Parse ECMA-48 CSI (Control Sequence Introducer) sequences. """ qmark = self.escbuf.startswith(B('?')) escbuf = [] for arg in self.escbuf[qmark and 1 or 0:].split(B(';')): try: num = int(arg) except ValueError: num = None escbuf.append(num) if CSI_COMMANDS[char] is not None: if CSI_COMMANDS[char][0] == 'alias': csi_cmd = CSI_COMMANDS[(CSI_COMMANDS[char][1])] else: csi_cmd = CSI_COMMANDS[char] number_of_args, default_value, cmd = csi_cmd while len(escbuf) < number_of_args: escbuf.append(default_value) for i in xrange(len(escbuf)): if escbuf[i] is None or escbuf[i] == 0: escbuf[i] = default_value try: cmd(self, escbuf, qmark) except ValueError: # ignore commands that don't match the # unpacked tuples in CSI_COMMANDS. pass
def test_view_window_refresh(self): data = [{"key": "value"}] config = parse() controller = Controller(config) view_manager = controller._view keymapper = view_manager._keymapper.json_browser json_browser = JSONBrowser(view_manager, keymapper, data) # expand the first line content = json_browser.render((18, 3)).content() texts_before_refresh = [[t[2] for t in row] for row in content] # refresh view window new_data = {"key": "value"} json_browser.set_top_node(new_data) content = json_browser.render((18, 3)).content() texts_after_refresh = [[t[2] for t in row] for row in content] # verify self.assertTrue(texts_before_refresh != texts_after_refresh) texts_before_refresh_expected = [ [B("[ ")], [B(" "), B("{\xe2\x80\xa6} ")], [B("] ")], ] self.assertEqual(texts_before_refresh_expected, texts_before_refresh) texts_after_refresh_expected = [ [B("{ ")], [B(" "), B("key"), B(": "), B("value ")], [B("} ")], ] self.assertEqual(texts_after_refresh_expected, texts_after_refresh)
def test_collapse_all_from_start_node(self): """ test listbox collapse all nested nodes when press key `c`. """ data = { "key": { "key": 'val' } } node = self._node_factory.create_root_node(data) # act walker = JSONListWalker(start_from=node) listbox = JSONListBox(walker) size = (18, 5) listbox.keypress(size, 'c') content = [[t[2] for t in row] for row in listbox.render(size).content()] # verify expected = [ [B("{\xe2\x80\xa6} ")], [B(" ")], [B(" ")], [B(" ")], [B(" ")] ] self.assertEqual(expected, content)
def cotest(self, desc, bgt, bga, fgt, fga, l, r, et): bgt = B(bgt) fgt = B(fgt) bg = urwid.CompositeCanvas(urwid.TextCanvas([bgt], [bga])) fg = urwid.CompositeCanvas(urwid.TextCanvas([fgt], [fga])) bg.overlay(fg, l, 0) result = list(bg.content()) assert result == et, "%s expected %r, got %r" % (desc, et, result)
def parse_osc(self, buf): """ Parse operating system command. """ if buf.startswith(B(';')): # set window title and icon self.widget.set_title(buf[1:]) elif buf.startswith(B('3;')): # set window title self.widget.set_title(buf[2:])
def test(self): urwid.set_encoding("euc-jp") self.assertRaises(text_layout.CanNotDisplayText, text_layout.default_layout.calculate_text_segments, B('\xA1\xA1'), 1, 'space') urwid.set_encoding("utf-8") self.assertRaises(text_layout.CanNotDisplayText, text_layout.default_layout.calculate_text_segments, B('\xe9\xa2\x96'), 1, 'space')
def read(self, raw=False, focus=False): self.term.wait_and_feed() rendered = self.term.render(self.termsize, focus=focus) if raw: is_empty = lambda c: c == (None, None, B(' ')) content = list(rendered.content()) lines = [list(dropwhile(is_empty, reversed(line))) for line in content] return [list(reversed(line)) for line in lines if len(line)] else: content = rendered.text lines = [line.rstrip() for line in content] return B('\n').join(lines).rstrip()
def test_ibmpc_mapping(self): vterm.util._target_encoding = 'ascii' self.write('\e[11m\x18\e[10m\x18') self.expect([[(None, 'U', B('\x18'))]], raw=True) self.write('\ec\e)U\x0e\x18\x0f\e[3h\x18\e[3l\x18') self.expect([[(None, None, B('\x18'))]], raw=True) self.write('\ec\e[11m\xdb\x18\e[10m\xdb') self.expect([[(None, 'U', B('\xdb')), (None, 'U', B('\x18')), (None, None, B('\xdb'))]], raw=True)
def test_set_title(self): self._the_title = None def _change_title(widget, title): self._the_title = title self.connect_signal('title') self.write('\e]666parsed right?\e\\te\e]0;test title\007st1') self.expect('test1') self.expect_signal(B('test title')) self.write('\e]3;stupid title\e\\\e[0G\e[2Ktest2') self.expect('test2') self.expect_signal(B('stupid title')) self.disconnect_signal('title')
def test_collapse_all_from_middle_node(self): """ test listbox collapse all nested nodes when press key `c`. """ data = [ { "key": [ "1", "2" ] }, { "key": [ "2" ] } ] node = self._node_factory.create_root_node(data) # act walker = JSONListWalker(start_from=node) listbox = JSONListBox(walker) size = (18, 13) # 13 rows after expanded in total # move to focus to the second item, thus move down twice, as the view # should be expanded at the first level listbox.move_focus_to_next_line(size) listbox.move_focus_to_next_line( size) # move to the second item in the list listbox.toggle_collapse_on_focused_parent( size) # expand the second item listbox.move_focus_to_next_line( size) # move to the first child of the object listbox.toggle_collapse_on_focused_parent(size) # expand the object listbox.move_focus_to_next_line( size) # move to the first child of the object listbox.keypress(size, 'c') content = [[t[2] for t in row] for row in listbox.render((18, 2)).content()] # verify expected = [ [B("[\xe2\x80\xa6] ")], [B(" ")] ] self.assertEqual(expected, content)
class CalcTranslateCantDisplayTest(CalcTranslateTest, unittest.TestCase): text = B('Hello\xe9\xa2\x96') mode = 'space' width = 1 result_left = [[]] result_right = [[]] result_center = [[]]
def test_boolean_node(self): """ test JSON `boolean` rendering """ data = True # act node = PrimitiveNode("", data, display_key=False) widget = node.get_widget() contents = [] while widget is not None: node = widget.get_node() if not node.is_expanded(): widget.keypress((18, ), "enter") widget = node.get_widget() contents.append(widget.render((18, )).content()) widget = widget.next_inorder() texts = [[[t[2] for t in row] for row in content] for content in contents] # verify self.assertEqual(1, len(texts)) expected = [[[B("True ")]]] self.assertEqual(expected, texts)
class DummyCommand(object): QUITSTRING = B('|||quit|||') def __init__(self): self.reader, self.writer = os.pipe() def __call__(self): # reset stdout = getattr(sys.stdout, 'buffer', sys.stdout) stdout.write(B('\x1bc')) while True: data = self.read(1024) if self.QUITSTRING == data: break stdout.write(data) stdout.flush() def read(self, size): while True: try: return os.read(self.reader, size) except OSError as e: if e.errno != errno.EINTR: raise def write(self, data): os.write(self.writer, data) def quit(self): self.write(self.QUITSTRING)
def cbtest(self, width, exp): result = text_layout.default_layout.calculate_text_segments( B(self.text), width, self.mode) assert len(result) == len(exp), repr((result, exp)) for l, e in zip(result, exp): end = l[-1][-1] assert end == e, repr((result, exp))
def cptest(self, desc, ct, ca, l, r, et): ct = B(ct) c = urwid.CompositeCanvas( urwid.TextCanvas([ct], [ca])) c.pad_trim_left_right(l, r) result = list(c.content()) assert result == et, "%s expected %r, got %r"%( desc, et, result)
def _sigwinch_handler(self, signum, frame=None): """ frame -- will always be None when the GLib event loop is being used. """ if not self._resized: self._resize_pipe_wr.send(B("R")) self._resized = True self.screen_buf = None
def ctest(self, desc, s, exp, expcs): exp = B(exp) util.set_encoding('ascii') c = urwid.Text(s).render((5, )) result = c._text[0] assert result == exp, "%s got:%r expected:%r" % (desc, result, exp) resultcs = c._cs[0] assert resultcs == expcs, "%s got:%r expected:%r" % (desc, resultcs, expcs)
def test_list_box_with_simple_object(self): """ test listbox rendering simple object with collapse pressing key `enter` and moving focus with pressing key `ctrl n`. """ data = { "key": "value" } node = NodeFactory.create_node("", data, parent=None, display_key=False) # act walker = JSONListWalker(start_from=node) listbox = JSONListBox(walker) contents_until_moving_to_end = [] prev_widget, prev_node = None, None cur_widget, cur_node = listbox.get_focus() while prev_widget != cur_widget: if not cur_node.is_expanded(): listbox.keypress((18, 18), "enter") cur_widget, cur_node = listbox.get_focus() contents_until_moving_to_end.append(cur_widget.render((18,)).content()) listbox.keypress((18, 18), "down") prev_widget, prev_node = cur_widget, cur_node cur_widget, cur_node = listbox.get_focus() texts_until_moving_to_end = [[[t[2] for t in row] for row in content] for content in contents_until_moving_to_end] # moving up until the start and collapse all expanded widgets contents_until_moving_to_start = [] prev_widget, prev_node = None, None cur_widget, cur_node = listbox.get_focus() while prev_widget != cur_widget: if cur_node.is_expanded(): listbox.keypress((18, 18), "enter") cur_widget, cur_node = listbox.get_focus() listbox.keypress((18, 18), "up") prev_widget, prev_node = cur_widget, cur_node cur_widget, cur_node = listbox.get_focus() contents_until_moving_to_start.append(listbox.render((18, 1)).content()) texts_until_moving_to_start = [[[t[2] for t in row] for row in content] for content in contents_until_moving_to_start] # verify # verify that after moving to the end, all the expandable lines have been expanded self.assertEqual(3, len(texts_until_moving_to_end)) expected = [ [[B("{ ")]], [[B(" "), B("key"), B(": "), B("value ")]], [[B("} ")]], ] self.assertEqual(expected, texts_until_moving_to_end) # verify that after moving to the start, all the expanded lines is collapsed self.assertEqual(1, len(texts_until_moving_to_start)) expected = [[[B("{\xe2\x80\xa6} ")]]] self.assertEqual(expected, texts_until_moving_to_start)
def expect(self, what, desc=None, raw=False, focus=False): if not isinstance(what, list): what = B(what) got = self.read(raw=raw, focus=focus) if desc is None: desc = '' else: desc += '\n' desc += 'Expected:\n%r\nGot:\n%r' % (what, got) self.assertEqual(got, what, desc)
def __call__(self): # reset stdout = getattr(sys.stdout, 'buffer', sys.stdout) stdout.write(B('\x1bc')) while True: data = self.read(1024) if self.QUITSTRING == data: break stdout.write(data) stdout.flush()
def rtest(self, w, expected_text, expected_cursor): expected_text = [B(t) for t in expected_text] get_cursor = w.get_cursor_coords((4, )) assert get_cursor == expected_cursor, "got: %r expected: %r" % ( get_cursor, expected_cursor) r = w.render((4, ), focus=1) text = [t for a, cs, t in [ln[0] for ln in r.content()]] assert text == expected_text, "got: %r expected: %r" % (text, expected_text) assert r.cursor == expected_cursor, "got: %r expected: %r" % ( r.cursor, expected_cursor)
class CalcTranslateWordTest3(CalcTranslateTest, unittest.TestCase): def setUp(self): urwid.set_encoding('utf-8') text = B('\xe6\x9b\xbf\xe6\xb4\xbc\n\xe6\xb8\x8e\xe6\xba\x8f\xe6\xbd\xba') width = 10 mode = 'space' result_left = [[(4, 0, 6), (0, 6)], [(6, 7, 16), (0, 16)]] result_right = [[(6, None), (4, 0, 6), (0, 6)], [(4, None), (6, 7, 16), (0, 16)]] result_center = [[(3, None), (4, 0, 6), (0, 6)], [(2, None), (6, 7, 16), (0, 16)]]