- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在为 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/
假设这样一个函数: In [56]: def add_numbers(x, y): return x + y 当我在没有括号的情况下使用它 In [57]: add_numbers Out[57]:
目前在 Django 网站上工作,我在将类及其属性从我的 models.py 模块导入到我的 views.py 模块时遇到问题音乐应用。据我了解,Django 使用元类来构建模型,因此定义的字段不会作
如果我执行 main.py它工作正常,问题是当我执行 demo2.py |myPackage |subPackage demo.py demo2.py main.p
当前尝试在 Python3 中工作并使用绝对导入将一个模块导入另一个模块,但出现错误 ModuleNotFoundError: No module named '__main__.moduleB';
我有一个 Tornado 应用程序,其文件结构如下: projectfolder |_ Dockerfile |_ src |_ __init__.py |_ __main__.py |_ co
我正在创建一个用于网页抓取的应用程序目录,该目录是在我的 django_project 中抓取的。我在将 models.py 模块中的类导入到views.py 模块中时遇到错误。 这是我的项目结构:
我在 Windows 10 上使用 Python 3.6。我在同一目录中有 2 个 .py 文件,char.py 和 char_user.py,如下所示: 字符.py: # char.py impor
import pickle class NoClass(): def __init__(self, name, level, cls, time_played): self.n
您好,我想测试我的可执行模块 main.py。在这个模块中有一个函数 main() 有两个参数: # main.py def main(population_size: int, number_of_
这在Python中合法吗?似乎有效... 谢谢 # with these lines you not need global variables anymore if __name__ == '__m
假设我们执行script_1。因此,script_1 是 __main__。但是,script_1 从 script_2 导入一些类。有没有办法,当我们输入 script_2 保存旧的 __main_
有没有这样的情况: import __main__ 可能会导致 ImportError?我尝试过的所有案例似乎都表明这总是有效的。 __main__ 上的文档似乎没有对此事发表任何看法。 为了提供一些
这个问题在这里已经有了答案: How to make __name__ == '__main__' when running module (4 个答案) 关闭 6 年前。 我有一个 python
我想通过测试确保:- 应用程序无法导入- 该应用程序可以作为真实应用程序启动(即:python src.py) 我对此很感兴趣,为什么以下不起作用: src.py class A: def x(se
我刚刚开始学习 Python,有一件事情困扰着我,那就是 "__main__" 的确切类型。到目前为止,我已经看到 "__main__" 主要用作字符串文字,如 __name__ == "__main
我有一个模块有通常的 if __name__ == '__main__': do stuff... 成语。 我想从另一个模块导入它,然后让它运行该代码。有什么办法吗? 我应该提一下,由于我不会
在Python,我们经常会编写 ? 1
我有这个 python 代码,我想从 Windows 运行中运行它。但是,当我尝试运行它时,cmd 会显示此消息。 C:\Users\myName\AppData\Local\Programs\Pyt
我无法在 python (2.7) 中正确命名子记录器。我有以下文件结构: -mypackage -__init__.py -main.py -log -__init__.py
当我尝试运行我的代码时出现此错误:\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra
我是一名优秀的程序员,十分优秀!