def test_file_directory(self): pl = Pl() segment_info = vim_module._get_segment_info() self.assertEqual(vim.file_directory(pl=pl, segment_info=segment_info), None) with replace_env('HOME', '/home/foo', os.environ): with vim_module._with('buffer', '/tmp/’’/abc') as segment_info: self.assertEqual(vim.file_directory(pl=pl, segment_info=segment_info), '/tmp/’’/') with vim_module._with('buffer', b'/tmp/\xFF\xFF/abc') as segment_info: self.assertEqual(vim.file_directory(pl=pl, segment_info=segment_info), '/tmp/<ff><ff>/') with vim_module._with('buffer', '/tmp/abc') as segment_info: self.assertEqual(vim.file_directory(pl=pl, segment_info=segment_info), '/tmp/') os.environ['HOME'] = '/tmp' self.assertEqual(vim.file_directory(pl=pl, segment_info=segment_info), '~/')
def test_cpu_load_percent(self): pl = Pl() with replace_module_module(common, 'psutil', cpu_percent=lambda **kwargs: 52.3): self.assertEqual(common.cpu_load_percent(pl=pl), [{ 'contents': '52%', 'gradient_level': 52.3, 'highlight_group': ['cpu_load_percent_gradient', 'cpu_load_percent'], }]) self.assertEqual(common.cpu_load_percent(pl=pl, format='{0:.1f}%'), [{ 'contents': '52.3%', 'gradient_level': 52.3, 'highlight_group': ['cpu_load_percent_gradient', 'cpu_load_percent'], }])
def test_battery(self): pl = Pl() def _get_capacity(pl): return 86 with replace_attr(common, '_get_capacity', _get_capacity): self.assertEqual(common.battery(pl=pl), [{ 'contents': '86%', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 86 }]) self.assertEqual(common.battery(pl=pl, format='{capacity:.2f}'), [{ 'contents': '0.86', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 86 }]) self.assertEqual(common.battery(pl=pl, steps=7), [{ 'contents': '86%', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 86 }]) self.assertEqual(common.battery(pl=pl, gamify=True), [ { 'contents': '♥♥♥♥', 'draw_inner_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 99 }, { 'contents': '♥', 'draw_inner_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 1 } ]) self.assertEqual(common.battery(pl=pl, gamify=True, full_heart='+', empty_heart='-', steps='10'), [ { 'contents': '++++++++', 'draw_inner_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 99 }, { 'contents': '--', 'draw_inner_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 1 } ])
def test_file_name(self): pl = Pl() segment_info = vim_module._get_segment_info() self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info), None) self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info, display_no_file=True), [{'contents': '[No file]', 'highlight_group': ['file_name_no_file', 'file_name']}]) self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info, display_no_file=True, no_file_text='X'), [{'contents': 'X', 'highlight_group': ['file_name_no_file', 'file_name']}]) with vim_module._with('buffer', '/tmp/abc') as segment_info: self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info), 'abc') with vim_module._with('buffer', '/tmp/’’') as segment_info: self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info), '’’') with vim_module._with('buffer', b'/tmp/\xFF\xFF') as segment_info: self.assertEqual(vim.file_name(pl=pl, segment_info=segment_info), '<ff><ff>')
def test_branch(self): pl = Pl() with vim_module._with('buffer', '/foo') as segment_info: with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: None, directory=path)): with replace_attr(vim, 'tree_status', lambda repo, pl: None): self.assertEqual(vim.branch(pl=pl, segment_info=segment_info, status_colors=False), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch'], 'contents': 'foo'}]) self.assertEqual(vim.branch(pl=pl, segment_info=segment_info, status_colors=True), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch_clean', 'branch'], 'contents': 'foo'}]) with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: 'DU', directory=path)): with replace_attr(vim, 'tree_status', lambda repo, pl: 'DU'): self.assertEqual(vim.branch(pl=pl, segment_info=segment_info, status_colors=False), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch'], 'contents': 'foo'}]) self.assertEqual(vim.branch(pl=pl, segment_info=segment_info, status_colors=True), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch_dirty', 'branch'], 'contents': 'foo'}])
def test_user(self): new_os = new_module('os', getpid=lambda: 1) new_psutil = new_module('psutil', Process=lambda pid: Args(username='******')) pl = Pl() with replace_env('USER', 'def') as segment_info: with replace_attr(common, 'os', new_os): with replace_attr(common, 'psutil', new_psutil): with replace_attr(common, '_geteuid', lambda: 5): self.assertEqual(common.user(pl=pl, segment_info=segment_info), [ {'contents': 'def', 'highlight_group': 'user'} ]) with replace_attr(common, '_geteuid', lambda: 0): self.assertEqual(common.user(pl=pl, segment_info=segment_info), [ {'contents': 'def', 'highlight_group': ['superuser', 'user']} ])
def test_uptime(self): pl = Pl() with replace_attr(common, '_get_uptime', lambda: 259200): self.assertEqual(common.uptime(pl=pl), [{'contents': '3d', 'divider_highlight_group': 'background:divider'}]) with replace_attr(common, '_get_uptime', lambda: 93784): self.assertEqual(common.uptime(pl=pl), [{'contents': '1d 2h 3m', 'divider_highlight_group': 'background:divider'}]) self.assertEqual(common.uptime(pl=pl, shorten_len=4), [{'contents': '1d 2h 3m 4s', 'divider_highlight_group': 'background:divider'}]) with replace_attr(common, '_get_uptime', lambda: 65536): self.assertEqual(common.uptime(pl=pl), [{'contents': '18h 12m 16s', 'divider_highlight_group': 'background:divider'}]) self.assertEqual(common.uptime(pl=pl, shorten_len=2), [{'contents': '18h 12m', 'divider_highlight_group': 'background:divider'}]) self.assertEqual(common.uptime(pl=pl, shorten_len=1), [{'contents': '18h', 'divider_highlight_group': 'background:divider'}]) def _get_uptime(): raise NotImplementedError with replace_attr(common, '_get_uptime', _get_uptime): self.assertEqual(common.uptime(pl=pl), None)
def test_branch(self): pl = Pl() segment_info = {'getcwd': os.getcwd} with replace_attr(common, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: None, directory='/tmp/tests')): with replace_attr(common, 'tree_status', lambda repo, pl: None): self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=True), [{'contents': 'tests', 'highlight_group': ['branch_clean', 'branch']}]) with replace_attr(common, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: 'D ', directory='/tmp/tests')): with replace_attr(common, 'tree_status', lambda repo, pl: 'D '): self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=True), [{'contents': 'tests', 'highlight_group': ['branch_dirty', 'branch']}]) self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) with replace_attr(common, 'guess', lambda path: None): self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), None)
def test_hostname(self): pl = Pl() with replace_env('SSH_CLIENT', '192.168.0.12 40921 22') as segment_info: with replace_module_module(common, 'socket', gethostname=lambda: 'abc'): self.assertEqual(common.hostname(pl=pl, segment_info=segment_info), 'abc') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, only_if_ssh=True), 'abc') with replace_module_module(common, 'socket', gethostname=lambda: 'abc.mydomain'): self.assertEqual(common.hostname(pl=pl, segment_info=segment_info), 'abc.mydomain') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, exclude_domain=True), 'abc') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, only_if_ssh=True), 'abc.mydomain') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, only_if_ssh=True, exclude_domain=True), 'abc') segment_info['environ'].pop('SSH_CLIENT') with replace_module_module(common, 'socket', gethostname=lambda: 'abc'): self.assertEqual(common.hostname(pl=pl, segment_info=segment_info), 'abc') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, only_if_ssh=True), None) with replace_module_module(common, 'socket', gethostname=lambda: 'abc.mydomain'): self.assertEqual(common.hostname(pl=pl, segment_info=segment_info), 'abc.mydomain') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, exclude_domain=True), 'abc') self.assertEqual(common.hostname(pl=pl, segment_info=segment_info, only_if_ssh=True, exclude_domain=True), None)
def test_position(self): pl = Pl() segment_info = vim_module._get_segment_info() try: segment_info['buffer'][0:-1] = [str(i) for i in range(99)] vim_module._set_cursor(49, 0) self.assertEqual(vim.position(pl=pl, segment_info=segment_info), '50%') self.assertEqual(vim.position(pl=pl, segment_info=segment_info, gradient=True), [{'contents': '50%', 'highlight_group': ['position_gradient', 'position'], 'gradient_level': 50.0}]) vim_module._set_cursor(0, 0) self.assertEqual(vim.position(pl=pl, segment_info=segment_info), 'Top') vim_module._set_cursor(97, 0) self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top':'Comienzo', 'bottom':'Final', 'all':'Todo'}), 'Final') segment_info['buffer'][0:-1] = [str(i) for i in range(2)] vim_module._set_cursor(0, 0) self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top':'Comienzo', 'bottom':'Final', 'all':'Todo'}), 'Todo') self.assertEqual(vim.position(pl=pl, segment_info=segment_info, gradient=True), [{'contents': 'All', 'highlight_group': ['position_gradient', 'position'], 'gradient_level': 0.0}]) finally: vim_module._bw(segment_info['bufnr'])
def test_network_load(self): from time import sleep def gb(interface): return None f = [gb] def _get_bytes(interface): return f[0](interface) pl = Pl() with replace_attr(common, '_get_bytes', _get_bytes): common.network_load.startup(pl=pl) try: self.assertEqual(common.network_load(pl=pl, interface='eth0'), None) sleep(common.network_load.interval) self.assertEqual(common.network_load(pl=pl, interface='eth0'), None) while 'prev' not in common.network_load.interfaces.get('eth0', {}): sleep(0.1) self.assertEqual(common.network_load(pl=pl, interface='eth0'), None) l = [0, 0] def gb2(interface): l[0] += 1200 l[1] += 2400 return tuple(l) f[0] = gb2 while not common.network_load.interfaces.get('eth0', {}).get('prev', (None, None))[1]: sleep(0.1) self.assertEqual(common.network_load(pl=pl, interface='eth0'), [ {'divider_highlight_group': 'background:divider', 'contents': '⬇ 1 KiB/s', 'highlight_group': ['network_load_recv', 'network_load']}, {'divider_highlight_group': 'background:divider', 'contents': '⬆ 2 KiB/s', 'highlight_group': ['network_load_sent', 'network_load']}, ]) self.assertEqual(common.network_load(pl=pl, interface='eth0', recv_format='r {value}', sent_format='s {value}'), [ {'divider_highlight_group': 'background:divider', 'contents': 'r 1 KiB/s', 'highlight_group': ['network_load_recv', 'network_load']}, {'divider_highlight_group': 'background:divider', 'contents': 's 2 KiB/s', 'highlight_group': ['network_load_sent', 'network_load']}, ]) self.assertEqual(common.network_load(pl=pl, recv_format='r {value}', sent_format='s {value}', suffix='bps', interface='eth0'), [ {'divider_highlight_group': 'background:divider', 'contents': 'r 1 Kibps', 'highlight_group': ['network_load_recv', 'network_load']}, {'divider_highlight_group': 'background:divider', 'contents': 's 2 Kibps', 'highlight_group': ['network_load_sent', 'network_load']}, ]) self.assertEqual(common.network_load(pl=pl, recv_format='r {value}', sent_format='s {value}', si_prefix=True, interface='eth0'), [ {'divider_highlight_group': 'background:divider', 'contents': 'r 1 kB/s', 'highlight_group': ['network_load_recv', 'network_load']}, {'divider_highlight_group': 'background:divider', 'contents': 's 2 kB/s', 'highlight_group': ['network_load_sent', 'network_load']}, ]) self.assertEqual(common.network_load(pl=pl, recv_format='r {value}', sent_format='s {value}', recv_max=0, interface='eth0'), [ {'divider_highlight_group': 'background:divider', 'contents': 'r 1 KiB/s', 'highlight_group': ['network_load_recv_gradient', 'network_load_gradient', 'network_load_recv', 'network_load'], 'gradient_level': 100}, {'divider_highlight_group': 'background:divider', 'contents': 's 2 KiB/s', 'highlight_group': ['network_load_sent', 'network_load']}, ]) class ApproxEqual(object): def __eq__(self, i): return abs(i - 50.0) < 1 self.assertEqual(common.network_load(pl=pl, recv_format='r {value}', sent_format='s {value}', sent_max=4800, interface='eth0'), [ {'divider_highlight_group': 'background:divider', 'contents': 'r 1 KiB/s', 'highlight_group': ['network_load_recv', 'network_load']}, {'divider_highlight_group': 'background:divider', 'contents': 's 2 KiB/s', 'highlight_group': ['network_load_sent_gradient', 'network_load_gradient', 'network_load_sent', 'network_load'], 'gradient_level': ApproxEqual()}, ]) finally: common.network_load.shutdown()
def test_continuation(self): pl = Pl() self.assertEqual(shell.continuation(pl=pl, segment_info={}), None) segment_info = {'parser_state': 'if cmdsubst'} self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info), [ { 'contents': 'if', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'l', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, right_align=True), [ { 'contents': 'if', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'r', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, omit_cmdsubst=False), [ { 'contents': 'if', 'draw_inner_divider': True, 'highlight_group': 'continuation', }, { 'contents': 'cmdsubst', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'l', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, omit_cmdsubst=False, right_align=True), [ { 'contents': 'if', 'draw_inner_divider': True, 'highlight_group': 'continuation', 'width': 'auto', 'align': 'r', }, { 'contents': 'cmdsubst', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, omit_cmdsubst=True, right_align=True), [ { 'contents': 'if', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'r', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, omit_cmdsubst=True, right_align=True, renames={'if': 'IF'}), [ { 'contents': 'IF', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'r', }, ]) self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info, omit_cmdsubst=True, right_align=True, renames={'if': None}), [ { 'contents': '', 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'r', }, ]) segment_info = {'parser_state': 'then then then cmdsubst'} self.assertEqual(shell.continuation(pl=pl, segment_info=segment_info), [ { 'contents': 'then', 'draw_inner_divider': True, 'highlight_group': 'continuation', }, { 'contents': 'then', 'draw_inner_divider': True, 'highlight_group': 'continuation', }, { 'contents': 'then', 'draw_inner_divider': True, 'highlight_group': 'continuation:current', 'width': 'auto', 'align': 'l', }, ])
def test_modified_buffers(self): pl = Pl() self.assertEqual(vim.modified_buffers(pl=pl), None)
def test_file_size(self): pl = Pl() segment_info = vim_module._get_segment_info() self.assertEqual(vim.file_size(pl=pl, segment_info=segment_info), '0 B') with vim_module._with('buffer', os.path.join(os.path.dirname(__file__), 'empty')) as segment_info: self.assertEqual(vim.file_size(pl=pl, segment_info=segment_info), '0 B')
def test_date(self): pl = Pl() with replace_attr(common, 'datetime', Args(now=lambda: Args(strftime=lambda fmt: fmt))): self.assertEqual(common.date(pl=pl), [{'contents': '%Y-%m-%d', 'highlight_group': ['date'], 'divider_highlight_group': None}]) self.assertEqual(common.date(pl=pl, format='%H:%M', istime=True), [{'contents': '%H:%M', 'highlight_group': ['time', 'date'], 'divider_highlight_group': 'time:divider'}])
def test_threaded_segment(self): log = [] pl = Pl() updates = [(None, )] lock = threading.Lock() event = threading.Event() block_event = threading.Event() class TestSegment(ThreadedSegment): interval = 10 def set_state(self, **kwargs): event.clear() log.append(('set_state', kwargs)) return super(TestSegment, self).set_state(**kwargs) def update(self, update_value): block_event.wait() event.set() # Make sleep first to prevent some race conditions log.append(('update', update_value)) with lock: ret = updates[0] if isinstance(ret, Exception): raise ret else: return ret[0] def render(self, update, **kwargs): log.append(('render', update, kwargs)) if isinstance(update, Exception): raise update else: return update # Non-threaded tests segment = TestSegment() block_event.set() updates[0] = (None, ) self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', None, { 'pl': pl, 'update_first': True }), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc', ) self.assertEqual(segment(pl=pl), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', { 'pl': pl, 'update_first': True }), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc', ) self.assertEqual(segment(pl=pl, update_first=False), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', { 'pl': pl, 'update_first': False }), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ValueError('abc') self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(len(pl.exceptions), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ]) log[:] = () pl.exceptions[:] = () segment = TestSegment() block_event.set() updates[0] = (TypeError('def'), ) self.assertRaises(TypeError, segment, pl=pl) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', updates[0][0], { 'pl': pl, 'update_first': True }), ]) log[:] = () # Threaded tests segment = TestSegment() block_event.clear() kwargs = {'pl': pl, 'update_first': False, 'other': 1} with lock: updates[0] = ('abc', ) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) block_event.set() event.wait() segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log, [ ('set_state', { 'update_first': False, 'other': 1 }), ('render', None, { 'pl': pl, 'update_first': False, 'other': 1 }), ('update', None), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'other': 1} with lock: updates[0] = ('def', ) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, 'def') self.assertEqual(log, [ ('set_state', { 'update_first': True, 'other': 1 }), ('update', None), ('render', 'def', { 'pl': pl, 'update_first': True, 'other': 1 }), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('abc', ) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = ('def', ) self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'abc') self.assertEqual(ret2, 'def') self.assertEqual(log[:5], [ ('set_state', { 'update_first': True, 'interval': 0.2 }), ('update', None), ('render', 'abc', { 'pl': pl, 'update_first': True, 'interval': 0.2 }), ('update', 'abc'), ('update', 'def'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('ghi', ) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = TypeError('jkl') self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'ghi') self.assertEqual(ret2, None) self.assertEqual(log[:5], [ ('set_state', { 'update_first': True, 'interval': 0.2 }), ('update', None), ('render', 'ghi', { 'pl': pl, 'update_first': True, 'interval': 0.2 }), ('update', 'ghi'), ('update', 'ghi'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) self.assertEqual(num_runs - 1, len(pl.exceptions)) log[:] = ()
def test_cwd(self): new_os = new_module('os', path=os.path, sep='/') pl = Pl() cwd = [None] def getcwd(): wd = cwd[0] if isinstance(wd, Exception): raise wd else: return wd segment_info = {'getcwd': getcwd, 'home': None} with replace_attr(common, 'os', new_os): cwd[0] = '/abc/def/ghi/foo/bar' self.assertEqual(common.cwd(pl=pl, segment_info=segment_info), [ {'contents': '/', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'abc', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'def', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'ghi', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'foo', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True, 'highlight_group': ['cwd:current_folder', 'cwd']}, ]) segment_info['home'] = '/abc/def/ghi' self.assertEqual(common.cwd(pl=pl, segment_info=segment_info), [ {'contents': '~', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'foo', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True, 'highlight_group': ['cwd:current_folder', 'cwd']}, ]) self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=3), [ {'contents': '~', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'foo', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True, 'highlight_group': ['cwd:current_folder', 'cwd']} ]) self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=1), [ {'contents': '⋯', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True, 'highlight_group': ['cwd:current_folder', 'cwd']} ]) self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=1, use_path_separator=True), [ {'contents': '⋯/', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': False}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': False, 'highlight_group': ['cwd:current_folder', 'cwd']} ]) self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=2, dir_shorten_len=2), [ {'contents': '~', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'fo', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': True, 'highlight_group': ['cwd:current_folder', 'cwd']} ]) self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=2, dir_shorten_len=2, use_path_separator=True), [ {'contents': '~/', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': False}, {'contents': 'fo/', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': False}, {'contents': 'bar', 'divider_highlight_group': 'cwd:divider', 'draw_inner_divider': False, 'highlight_group': ['cwd:current_folder', 'cwd']} ]) ose = OSError() ose.errno = 2 cwd[0] = ose self.assertEqual(common.cwd(pl=pl, segment_info=segment_info, dir_limit_depth=2, dir_shorten_len=2), [{'contents': '[not found]', 'divider_highlight_group': 'cwd:divider', 'highlight_group': ['cwd:current_folder', 'cwd'], 'draw_inner_divider': True}]) cwd[0] = OSError() self.assertRaises(OSError, common.cwd, pl=pl, segment_info=segment_info, dir_limit_depth=2, dir_shorten_len=2) cwd[0] = ValueError() self.assertRaises(ValueError, common.cwd, pl=pl, segment_info=segment_info, dir_limit_depth=2, dir_shorten_len=2)
def test_external_ip(self): pl = Pl() with replace_attr(common, 'urllib_read', urllib_read): self.assertEqual(common.external_ip(pl=pl), [{'contents': '127.0.0.1', 'divider_highlight_group': 'background:divider'}])
def test_kw_threaded_segment(self): log = [] pl = Pl() event = threading.Event() class TestSegment(KwThreadedSegment): interval = 10 @staticmethod def key(_key=(None, ), **kwargs): log.append(('key', _key, kwargs)) return _key def compute_state(self, key): event.set() sleep(0.1) log.append(('compute_state', key)) ret = key if isinstance(ret, Exception): raise ret else: return ret[0] def render_one(self, state, **kwargs): log.append(('render_one', state, kwargs)) if isinstance(state, Exception): raise state else: return state # Non-threaded tests segment = TestSegment() event.clear() self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', (None, ), { 'pl': pl }), ('compute_state', (None, )), ('render_one', None, { 'pl': pl }), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ('abc', ), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), 'abc') kwargs.update(_key=('def', )) self.assertEqual(segment(**kwargs), 'def') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', ('abc', ), { 'pl': pl }), ('compute_state', ('abc', )), ('render_one', 'abc', { 'pl': pl, '_key': ('abc', ) }), ('key', ('def', ), { 'pl': pl }), ('compute_state', ('def', )), ('render_one', 'def', { 'pl': pl, '_key': ('def', ) }), ]) log[:] = () segment = TestSegment() kwargs = {'pl': pl, '_key': ValueError('xyz'), 'update_first': False} event.clear() self.assertEqual(segment(**kwargs), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], { 'pl': pl }), ('compute_state', kwargs['_key']), ]) log[:] = () segment = TestSegment() kwargs = { 'pl': pl, '_key': (ValueError('abc'), ), 'update_first': False } event.clear() self.assertRaises(ValueError, segment, **kwargs) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('key', kwargs['_key'], { 'pl': pl }), ('compute_state', kwargs['_key']), ('render_one', kwargs['_key'][0], { 'pl': pl, '_key': kwargs['_key'] }), ]) log[:] = () # Threaded tests segment = TestSegment() kwargs = {'pl': pl, 'update_first': False, '_key': ('_abc', )} event.clear() segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log[:2], [ ('key', kwargs['_key'], { 'pl': pl }), ('render_one', None, { 'pl': pl, '_key': kwargs['_key'] }), ]) self.assertLessEqual(len(log), 3) if len(log) > 2: self.assertEqual(log[2], ('compute_state', kwargs['_key'])) log[:] = () segment = TestSegment() kwargs = {'pl': pl, 'update_first': True, '_key': ('_abc', )} event.clear() segment.startup(**kwargs) ret1 = segment(**kwargs) kwargs.update(_key=('_def', )) ret2 = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret1, '_abc') self.assertEqual(ret2, '_def') self.assertEqual(log, [ ('key', ('_abc', ), { 'pl': pl }), ('compute_state', ('_abc', )), ('render_one', '_abc', { 'pl': pl, '_key': ('_abc', ) }), ('key', ('_def', ), { 'pl': pl }), ('compute_state', ('_def', )), ('render_one', '_def', { 'pl': pl, '_key': ('_def', ) }), ]) log[:] = ()
def test_virtualenv(self): pl = Pl() with replace_env('VIRTUAL_ENV', '/abc/def/ghi') as segment_info: self.assertEqual(common.virtualenv(pl=pl, segment_info=segment_info), 'ghi') segment_info['environ'].pop('VIRTUAL_ENV') self.assertEqual(common.virtualenv(pl=pl, segment_info=segment_info), None)
def test_threaded_segment(self): log = [] pl = Pl() updates = [(None,)] lock = threading.Lock() event = threading.Event() block_event = threading.Event() class TestSegment(ThreadedSegment): interval = 10 def set_state(self, **kwargs): event.clear() log.append(('set_state', kwargs)) return super(TestSegment, self).set_state(**kwargs) def update(self, update_value): block_event.wait() event.set() # Make sleep first to prevent some race conditions log.append(('update', update_value)) with lock: ret = updates[0] if isinstance(ret, Exception): raise ret else: return ret[0] def render(self, update, **kwargs): log.append(('render', update, kwargs)) if isinstance(update, Exception): raise update else: return update # Non-threaded tests segment = TestSegment() block_event.set() updates[0] = (None,) self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', None, {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ('abc',) self.assertEqual(segment(pl=pl, update_first=False), 'abc') self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': False}), ]) log[:] = () segment = TestSegment() block_event.set() updates[0] = ValueError('abc') self.assertEqual(segment(pl=pl), None) self.assertEqual(thread_number(), 1) self.assertEqual(len(pl.exceptions), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ]) log[:] = () pl.exceptions[:] = () segment = TestSegment() block_event.set() updates[0] = (TypeError('def'),) self.assertRaises(TypeError, segment, pl=pl) self.assertEqual(thread_number(), 1) self.assertEqual(log, [ ('set_state', {}), ('update', None), ('render', updates[0][0], {'pl': pl, 'update_first': True}), ]) log[:] = () # Threaded tests segment = TestSegment() block_event.clear() kwargs = {'pl': pl, 'update_first': False, 'other': 1} with lock: updates[0] = ('abc',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) block_event.set() event.wait() segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, None) self.assertEqual(log, [ ('set_state', {'update_first': False, 'other': 1}), ('render', None, {'pl': pl, 'update_first': False, 'other': 1}), ('update', None), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'other': 1} with lock: updates[0] = ('def',) segment.startup(**kwargs) ret = segment(**kwargs) self.assertEqual(thread_number(), 2) segment.shutdown_event.set() segment.thread.join() self.assertEqual(ret, 'def') self.assertEqual(log, [ ('set_state', {'update_first': True, 'other': 1}), ('update', None), ('render', 'def', {'pl': pl, 'update_first': True, 'other': 1}), ]) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('abc',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = ('def',) self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'abc') self.assertEqual(ret2, 'def') self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'abc', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'abc'), ('update', 'def'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) log[:] = () segment = TestSegment() block_event.set() kwargs = {'pl': pl, 'update_first': True, 'interval': 0.2} with lock: updates[0] = ('ghi',) segment.startup(**kwargs) start = monotonic() ret1 = segment(**kwargs) with lock: updates[0] = TypeError('jkl') self.assertEqual(thread_number(), 2) sleep(0.5) ret2 = segment(**kwargs) segment.shutdown_event.set() segment.thread.join() end = monotonic() duration = end - start self.assertEqual(ret1, 'ghi') self.assertEqual(ret2, None) self.assertEqual(log[:5], [ ('set_state', {'update_first': True, 'interval': 0.2}), ('update', None), ('render', 'ghi', {'pl': pl, 'update_first': True, 'interval': 0.2}), ('update', 'ghi'), ('update', 'ghi'), ]) num_runs = len([e for e in log if e[0] == 'update']) self.assertAlmostEqual(duration / 0.2, num_runs, delta=1) self.assertEqual(num_runs - 1, len(pl.exceptions)) log[:] = ()
def test_workspace_lister(self): pl = Pl() with replace_attr(i3wm, 'get_i3_connection', lambda: Args(get_workspaces=self.get_workspaces)): self.assertEqual( list(i3wm.workspace_lister(pl=pl, segment_info={'a': 1})), [ ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '1: w1', 'focused': False, 'urgent': False, 'visible': False } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '2: w2', 'focused': False, 'urgent': False, 'visible': True } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'HDMI1', 'workspace': { 'name': '3: w3', 'focused': False, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'DVI01', 'workspace': { 'name': '4: w4', 'focused': True, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ]) self.assertEqual( list( i3wm.workspace_lister(pl=pl, segment_info={'a': 1}, output='LVDS1')), [ ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '1: w1', 'focused': False, 'urgent': False, 'visible': False } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '2: w2', 'focused': False, 'urgent': False, 'visible': True } }, { 'draw_inner_divider': None }), ]) self.assertEqual( list( i3wm.workspace_lister(pl=pl, segment_info={ 'a': 1, 'output': 'LVDS1' })), [ ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '1: w1', 'focused': False, 'urgent': False, 'visible': False } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '2: w2', 'focused': False, 'urgent': False, 'visible': True } }, { 'draw_inner_divider': None }), ]) self.assertEqual( list( i3wm.workspace_lister(pl=pl, segment_info={ 'a': 1, 'output': 'LVDS1' }, output=False)), [ ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '1: w1', 'focused': False, 'urgent': False, 'visible': False } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'LVDS1', 'workspace': { 'name': '2: w2', 'focused': False, 'urgent': False, 'visible': True } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'HDMI1', 'workspace': { 'name': '3: w3', 'focused': False, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'DVI01', 'workspace': { 'name': '4: w4', 'focused': True, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ]) self.assertEqual( list( i3wm.workspace_lister(pl=pl, segment_info={'a': 1}, only_show=['focused', 'urgent'])), [ ({ 'a': 1, 'output': 'HDMI1', 'workspace': { 'name': '3: w3', 'focused': False, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'DVI01', 'workspace': { 'name': '4: w4', 'focused': True, 'urgent': True, 'visible': True } }, { 'draw_inner_divider': None }), ])