简体   繁体   English

如何使用py.test正确导入包?

[英]How do I correctly import packages with py.test?

I have the following layout: 我有以下布局:

/spamalot
    /spam
        __init__.py
        spam.py
        /spam_on_eggs
            __init__.py
            spam_on_eggs.py
    /tests

        test_spam.py

Spam just so happens to be a flask application. 垃圾邮件恰好是一个烧瓶应用程序。

Within spam.py I have spam.py我有

import spam_on_eggs.spam_on_eggs as eggs
# Other Flask setup & application code here.

And this works fine - from the spamalot directory I'm able to run python spam/spam.py 这很好 - 从spamalot目录我可以运行python spam/spam.py

However, when I start to throw tests into the mix, it's not as awesome. 但是,当我开始将测试投入混音时,它并不那么棒。

In my test_spam.py file I have: 在我的test_spam.py文件中,我有:

import spam.spam
test_client = spam.spam.app.test_client()

def test_it_fails():
     assert False

However, rather than failing where I would expect, it fails on the import line: 但是,它不是在我预期的地方失败,而是在导入行上失败:

/spamalot/ $ py.test
# some output
E    ImportError

I can fix this by putting __init__.py in my /tests folder, but then I get a different ImportError: 我可以通过在我的/tests文件夹中放置__init__.py来解决这个问题,但后来我得到了一个不同的ImportError:

spam/spam.py:1: in <module>
>    import spam_on_eggs.spam_on_eggs as eggs
E    ImportError: No module named 'spam_on_eggs'

I can solve that one by changing the line to: 我可以解决一个通过改变线路:

from spam.spam_on_eggs import spam_on_eggs

Which allows me to test but then I break my ability to run $ python spam/spam.py - because I get 这允许我测试, 后来我打破了运行$ python spam/spam.py - 因为我得到了

ImportError: no module named 'spam'

Obviously I have a gap in my understanding of how module imports work and how py.test works with this system. 显然,我对模块导入如何工作以及py.test如何与该系统一起工作的理解存在差距。

What am I missing? 我错过了什么?

Is it even possible to have the layout I've described - and be able to run both py.test and my server from the spamalot directory? 是否有可能拥有我所描述的布局 - 并且能够从spamalot目录运行py.test和我的服务器?

py.test will always use the shortest directory path with an __init__.py in it. py.test将始终使用带有__init__.py的最短目录路径。

Put a __init__.py into spamalot and you can import spamalot.spam.spam . __init__.py放入spamalot,您可以导入spamalot.spam.spam

Reference: choosing a test layout 参考: 选择测试布局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM