def test_Logging_context_manager(self): # # Note: We must make sure to acquire a fresh logger *within* the capture_all # context, because otherwise, stderr redirection won't work. Thus, we have to # initialize the logger and call one of its logging methods within one function # which we will then pass to capture_all. # def _log(method='debug', with_context_manager=False, level=logging.DEBUG): logger = log.get_logger( test=True, force_default_config=True, config_dir=self.tmp_path()) method = getattr(logger, method) if with_context_manager: with log.Logging(logger=logger, level=level): method('', extra=dict(lines=['a', 'ä'])) else: method('') with capture_all(_log, with_context_manager=False) as res: self.assertNotIn('DEBUG', res[2]) with capture_all(_log, with_context_manager=True) as res: self.assertIn('DEBUG', res[2]) with capture_all(_log, with_context_manager=True, level=logging.WARN) as res: self.assertNotIn('DEBUG', res[2]) with capture_all( _log, method='warn', with_context_manager=True, level=logging.WARN ) as res: self.assertIn('WARN', res[2])
def test_ArgumentParser(self): from clldutils.clilib import ArgumentParser, ParserError def cmd(args): """ docstring """ if len(args.args) < 1: raise ParserError('not enough arguments') print(args.args[0]) parser = ArgumentParser('pkg', cmd) with capture(parser.main, args=['help', 'cmd']) as out: self.assertIn('docstring', out) with capture(parser.main, args=['cmd', 'arg']) as out: self.assertIn('arg', out) self.assertEqual(parser.main(args=['cmd', 'arg']), 0) with capture(parser.main, args=['cmd']) as out: self.assertIn('not enough arguments', out) with capture_all(parser.main, args=['x']) as res: self.assertNotEqual(res[0], 0) self.assertTrue(res[1].startswith('invalid'))
def test_git_describe(self): from clldutils.path import git_describe d = self.tmp_path('testdir') self.assertRaises(ValueError, git_describe, d) d.mkdir() with capture_all(git_describe, d) as res: self.assertEqual(res[0], 'testdir')
def test_confirm(self): from clldutils.clilib import confirm with patch('clldutils.clilib.input', Mock(return_value='')): self.assertTrue(confirm('a?')) self.assertFalse(confirm('a?', default=False)) with patch('clldutils.clilib.input', Mock(side_effect=['x', 'y'])): with capture_all(confirm, 'a?') as res: self.assertTrue(res[0]) self.assertIn('Please respond', res[1])
def test_capture_all(self): from clldutils.testing import capture_all, capture def func(): print('hello') print('world', file=sys.stderr) return 5 with capture_all(func) as res: ret, out, err = res self.assertEqual(ret, 5) self.assertEqual(out.strip(), 'hello') self.assertEqual(err.strip(), 'world') with capture(func) as out: self.assertEqual(out.strip(), 'hello')