最近,Ned Batchelder 在PyCon 2016的演讲中指出:
如果您正在使用
unittest编写测试,请务必使用addCleanup,这比使用 它要好得多tearDown.
到目前为止,我从未使用addCleanup()并习惯了setUp()/ tearDown()用于测试"设置"和"拆除"阶段的方法.
我为什么要改用addCleanup()替代的tearDown()?
最近还在Robert Collins播客的Python单元测试中进行了讨论.
我有一个包含目录"tests"的包,我正在存储我的单元测试.我的包看起来像:
.
??? LICENSE
??? models
? ??? __init__.py
??? README.md
??? requirements.txt
??? tc.py
??? tests
? ??? db
? ? ??? test_employee.py
? ??? test_tc.py
??? todo.txt
Run Code Online (Sandbox Code Playgroud)
从我的包目录,我希望能够找到tests/test_tc.py和tests/db/test_employee.py.我不想安装第三方库(nose或其他),或者必须手动构建一个TestSuite以运行它.
当然有一种方法可以告诉unittest discover他们一旦发现测试就不要停止寻找?python -m unittest discover -s tests会发现tests/test_tc.py并python -m unittest discover -s tests/db会找到tests/db/test_employee.py.有没有找到两者的方法?
我有两个测试用例(两个不同的文件),我想在测试套件中一起运行.我可以通过"正常"运行python来运行测试但是当我选择运行python-unit测试时它会说0个测试运行.现在我只想尝试至少进行一次测试才能正确运行.
import usertest
import configtest # first test
import unittest # second test
testSuite = unittest.TestSuite()
testResult = unittest.TestResult()
confTest = configtest.ConfigTestCase()
testSuite.addTest(configtest.suite())
test = testSuite.run(testResult)
print testResult.testsRun # prints 1 if run "normally"
Run Code Online (Sandbox Code Playgroud)
这是我的测试用例设置的一个例子
class ConfigTestCase(unittest.TestCase):
def setUp(self):
##set up code
def runTest(self):
#runs test
def suite():
"""
Gather all the tests from this module in a test suite.
"""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(ConfigTestCase))
return test_suite
if __name__ == "__main__":
#So you can run tests from this module individually. …Run Code Online (Sandbox Code Playgroud) python unit-testing regression-testing test-suite python-unittest
功能foo打印到控制台.我想测试控制台打印.我怎么能在python中实现这一点?
需要测试这个函数,有没有返回语句:
def foo(inStr):
print "hi"+inStr
Run Code Online (Sandbox Code Playgroud)
我的测试:
def test_foo():
cmdProcess = subprocess.Popen(foo("test"), stdout=subprocess.PIPE)
cmdOut = cmdProcess.communicate()[0]
self.assertEquals("hitest", cmdOut)
Run Code Online (Sandbox Code Playgroud) 好的,
我知道这在手册中有提及,可能side_effect与/和/有关return_value,但一个简单直接的例子对我帮助很大.
我有:
class ClassToPatch():
def __init__(self, *args):
_do_some_init_stuff()
def some_func():
_do_stuff()
class UUT():
def __init__(self, *args)
resource_1 = ClassToPatch()
resource_2 = ClassToPatch()
Run Code Online (Sandbox Code Playgroud)
现在,我想对这个UUT类进行单元测试,然后嘲笑ClassToPatch.知道UUT该类将实例化两个ClassToPatch对象,我希望Mock框架为每个实例化返回一个新的Mock对象,所以我可以稍后在每个实例上断言.
如何@patch在测试用例中使用装饰器实现此目的?即,如何修复以下代码示例?
class TestCase1(unittest.TestCase):
@patch('classToPatch.ClassToPatch',autospec=True)
def test_1(self,mock1,mock2):
_assert_stuff()
Run Code Online (Sandbox Code Playgroud) Python unittest使用nosetests来试验Python Class和Module fixture,在我的测试中进行最小化设置.
我面临的问题是,我不确定如何使用我的测试中setupUpModule的setUpClass函数和函数中定义的任何变量(例如: - test_1).
这是我用来尝试的:
import unittest
def setUpModule():
a = "Setup Module variable"
print "Setup Module"
def tearDownModule():
print "Closing Module"
class TrialTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print a #<======
b = "Setup Class variable"
@classmethod
def tearDownClass(cls):
print "Closing Setup Class"
def test_1(self):
print "in test 1"
print a #<======
print b #<======
def test_2(self):
print "in test 2"
def test_3(self):
print "in test 3"
def test_4(self): …Run Code Online (Sandbox Code Playgroud) 我在Ubuntu 14.04.2 LTS上使用python 2.7.6.我正在使用mock来模拟一些单元测试并注意到当我导入mock时它无法导入换行.
不确定是否有一个不同版本的模拟或六个我应该使用它的导入工作?找不到任何相关答案,我没有使用虚拟环境.
mock模块说它与python 2.7.x兼容:https://pypi.python.org/pypi/mock
mock == 1.1.3 six == 1.9.0
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mock import Mock
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/mock/__init__.py", line 2, in <module>
import mock.mock as _mock
File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 68, in <module>
from six import wraps
ImportError: cannot import name wraps
Run Code Online (Sandbox Code Playgroud)
也试过sudo没有运气.
$ sudo python …Run Code Online (Sandbox Code Playgroud) 如何在Travis-CI中使用Tox测试不同的Python版本?
我有一个tox.ini:
[tox]
envlist = py{27,33,34,35}
recreate = True
[testenv]
basepython =
py27: python2.7
py33: python3.3
py34: python3.4
py35: python3.5
deps =
-r{toxinidir}/pip-requirements.txt
-r{toxinidir}/pip-requirements-test.txt
commands = py.test
Run Code Online (Sandbox Code Playgroud)
它运行我的Python单元测试在几个Python版本,并完美地工作.
我想在Travis-CI中设置一个构建,当我将更改推送到Github时自动运行它,所以我有一个.travis.yml:
language: python
python:
- "2.7"
- "3.3"
- "3.4"
- "3.5"
install:
- pip install tox
script:
- tox
Run Code Online (Sandbox Code Playgroud)
这在技术上似乎有效,但它在每个Python版本中冗余地运行我的所有测试......来自每个版本的Python.因此,需要5分钟的构建需要45分钟.
我尝试python从我的yaml文件中删除列表,因此Travis只运行一个Python实例,但这导致我的Python3.5测试失败,因为找不到3.5解释器.显然,这是一个已知的限制,因为Travis-CI不会安装Python3.5,除非您在配置中指定了确切的版本......但它不会为其他版本执行此操作.
有没有办法解决这个问题?
我是 Python 开发新手,我正在使用pytest编写测试用例,我需要模拟一些行为。谷歌搜索pytest 的最佳模拟库,只会让我感到困惑。我见过unittest.mock、mock、mocker 和pytest-mock。不太确定该使用哪一个。有人可以解释一下它们之间的区别并向我推荐一个吗?
这是我的文件夹结构:
Mopy/ # no init.py !
bash/
__init__.py
bash.py # <--- Edit: yep there is such a module too
bass.py
bosh/
__init__.py # contains from .. import bass
bsa_files.py
...
test_bash\
__init__.py # code below
test_bosh\
__init__.py
test_bsa_files.py
Run Code Online (Sandbox Code Playgroud)
在test_bash\__init__.py我有:
import sys
from os.path import dirname, abspath, join, sep
mopy = dirname(dirname(abspath(__file__)))
assert mopy.split(sep)[-1].lower() == 'mopy'
sys.path.append(mopy)
print 'Mopy folder appended to path: ', mopy
Run Code Online (Sandbox Code Playgroud)
在test_bsa_files.py:
import unittest
from unittest import TestCase
import bosh
class TestBSAHeader(TestCase):
def …Run Code Online (Sandbox Code Playgroud) python python-import python-2.7 relative-import python-unittest
python ×10
python-unittest ×10
unit-testing ×5
python-2.7 ×3
mocking ×2
console ×1
nose ×1
oop ×1
pytest ×1
pytest-mock ×1
python-mock ×1
tdd ×1
test-suite ×1
tox ×1
travis-ci ×1