codecamp

14.5 忽略或者期望测试失败

问题

You want to skip or mark selected tests as an anticipated failure in your unit tests.

解决方案

The unittest module has decorators that can be applied to selected test methods tocontrol their handling. For example:

import unittestimport osimport platform

class Tests(unittest.TestCase):def test_0(self):self.assertTrue(True)
@unittest.skip(‘skipped test')def test_1(self):

self.fail(‘should have failed!')

@unittest.skipIf(os.name=='posix', ‘Not supported on Unix')def test_2(self):

import winreg

@unittest.skipUnless(platform.system() == ‘Darwin', ‘Mac specific test')def test_3(self):

self.assertTrue(True)

@unittest.expectedFailuredef test_4(self):

self.assertEqual(2+2, 5)

if name == ‘main':unittest.main()
If you run this code on a Mac, you’ll get this output:

bash % python3 testsample.py -vtest_0 (main.Tests) ... oktest_1 (main.Tests) ... skipped ‘skipped test'test_2 (main.Tests) ... skipped ‘Not supported on Unix'test_3 (main.Tests) ... oktest_4 (main.Tests) ... expected failure

Ran 5 tests in 0.002s

OK (skipped=2, expected failures=1)

讨论

The skip() decorator can be used to skip over a test that you don’t want to run at all.skipIf() and skipUnless() can be a useful way to write tests that only apply to certainplatforms or Python versions, or which have other dependencies. Use the @expectedFailure decorator to mark tests that are known failures, but for which you don’t wantthe test framework to report more information.The decorators for skipping methods can also be applied to entire testing classes. Forexample:

@unittest.skipUnless(platform.system() == ‘Darwin', ‘Mac specific tests')class DarwinTests(unittest.TestCase):

...

14.4 将测试输出用日志记录到文件中
14.6 处理多个异常
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }