python-3.x - python : mock file input for testing function

标签 python-3.x unit-testing mocking

我知道有类似的帖子,但我没有找到类似的帖子。

我在 python 中有一个函数,它接收要读取的文件名作为输入,处理并返回一些东西,我想测试我的函数的输出。例子:

#main function
def myfunction(filename):
    f=open(filename)

    for line in f:
        # process data
        pass
    f.close()

    return # something

#test function for the main function
def test_myfunction():
    mockfile = #mymockfile
    assert myfunction(mockfile) == #something

我怎样才能创建一个模拟文件来测试这个函数而不必编写一个读取文件?

这是我发现最接近我需要的东西 (http://www.voidspace.org.uk/python/mock/helpers.html#mock-open)

最佳答案

遇到了同样的问题,请在下面找到我的答案。其中大部分来自:
http://omiron.ro/post/python/how_to_mock_open_file/ .
我通过 Eclipse 中的 pydev 插件使用了 Python 3.6 和 Py.test。

import unittest.mock as mock
from unittest.mock import mock_open

#main function
def myfunction(filename):
    f=open(filename)
    maximum = 0
    for line in f:
        if maximum < len(line):
            maximum = len(line)
        pass
    f.close()
    return maximum

#test function for the main function
@mock.patch('builtins.open', new_callable=mock_open, create=True)
def test_myfunction(mock_open):
    mock_open.return_value.__enter__ = mock_open
    mock_open.return_value.__iter__ = mock.Mock(
        return_value = iter(['12characters', '13_characters']))
    answer = myfunction('foo')
    assert not answer == 12
    assert answer == 13

关于python-3.x - python : mock file input for testing function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43567678/

相关文章:

python - 如何使用存储在变量中的值作为案例模式?

python - 如何用漂亮的汤按标题提取网址?

regex - 获取包含在特殊字符 « 和 » 中的字符串之外的所有双引号字符

c# - 使用带有单元测试的 ViewModel 进行 CRUD 编辑操作

php - 设置 PHPUnit Mock 后,我可以更改方法吗?

python - Python 3.4 中的 "async with"

unit-testing - 单元测试气味

node.js - 单元测试 Express Controller

c# - 将同一类中的方法分开,用于被测试的方法,以允许模拟

iphone - 是否有任何可用于 Objective-C 的测试 spy 库?