2017-05-14 8 views
2

unittestを実行しようとしていますが、test_fruit.pywhatis.pyというメインスクリプトが見つかりませんでした。 __init__.pyのファイルはすべて空で、このサンプルプロジェクトの完全パスは/home/user/unittest_testです。Python - ModuleNotFoundError: 'x'というモジュールはありません

私はいつもこのエラーを受け取ります:ModuleNotFoundError: No module named 'x'。相対的なインポートを使用すると、私はいつもこのメッセージを受け取ります:ValueError: attempted relative import beyond top-level package

# python tests/test_fruit.py 
Traceback (most recent call last): 
File "tests/test_fruit.py", line 2, in <module> 
    from app.whatis import whatis 
ModuleNotFoundError: No module named 'app' 
# python tests/test_fruit.py 
Traceback (most recent call last): 
File "tests/test_fruit.py", line 2, in <module> 
    from ..app.whatis import whatis 
ValueError: attempted relative import beyond top-level package 
# 

は、ここでのディレクトリ構造です:

unittest_test 
├── app 
│   ├── __init__.py 
│   └── whatis.py 
├── env 
│   ├── bin 
│   ├── include 
│   ├── lib 
│   └── pip-selfcheck.json 
└── tests 
    ├── __init__.py 
    └── test_fruit.py 

6 directories, 5 files 

ここでは、コードunittest_test/app/whatis.pyにあります:

import sys 


def whatis(fruit): 
    if fruit == 'apple': 
     print('APPLE!') 
     return 'apple' 
    else: 
     print('Sorry, I only return "apple".') 
     sys.exit(1) 


if __name__ == "__main__": 
    try: 
     fruit = sys.argv[1].lower() 
    except IndexError: 
     print('Please provide a name of fruit.') 
     sys.exit(1) 
    else: 
     whatis(fruit) 

ここunittest_test/tests/test_fruit.pyのコードです:

import unittest 
from app.whatis import whatis 


class FruitTest(unittest.TestCase): 
    def test_fruit(self): 
     self.assertEqual(whatis('apple'), 'apple') 

if __name__ == '__main__': 
    unittest.main() 
+1

最近、同様の質問に回答しました:http://stackoverflow.com/a/43859946/723891 Pythonでのインポートの仕組みを理解するのに役立ちます – Igonato

答えて

-1

を見ます代わりにpytest。すべてがうまくいきました。

関連する問題