pytest 以及为什么要避免使用 init 文件 [英] pytest and why avoid init file

查看:197
本文介绍了pytest 以及为什么要避免使用 init 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从前,pytest 文档现在位于 https://docs.pytest.org/en/latest/goodpractices.html 曾经说过:

Once upon a time, the pytest document now at https://docs.pytest.org/en/latest/goodpractices.html used to say:

避免在测试目录中使用__init__.py"文件.通过这种方式,您的测试可以轻松地针对已安装的 mypkg 版本运行,独立于已安装的包(无论是否包含测试).

avoid "__init__.py" files in your test directories. This way your tests can run easily against an installed version of mypkg, independently from the installed package if it contains the tests or not.

我不明白以下关于那句话的内容:

I don't understand following about that quote:

  1. mypkg 的安装版本是什么意思?如果我有一个简单的 Flask 应用程序,当您在本地主机上打根时只说hello world",我该如何安装应用程序?
  2. 已安装版本与已安装软件包有何不同?
  3. 是否包含测试"是什么意思?是否与测试发现有关?
  4. 有人能解释一下没有 __init__.py 有什么好处吗?
  1. What does it mean by installed version of mypkg? How can I relate installing an app if I have a simple flask app that only says "hello world" when you hit the root at the localhost?
  2. How is installed version different from installed package?
  3. What does it mean "if it contains tests or not"? Is it related to test discovery?
  4. Can someone practically explain how not having __init__.py is good?

推荐答案

py.test 需要通过向 sys.path 添加一个目录来使测试可导入,如果您在项目根目录中有一个 test 文件夹和一个 __init__.py 在里面,然后 py.test 将选择项目根进行路径插入,因此它总是首先使源树可导入,这可以在运行测试时隐藏已安装版本中的错误

py.test needs to make the tests importable by adding a directory to sys.path, if you have a test folder in the project root and a __init__.py in it, then py.test will pick the project root for path insertion and it thus always making the source tree importable first, which can hide bugs in the installed version while running tests

避免该问题的另一种方法是使用 src 文件夹并使用 setup.py

an alternative way to avoid the issue is having a src folder and using the package_dirs option in setup.py

这篇关于pytest 以及为什么要避免使用 init 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆