ModuleNotFoundError issue for pytest

回眸只為那壹抹淺笑 提交于 2019-12-23 17:43:23

问题


I want to use pytest to do unit testing for the scripts in another folder called src. Here is my directory structure:

src      
  __init__.py
  script1.py
  script2.py
test
  test_fun.py

However, when I try to run pytest in the test folder through command line, I saw the following error

from script2 import fun2
E ModuleNotFoundError: No module named 'script2'

In each script, I have the following contents

script2.py:

def fun2():
return('result_from_2')

script1.py:

from script2 import fun2

def fun1():
    return(fun2()+'_plus_something')

test_fun.py:

import sys
sys.path.append('../')
from src.script1 import fun1

def test_fun1():        
    output1 = fun1()

    # check output
    assert output1=='result_from_2_plus_something'

How can I run pytest with the directory provided above?


回答1:


When importing a file, Python only searches the current directory, the directory that the entry-point script is running from and sys.path.

Modify test_fun.py as follows:

import sys
sys.path.insert(0, '../src/')
from script1 import fun1

def test_fun1():        
    output1 = fun1()

    # check output
    assert output1=='result_from_2_plus_something'


来源:https://stackoverflow.com/questions/49605830/modulenotfounderror-issue-for-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!