标签: python-unittest

测试Python装饰器?

我正在为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)

python django unit-testing decorator python-unittest

19
推荐指数
1
解决办法
9566
查看次数

Pycharm和unittest不起作用

我有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)

python pycharm python-unittest

19
推荐指数
4
解决办法
2万
查看次数

修补在另一个函数中导​​入的函数

为了避免循环导入,我被迫定义一个看起来像这样的函数:

# 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)

但这产生了类似的错误.有没有办法模拟这个函数,因为我被迫在它使用的函数中导入它?

python testing unit-testing mocking python-unittest

19
推荐指数
1
解决办法
7691
查看次数

如何模拟pyun的stdin输入?

我正在尝试测试一个接受输入的函数,stdin我目前正在测试这样的东西:

cat /usr/share/dict/words | ./spellchecker.py
Run Code Online (Sandbox Code Playgroud)

在测试自动化的名义,有什么方法pyunit可以伪输入raw_input()

python linux python-unittest

18
推荐指数
2
解决办法
2万
查看次数

是否可以跳过python的unittest中特定测试的setUp()?

当我创建一个时unittest.TestCase,我可以定义一个setUp()在该测试用例中的每个测试之前运行的函数.是否可以跳过setUp()单个特定测试?

想要跳过setUp()给定测试可能不是一个好习惯.我对单元测试相当新,欢迎任何有关该主题的建议.

python testing unit-testing python-unittest

18
推荐指数
3
解决办法
5719
查看次数

如何通过将assertSequenceEqual应用于值来实现assertDictEqual

我知道,在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)

我如何通过递归地将类似语义应用于值来测试诸如d1d2正确比较它们的相等的字典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 unit-testing python-unittest

18
推荐指数
2
解决办法
3万
查看次数

在单元测试中抑制打印输出

编辑:请注意我正在使用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标准输出,我不想禁用我测试过的脚本的标准输出.

python python-2.6 python-unittest

17
推荐指数
2
解决办法
8037
查看次数

更改unittest中的日志级别

我有一个印象(但没有找到它的文档)unittest WARNING 为所有记录器设置日志记录级别.我想要:

  • 能够从命令行(运行测试时)或测试模块本身指定所有记录器的日志记录级别
  • 避免unittest搞乱应用程序日志记录级别:运行测试时我希望获得与运行应用程序时相同的日志记录输出(相同级别)

我怎样才能做到这一点?

python logging python-unittest

17
推荐指数
2
解决办法
2365
查看次数

使用 pytest.fixture 返回模拟对象的正确方法

我正在尝试设置被测目标@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)

python unit-testing pytest python-3.x python-unittest

17
推荐指数
2
解决办法
1万
查看次数

如何在Python单元测试中存根time.sleep()

我想制作一个存根来防止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 time constructor class python-unittest

16
推荐指数
4
解决办法
1万
查看次数