0
我想把我所有的單元測試放在一個單獨的目錄中。我的項目佈局是這樣的:Python單元測試導入模塊與nostest
project
package
__init__.py
package.py
tests
__init__.py
package_test.py
package_test.py樣子:
from unittest import TestCase
from package import Service
class ServiceTest(TestCase):
def test_build():
service = Service.build()
self.assertIsNotNone(service)
當我嘗試運行我得到以下錯誤
$ cd project
$ nosetest
E
======================================================================
ERROR: Failure: ImportError (cannot import name 'ScraperService')
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/usr/local/lib/python3.6/site-packages/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python3.6/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python3.6/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/usr/local/lib/python3.6/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/usr/local/lib/python3.6/imp.py", line 172, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 675, in _load
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/usr/src/project/tests/package_test.py", line 2, in <module>
from package import Service
ImportError: cannot import name 'Service'
----------------------------------------------------------------------
Ran 1 test in 0.046s
FAILED (errors=1)
如何導入測試我的包裝進我的測試課?
我必須讓項目成爲一個模塊嗎?
我是否必須打包才能發貨?setup.py
?
會改變導入到'從package.package導入服務'有什麼區別? – grundic
哇!它確實!但爲什麼? – Martinffx
第一個來自文件夾的'package',第二個來自文件。您必須提供導入模塊的完整路徑,包括所有子目錄。 – grundic