我对编写测试(python)还很陌生,所以我现在有一个问题:如何将字典传递给测试函数?目前我做了以下工作:
import os
import sys
import shutil
from app.views import file_io
import pytest
from tempfile import mkdtemp
import codecs
@pytest.fixture()
def tempdir():
tempdir = mkdtemp()
yield tempdir
shutil.rmtree(tempdir)
articles = [
["", "README.md", "# Hallo Welt", "<h1>Hallo Welt</h1>\n"],
["test", "article.md", "# Hallo Welt", "<h1>Hallo Welt</h1>\n"]
]
@pytest.mark.parametrize("dir, file, content_plain, content_md", articles)
def test_readRaw(tempdir, dir, file, content_plain, content_md):
dest_path=os.path.join(tempdir, dir)
os.makedirs(dest_path, exist_ok=True)
with codecs.open(os.path.join(dest_path, file), 'w', 'utf-8') as fh:
fh.write(content_plain)
assert file_io.readRaw(os.path.join(dest_path, file)) == content_plain
我的想法/希望是我可以修改代码,这样我就可以做如下事情:
articles = [
{ "dir": "",
"filename": "README.md",
"content_md": "# Hello World",
"content_html": "<h1>Hello World</h1>\n" },
{ "dir": "test",
"filename": "article.md",
"content_md": "# Hallo Welt",
"content_html": "<h1>Hallo Welt</h1>\n"}
]
@pytest.mark.parametrize(**articles, articles)
def test_readRaw(tempdir, **articles):
with codecs.open(os.path.join(dir, file), 'w', 'utf-8') as fh:
fh.write(content_md)
assert file_io.readRaw(os.path.join(dir, file)) == content_md
特别是我想避免提及所有键,这样我可以扩展字典,如果我错过了一些东西,而不修改所有测试。你知道吗
也许这是一个愚蠢的问题,但正如我所说,我刚刚开始这个话题,所以我会非常感谢每一个提示我如何可以做到这一点(或什么是更好的方式)。 致以最诚挚的问候 丹
与其尝试splat/unsplat,不如尝试将
article
作为参数:另一个选择(利用python3.6+特性)是手动展开键,尽管您必须注意以相同的顺序定义每个字典
不管它值多少钱,我认为采用第二种方法会牺牲一些可读性(并使测试特别脆弱)
~相关建议
dir
或file
,最好不要参数化这些函数考虑到这两个因素,使用经典参数化(一个简单的输入/输出表)测试变得简单得多:
免责声明:我是
pytest
当前的核心开发者之一相关问题 更多 >
编程相关推荐