这应该是地球上最简单的问题,但即使经过大量的搜索和修补,我仍然在寻找一种"正确"的方式来构建目录结构并设法正确运行pytest等方面遇到了麻烦.
假设我有一个名为apple的程序.
|- README.md
|- apple
| |-- __init__.py
| |-- apple.py
| - tests
| |-- test_everything.py
Run Code Online (Sandbox Code Playgroud)
apple.py包含一些函数,例如,让我们调用一个函数eat().该test_everything.py文件包含一些测试assert eat()=="foobar".好那么容易,但随后开始有趣:
__init__.py那苹果目录怎么样......对吗?空或应该在里面?py.test从根目录调用是最佳做法吗?还是py.test tests?__init__.py在他们的测试目录中,但是在py.test文档中明确说明这是错误的.那么为什么上帝呢test_everything.py文件顶部的内容是:a import apple还是from apple import *?或完全不同的东西eat()或调用函数apple.eat()吗?os.path.dirname在python中进行操作这应该很容易,但我已经看到了上述的所有组合,甚至没有谈到tox和无数其他工具.然而,有一点点错误,你会被抛出一些ImportError: No module named 'apple'或其他一些时髦的错误.
什么是"正确"的方式?github等上的建议和现有代码遵循极为不同的约定.对于经验丰富的中档编码器,这应该更容易.
我无法从pytest函数导入模块。我知道有100万个问题,但是我已经读了一堆,但仍然难以理解。
$ tree
.
??? code
??? eight_puzzle.py
??? missionaries_and_cannibals.py
??? node.py
??? search.py
??? test
??? test_eight_puzzle.py
??? test_search.py
2 directories, 6 files
$
$ grep import code/test/test_search.py
import sys
import pytest
import code.search
$
$ pytest
...
ImportError while importing test module '~/Documents/code/test/test_search.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
code/test/test_search.py:14: in <module>
import code.search
E ModuleNotFoundError: No module named 'code.search'; 'code' is not a package
...
Run Code Online (Sandbox Code Playgroud)
我希望那能奏效。“代码”是一个包,对吗?Python 3中的软件包是其中包含.py文件的任何目录。
我也尝试了相对导入-- from .. import search …