如何通过字典进行测试

问题描述 投票:0回答:2

我在编写测试(对于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

尤其是我想避免提及所有键,因此如果我错过了一些内容而没有修改所有测试,则可以扩展字典。

也许这是一个愚蠢的问题,但是正如我所说的,我只是从这个话题开始,所以我非常感谢每一个提示,我将如何做到这一点(或者什么是更好的方法)。最好的祝福丹

python python-3.x pytest
2个回答
0
投票

而不是尝试进行splat / unsplat,请尝试将article作为参数:

@pytest.mark.parametrize('article', articles)
def test_readRaw(tempdir, article):
    # use `article['foo']` here...

[另一个选项(利用python3.6 +功能)是手动扩展键-尽管您必须注意以相同的顺序定义每个词典]]

@pytest.mark.parametrize(tuple(articles[0]), [tuple(dct.values()) for dct in articles])
def test_readRaw(tempdir, dir, file, content_plain, content_md):
    ...

对于它的价值,我认为您采用第二种方法会牺牲一些可读性(并使测试特别脆弱)


〜相关建议

  • 您可以使用内置的tmp_path / tmpdir fixtures代替自己构建的
  • 您的被测函数实际上并不依赖于tmp_pathtmpdir,最好不要对它们进行参数化
  • 考虑到这两个因素,使用经典的参数化(简单的输入/输出表),您的测试将变得更加简单:

dir

免责声明:我是file上目前的核心开发人员之一>

© www.soinside.com 2019 - 2024. All rights reserved.