Programing

파이썬 코 가져 오기 오류

lottogame 2020. 7. 18. 10:25
반응형

파이썬 코 가져 오기 오류


파일 구조에서 테스트 스크립트 아래의 모듈을 인식 하기 위해 코 테스트 프레임 워크 를 얻지 못하는 것 같습니다 . 문제를 보여주는 가장 간단한 예를 설정했습니다. 아래에 설명하겠습니다.

패키지 파일 구조는 다음과 같습니다.

./__init__.py
./foo.py
./tests
   ./__init__.py
   ./test_foo.py

foo.py는 다음을 포함합니다 :

def dumb_true():
    return True

tests / test_foo.py는 다음을 포함합니다 :

import foo

def test_foo():
    assert foo.dumb_true()

모두 초기화 평 파일은 비어 있습니다

nosetests -vv메인 디렉토리 (foo.py가있는 곳)에서 실행 하면 다음을 얻습니다.

Failure: ImportError (No module named foo) ... ERROR

======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 379, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 39, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 86, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/user/nose_testing/tests/test_foo.py", line 1, in <module>
    import foo
ImportError: No module named foo

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

tests / 디렉토리 내부에서 실행할 때 동일한 오류가 발생합니다. 내가 찾은 문서와 예제 에 따르면 , nose는 모든 상위 패키지를 경로와 디렉토리에 추가해야한다고 생각하지만 내 경우에는 일어나지 않는 것 같습니다.

Python 2.6.2에서 Ubuntu 8.04를 실행하고 있습니다. 중요한 경우 수동으로 코를 만들고 설치했습니다 (setup_tools가 아님).


당신은있어 __init__.py당신의 최상위 디렉토리에. 그것은 그것을 패키지로 만듭니다. 제거하면 효과 nosetests가 있습니다.

제거하지 않으면를로 변경해야 import합니다 import dir.foo. 여기서 dir디렉토리 이름은입니다.


당신은 virtualenv에 있습니까? 내 경우 에는를 사용하는 nosetests의 하나 /usr/bin/nosetests였습니다 /usr/bin/python. virtualenv의 패키지는 확실히 시스템 경로에 있지 않습니다. 다음은 이것을 수정했습니다.

source myvirtualenv/activate
pip install nose
which nosetests
/home/me/myvirtualenv/bin/nosetests

나중에이 질문을 찾는 사람들에게 : __init__.py테스트 디렉토리에 파일 이 없으면 가져 오기 오류가 발생합니다 .

내 디렉토리 구조는 다음과 같습니다.

./tests/
  ./test_some_random_stuff.py

코 테스트를 실시한 경우 :

nosetests -w tests

It would give the ImportError that everyone else is seeing. If I add a blank __init__.py file it works just fine:

./tests/
  ./__init__.py
  ./test_some_random_stuff.py

Another potential problem appears to be hyphens/dashes in the directory tree. I recently fixed a nose ImportError issue by renaming a directory from sub-dir to sub_dir.


Of course if you have a syntax error in the module being imported that will cause this. For me the problem reared its head when I had a backup of a tests file with a path like module/tests.bak.py in the same directory as tests.py. Also, to deal with the init package/module problem in a Django app, you can run the following (in a bash/OSX shell) to make sure you don't have any init.pyc files lying around:

find . -name '*.pyc' -delete

I got this error message because I run the nosetests command from the wrong directory.

Silly, but happens.


I just ran into one more thing that might cause this issue: naming of tests in the form testname.test.py. That extra . confounds nose and leads to it importing things it should not. I suppose it may be obvious that using unconventional test naming conventions will break things, but I thought it might be worth noting.


For example, with the following directory structure, if you want to run nosetests in m1, m2 or m3 to test some functions in n.py, you should use from m2.m3 import n in test.py.

m1
└── m2
    ├── __init__.py
    └── m3
        ├── __init__.py
        ├── n.py
        └── test
            └── test.py

Just to complete the question: If you're struggling with structure like this:

project
├── m1
├    ├── __init__.py
├    ├── foo1.py
├    └──m2
├       ├── __init__.py
├       └── foo2.py
└── test
     ├── __init__.py
     └── test.py

And maybe you want to run test from a path outside the project, include your project path inside your PYTHONPATH.

export PYTHONPATH=$PYTHONPATH:$HOME/path/to/project

paste it inside your .profile. If you're under a virtual environment, paste it inside the activate in your venv root

참고URL : https://stackoverflow.com/questions/3073259/python-nose-import-error

반응형