【问题标题】:How to do unit test to check input is not null in Python如何进行单元测试以检查 Python 中的输入不为空
【发布时间】:2019-07-04 12:49:17
【问题描述】:

这是我第一次尝试用 Python 编写单元测试。我有一个像这样的简单函数:

def sum_num(a, b):
  return a+b

我想做单元测试,检查输入(a,b)不为空,输出不为空。

import unittest

class SumTest(unittest.TestCase):
    def test_sum_output_not_null(self):
        self.assertTrue(add_num(3,4))

    def test_sum_input_not_null(self):
        # How to check input (a and b) is not None ?
        self.assertIsNotNone(a)
...

suite = unittest.TestLoader().loadTestsFromTestCase(SumTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)

我在单元测试运行中遇到错误..

test_sum_input_not_null (__main__.SumTest) ... ERROR
test_sum_output_not_null (__main__.SumTest) ... ok

======================================================================
ERROR: test_sum_input_not_null (__main__.SumTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<command-1933936>", line 7, in test_sum_input_not_null
    self.assertIsNotNone(a)
NameError: name 'a' is not defined

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)
Out[4]: <unittest.runner.TextTestResult run=2 errors=1 failures=0>

如何检查 a 和 b 不为空?也可能想检查 a 和 b 是否也是整数。我在某处读到有关 setup() 的信息。我需要这样做来测试函数的输入吗?

【问题讨论】:

  • 你得到了错误,因为 a 从未定义..
  • 我知道这一点。我不确定如何定义它以及在哪里定义它或如何将它传递到单元测试中。
  • 您的单元测试需要检查函数/方法调用的结果。您可以在关键函数的主体中添加对空参数的检查。然后,您的测试可以调用具有不同参数的函数
  • 单元测试基本上需要对任意输入进行测试,其中预期输出是已知的。因此,人们会期望一系列预定义单元测试的某些固定输入,您可以在其中针对预期输出进行断言。所以在这种情况下,你会做一些asserts 语句,输入(无,无)作为你的例子之一,看看它们返回什么
  • @BlueRineS 我刚开始尝试在 python 中进行单元测试......我不确定它与像你提到的那样在函数中进行定期检查有什么不同。如果是这样,为什么我们还需要单元测试?

标签: python python-unittest assertion


【解决方案1】:

我想做单元测试,检查输入(a,b)不为空,输出不为空。

要么你还不明白测试的目的,要么你在问一些与 TDD 相关的问题。

你不测试引用,你测试当这种情况发生时你的函数是否处理好。

因此,您应该创建测试函数并在其中调用:

def test_when_a_is_null(self):
    self.assertIsNotNone(add_num(None, 5))

当 b 为 None 并且两者都为 None 时类似。

但是,这意味着你的函数应该处理条件:

def add_num(a, b):
    if a is not None and b is not None:
        return a + b
    elif a is not None:
        return a
    elif b is not None:
        return b
    return 0

【讨论】:

  • if a is not None and b is not None 据我所知可以简化为if not a and not b
  • 不,试试 (None, False)。
  • 当然,这就是目的,它应该起作用,因为这两个参数都不是 None。问题是关于 value 为 null (并且 None 在 Python 中是对应的),所以答案涉及到这个问题。顺便说一句,1+False 等于 1。
  • 是的,我知道。这就是为什么我编辑了我的评论(在我意识到之后),包括当你添加它们时它确实有效 XD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多