- 浏览: 180005 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
beiizl:
用了博主的方法和代码,不同证书居然可以正常通讯?
Java SSLSocket的使用 -
SHANGLIJAVA:
sorry,运行时没看清。博主的代码确实没问题。。。
Java SSLSocket的使用 -
SHANGLIJAVA:
YoungeeOne 写道最后一个为什么初始化一个空的证书,也 ...
Java SSLSocket的使用 -
q979713444:
那这个的心跳怎么弄呢
Java SSLSocket的使用 -
43350860:
busybox不是每台机器有安装的, 有没有比较裸的办法获取p ...
android中查看端口占用
使用python unittest做测试
http://www.cnblogs.com/imouren/archive/2011/08/04/2127997.html
python unittest单元测试
http://catmic27.blog.51cto.com/2517040/946852
# coding: utf-8 class Area: def __init__(self, width=100, height=100): self._width = width self._height = height def get_width(self): return self._width def get_height(self): return self._height def get_area(self): return self._width * self._height def set_width(self, width): if width <= 0: raise ValueError, "Illegal width value" self._width = width def set_height(self, height): if height <= 0: raise ValueError, "Illegal height value" self._height = height import unittest class AreaTest(unittest.TestCase): def setUp(self): self.area = Area() def tearDown(self): self.area = None def test_area(self): self.assertEqual(self.area.get_area(), 100 * 100) def test_width(self): self.area.set_width(1) self.assertEqual(self.area.get_area(), 1 * 100) if __name__ == '__main__': unittest.main()
unittest.TestCase有如下用于测试的方法
assertAlmostEqual assertAlmostEquals assertEqual assertEquals assertFalse assertNotAlmostEqual assertNotAlmostEquals assertNotEqual assertNotEquals assertRaises assertTrue assert_ countTestCases debug defaultTestResult fail failIf failIfAlmostEqual failIfEqual failUnless failUnlessAlmostEqual failUnlessEqual failUnlessRaises failureException id run setUp shortDescription tearDown
# coding: utf-8 class SampleClass: """ >>> print 1 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: >>> ... Multiline example: >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() ... print sc.get(), 6 12 24 48 96 192 384 768 1536 3072 """ def __init__(self, val): """ >>> print SampleClass(12).get() 12 """ self.val = val def get(self): """ >>> print SampleClass(3).get() 3 """ return self.val def double(self): """ >>> print SampleClass(10).double().get() 20 """ return SampleClass(self.val + self.val) def a_staticmethod(val): """ 这个静态方法将传入的值加1并返回 >>> print SampleClass.a_staticmethod(10) 11 """ return val + 1 a_staticmethod = staticmethod(a_staticmethod) def a_classmethod(cls, val): """ 这个类方法将传入的值加12并返回 >>> print SampleClass.a_classmethod(100) 112 >>> print SampleClass(0).a_classmethod(0) 12 """ return val + 12 a_classmethod = classmethod(a_classmethod) a_property = property(get, doc=""" >>> print SampleClass(22).a_property 22 """) class NestedClass: """ 这个嵌套类对val进行平方求值 >>> x = SampleClass.NestedClass(5) >>> y = x.square() >>> print y.get() 25 """ def __init__(self, val=0): """ """ self.val = val def square(self): return SampleClass.NestedClass(self.val * self.val) def get(self): return self.val def sample_func(v): """ Blah blah >>> print sample_func(22) 44 >>> print sample_func(0) 0 >>> print sample_func(-22) -44 Yee ha! """ return v+v """ 这是一个使用doctest进行测试的小例子. 主要测试factorial 是否返回阶乘 >>> factorial(5) 120 """ def factorial(n): """Return the factorial of n, an exact integer >= 0. If the result is small enough to fit in an int, return an int. Else return a long. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> [factorial(long(n)) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000L >>> factorial(30L) 265252859812191058636308480000000L """ result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result if __name__ == '__main__': import doctest doctest.testmod()
# -*- coding: utf-8 -*- import doctest class SampleNewStyleClass(object): r""" 打印1, 2, 3, 中间有换行 >>> print '1\n2\n3' 1 2 3 """ def __init__(self, val): """ """ self.val = val def double(self): """ 这个方法返回一个新的SampleNewStyleClass对象, 其值为原来的2倍 >>> print SampleNewStyleClass(23).double().get() 46 """ return SampleNewStyleClass(self.val + self.val) def get(self): """ 这个方法返回val值 >>> print SampleNewStyleClass(25).get() 25 """ return self.val if __name__ == '__main__': doctest.testmod()
def test_DocTestSuite(): """DocTestSuite creates a unittest test suite from a doctest. We create a Suite by providing a module. A module can be provided by passing a module object: >>> import unittest >>> import test.sample_doctest >>> suite = doctest.DocTestSuite(test.sample_doctest) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can also supply the module by name: >>> suite = doctest.DocTestSuite('test.sample_doctest') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can use the current module: >>> suite = test.sample_doctest.test_suite() >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=4> We can supply global variables. If we pass globs, they will be used instead of the module globals. Here we'll pass an empty globals, triggering an extra error: >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> Alternatively, we can provide extra globals. Here we'll make an error go away by providing an extra global variable: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... extraglobs={'y': 1}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> You can pass option flags. Here we'll cause an extra error by disabling the blank-line feature: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=5> You can supply setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocTestSuite('test.sample_doctest', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: 'module' object has no attribute 'sillySetup' The setUp and tearDown funtions are passed test objects. Here we'll use the setUp function to supply the missing variable y: >>> def setUp(test): ... test.globs['y'] = 1 >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=9 errors=0 failures=3> Here, we didn't need to use a tearDown function because we modified the test globals, which are a copy of the sample_doctest module dictionary. The test globals are automatically cleared for us after a test. """ def test_DocFileSuite(): """We can test tests found in text files using a DocFileSuite. We create a suite by providing the names of one or more text files that include examples: >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=3> The test files are looked for in the directory containing the calling module. A package keyword argument can be provided to specify a different relative location. >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=3> Support for using a package's __loader__.get_data() is also provided. >>> import unittest, pkgutil, test >>> added_loader = False >>> if not hasattr(test, '__loader__'): ... test.__loader__ = pkgutil.get_loader(test) ... added_loader = True >>> try: ... suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... package='test') ... suite.run(unittest.TestResult()) ... finally: ... if added_loader: ... del test.__loader__ <unittest.result.TestResult run=3 errors=0 failures=3> '/' should be used as a path separator. It will be converted to a native separator at run time: >>> suite = doctest.DocFileSuite('../test/test_doctest.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> If DocFileSuite is used from an interactive session, then files are resolved relative to the directory of sys.argv[0]: >>> import types, os.path, test.test_doctest >>> save_argv = sys.argv >>> sys.argv = [test.test_doctest.__file__] >>> suite = doctest.DocFileSuite('test_doctest.txt', ... package=types.ModuleType('__main__')) >>> sys.argv = save_argv By setting `module_relative=False`, os-specific paths may be used (including absolute paths and paths relative to the working directory): >>> # Get the absolute path of the test package. >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__) >>> test_pkg_path = os.path.split(test_doctest_path)[0] >>> # Use it to find the absolute path of test_doctest.txt. >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt') >>> suite = doctest.DocFileSuite(test_file, module_relative=False) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=1> It is an error to specify `package` when `module_relative=False`: >>> suite = doctest.DocFileSuite(test_file, module_relative=False, ... package='test') Traceback (most recent call last): ValueError: Package may only be specified for module-relative paths. You can specify initial global variables: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> In this case, we supplied a missing favorite color. You can provide doctest options: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE, ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=3> And, you can provide setUp and tearDown functions: >>> def setUp(t): ... import test.test_doctest ... test.test_doctest.sillySetup = True >>> def tearDown(t): ... import test.test_doctest ... del test.test_doctest.sillySetup Here, we installed a silly variable that the test expects: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (most recent call last): ... AttributeError: 'module' object has no attribute 'sillySetup' The setUp and tearDown funtions are passed test objects. Here, we'll use a setUp function to set the favorite color in test_doctest.txt: >>> def setUp(test): ... test.globs['favorite_color'] = 'blue' >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp) >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> Here, we didn't need to use a tearDown function because we modified the test globals. The test globals are automatically cleared for us after a test. Tests in a file run using `DocFileSuite` can also access the `__file__` global, which is set to the name of the file containing the tests: >>> suite = doctest.DocFileSuite('test_doctest3.txt') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=1 errors=0 failures=0> If the tests contain non-ASCII characters, we have to specify which encoding the file is encoded with. We do so by using the `encoding` parameter: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... encoding='utf-8') >>> suite.run(unittest.TestResult()) <unittest.result.TestResult run=3 errors=0 failures=2>
发表评论
-
python中的with用法简介
2013-01-01 11:00 0#! /usr/bin/python # enco ... -
(正式)Python学习及资源
2012-12-17 20:13 0python程序计时 http://www.cnblogs. ... -
开发工具收集
2012-12-15 10:17 0eclipse插件 http://developer. ... -
(正式)Java之JUnit, Log4J, Ant, HttpClient, ApacheCommons
2012-11-29 09:57 01. JUnit JUnit和EasyMock Unit ... -
python进行文件夹复制和jar包的合并
2012-10-28 20:21 0http://desert3.iteye.com/blog/7 ... -
python ui--好玩而已
2012-09-17 20:29 0http://forum.ubuntu.org.cn/view ... -
c/c++学习之mutest
2012-08-14 11:22 0最近使用mutest进行单元测试时发现无法找到testcase ... -
Java学习之JUnit(2)
2012-08-03 16:56 0JUnit4的参数化测试 http://yinhe2726. ... -
Java学习之JUnit
2012-08-03 14:51 0参考 http://www.cnblogs.com/eggb ... -
python小技巧
2012-08-02 21:28 0通过Python获取Mac地址 def get_mac ... -
工作积累(6)-使用python进行log分析
2012-08-02 17:38 02012-08-08 主要是使用python分析待机日志中的 ... -
工作积累(4)-如何加载assets下的html网页和testAccessAllowFileAccess cts测试失败
2012-07-30 13:54 01. 按照file:///android_asset/ ... -
web.py建站(4)-div居中以及字体颜色
2012-07-23 15:35 0div style常用属性 http://www.c ... -
web.py建站(4)-jquery
2012-07-23 12:23 0jquery选择器 http://www.cnblogs.c ... -
web.py建站(4)-如何操作sqlite
2012-07-21 09:40 0python sqlite http://askandstu ... -
web.py建站(3)-获取get请求或post请求参数
2012-07-20 17:25 0通过web.input()获取各个请求参数; 通过web.d ... -
web.py建站(2)-template传递参数
2012-07-20 17:05 0(转) http://bbs.python520.com/ar ... -
web.py建站(1)-备忘
2012-07-20 17:03 0web.py与jquery的$冲突 使用$$代替$ ... -
python socket
2012-07-06 15:45 0server端 import socket impo ... -
快速排序(2)
2012-07-06 14:02 0一个Quicksort究竟可以写到多么短 http: ...
相关推荐
在本文中,我们主要介绍了Python的两个单元测试工具:doctest和unittest。这两个工具都是Python标准库中的一部分,它们各有特点,适用于不同的测试场景。 doctest是一个简单的测试模块,它最初是设计用于检查Python...
用户在开始使用`mod2doctest`之前,应首先阅读此文件,了解基本操作和注意事项。另一方面,"mod2doctest-0.1.0"可能是库的源代码文件或编译后的二进制文件,这取决于库的分发方式。如果是源代码,用户可以通过Python...
以下将详细介绍`doctest`模块的使用方法和相关知识点。 首先,`doctest`模块的核心功能是扫描模块中的文档字符串(docstring),寻找以`>>>`开头的行,这些行被认为是测试输入,接下来的一行或几行(直到下一个`>>>...
doctest还可以用来测试模块、函数、类或者任何包含文档字符串的Python对象,它特别适用于小规模的测试和帮助文档中的示例验证。 为了运行doctest,可以将测试用例放在一个单独的Python文件中,并在文件的末尾调用...
### Python单元测试和Mock使用总结 #### 一、单元测试的概念及...通过选择合适的工具(如doctest和unittest),以及合理地使用技术(如Mock),开发者可以构建出高效且可靠的测试体系,进而提高软件产品的整体质量。
6. **集成到测试框架**:doctest可以与Python的unittest等测试框架结合,增强测试覆盖率。 7. **选项定制**:doctest提供了许多可配置的选项,例如忽略某些特定的错误,或者更改输出的格式。 在实际应用中,...
zope.testing 包只支持 unittest 和 doctest 等传统 Python 测试风格,而不支持更现代的框架支持的简化风格。但是,它提供一个强大的分层系统,在这种系统中包含测试的目录可以依赖于通用的设置代码,设置代码为层...
内置的测试模块如unittest和doctest,第三方测试工具如py.test和mock,都是在进行代码质量控制时不可或缺的工具。此外,消息队列和Celery的使用,以及如何在Flask应用中使用Celery进行后台任务处理,也是Python Web...
7. **集成单元测试**:支持unittest和doctest框架,方便进行单元测试和集成测试。 8. **语法高亮和代码格式化**:使代码更易于阅读,同时可以按照个人喜好调整代码格式。 9. **集成版本控制系统**:与Git、SVN等版本...
与Python自带的unittest测试框架相比,pytest的语法更为简洁,使用起来也更加方便。pytest具有以下特点: 1. 入门简单,文档丰富:pytest提供了大量的实例,使得初学者能够快速地学习和上手。 2. 支持简单的单元...
10. **调试和测试**:文档会讲解如何使用pdb进行交互式调试,以及如何编写测试用例和使用unittest、doctest等测试框架进行单元测试和集成测试。 11. **性能优化**:Python虽然是一种解释型语言,但仍然有多种方法...
4. 集成测试:PyDev内置了对unittest和doctest的支持,可以方便地编写和运行测试用例,确保代码质量。 5. Django支持:对于Web开发,PyDev对Django框架提供了良好的支持,包括模型感知、模板语法高亮等。 三、...
PyDev 2.3.0集成了Python的单元测试框架,如unittest和doctest,开发者可以直接在Eclipse环境中编写和运行测试用例,提高了测试效率和覆盖率。 4. **插件生态系统扩展**: PyDev 2.3.0提供了对Eclipse插件生态...
12. **异常测试与调试**:了解如何编写单元测试,使用unittest或doctest模块,理解断言assert的用法,掌握调试技巧。 在实际的二级考试中,可能会出现编程题,要求考生编写完成特定功能的代码,或者分析和修改已有...
通过合理选择和使用Python提供的测试工具(如unittest、pytest、doctest),结合上述的最佳实践,开发者可以有效地提升软件项目的稳定性和维护性。此外,将单元测试纳入日常开发流程,不仅能够加快问题的发现和解决...