How to use format_exception_only method in Testify

Best Python code snippet using Testify_python

test_traceback.py

Source:test_traceback.py Github

copy

Full Screen

...12 def get_exception_format(self, func, exc):13 try:14 func()15 except exc, value:16 return traceback.format_exception_only(exc, value)17 else:18 raise ValueError, "call did not raise exception"19 def syntax_error_with_caret(self):20 compile("def fact(x):\n\treturn x!\n", "?", "exec")21 def syntax_error_with_caret_2(self):22 compile("1 +\n", "?", "exec")23 def syntax_error_without_caret(self):24 # XXX why doesn't compile raise the same traceback?25 import test.badsyntax_nocaret26 def syntax_error_bad_indentation(self):27 compile("def spam():\n print 1\n print 2", "?", "exec")28 def test_caret(self):29 err = self.get_exception_format(self.syntax_error_with_caret,30 SyntaxError)31 self.assertTrue(len(err) == 4)32 self.assertTrue(err[1].strip() == "return x!")33 self.assertIn("^", err[2]) # third line has caret34 self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place35 err = self.get_exception_format(self.syntax_error_with_caret_2,36 SyntaxError)37 self.assertIn("^", err[2]) # third line has caret38 self.assertTrue(err[2].count('\n') == 1) # and no additional newline39 self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place40 def test_nocaret(self):41 if is_jython:42 # jython adds a caret in this case (why shouldn't it?)43 return44 err = self.get_exception_format(self.syntax_error_without_caret,45 SyntaxError)46 self.assertTrue(len(err) == 3)47 self.assertTrue(err[1].strip() == "[x for x in x] = x")48 def test_bad_indentation(self):49 err = self.get_exception_format(self.syntax_error_bad_indentation,50 IndentationError)51 self.assertTrue(len(err) == 4)52 self.assertTrue(err[1].strip() == "print 2")53 self.assertIn("^", err[2])54 self.assertTrue(err[1].find("2") == err[2].find("^"))55 def test_bug737473(self):56 import os, tempfile, time57 savedpath = sys.path[:]58 testdir = tempfile.mkdtemp()59 try:60 sys.path.insert(0, testdir)61 testfile = os.path.join(testdir, 'test_bug737473.py')62 print >> open(testfile, 'w'), """63def test():64 raise ValueError"""65 if 'test_bug737473' in sys.modules:66 del sys.modules['test_bug737473']67 import test_bug73747368 try:69 test_bug737473.test()70 except ValueError:71 # this loads source code to linecache72 traceback.extract_tb(sys.exc_traceback)73 # If this test runs too quickly, test_bug737473.py's mtime74 # attribute will remain unchanged even if the file is rewritten.75 # Consequently, the file would not reload. So, added a sleep()76 # delay to assure that a new, distinct timestamp is written.77 # Since WinME with FAT32 has multisecond resolution, more than78 # three seconds are needed for this test to pass reliably :-(79 time.sleep(4)80 print >> open(testfile, 'w'), """81def test():82 raise NotImplementedError"""83 reload(test_bug737473)84 try:85 test_bug737473.test()86 except NotImplementedError:87 src = traceback.extract_tb(sys.exc_traceback)[-1][-1]88 self.assertEqual(src, 'raise NotImplementedError')89 finally:90 sys.path[:] = savedpath91 for f in os.listdir(testdir):92 os.unlink(os.path.join(testdir, f))93 os.rmdir(testdir)94 def test_base_exception(self):95 # Test that exceptions derived from BaseException are formatted right96 e = KeyboardInterrupt()97 lst = traceback.format_exception_only(e.__class__, e)98 self.assertEqual(lst, ['KeyboardInterrupt\n'])99 # String exceptions are deprecated, but legal. The quirky form with100 # separate "type" and "value" tends to break things, because101 # not isinstance(value, type)102 # and a string cannot be the first argument to issubclass.103 #104 # Note that sys.last_type and sys.last_value do not get set if an105 # exception is caught, so we sort of cheat and just emulate them.106 #107 # test_string_exception1 is equivalent to108 #109 # >>> raise "String Exception"110 #111 # test_string_exception2 is equivalent to112 #113 # >>> raise "String Exception", "String Value"114 #115 def test_string_exception1(self):116 str_type = "String Exception"117 err = traceback.format_exception_only(str_type, None)118 self.assertEqual(len(err), 1)119 self.assertEqual(err[0], str_type + '\n')120 def test_string_exception2(self):121 str_type = "String Exception"122 str_value = "String Value"123 err = traceback.format_exception_only(str_type, str_value)124 self.assertEqual(len(err), 1)125 self.assertEqual(err[0], str_type + ': ' + str_value + '\n')126 def test_format_exception_only_bad__str__(self):127 class X(Exception):128 def __str__(self):129 1 // 0130 err = traceback.format_exception_only(X, X())131 self.assertEqual(len(err), 1)132 str_value = '<unprintable %s object>' % X.__name__133 self.assertEqual(err[0], X.__name__ + ': ' + str_value + '\n')134 def test_without_exception(self):135 err = traceback.format_exception_only(None, None)136 self.assertEqual(err, ['None\n'])137 def test_unicode(self):138 err = AssertionError('\xff')139 lines = traceback.format_exception_only(type(err), err)140 self.assertEqual(lines, ['AssertionError: \xff\n'])141 err = AssertionError(u'\xe9')142 lines = traceback.format_exception_only(type(err), err)143 self.assertEqual(lines, ['AssertionError: \\xe9\n'])144class TracebackFormatTests(unittest.TestCase):145 def test_traceback_format(self):146 try:147 raise KeyError('blah')148 except KeyError:149 type_, value, tb = sys.exc_info()150 traceback_fmt = 'Traceback (most recent call last):\n' + \151 ''.join(traceback.format_tb(tb))152 file_ = StringIO()153 traceback_print(tb, file_)154 python_fmt = file_.getvalue()155 else:156 raise Error("unable to create test traceback string")...

Full Screen

Full Screen

format_exc_only_tests.py

Source:format_exc_only_tests.py Github

copy

Full Screen

...13 try:14 num1 / num215 except ZeroDivisionError as e:16 # new style17 traceback_new_out: list = format_exception_only(e)18 # old style19 exc_type, exc_value, _ = exc_info()20 traceback_old_out: list = format_exception_only(exc_type, exc_value)21 self.assertEqual(traceback_new_out, traceback_old_out)22 self.assertEqual(''.join(traceback_old_out), 'ZeroDivisionError: division by zero\n')23 def test_new_arg_name(self):24 """25 Testing new name for first parameter in method format_exception_only.26 """27 check_name: str = getfullargspec(format_exception_only).args[0]28 self.assertEqual(check_name, "exc")29if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful