标签: python-unittest

如果在单元测试中则跳过 python 中的代码

我当前的脚本调用外部脚本来执行某些任务。我想在单元测试中检查到目前为止的代码,但实际上不运行外部脚本。如果代码作为单元测试的一部分运行,是否有某种方法可以告诉脚本有效地跳过以下块?

python unit-testing python-unittest

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

使用Python的unittest模块测试类实例方法的返回值

class Solution:

    def addNums(self, a, b):
        return a + b

test1 = Solution()   
test1.addNums(5, 6)
Run Code Online (Sandbox Code Playgroud)

以上是我的课!用简单的添加方法。

本质上,我想做的是,为算法和数据结构/编程面试做准备,我为每个输入创建实例,并希望为实例编写单元测试。

这是我在下面尝试过的:

import unittest

class TestSolution(unittest.TestCase):

    def test_addNums(self):
        example = Solution()  
        self.assertEqual(example.addNums(9, 10), 19)


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

不知道如何执行此操作,如果我运行上面的代码,我会收到以下错误消息:

----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '/Users/abhishekbabuji/Library/Jupyter/runtime/kernel-eb5f1d39-4880-49a7-9355-bbddc95464ff'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.

SystemExit: True
Run Code Online (Sandbox Code Playgroud)

我希望能够测试类的实例方法的返回值Solution,在本例中addNums(self, a, b)

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

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

pytest:为每个测试函数设置一个模拟

为 python 项目创建单元测试,我们正在达到这种“模板”

from unittest import TestCase
from unittest.mock import patch, Mock

@patch('......dependency1')
@patch('......dependency2')
@patch('......dependencyn')
class MyTest(TestCase):

  def test_1(self, mock1, mock2, mockn):
      # setup mock1 & mock2...
      # call the subject case 1
      # assert response and/or interactions with mock1 and mock2...

  def test_2(self, mock1, mock2, mockn):
      # setup mock1 & mock2...
      # call the subject case 2
      # assert response and/or interactions with mock1 and mock2...
Run Code Online (Sandbox Code Playgroud)

关键是,有时“设置”部分在某些测试用例中是重复的,因此我想将配置提取到方法中setUp(),例如,以下是伪代码:

def setUp(self):
  mock1.foo.return_value = 'xxx'
  mock2.goo.side_effect = [ ... ] …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking pytest python-unittest

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

如何在 python unittest 中检查断言空字符串?

我有一个问题,我想msg = ''在 python unittest 中测试给定的空字符串,但我找不到正确的断言函数。

我尝试过:

self.assertIsNone(msg)
Run Code Online (Sandbox Code Playgroud)

但我得到了一个错误

AssertionError: '' is not None
Run Code Online (Sandbox Code Playgroud)

所以我继续

self.assertIsEmpty(msg)
Run Code Online (Sandbox Code Playgroud)

但我得到了

object has no attribute 'assertIsEmpty'
Run Code Online (Sandbox Code Playgroud)

因此,在unittest中检查空字符串的正确方法是什么?谢谢

python-2.7 python-unittest

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

跳过 Python 预提交单元测试

我想使用预提交来处理我的 git 项目的 git hooks。但是,当我使用它时,该git commit命令不断跳过unittest执行:

(smartexchange) trnbook:SmartExchange ale$ git commit -m "add pre-commit yaml config"
autopep8.............................................(no files to check)Skipped
unittest.............................................(no files to check)Skipped
[hook_precommit da26d1e] add pre-commit yaml config
1 file changed, 14 insertions(+)
create mode 100644 .pre-commit-config.yaml
Run Code Online (Sandbox Code Playgroud)

预提交挂钩手动执行的结果相同:

(smartexchange) trnbook:SmartExchange ale$ pre-commit install && python .git/hooks/pre-commit
pre-commit installed at .git/hooks/pre-commit
autopep8.............................................(no files to check)Skipped
unittest.............................................(no files to check)Skipped
Run Code Online (Sandbox Code Playgroud)

我缺少什么?手动执行python -m unittest discover是可以的,它执行了4个单元测试:

(smartexchange) trnbook:SmartExchange ale$ python -m unittest discover -s …
Run Code Online (Sandbox Code Playgroud)

python git githooks python-unittest pre-commit.com

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

模拟被测函数中使用的同一类的多个实例

我有一个函数,它使用同一个类的 2 个实例,我想使用 python 模拟来测试该函数。但我很头疼我怎么能嘲笑这个。我已经使用我的朋友 Google 和 Stackoverflow 来寻找解决方案,但到目前为止还没有找到任何解决方案。

作为简单的模拟示例,它显示了我要测试的原理:

class MyClass(object): # this class is inside a module I'm not allowed to change.
    def __init__(self, name, value):
        self._name  = name
        self._value = value

    def get_value(self):
        return self._value
Run Code Online (Sandbox Code Playgroud)

然后是被测模块(再次是一个模拟实现来展示这个想法):

import my_class_module

def my_function():
    a = my_class_module.MyClass('a', 3)
    b = my_class_module.MyClass('b', 4)

    return a.get_value() + b.get_value()
Run Code Online (Sandbox Code Playgroud)

我想到的 my_function 的单元测试的全局想法如下(但这个想法目前当然行不通):

mock.patch('module.my_class_module.MyClass')
def test_my_function(self, mock_my_class):
    def _my_get_value(self): # ideally I would like to use get_value.return_value per instance, but I don't know how.
        if …
Run Code Online (Sandbox Code Playgroud)

python mocking python-unittest

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

使用 Python 中的 unittest 检查系统退出和错误日志

是否可以检查程序是否停止sys.exit()并检查使用该模块记录的消息logging

例如,假设我在名为 func.py 的文件中有以下函数:

import logging
import sys

logging.basicConfig(level=logging.INFO,format='%(levelname)s:%(message)s')

def my_func(word):
    if word == "orange":
        logging.info("All is good with {}.".format(word))
    elif word == "apple":
        logging.error("Something went wrong with {}.".format(word))
        sys.exit()
Run Code Online (Sandbox Code Playgroud)

现在,我创建了几个测试来检查我的函数的性能。我知道,要测试记录的消息(假设程序完成其功能),我可以执行以下操作:

import unittest
from func import *

class Test_errors_and_messages(unittest.TestCase):

    def test_logs(self):
        with self.assertLogs() as captured:
            my_func("orange")
        self.assertEqual(len(captured.records), 1)
        self.assertEqual(captured.records[0].getMessage(), "All is good with orange.")
Run Code Online (Sandbox Code Playgroud)

如果我想检查程序是否按预期停止,我正在做类似的事情:

import unittest
from func import *

class Test_errors_and_messages(unittest.TestCase):

    def test_exit(self):
        with self.assertRaises(SystemExit):
            my_func("apple")
Run Code Online (Sandbox Code Playgroud)

我的问题是:是否可以测试系统退出和同时记录的消息?换句话说,我想修改测试test_exit()来检查(a)程序是否以 a 停止SystemExit,(b)消息

苹果出了点问题。 …

python logging python-unittest

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

如何在 python 中模拟 uuid4() ?

A_script.py

from uuid import uuid4

def get_unique_identifier(env, customer_id):
    return env + '-' + customer_id + '-' + str(uuid4())[0:8]
Run Code Online (Sandbox Code Playgroud)

测试_A_脚本.py

import unittest
from unittest.mock import patch
import src.A_script as a_script

class MyTestCase(unittest.TestCase):
   @patch('uuid.uuid4')
   def test_get_unique_identifier(self, mock_uuid4):
      mock_uuid4.return_value = 'abcd1234'
      expected = 'test_env-test_cust-abcd1234'
      unique_identifier = a_script.get_unique_identifier('test_env', 'test_cust')
      self.assertEqual(expected, unique_identifier)
Run Code Online (Sandbox Code Playgroud)

如何让 uuid4 返回“abcd1234”?

python unit-testing patch mocking python-unittest

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

在 VSCode 中运行 Python 单元测试时设置环境变量

我想在单元测试中执行代码,条件是它们是从 VSCode 还是命令行中运行。有办法这样做吗?

原因是通过cv2.imwrite语句添加额外的视觉反馈,但在从命令行运行完整回归或运行 CI 时忽略这些反馈。

我知道我可以在内部设置调试配置文件launch.json并在那里定义环境变量,但这仅适用于调试单元测试时:

       {
            "name": "Debug Tests",
            "type": "python",
            "request": "test",
            "console": "integratedTerminal",
            "python": "${command:python.interpreterPath}",
            "justMyCode": false,
            "env": {
                "MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS": "1"
            }
        },
Run Code Online (Sandbox Code Playgroud)

有没有办法在不通过调试器运行时实现类似的效果?

python environment-variables python-unittest visual-studio-code

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

Python:运行unittest.TestCase而不调用unittest.main()?

我在Python的unittest中编写了一个小测试套件:

class TestRepos(unittest.TestCase):

@classmethod
def setUpClass(cls):
    """Get repo lists from the svn server."""
    ...

def test_repo_list_not_empty(self):
    """Assert the the repo list is not empty"""
    self.assertTrue(len(TestRepoLists.all_repos)>0)

def test_include_list_not_empty(self):
    """Assert the the include list is not empty"""
    self.assertTrue(len(TestRepoLists.svn_dirs)>0)

...

if __name__ == '__main__':
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='tests', 
                                                 descriptions=True))
Run Code Online (Sandbox Code Playgroud)

使用xmlrunner pacakge将输出格式化为Junit测试.

我添加了一个命令行参数来切换JUnit输出:

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Validate repo lists.')
    parser.add_argument('--junit', action='store_true')
    args=parser.parse_args()
    print args
    if (args.junit):
        unittest.main(testRunner=xmlrunner.XMLTestRunner(output='tests', 
                                                     descriptions=True))
    else:
        unittest.main(TestRepoLists)
Run Code Online (Sandbox Code Playgroud)

问题是运行脚本没有--junit工作,但使用--junitunittest参数的冲突调用它:

option --junit not recognized
Usage: …
Run Code Online (Sandbox Code Playgroud)

python unit-testing command-line-arguments python-2.7 python-unittest

0
推荐指数
1
解决办法
3337
查看次数