标签: python-unittest

从pyunit unittests生成测试覆盖率信息?

我正在为一个简单的命令行程序进行一些pyunit单元测试.我可以生成测试覆盖率数字吗?我想看看我的测试没有涵盖哪些线条.

python testing unit-testing code-coverage python-unittest

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

使用哪个Python测试框架?

我有很多目录,其中有python文件.所有都是普通的python文件.我没有使用任何类型的框架.我想从一个中心位置测试这些py文件.我应该只发出一个命令,并且应该调用每个目录中的所有*_test.py文件.那么,有没有可用于我的要求的现成工具或框架?

我正在寻找PyUnit来测试普通的py文件.并考虑编写一个shell脚本,它将使用正则表达式匹配文件名来调用所有这些*_test.py文件.

任何人都可以建议任何其他方法 随时欢迎你.

谢谢.

python unit-testing python-unittest

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

unittest setUpClass替代python <2.7

在Python 2.7中,可以在unittest.Testcase中运行类级别设置,如下所示:

class ClassName(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        print 'Some class level setup'
Run Code Online (Sandbox Code Playgroud)

不幸的是,我需要在Python 2.6环境中运行一些测试.该版本中setUpClass的替代方案是什么?

python python-2.6 python-unittest

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

Python unittest:在循环中运行多个断言而不会在第一个失败,但继续

场景: 我的一个测试用例是执行带有几个输入文件和特定输出的shell程序.我想测试这些输入/输出的不同变体,每个变体都保存在自己的文件夹中,即文件夹结构

/testA
/testA/inputX
/testA/inputY
/testA/expected.out
/testB
/testB/inputX
/testB/inputY
/testB/expected.out
/testC/
...
Run Code Online (Sandbox Code Playgroud)

这是我运行此测试的代码:

def test_folders(self):
    tfolders = glob.iglob(os.environ['testdir'] + '/test_*')                
    for testpath in tfolders:
        testname = os.path.basename(testpath)
        self.assertTrue(self.runTest(testname))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,testname是"testX".它inputs在该文件夹中执行外部程序,并将其与expected.out同一文件夹进行比较.

问题: 一旦它遇到失败的测试,测试就会停止并获得:

Could not find or read expected output file: C:/PROJECTS/active/CMDR-Test/data/test_freeTransactional/expected.out
======================================================================
FAIL: test_folders (cmdr-test.TestValidTypes)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\PROJECTS\active\CMDR-Test\cmdr-test.py", line 52, in test_folders
    self.assertTrue(self.runTest(testname))
AssertionError: False is not true
Run Code Online (Sandbox Code Playgroud)

问题: 如何使其继续其余测试并显示失败的数量?(本质上是动态创建单元测试并执行它)

谢谢

python testing unit-testing assertions python-unittest

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

按顺序执行pytest

嗨,我正在检查" http://pytest-ordering.readthedocs.org/en/develop/ "按顺序执行pytest

我尝试了以下代码,

import pytest

@pytest.mark.order2
def test_foo():
    assert True

@pytest.mark.order1
def test_bar():
    assert True
Run Code Online (Sandbox Code Playgroud)

但执行仍然是随机的.有人可以让我知道如何解决它?

python pytest python-unittest

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

Python unittest无法解析import语句

我有一个类似于以下的文件结构

project
    src
        __init__.py
        main.py
        module.py
        secondary.py
    test
        test_module.py        
Run Code Online (Sandbox Code Playgroud)

module.py

import secondary
x = False
Run Code Online (Sandbox Code Playgroud)

secondary.py

pass
Run Code Online (Sandbox Code Playgroud)

test_module.py

from unittest import TestCase

from src import module

 class ModuleTest(TestCase):
    def test_module(self):
        self.assertTrue(module.x)
Run Code Online (Sandbox Code Playgroud)

调用python3 -m unittest discover/project/给出了一个错误:

 File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
  from src import module
 File "/Users/Me/Code/project/src/module.py", line 1, in <module>
  import secondary
ImportError: No module named 'secondary'
Run Code Online (Sandbox Code Playgroud)

我可以做什么,secondary.py导入没有错误?

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

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

使用unittest测试argparse-退出错误

要去关格雷格·哈斯在这个问题的答案,我试图让一个单元测试来检查当我通过它的一些ARGS不存在在该argparse是给相应的错误choices。但是,unittest使用以下try/except语句会产生误报。

另外,当我仅使用一条with assertRaises语句进行测试时,会argparse强制系统退出,并且程序不再执行任何其他测试。

我希望能够对此进行测试,但是鉴于argparse错误退出,也许这是多余的?

#!/usr/bin/env python3

import argparse
import unittest

class sweep_test_case(unittest.TestCase):
    """Tests that the merParse class works correctly"""

    def setUp(self):
        self.parser=argparse.ArgumentParser()
        self.parser.add_argument(
            "-c", "--color",
            type=str,
            choices=["yellow", "blue"],
            required=True)

    def test_required_unknown_TE(self):
        """Try to perform sweep on something that isn't an option.
        Should return an attribute error if it fails.
        This test incorrectly shows that the test passed, even though that must
        not be true."""
        args = …
Run Code Online (Sandbox Code Playgroud)

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

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

有没有更快的方法为Django视图编写类似的测试用例?

基本上,我意识到我正在test_update_with_only_1_field为多个模型的相似网址编写相同的测试用例()

from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field 

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial …
Run Code Online (Sandbox Code Playgroud)

python django python-unittest parameterized-tests

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

空记录数组的单元测试相等性

我注意到以下unittest.TestCase断言失败,并且想知道如何正确比较空的Recarray:

失败:

self.assertEqual(
    np.array(
        [],
        dtype=[
            ('time', 'datetime64[ns]'),
            ('end_time', int)
        ]
    ).view(np.recarray),
    np.array(
        [],
        dtype=[
            ('time', 'datetime64[ns]'),
            ('end_time', int)
        ]
    ).view(np.recarray)
)
Run Code Online (Sandbox Code Playgroud)

通过:

self.assertEqual(
    np.array(
        [(1,1)],
        dtype=[
            ('time', 'datetime64[ns]'),
            ('end_time', int)
        ]
    ).view(np.recarray),
    np.array(
        [(1,1)],
        dtype=[
            ('time', 'datetime64[ns]'),
            ('end_time', int)
        ]
    ).view(np.recarray)
)
Run Code Online (Sandbox Code Playgroud)

这是一个错误还是我在这里做错了什么?

python arrays numpy python-unittest

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

Python-如何断言未使用特定参数调用模拟对象?

我意识到unittest.mock对象现在有assert_not_called可用的方法,但是我正在寻找的是assert_not_called_with。有没有类似的东西?我在Google上查看时没有看到任何内容,当我尝试仅使用mock_function.assert_not_called_with(...)它时便引发了AttributeError,表示该功能不存在该名称。

我目前的解决方案

with self.assertRaises(AssertionError):
    mock_function.assert_called_with(arguments_I_want_to_test)
Run Code Online (Sandbox Code Playgroud)

这可以工作,但是如果我要打几个这样的调用,会使代码混乱。

有关

断言未使用Mock调用函数/方法

python python-unittest python-unittest.mock

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