티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보) 된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 주요 키워드를 미리 확인하세요.

pytest cannot import module while python can

pytest는 모듈을 가져올 수 없지만 python은 가져올 수 있음

 문제 내용 

I am working on a package in Python. I use virtualenv. I set the path to the root of the module in a .pth path in my virtualenv, so that I can import modules of the package while developing the code and do testing (Question 1: is it a good way to do?). This works fine (here is an example, this is the behavior I want):

나는 파이썬에서 패키지 작업을 하고 있다. 나는 virtualenv를 사용한다. virtualenv의 .p번째 경로에 모듈의 루트 경로를 설정하여 코드를 개발하고 테스트하는 동안 패키지의 모듈을 가져올 수 있습니다(질문 1: 좋은 방법입니까?). 이것은 잘 작동합니다(예를 들어, 제가 원하는 동작은 다음과 같습니다).

 

(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python
Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rc import ns
>>> exit()
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ python tests/test_ns.py 
issued command: echo hello
command output: hello

However, if I try to use PyTest, I get some import error messages:

그러나 PyTest를 사용하려고 하면 다음과 같은 가져오기 오류 메시지가 나타납니다.

 

(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ pytest
=========================================== test session starts ============================================
platform linux2 -- Python 2.7.12, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /home/zz/Desktop/GitFolders/rc, inifile: 
collected 0 items / 1 errors 

================================================== ERRORS ==================================================
________________________________ ERROR collecting tests/test_ns.py ________________________________
ImportError while importing test module '/home/zz/Desktop/GitFolders/rc/tests/test_ns.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_ns.py:2: in <module>
    from rc import ns
E   ImportError: cannot import name ns
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================= 1 error in 0.09 seconds ==========================================
(VEnvTestRc) zz@zz:~/Desktop/GitFolders/rc$ which pytest
/home/zz/Desktop/VirtualEnvs/VEnvTestRc/bin/pytest

I am a bit puzzled, it looks like this indicates an import error, but Python does it fine so why is there a problem specifically with PyTest? Any suggestion to the reason / remedy (Question 2)? I googled and stack-overflowed the 'ImportError: cannot import' error for PyTest, but the hits I got were related to missing python path and remedy to this, which does not seem to be the problem here. Any suggestions?

나는 약간 어리둥절한데, 이것은 가져오기 오류를 나타내는 것처럼 보이지만, 파이썬은 문제가 없는데 왜 PyTest에 특별히 문제가 있는 것인가? 이유/해결 방법에 대한 제안이 있습니까(질문 2)? PyTest에 대해 'ImportError: cannot import' 오류를 구글링하여 스택 오버플로했지만, 내가 받은 히트는 파이썬 경로 누락 및 이에 대한 해결책과 관련이 있으며, 이것은 여기서 문제가 되지 않는 것으로 보인다. 좋은 의견이라도 있나?

 

 

 

 높은 점수를 받은 Solution 

Found the answer:

정답 찾기:

 

DO NOT put a __init__.py file in a folder containing TESTS if you plan on using pytest. I had one such file, deleting it solved the problem.

pytest를 사용하려는 경우 테스트가 포함된 폴더에 __init_.py 파일을 넣지 마십시오. 나는 그런 파일 하나를 가지고 있었는데, 그것을 삭제하면 문제가 해결되었다.

 

This was actually buried in the comments to the second answer of PATH issue with pytest 'ImportError: No module named YadaYadaYada' so I did not see it, hope it gets more visibility here.

이것은 실제로 pytest 'ImportError: YadaYada라는 이름의 모듈이 없습니다'와 함께 PATH 문제의 두 번째 답변에 대한 댓글에 묻혔기 때문에 저는 보지 못했습니다. 여기서 더 많은 가시성을 얻기를 바랍니다.

 

 

 

 가장 최근 달린 Solution 

As of pytest 7.0, you can now add pythonpath in pytest.ini. No need to add __init__.py or conftest.py in your root directory.

pytest 7.0부터는 pytest.ini에 python 경로를 추가할 수 있습니다. 루트 디렉토리에 __init_.py 또는 conftest.py를 추가할 필요가 없습니다.

 

[pytest]
minversion = 7.0
addopts = --cov=src
pythonpath = src
testpaths =
    tests

You can run pytest without any parameters.

매개 변수 없이 pytest를 실행할 수 있습니다.

 

https://docs.pytest.org/en/7.0.x/reference/reference.html#confval-pythonpath

https://docs.pytest.org/en/7.0.x/reference/reference.html#confval-pythonpath

 

 

 

출처 : https://stackoverflow.com/questions/41748464/pytest-cannot-import-module-while-python-can

반응형
댓글
공지사항
최근에 올라온 글