标签: python-unittest

当 setUpClass 失败时,如何清理 Python UnitTest?

假设我有以下 Python UnitTest:

import unittest

def Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Get some resources
        ...

        if error_occurred:
            assert(False)

    @classmethod
    def tearDownClass(cls):
        # release resources
        ...
Run Code Online (Sandbox Code Playgroud)

如果 setUpClass 调用失败,则不会调用 tearDownClass,因此永远不会释放资源。如果下一次测试需要资源,这在测试运行期间会出现问题。

当 setUpClass 调用失败时,有没有办法进行清理?

python unit-testing python-unittest

4
推荐指数
3
解决办法
8398
查看次数

具有多个返回值的模拟/补丁 os.path.exists

我正在尝试测试我创建的一个函数,该函数遍历列表并调用列表os.path.exists中的每个项目。我的测试是向函数传递 2 个对象的列表。我需要os.path.exists返回True的其中之一,并False为其他。我试过这个:

import mock
import os
import unittest

class TestClass(unittest.TestCase):
    values = {1 : True, 2 : False}
    def side_effect(arg):
        return values[arg]

    def testFunction(self):
        with mock.patch('os.path.exists') as m:
            m.return_value = side_effect # 1
            m.side_effect = side_effect # 2

            arglist = [1, 2]
            ret = test(argList)
Run Code Online (Sandbox Code Playgroud)

使用第 1 行和第 2 行中的任何一个但不是同时使用 NameError: global name 'side_effect' is not defined

我发现了这个问题并像这样修改了我的代码:

import mock
import os

class TestClass(unittest.TestCase):
    values = {1 : True, …
Run Code Online (Sandbox Code Playgroud)

python mocking python-2.7 python-unittest

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

如何重用使用 unittest.testcase 编写的测试

我已经使用 unittest 编写了一些测试,如下所示,我想在另一个我遇到困难并需要帮助的类中重用它们。代码片段如下。

    MyTestClass.py
    Class MyTestClass(unittest.TestCase):   
        @classmethod
        def test_TC01_set(self):
            self.devAddr = "127.0.0.0"
            self.teststoSkip = 'TC02'

        def skip(type):
            if type in self.teststoSkip:
                self.skipTest('skipped!!') #unittest.Testcase method

        def test_TC02(self):
            self.skip('TC02')
            print 'test_TC02 will do other tasks'

        def test_TC03(self):
            self.skip('TC03')
            print 'test_TC03 will do other tasks'
Run Code Online (Sandbox Code Playgroud)

这将正常工作。现在我想在另一个类中重用相同的测试用例。说,

    RegressionMyTest.py
    from MyTestClass import MyTestClass
    Class RegressionMyTest(MyTestClass):
        @classmethod
        def setupmytest(self):
            self.test_TC01_set(self)#this will work fine since it is accessing classmethod
            self.tes_TC02(self)#cant access like this since it is not a class method
            self.tes_TC03(self)#cant access like this since it is …
Run Code Online (Sandbox Code Playgroud)

python python-unittest

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

这个 DeprecationWarning ("callable is None") 有什么用?

我正在编写一个模块,我正在使用unittest与实际代码一起编写单元测试。

有时(似乎几乎是不确定的),像下面这样的函数没有明确返回一个值,用self.assertRaises(mymodule.MyEmptyException, myfunc())(whereself指的是 的子类unittest.TestCase)断言会引发一个神秘的DeprecationWarning.

这是此类函数的示例:

def insertn(self, items, lidex):
    """( z y x -- z b y x )
    add a list of items to the stack at the given index"""
    iter(items)
    for idx, obj in enumerate(items):
        self.insert(lidex, obj)
        lidex += 1
Run Code Online (Sandbox Code Playgroud)

其对应的单元测试:

def test_insertn_fail(self):
    """expect failure during multiple insertion"""
    self.assertRaises(mouse16.BadInternalCallException,
        stack.insertn([8, 4, 12], 16))
    with self.assertRaises(TypeError):
        stack.insertn(8, 16)
Run Code Online (Sandbox Code Playgroud)

给出(例如):

./mousetesting.py:103: DeprecationWarning: callable is None
Run Code Online (Sandbox Code Playgroud)

我认为使函数具有非None返回值可能会解决问题(即return 0 …

python python-unittest

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

使用 Tornado Websocket 进行单元测试 - 没有属性“io_loop”错误

我已经将一个龙卷风 websocket 客户端代码拼接在一起,并在我的 python 单元测试用例中使用它。这是我第一次使用 tornado websocket,对它的单元测试 API 不是很熟悉。寻找一些帮助来理解 tornado websocket 异步单元测试代码的使用和下面的案例工作。

客户端类代码:

import logging
import logging.config
import ssl
import time
import traceback

from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError, HTTPRequest
from tornado.log import gen_log, app_log

from tornado.web import Application, RequestHandler

class TorWebSocketClient():

    def __init__(self, ip_addr, port, cookie):
        self.ip_addr = ip_addr
        self.port = port
        self.cookie = cookie
        self.sockConnected = False
        self.logger = logging.getLogger(__name__)

    def Connect(self):

        # Creating the websocket client for each test case.
        url …
Run Code Online (Sandbox Code Playgroud)

python unit-testing tornado python-unittest

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

使用Python进行单元测试中的依赖注入

我正在学习python

我想知道是否有一种机制可以将一个对象(在我的情况下是一个假对象)"注入"到被测试的类中,而无需在costructor/setter中明确添加它.

## source file
class MyBusinessClass():
    def __init__(self):
        self.__engine = RepperEngine()

    def doSomething(self):
        ## bla bla ...
        success

## test file
## fake I'd like to inkject
class MyBusinessClassFake():
   def __init__(self):
      pass

def myPrint(self) :
    print ("Hello from Mock !!!!")

class Test(unittest.TestCase):

    ## is there an automatic mechanism to inject MyBusinessClassFake 
    ## into MyBusinessClass without costructor/setter?
    def test_XXXXX_whenYYYYYY(self):

        unit = MyBusinessClass()
        unit.doSomething()
        self.assertTrue(.....)
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我想"注入"对象"引擎",而不是在构造函数中传递它.我尝试了很少的选项(例如:@patch ......)没有成功.

python mocking python-unittest

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

删除 :memory 中的数据库文件:

背景和问题

我们在:memory:测试时使用来存储我们的数据库,并希望在每个测试用例运行之前将其删除,以便我们从每个测试用例的空数据库开始。(如果我们将数据库存储在磁盘上,我们只需删除文件)

我们的设置

  • 我们正在使用 Python 的unittest模块
  • (Python 版本:3.6)
  • 这是我们创建数据库的样子: db_connection = sqlite3.connect(":memory:")

我们如何从内存中删除我们的数据库?

python sqlite python-3.x python-unittest

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

使用 unittest 测试记录器消息

我想在我的单元测试中测试记录器消息而不将它们打印到屏幕上。鉴于此代码:

 import logging
 logging.basicConfig(level=logging.ERROR)
 logger = logging.getLogger('test')
 logger.warning('this is a warning')

 # How do I see that there was a warning?
Run Code Online (Sandbox Code Playgroud)

如何查看记录器中的日志记录以查看是否有警告?我在 Logger 中找不到可以完成这项工作的迭代器。

python logging python-unittest

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

unittest - 如何断言两个可能的 NaN 值是否相等

在我的测试用例中,我假设如果两个值NaN相等,则它们相等。使用unittest断言的表达方式是什么?下面介绍的两个常用函数不处理这种情况。

v1 = np.nan
v2 = np.nan
self.assertEquals(v1, v2)
self.assertTrue(v1 == v2)
Run Code Online (Sandbox Code Playgroud)

现在对我有用的解决方案是在内部使用布尔表达式assertTrue

self.assertTrue(v1 == v2 or (np.isnan(v1) and np.isnan(v2))
Run Code Online (Sandbox Code Playgroud)

python equality nan python-unittest

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

如何在没有太多负担的情况下使用 `assertEqual()` [或等效的]?

我正在寻找一种方法(如果可用),它可以比较两个值并在比较失败时引发带有有意义消息的断言错误。

如果我使用assert,则失败消息不包含断言失败时比较的值。

>>> a = 3
>>> b = 4
>>> assert a == b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> 
Run Code Online (Sandbox Code Playgroud)

如果我使用包中的assertEqual()方法unittest.TestCase,断言消息将包含比较的值。

        a = 3
        b = 4
>       self.assertEqual(a, b)
E       AssertionError: 3 != 4
Run Code Online (Sandbox Code Playgroud)

请注意,这里的断言错误消息包含比较的值。这在现实生活中非常有用,因此对我来说是必要的。平原assert(见上文)不会这样做。

但是,到目前为止,我assertEqual()只能在继承自unittest.TestCase并提供一些其他必需方法的类中使用,例如runTest(). 我想在assertEqual()任何地方使用,而不仅仅是在继承的类中。那可能吗?

我尝试了以下方法,但没有奏效。

>>> import unittest
>>> unittest.TestCase.assertEqual(a, b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> …
Run Code Online (Sandbox Code Playgroud)

python assert python-unittest

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