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
446 views
in Technique[技术] by (71.8m points)

python - ModuleNotFoundError issue for pytest

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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'

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

...