pytest配置问题(从nosetests(71秒)到pytest(153​​6秒)的过渡)

2023-12-31

问题:

pytest(由策略决定)运行相同的测试套件(585 个测试)需要 1536 秒nosetest,运行时间为 71 秒。

The pytest.ini文件是:

[pytest]
python_files = tests_*.py *_tests.py
norecursedirs = .idea  (pycharm env).
testpaths = tests

该文件放置在项目的根目录下:

root
 |-+ mod1
 | |-- core.py
 | |-- utils.py
 |-+ mod2
 | |-- core.py
 | |-- utils2.py
 |-+ tests
 | |-- test_mod1
 | |-- test_mod2
 |-+ utils (don't test).
 | |-- u1.py
 | |-- u2.py
 |- pytest.ini
 |- readme.md

我检查过的事情(遵循其他 14 个 SO 帖子的建议):

  • 通过/失败的次数是相同的。
  • 当使用 pytests 单独运行测试时,它们需要大约 20 毫秒。
  • 使用 pytests 运行文件夹时,10-20 个测试需要 14-15 秒。
  • 测试套件只有一个环境,没有 env 或 os 魔法。只是很多技术逻辑。
  • 每个 test_xyz.py 文件都有自己的隔离def setup and def teardown创建/删除 SQLite 数据库。测试通过添加新事务并检查添加内容来与数据库进行交互。例子:
global db

def setup():
   db = get_new_db()

def teardown():
   pass

def test_01():
   w = Widget(db)  # create widget instance.
   w.add_friend('[email protected] /cdn-cgi/l/email-protection')
   assert '[email protected] /cdn-cgi/l/email-protection' in w.friends()

问题:

  1. 我真的必须在上面贴上 @pytest.fixtures(scope='module') 吗setup and teardown每 585 次测试中?我希望不是。

  2. 我该怎么做才能获得运行时间pytest类似于nosetests?


我不知道为什么pytest选择调用模块设置函数pytest_runtest_setup每个测试运行一次的钩子,而不是模块范围内的自动使用装置,但是这里是 https://github.com/pytest-dev/pytest/blob/8ffa3aa65dcb10fee7ab0ffe7508cad7386ce9ce/src/_pytest/nose.py#L35:

@hookimpl(trylast=True)
def pytest_runtest_setup(item):
    if is_potential_nosetest(item):
        if not call_optional(item.obj, "setup"):
            # call module level setup if there is no object level one
            call_optional(item.parent.obj, "setup")
        # XXX this implies we only call teardown when setup worked
        item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item)

这意味着您需要将设置/拆卸函数重命名为setup_module()/teardown_module()。如果您使用的是 Linux/MacOS,则可以使用sed结合grep批量重命名:

$ grep -lr "\(def setup():\|def teardown():\)" | \
  xargs sed -i 's/def setup():/def setup_module():/g;s/def teardown():/def teardown_module():/g'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytest配置问题(从nosetests(71秒)到pytest(153​​6秒)的过渡) 的相关文章