pytest模块导入ImportError:没有命名的模块

时间:2018-02-08 21:00:27

标签: python python-2.7 pytest python-module

此问题之前曾被问过 DOZENS ,但我遇到的每一个人都没有为我提供任何有用的解决方案。

我使用Python 2.7和import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class DataChange { public static void main(String[] args) throws IOException { String absolutePathOne = "C:\\Users\\hoflerj\\Desktop\\After\\test.txt"; String[] files = { "test.txt" }; for (String file : files) { File f = new File(file); String content = FileUtils.readFileToString(new File(absolutePathOne)); FileUtils.writeStringToFile(f, content.replaceAll("2018(.+)", "X")); } } } 来运行测试。

结构如下(从我的项目/ git repo的根目录):

pytest

然后我尝试运行tests / test_stuff.py文件:

myapp/
    myapp/
        __init__.py           # def main():
                              #    ... stuff
                              # if __name__ == "__main__":
                              #    main()

        __main__.py           # import __init__ as myapp
                              # myapp.main()

        config.yaml           # (app config file)

        myapplib/
                __init__.py   # (Empty file)

                config.py     # Loads {projectroot}/config.yaml
                              # def cfg(): 
                              #    ... stuff
    tests/
        test_stuff.py         # from myapplib.config import cfg

它抱怨道:

cd {projectroot}
pytest

我尝试过的一些事情:

  1. 使用myapp/tests/test_stuff.py:38: in <module> from myapplib.config import cfg E ImportError: No module named myapp.config 导入-mmyapplib
  2. 从其他目录开始myapp.myapplib(例如内部测试/)
  3. 在所有其他答案中使用所有路径黑客
  4. 将其更改为pytestfrom . import XXX或任何相关导入选项(但这些选项均以..失败。
  5. 从项目目录中看,应用程序本身没有任何好处:

    ValueError: Attempted relative import in non-package

    ...并且所有配置和路径都可以正常工作。它只是无法找到路径的测试。

    这是我迄今为止完整复制的内容:

    https://pyfiddle.io/fiddle/4fa60f5a-02df-43bb-8aa3-03e59ff72650/?m=Saved%20fiddle

1 个答案:

答案 0 :(得分:2)

你正在运行

web_accessible_resources

您需要修改myapp/tests/test_stuff.py 中的路径以指向test_stuff.py(其中包含myapp

我在我的系统上测试了这个(文件__init__.py):

test_stuff.py

(获取python模块的完整路径,然后使用父目录将python路径添加到import sys,os sys.path.append(os.path.join(os.path.dirname(__file__),os.pardir,"myapp")) import myapplib 的第二级)

适用于我的配置像你的:

myapp

建议:摆弄S:\python\myapp\myapp S:\python\myapp\tests S:\python\myapp\myapp\myapplib S:\python\myapp\myapp\myapplib\__init__.py S:\python\myapp\tests\test_stuff.py 时:

  • 始终使用绝对路径,使用sys.path.append()确保当前目录不会妨碍。 从不依赖于当前目录,或者此技巧仅在给定目录中有效。
  • debug:打印您添加的路径以检查它是否正确。由于它是绝对的,你很容易看出它是否正确。
相关问题