Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

unit testing - How to import the src from the tests module in python

I have an application that I'd like to test using unittest but I have some problems. My directory structure is as follows:

root_dir
├── src
│?? ├── cmds
│?? │?? ├── baz.py
│?? │?? ├── __init__.py
│?? │?? └── bar.py
│?? └── foo.py
└── tests
    ├── cmds.py
    └── __init__.py

I want to test the baz and bar modules from cmds and I'm trying to do

root_dir> python2.7 -m unittest tests.cmds

But in tests.cmds I cannot import the cmds package in my src dir.

How can I make this work?

Basically I want to test the application from root_dir with the src and tests directories separately.

I tried appending src to sys.path, but when I import cmds.baz from tests/cmds.py I still get an AttributeError: 'module' object has no attribute 'cmds' from unittest.

Edit: My import and sys.path statement is:

import sys
sys.path.append('../src')
from cmds.baz import about

And the traceback:

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module>
    main(module=None)
  File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'cmds'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A very wrong thing to do is appending a relative path to sys.path. If you want to be sure about the path, make it as follows:

# assuming that the code is in test's __init__.py
import os
import sys
sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__file__), 
                                               '../src/') ))
# now you can be sure that the project_root_dir/src comes first in sys.path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...