我正在为Django项目编写一些单元测试,我想知道是否可能(或必要?)来测试我为它编写的一些装饰器.
这是我写的一个装饰器的例子:
class login_required(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
request = args[0]
if request.user and request.user.is_authenticated():
return self.f(*args)
return redirect('/login')
Run Code Online (Sandbox Code Playgroud) 我有PYCharm 3.0.1的问题我无法运行基本的单元测试.
这是我的代码:
import unittest from MysqlServer import MysqlServer
class MysqlServerTest(unittest.TestCase):
def setUp(self):
self.mysqlServer = MysqlServer("ip", "username", "password", "db", port)
def test_canConnect(self):
self.mysqlServer.connect()
self.fail()
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
这是pycharm给我的所有东西
无法将测试报告者附加到测试框架或测试框架意外退出
也说
AttributeError: class TestLoader has no attribute '__init__'
Run Code Online (Sandbox Code Playgroud)
事件日志:
2:14:28 PM Empty test suite
Run Code Online (Sandbox Code Playgroud)
问题是我手动运行python文件(使用pycharm,作为脚本)
----------------------------------------------------------------------
Ran 1 tests in 0.019s
FAILED (failures=1)
Run Code Online (Sandbox Code Playgroud)
这是正常的我让测试失败了.我对这里发生的事情有点了解更多信息:设置 - > Python集成工具 - >包需求文件:/ src/test默认测试运行器:Unittests pyunit 1.4.1已安装
谢谢你的帮助.
编辑:unitests.py的基本用法也是如此
import unittest
class IntegerArithmenticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEquals((1 + 2), …Run Code Online (Sandbox Code Playgroud) 为了避免循环导入,我被迫定义一个看起来像这样的函数:
# do_something.py
def do_it():
from .helpers import do_it_helper
# do stuff
Run Code Online (Sandbox Code Playgroud)
现在我希望能够通过do_it_helper修补来测试这个功能.如果导入是顶级导入,
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('do_something.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
Run Code Online (Sandbox Code Playgroud)
会工作得很好.但是,上面的代码给了我:
AttributeError: <module 'do_something'> does not have the attribute 'do_it_helper'
Run Code Online (Sandbox Code Playgroud)
一时兴起,我也尝试将补丁语句更改为:
with patch('do_something.do_it.do_it_helper') as helper_mock:
Run Code Online (Sandbox Code Playgroud)
但这产生了类似的错误.有没有办法模拟这个函数,因为我被迫在它使用的函数中导入它?
我正在尝试测试一个接受输入的函数,stdin我目前正在测试这样的东西:
cat /usr/share/dict/words | ./spellchecker.py
Run Code Online (Sandbox Code Playgroud)
在测试自动化的名义,有什么方法pyunit可以伪输入raw_input()?
当我创建一个时unittest.TestCase,我可以定义一个setUp()在该测试用例中的每个测试之前运行的函数.是否可以跳过setUp()单个特定测试?
想要跳过setUp()给定测试可能不是一个好习惯.我对单元测试相当新,欢迎任何有关该主题的建议.
我知道,在assertEqual字典上执行时,会assertDictEqual被调用.同样,assertEqual序列将执行assertSequenceEqual.
但是,在assertDictEqual比较值时,似乎没有使用assertEqual,因此assertSequenceEqual不会被调用.
请考虑以下简单的词典:
lst1 = [1, 2]
lst2 = [2, 1]
d1 = {'key': lst1}
d2 = {'key': lst2}
self.assertEqual(lst1, lst2) # True
self.assertEqual(d1, d2) # False ><
Run Code Online (Sandbox Code Playgroud)
我如何通过递归地将类似语义应用于值来测试诸如d1并d2正确比较它们的相等的字典assertEqual?
我想尽可能避免使用外部模块(如本问题所示),除非它们是本机django扩展.
编辑
基本上,我所追求的是这个的内置版本:
def assertDictEqualUnorderedValues(self, d1, d2):
for k,v1 in d1.iteritems():
if k not in d2:
self.fail('Key %s missing in %s'%(k, d2))
v2 = d2[k]
if isinstance(v1, Collections.iterable) and …Run Code Online (Sandbox Code Playgroud) 编辑:请注意我正在使用Python 2.6(标记为)
说我有以下内容:
class Foo:
def bar(self):
print 'bar'
return 7
Run Code Online (Sandbox Code Playgroud)
并说我有以下单元测试:
import unittest
class ut_Foo(unittest.TestCase):
def test_bar(self):
obj = Foo()
res = obj.bar()
self.assertEqual(res, 7)
Run Code Online (Sandbox Code Playgroud)
所以如果我跑:
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我明白了:
bar # <-- I don't want this, but I *do* want the rest
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
Exit code: False
Run Code Online (Sandbox Code Playgroud)
我的问题是:有没有办法抑制被测对象的输出,同时仍然得到unittest框架的输出?
编辑 此问题不是标记问题的副本,该问题询问是否在正常python脚本中对特定函数的stdout进行静默.
虽然这个问题是在运行它的单元测试时询问是否隐藏了python脚本的正常标准输出.我仍然希望显示unittest标准输出,我不想禁用我测试过的脚本的标准输出.
我有一个印象(但没有找到它的文档)unittest WARNING 为所有记录器设置日志记录级别.我想要:
我怎样才能做到这一点?
我正在尝试设置被测目标@pytest.fixture并在模块中的所有测试中使用它。我能够正确修补测试,但是在我添加@pytest.fixture返回模拟对象并在其他单元测试中调用模拟对象后,该对象开始引用回原始函数。
以下是我拥有的代码。我期望mocked_worker单元测试中的 引用返回值,但它正在调用实际os.getcwd方法。
请帮我更正代码:
import os
import pytest
from unittest.mock import patch
class Worker:
def work_on(self):
path = os.getcwd()
print(f'Working on {path}')
return path
@pytest.fixture()
def mocked_worker():
with patch('test.test_module.os.getcwd', return_value="Testing"):
result = Worker()
return result
def test_work_on(mocked_worker):
ans = mocked_worker.work_on()
assert ans == "Testing"
Run Code Online (Sandbox Code Playgroud) 我想制作一个存根来防止time.sleep(..)进入睡眠状态以改善单元测试执行时间.
我有的是:
import time as orgtime
class time(orgtime):
'''Stub for time.'''
_sleep_speed_factor = 1.0
@staticmethod
def _set_sleep_speed_factor(sleep_speed_factor):
'''Sets sleep speed.'''
time._sleep_speed_factor = sleep_speed_factor
@staticmethod
def sleep(duration):
'''Sleeps or not.'''
print duration * time._sleep_speed_factor
super.sleep(duration * time._sleep_speed_factor)
Run Code Online (Sandbox Code Playgroud)
但是,我在上面的第二个代码行(类定义)上收到以下错误:
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given).
Run Code Online (Sandbox Code Playgroud)
如何修复错误?
python ×10
python-unittest ×10
unit-testing ×5
testing ×2
class ×1
constructor ×1
decorator ×1
django ×1
linux ×1
logging ×1
mocking ×1
pycharm ×1
pytest ×1
python-2.6 ×1
python-3.x ×1
time ×1