def test_repository_status(self): pl = Pl() segment_info = vim_module._get_segment_info() with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: None, directory=path)): self.assertEqual(vim.repository_status(pl=pl, segment_info=segment_info), None) with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda: 'DU', directory=path)): self.assertEqual(vim.repository_status(pl=pl, segment_info=segment_info), 'DU')
def test_user(self): new_os = new_module('os', getpid=lambda: 1) class Process(object): def __init__(self, pid): pass def username(self): return 'def' if hasattr(common, 'psutil') and not callable(common.psutil.Process.username): username = property(username) new_psutil = new_module('psutil', Process=Process) pl = Pl() with replace_env('USER', 'def') as segment_info: common.username = False 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'} ]) self.assertEqual(common.user(pl=pl, segment_info=segment_info, hide_user='******'), [ {'contents': 'def', 'highlight_group': 'user'} ]) self.assertEqual(common.user(pl=pl, segment_info=segment_info, hide_user='******'), None) 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_file_vcs_status(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 file: 'M', directory=path)): self.assertEqual(vim.file_vcs_status(pl=pl, segment_info=segment_info), [{'highlight_group': ['file_vcs_status_M', 'file_vcs_status'], 'contents': 'M'}]) with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda file: None, directory=path)): self.assertEqual(vim.file_vcs_status(pl=pl, segment_info=segment_info), None) with vim_module._with('buffer', '/bar') as segment_info: with vim_module._with('bufoptions', buftype='nofile'): with replace_attr(vim, 'guess', lambda path: Args(branch=lambda: os.path.basename(path), status=lambda file: 'M', directory=path)): self.assertEqual(vim.file_vcs_status(pl=pl, segment_info=segment_info), None)
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)): self.assertEqual(vim.branch(pl=pl, segment_info=segment_info), [{'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)): self.assertEqual(vim.branch(pl=pl, segment_info=segment_info), [{'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_file_vcs_status(self): pl = Pl() create_watcher = get_fallback_create_watcher() file_vcs_status = partial(vim.file_vcs_status, pl=pl, create_watcher=create_watcher) with vim_module._with('buffer', '/foo') as segment_info: with replace_attr(vim, 'guess', get_dummy_guess(status=lambda file: 'M')): self.assertEqual(file_vcs_status(segment_info=segment_info), [{'highlight_group': ['file_vcs_status_M', 'file_vcs_status'], 'contents': 'M'}]) with replace_attr(vim, 'guess', get_dummy_guess(status=lambda file: None)): self.assertEqual(file_vcs_status(segment_info=segment_info), None) with vim_module._with('buffer', '/bar') as segment_info: with vim_module._with('bufoptions', buftype='nofile'): with replace_attr(vim, 'guess', get_dummy_guess(status=lambda file: 'M')): self.assertEqual(file_vcs_status(segment_info=segment_info), 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')): self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), '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')): self.assertEqual(common.branch(pl=pl, segment_info=segment_info, status_colors=False), '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), 'tests') with replace_attr(common, 'guess', lambda path: None): self.assertEqual(common.branch(pl=pl, segment_info=segment_info), None)
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_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_main_err(self): parser = get_argparser() out = StrIO() err = StrIO() def flush(): out.truncate(0) err.truncate(0) with replace_attr(sys, 'stdout', out, 'stderr', err): for raising_args, raising_reg in [ ([], 'too few arguments|the following arguments are required: ext'), (['-r'], 'expected one argument'), (['shell', '-r'], 'expected one argument'), (['shell', '-w'], 'expected one argument'), (['shell', '-c'], 'expected one argument'), (['shell', '-t'], 'expected one argument'), (['shell', '-p'], 'expected one argument'), (['shell', '-R'], 'expected one argument'), (['shell', '--renderer_module'], 'expected one argument'), (['shell', '--width'], 'expected one argument'), (['shell', '--last_exit_code'], 'expected one argument'), (['shell', '--last_pipe_status'], 'expected one argument'), (['shell', '--config'], 'expected one argument'), (['shell', '--theme_option'], 'expected one argument'), (['shell', '--config_path'], 'expected one argument'), (['shell', '--renderer_arg'], 'expected one argument'), (['shell', '--jobnum'], 'expected one argument'), (['-r', 'zsh_prompt'], 'too few arguments|the following arguments are required: ext'), (['shell', '--last_exit_code', 'i'], 'invalid int value'), (['shell', '--last_pipe_status', '1 i'], 'invalid <lambda> value'), (['shell', '-R', 'abc'], 'invalid <lambda> value'), ]: self.assertRaises(SystemExit, parser.parse_args, raising_args) self.assertFalse(out.getvalue()) self.assertRegexpMatches(err.getvalue(), raising_reg) flush()
def test_top_log_format(self): out = StringIO() err = StringIO() stream = StringIO() stream1 = StringIO() stream2 = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config( 'utf-8', { 'log_file': [ [ 'logging.StreamHandler', [[stream1]], 'WARNING', 'FOO' ], ['logging.StreamHandler', [[stream2]], 'WARNING'], ], 'log_format': 'BAR' }) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.warn('Foo') pl.error('Bar') close_handlers(logger) self.assertEqual(stream2.getvalue(), 'BAR\nBAR\n') self.assertEqual(stream1.getvalue(), 'FOO\nFOO\n') self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_file_handler_create_dir(self): out = StringIO() err = StringIO() stream = StringIO() file_name = 'test_logging-test_file_handler_create_dir/file' self.assertFalse(os.path.isdir(os.path.dirname(file_name))) with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': file_name}) try: logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') close_handlers(logger) self.assertTrue(os.path.isdir(os.path.dirname(file_name))) with codecs.open(file_name, encoding='utf-8') as fp: self.assertMatches( fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') finally: rmtree(os.path.dirname(file_name)) self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_multiple_files_and_stream(self): out = StringIO() err = StringIO() stream = StringIO() file_name_1 = 'test_logging-test_multiple_files_and_stream-1' file_name_2 = file_name_1[:-1] + '2' with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config( 'utf-8', {'log_file': [file_name_1, file_name_2, None]}) try: try: logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') close_handlers(logger) for file_name in (file_name_1, file_name_2): with codecs.open(file_name, encoding='utf-8') as fp: self.assertMatches( fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') finally: os.unlink(file_name_1) finally: os.unlink(file_name_2) self.assertMatches( stream.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_top_log_level(self): out = StringIO() err = StringIO() stream = StringIO() stream1 = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config( 'utf-8', { 'log_file': [ ['logging.StreamHandler', [[stream1]], 'DEBUG'], ], 'log_level': 'DEBUG' }) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.debug('Foo') pl.error('Bar') close_handlers(logger) self.assertMatches( stream1.getvalue(), ('^' + TIMESTAMP_RE + ':DEBUG:__unknown__:Foo\n' + TIMESTAMP_RE + ':ERROR:__unknown__:Bar\n$')) self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_handler_args_kwargs(self): out = StringIO() err = StringIO() stream = StringIO() file_name = 'test_logging-test_handler_args_kwargs' with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': [ ['RotatingFileHandler', [[file_name], {'maxBytes': 1, 'backupCount': 1}]] ]}) try: try: logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') pl.error('Bar') close_handlers(logger) with codecs.open(file_name, encoding='utf-8') as fp: self.assertMatches(fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Bar\n$') with codecs.open(file_name + '.1', encoding='utf-8') as fp: self.assertMatches(fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') finally: os.unlink(file_name + '.1') finally: os.unlink(file_name) self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_weather(self): pl = Pl() with replace_attr(common, 'urllib_read', urllib_read): self.assertEqual(common.weather(pl=pl), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9°C', 'gradient_level': 30.0} ]) self.assertEqual(common.weather(pl=pl, temp_coldest=0, temp_hottest=100), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9°C', 'gradient_level': 0} ]) self.assertEqual(common.weather(pl=pl, temp_coldest=-100, temp_hottest=-50), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9°C', 'gradient_level': 100} ]) self.assertEqual(common.weather(pl=pl, icons={'cloudy': 'o'}), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': 'o '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9°C', 'gradient_level': 30.0} ]) self.assertEqual(common.weather(pl=pl, icons={'partly_cloudy_day': 'x'}), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': 'x '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9°C', 'gradient_level': 30.0} ]) self.assertEqual(common.weather(pl=pl, unit='F'), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '16°F', 'gradient_level': 30.0} ]) self.assertEqual(common.weather(pl=pl, unit='K'), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '264K', 'gradient_level': 30.0} ]) self.assertEqual(common.weather(pl=pl, temp_format='{temp:.1e}C'), [ {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_condition_partly_cloudy_day', 'weather_condition_cloudy', 'weather_conditions', 'weather'], 'contents': '☁ '}, {'divider_highlight_group': 'background:divider', 'highlight_group': ['weather_temp_gradient', 'weather_temp', 'weather'], 'contents': '-9.0e+00C', 'gradient_level': 30.0} ])
def test_output_lister(self): pl = Pl() with replace_attr(i3wm, 'get_connected_xrandr_outputs', self.get_outputs): self.assertEqual( list(i3wm.output_lister(pl=pl, segment_info={'a': 1})), [ ({ 'a': 1, 'output': 'LVDS1' }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'HDMI1' }, { 'draw_inner_divider': None }), ({ 'a': 1, 'output': 'DVI01' }, { 'draw_inner_divider': None }), ])
def test_wm(self): from powerline.segments import common from imp import reload reload(common) from powerline import Powerline with replace_attr(common, 'urllib_read', urllib_read): Powerline(ext='wm', renderer_module='pango_markup', run_once=True).render() reload(common)
def test_branch(self): pl = Pl() create_watcher = get_fallback_create_watcher() branch = partial(vim.branch, pl=pl, create_watcher=create_watcher) with vim_module._with('buffer', '/foo') as segment_info: with replace_attr(vim, 'guess', get_dummy_guess(status=lambda: None)): with replace_attr(vim, 'tree_status', lambda repo, pl: None): self.assertEqual(branch(segment_info=segment_info, status_colors=False), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch'], 'contents': 'foo'}]) self.assertEqual(branch(segment_info=segment_info, status_colors=True), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch_clean', 'branch'], 'contents': 'foo'}]) with replace_attr(vim, 'guess', get_dummy_guess(status=lambda: 'DU')): with replace_attr(vim, 'tree_status', lambda repo, pl: 'DU'): self.assertEqual(branch(segment_info=segment_info, status_colors=False), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch'], 'contents': 'foo'}]) self.assertEqual(branch(segment_info=segment_info, status_colors=True), [{'divider_highlight_group': 'branch:divider', 'highlight_group': ['branch_dirty', 'branch'], 'contents': 'foo'}])
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_tmux(self): from powerline.segments import common from imp import reload reload(common) from powerline.shell import ShellPowerline with replace_attr(common, 'urllib_read', urllib_read): with ShellPowerline(Args(ext=['tmux']), run_once=False) as powerline: powerline.render() with ShellPowerline(Args(ext=['tmux']), run_once=False) as powerline: powerline.render()
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_output_lister(self): pl = Pl() with replace_attr(i3wm, 'get_connected_xrandr_outputs', self.get_outputs): self.assertEqual( list(i3wm.output_lister(pl=pl, segment_info={'a': 1})), [ ({'a': 1, 'output': 'LVDS1'}, {'draw_inner_divider': None}), ({'a': 1, 'output': 'HDMI1'}, {'draw_inner_divider': None}), ({'a': 1, 'output': 'DVI01'}, {'draw_inner_divider': None}), ] )
def swap_attributes(config, powerline_module): return replace_attr(powerline_module, 'os', Args( path=Args( isfile=lambda path: path.lstrip('/').replace('.json', '') in config, join=os.path.join, expanduser=lambda path: path, realpath=lambda path: path, dirname=os.path.dirname, ), environ={}, ))
def test_stderr_handler_is_default(self): out = StringIO() err = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {}) logger, pl, get_module_attr = create_logger(common_config) pl.error('Foo') close_handlers(logger) self.assertMatches(err.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') self.assertEqual(out.getvalue(), '')
def test_system_load(self): pl = Pl() with replace_module_module(common, 'os', getloadavg=lambda: (7.5, 3.5, 1.5)): with replace_attr(common, '_cpu_count', lambda: 2): self.assertEqual(common.system_load(pl=pl), [{'contents': '7.5 ', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 100}, {'contents': '3.5 ', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 75.0}, {'contents': '1.5', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 0}]) self.assertEqual(common.system_load(pl=pl, format='{avg:.0f}', threshold_good=0, threshold_bad=1), [{'contents': '8 ', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 100}, {'contents': '4 ', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 100}, {'contents': '2', 'highlight_group': ['system_load_gradient', 'system_load'], 'divider_highlight_group': 'background:divider', 'gradient_level': 75.0}])
def test_branch(self): pl = Pl() create_watcher = get_fallback_create_watcher() segment_info = {'getcwd': os.getcwd} branch = partial(common.branch, pl=pl, create_watcher=create_watcher) with replace_attr(common, 'guess', get_dummy_guess(status=lambda: None, directory='/tmp/tests')): with replace_attr(common, 'tree_status', lambda repo, pl: None): self.assertEqual(branch(segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) self.assertEqual(branch(segment_info=segment_info, status_colors=True), [{'contents': 'tests', 'highlight_group': ['branch_clean', 'branch']}]) with replace_attr(common, 'guess', get_dummy_guess(status=lambda: 'D ', directory='/tmp/tests')): with replace_attr(common, 'tree_status', lambda repo, pl: 'D '): self.assertEqual(branch(segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) self.assertEqual(branch(segment_info=segment_info, status_colors=True), [{'contents': 'tests', 'highlight_group': ['branch_dirty', 'branch']}]) self.assertEqual(branch(segment_info=segment_info, status_colors=False), [{'highlight_group': ['branch'], 'contents': 'tests'}]) with replace_attr(common, 'guess', lambda path, create_watcher: None): self.assertEqual(branch(segment_info=segment_info, status_colors=False), None)
def test_fuzzy_time(self): time = Args(hour=0, minute=45) pl = Pl() with replace_attr(common, 'datetime', Args(now=lambda: time)): self.assertEqual(common.fuzzy_time(pl=pl), 'quarter to one') time.hour = 23 time.minute = 59 self.assertEqual(common.fuzzy_time(pl=pl), 'round about midnight') time.minute = 33 self.assertEqual(common.fuzzy_time(pl=pl), 'twenty-five to twelve') time.minute = 60 self.assertEqual(common.fuzzy_time(pl=pl), 'twelve o\'clock')
def test_stderr_handler_is_default(self): out = StringIO() err = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {}) logger, pl, get_module_attr = create_logger(common_config) pl.error('Foo') close_handlers(logger) self.assertMatches( err.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') self.assertEqual(out.getvalue(), '')
def test_safe_unicode(self): self.assertStringsIdentical('abc', plu.safe_unicode('abc')) self.assertStringsIdentical('abc', plu.safe_unicode(b'abc')) self.assertStringsIdentical('«»', plu.safe_unicode(b'\xc2\xab\xc2\xbb')) with replace_attr(plu, 'get_preferred_output_encoding', lambda: 'latin1'): self.assertStringsIdentical('ÿ', plu.safe_unicode(b'\xFF')) self.assertStringsIdentical('None', plu.safe_unicode(None)) class FailingStr(object): def __str__(self): raise NotImplementedError('Fail!') self.assertStringsIdentical('Fail!', plu.safe_unicode(FailingStr()))
def test_explicit_stream_handler_implicit_stream(self): out = StringIO() err = StringIO() stream = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': [['logging.StreamHandler', []]]}) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') close_handlers(logger) self.assertMatches(stream.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
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_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': 14, }]) self.assertEqual(common.battery(pl=pl, format='{capacity:.2f}'), [{ 'contents': '0.86', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 14, }]) self.assertEqual(common.battery(pl=pl, steps=7), [{ 'contents': '86%', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 14, }]) self.assertEqual(common.battery(pl=pl, gamify=True), [ { 'contents': '♥♥♥♥', 'draw_inner_divider': False, 'highlight_group': ['battery_full', 'battery_gradient', 'battery'], 'gradient_level': 0 }, { 'contents': '♥', 'draw_inner_divider': False, 'highlight_group': ['battery_empty', 'battery_gradient', 'battery'], 'gradient_level': 100 } ]) self.assertEqual(common.battery(pl=pl, gamify=True, full_heart='+', empty_heart='-', steps='10'), [ { 'contents': '++++++++', 'draw_inner_divider': False, 'highlight_group': ['battery_full', 'battery_gradient', 'battery'], 'gradient_level': 0 }, { 'contents': '--', 'draw_inner_divider': False, 'highlight_group': ['battery_empty', 'battery_gradient', 'battery'], 'gradient_level': 100 } ])
def test_strwidth_ucs_4(self): self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'abcd')) self.assertEqual(4, plu.strwidth_ucs_4(width_data, 'AB')) if sys.maxunicode < 0x10FFFF: raise SkipTest('Can only test strwidth_ucs_4 in UCS-4 Pythons') def east_asian_width(ch): assert (len(ch) == 1) assert ord(ch) == 0x1F48E return 'F' with replace_attr(plu, 'east_asian_width', east_asian_width): # Warning: travis unicodedata.east_asian_width for some reason # thinks this character is 5 symbols wide. self.assertEqual(2, plu.strwidth_ucs_4(width_data, '\U0001F48E'))
def test_explicit_none(self): out = StringIO() err = StringIO() stream = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': [None]}) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') close_handlers(logger) self.assertMatches( stream.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_logger_format(self): out = StringIO() err = StringIO() stream = StringIO() stream1 = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': [ ['logging.StreamHandler', [[stream1]], 'WARNING', 'FOO'], ]}) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.warn('Foo') pl.error('Bar') close_handlers(logger) self.assertEqual(stream1.getvalue(), 'FOO\nFOO\n') self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_logger_level_not_overriding_default(self): out = StringIO() err = StringIO() stream = StringIO() stream1 = StringIO() with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': [ ['logging.StreamHandler', [[stream1]], 'DEBUG'], ]}) logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.debug('Foo') pl.error('Bar') close_handlers(logger) self.assertMatches(stream1.getvalue(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Bar\n$') self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_file_handler(self): out = StringIO() err = StringIO() stream = StringIO() file_name = 'test_logging-test_file_handler' with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config('utf-8', {'log_file': file_name}) try: logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') close_handlers(logger) with codecs.open(file_name, encoding='utf-8') as fp: self.assertMatches(fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') finally: os.unlink(file_name) self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_main_err(self): parser = get_argparser() out = StrIO() err = StrIO() def flush(): out.truncate(0) err.truncate(0) with replace_attr(sys, 'stdout', out, 'stderr', err): for raising_args, raising_reg in [ ([], 'too few arguments|the following arguments are required: ext' ), (['-r'], 'expected one argument'), (['shell', '-r'], 'expected one argument'), (['shell', '-w'], 'expected one argument'), (['shell', '-c'], 'expected one argument'), (['shell', '-t'], 'expected one argument'), (['shell', '-p'], 'expected one argument'), (['shell', '-R'], 'expected one argument'), (['shell', '--renderer_module'], 'expected one argument'), (['shell', '--width'], 'expected one argument'), (['shell', '--last_exit_code'], 'expected one argument'), (['shell', '--last_pipe_status'], 'expected one argument'), (['shell', '--config'], 'expected one argument'), (['shell', '--theme_option'], 'expected one argument'), (['shell', '--config_path'], 'expected one argument'), (['shell', '--renderer_arg'], 'expected one argument'), (['shell', '--jobnum'], 'expected one argument'), (['-r', 'zsh_prompt'], 'too few arguments|the following arguments are required: ext' ), (['shell', '--last_exit_code', 'i'], 'invalid int value'), (['shell', '--last_pipe_status', '1 i'], 'invalid <lambda> value'), (['shell', '-R', 'abc'], 'invalid <lambda> value'), ]: self.assertRaises(SystemExit, parser.parse_args, raising_args) self.assertFalse(out.getvalue()) self.assertRegexpMatches(err.getvalue(), raising_reg) flush()
def test_handler_args_kwargs(self): out = StringIO() err = StringIO() stream = StringIO() file_name = 'test_logging-test_handler_args_kwargs' with replace_attr(sys, 'stdout', out, 'stderr', err): common_config = finish_common_config( 'utf-8', { 'log_file': [[ 'RotatingFileHandler', [[file_name], { 'maxBytes': 1, 'backupCount': 1 }] ]] }) try: try: logger, pl, get_module_attr = create_logger(common_config, stream=stream) pl.error('Foo') pl.error('Bar') close_handlers(logger) with codecs.open(file_name, encoding='utf-8') as fp: self.assertMatches( fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Bar\n$') with codecs.open(file_name + '.1', encoding='utf-8') as fp: self.assertMatches( fp.read(), '^' + TIMESTAMP_RE + ':ERROR:__unknown__:Foo\n$') finally: os.unlink(file_name + '.1') finally: os.unlink(file_name) self.assertEqual(stream.getvalue(), '') self.assertEqual(err.getvalue(), '') self.assertEqual(out.getvalue(), '')
def test_battery(self): pl = Pl() def _get_capacity(): return 86 with replace_attr(common, '_get_capacity', _get_capacity): self.assertEqual(common.battery(pl=pl), [{ 'contents': '80%', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 80.0 }]) self.assertEqual(common.battery(pl=pl, format='{batt:.2f}'), [{ 'contents': '0.80', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 80.0 }]) self.assertEqual(common.battery(pl=pl, steps=7), [{ 'contents': '86%', 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 85.71428571428571 }]) self.assertEqual(common.battery(pl=pl, gamify=True), [ { 'contents': '♥♥♥♥', 'draw_soft_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 99 }, { 'contents': '♥', 'draw_soft_divider': False, 'highlight_group': ['battery_gradient', 'battery'], 'gradient_level': 1 } ])
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 }), ])
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_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_main_normal(self): parser = get_argparser() out = StrIO() err = StrIO() with replace_attr(sys, 'stdout', out, 'stderr', err): for argv, expargs in [ (['shell'], { 'ext': ['shell'] }), (['shell', '-r', '.zsh'], { 'ext': ['shell'], 'renderer_module': '.zsh' }), ([ 'shell', 'left', '-r', '.zsh', '--last_exit_code', '10', '--last_pipe_status', '10 20 30', '--jobnum=10', '-w', '100', '-c', 'common.term_truecolor=true', '-c', 'common.spaces=4', '-t', 'default.segment_data.hostname.before=H:', '-p', '.', '-p', '..', '-R', 'smth={"abc":"def"}', ], { 'ext': ['shell'], 'side': 'left', 'renderer_module': '.zsh', 'last_exit_code': 10, 'last_pipe_status': [10, 20, 30], 'jobnum': 10, 'width': 100, 'config': { 'common': { 'term_truecolor': True, 'spaces': 4 } }, 'theme_option': { 'default': { 'segment_data': { 'hostname': { 'before': 'H:' } } } }, 'config_path': ['.', '..'], 'renderer_arg': { 'smth': { 'abc': 'def' } }, }), (['shell', '-R', 'arg=true'], { 'ext': ['shell'], 'renderer_arg': { 'arg': True } }), (['shell', '-R', 'arg=true', '-R', 'arg='], { 'ext': ['shell'], 'renderer_arg': {} }), (['shell', '-R', 'arg='], { 'ext': ['shell'], 'renderer_arg': {} }), (['shell', '-t', 'default.segment_info={"hostname": {}}'], { 'ext': ['shell'], 'theme_option': { 'default': { 'segment_info': { 'hostname': {} } } }, }), (['shell', '-c', 'common={ }'], { 'ext': ['shell'], 'config': { 'common': {} } }), ]: args = parser.parse_args(argv) finish_args(args) for key, val in expargs.items(): self.assertEqual(getattr(args, key), val) for key, val in args.__dict__.items(): if key not in expargs: self.assertFalse( val, msg= 'key {0} is {1} while it should be something false' .format(key, val)) self.assertFalse(err.getvalue() + out.getvalue(), msg='unexpected output: {0!r} {1!r}'.format( err.getvalue(), out.getvalue(), ))
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_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)