여기에 2 개의 작은 문제가 있습니다. 첫째, 잘못된 디렉토리에서 테스트 명령을 실행하고 두 번째로 프로젝트를 제대로 구조화하지 않았습니다.
보통 저는 파이썬 프로젝트를 개발할 때 프로젝트의 루트를 중심으로 모든 것을 유지하려고 노력합니다. 귀하의 경우에는 hello_python/
이 될 것입니다. 파이썬은 기본적으로는 부하 경로에 현재 작업 디렉토리를 가지고, 그래서 당신이 프로젝트를 같이 가지고있는 경우 :
hello_python/
hello/
hello.py
__init__.py
test/
test_hello1.py
test_hello2.py
# hello/hello.py
def do_hello():
return 'hello'
# test/test_hello.py
import unittest2
from hello.hello import do_hello
class HelloTest(unittest2.TestCase):
def test_hello(self):
self.assertEqual(do_hello(), 'hello')
if __name__ == '__main__':
unittest2.main()
두 번째는 __init__.py
에서 놓친 이후, test
는 지금 모듈 아니다 그 디렉토리.
hello_python/
hello/
hello.py
__init__.py
test/
__init__.py # <= This is what you were missing
test_hello1.py
test_hello2.py
내가
python -m unittest test.hello_test
나를 위해 잘 작동 실행, 내 컴퓨터에서 그 시도 : 당신은 다음과 같습니다 계층 구조를 가져야한다.
그래도 조금 성가신 것을 알 수 있습니다. nose을 설치하는 것이 좋습니다. 그러면 프로젝트 루트에서 nosetests
을 호출하여 모든 테스트를 자동으로 찾아 실행합니다. 정확한 모듈을 __init__.py
으로 지정하면됩니다.
테스트에서 가져 오기는 다른 코드에서 가져 오는 것과 다르지 않습니다. 귀하의 경우에는'from hello.hello import do_hello'를 할 것입니다. –
감사합니다. 알았다. 이제 테스트는'PyCharm'에서 Ok를 실행합니다. 그러나 현재 디렉토리'test'에서'python -m unittest test_hello_server' 명령을 실행하면 ImportError : No hello_server.hello_server 모듈이 생깁니다. – Michael
상위 디렉토리가 pythonpath에 없기 때문에. 오히려,'hello_python' 내부에서 시작하여'python -m unittest test.test_hello' 또는 무엇이든해야합니다. –