python - AttributeError : <module '__main__' from [. .] 没有属性 'open'

标签 python unit-testing tox

我正在为 docker-py 的模块编写测试,但我似乎无法让测试正常工作。

我正在测试的函数如下所示:

def parse_env_file(env_file):
    """
    Reads a line-separated environment file.
    The format of each line should be "key=value".
    """
    environment = []

    if os.path.isfile(env_file):
        with open(env_file, 'r') as f:
            # We can't use f.readlines() here as it's not implemented in Mock
            for line in f.read().split('\n'):
                parse_line = line.strip().split('=')
                if len(parse_line) == 2 and line[0] != '#':
                    k = parse_line[0]
                    v = parse_line[1]
                    environment.append('{0}={1}'.format(k, v))

    return environment

然后测试看起来像这样:

def test_parse_env_file_proper(self):
    with mock.patch('os.path.isfile', return_value=True):
        mock_env_file = 'USER=jdoe\nPASS=secret'
        with mock.patch('{}.open'.format(__name__), mock.mock_open(read_data=mock_env_file)):
            get_parse_env_file = parse_env_file('foobar')
    self.assertEqual(get_parse_env_file, ['USER=jdoe', 'PASS=secret'])

但是,当我运行测试时,出现以下错误:

======================================================================
ERROR: test_parse_env_file_proper (__main__.UtilsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/utils_test.py", line 102, in test_parse_env_file_proper
    with mock.patch('{}.open'.format(__name__), mock.mock_open(read_data=mock_env_file)):
  File "/Users/mvip/code/private/github/docker-py/.tox/py27/lib/python2.7/site-packages/mock.py", line 1268, in __enter__
    original, local = self.get_original()
  File "/Users/mvip/code/private/github/docker-py/.tox/py27/lib/python2.7/site-packages/mock.py", line 1242, in get_original
    "%s does not have the attribute %r" % (target, name)
AttributeError: <module '__main__' from 'tests/utils_test.py'> does not have the attribute 'open'

此处的任何指示都会有所帮助。

最佳答案

问题是,作为内置函数,open 不是直接在模块中找到的,而是作为 builtins 模块中的后备。

要解决这个问题,您应该在修补时包含 create=True

from unittest import mock

with mock.patch(__name__+".open", mock.mock_open(read_data="data"), create=True):
    with open("somefile") as f:
        assert f.read() == "data"

但是,这只会修补当前模块中的open(正在运行测试的模块,而不是正在测试的模块)。 p>

所以你最好这样做:

import unittest
from unittest.mock import mock_open, patch

import module_under_test


def func():
    with open("somefile") as f:
        return f.read()


class MyTestCase(unittest.TestCase):

    def test_open(self):
        data = "some data"
        with patch.object(module_under_test, "open", mock_open(read_data=data), create=True):
            result = module_under_test.func()

        self.assertEqual(result, data)


if __name__ == "__main__":
    unittest.main()

关于python - AttributeError : <module '__main__' from [. .] 没有属性 'open',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31705057/

相关文章:

c# - 在 VS 开发人员命令提示符之外运行单元测试?

unit-testing - 创建易于维护的测试

android - "java.lang.SecurityException:Injecting to another application requires INJECT_EVENTS permission"多个 Activity 工作流测试 android 时出错

python - Python 3 的 tox 调用失败

python - 在类中获取变量?

python - 代码不适用于十位和百位的奇数

python - 运行测试时如何让 tox 尊重系统版本?

python - 无法在开发模式下从 Windows 上的 pypy virtualenv 卸载 python 包

python - 如何在 setup.py 中为 cython 设置 sysroot

python - 套接字.gaierror : [Errno 11003] getaddrinfo failed