简体   繁体   中英

How do I import a module from a parent directory? (unittest purposes)

I have just finished writing the core section of a project I am working on and I want to write test for it using unittest before I continue. I am aware that I should have done this before, but when I started I didn't know Python, so.. whatever..

What I would like to achieve: I have a sub-package of the main package which contains all the modules I want to test inside it. I want to put a subsubpackage inside that called 'tests' or something which then contains all of my test cases, which I'd like to be able to aggregate into a test suite from outside the package so eventually I can run all the test for the entire project in one go.

The structure is something like this:

/projectPackage
/projectPackage/package
/projectPackage/package/\__init__.py (empty)
/projectPackage/package/someModule.py
/projectPackage/package/... (more modules)
/projectPackage/package/testing.py (runs all the tests in /tests/)
/projectPackage/package/tests
/projectPackage/package/tests/\__init__.py (empty)
/projectPackage/package/tests/someModuleTests.py

Problem I am having:

someModuleTests has to import someModule from the parent package so it can test its methods. This doesn't seem to work. I get various errors like:

Attempted relative import beyond toplevel package

Anyway, I expect it's just because I am a Python noob! I have my own ideas on how I am going to do it for this project, because of course each is different, but any general advice on the structuring of medium-large python projects is also appreciated.

Run the unit test from the parent directory so the directory is in your PYTHONPATH (the current working directory always is). This is done by executing the test file from your parent directory or by using something like nosetest which recursively looks for all tests in your package.

Don't use relative imports, they cause things like this. Don't hack your PYTHONPATH and/or sys.path to try and fix it either.

考虑到您使用命令行工具来运行测试,您可以按照文档操作并执行以下操作:

python -m unittest package.tests.someModuleTests

If you can execute your code then your PYTHONPATH should already be set correctly. What you need to do is to specify the module you want to import, eg

import projectPackage.package.someModule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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