Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 单元测试应该如何与外部资源一起工作?什么是正确的方法?_Python_Unit Testing - Fatal编程技术网

Python 单元测试应该如何与外部资源一起工作?什么是正确的方法?

Python 单元测试应该如何与外部资源一起工作?什么是正确的方法?,python,unit-testing,Python,Unit Testing,我最近学习了单元测试,知道不应该对外部资源进行单元测试。因此,这就引出了一个测试简单函数的问题,我想将其改写为单元测试的标准 为简单起见,下面是该函数的一个示例: def longTask(somearg): # Check somearg # Begin infinite loop # Check remote resource loop based on somearg # Write results to a database or file # Ch

我最近学习了单元测试,知道不应该对外部资源进行单元测试。因此,这就引出了一个测试简单函数的问题,我想将其改写为单元测试的标准

为简单起见,下面是该函数的一个示例:

def longTask(somearg):
  # Check somearg

  # Begin infinite loop
    # Check remote resource loop based on somearg

    # Write results to a database or file

    # Check to break loop

  # Cleanup upon end
我想确保上面的代码已经过单元测试(现在我知道了单元测试)

我的主要困惑来自这样一个事实:当您不应该对外部资源进行单元测试时,如何对正在进行外部资源调用的简单函数进行单元测试


注意:我已经阅读了其他关于此的帖子,但这些帖子没有回答我的问题。

您是否考虑过使用类似伪对象[1]的东西来测试代码。您可以为外部资源提供一个包装器/接口,对于您的测试,可以使用该包装器/接口的一个版本,该版本提供了方便测试的行为

[1]

在这种情况下,我通常会使用某种模拟。例如,有一些优秀的python模拟包,可以使测试对象对真实对象的替换更加容易

比如说

    def test_au(self):
        user_id=124
        def apple(req):
            return 104
        with patch('pyramid.security.authenticated_userid', return_value=user_id
):
            authenticated_userid = apple
            self.assertEqual("104", authenticated_userid(self.request).__str__()
)
补丁是从mock导入的方法。它在给定的范围内改变其他包的行为

在本例中,已验证的_userid的预定义库方法从pyramid.security import authenticated_userid导入
,并在pyramid框架内工作。要测试它在我的设置函数运行后是否返回正确的值,我可以在测试期间“覆盖”该方法

    def test_au(self):
        user_id=124
        def apple(req):
            return 104
        with patch('pyramid.security.authenticated_userid', return_value=user_id
):
            authenticated_userid = apple
            self.assertEqual("104", authenticated_userid(self.request).__str__()
)