Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 819
Johnny Chiu Avatar asked Apr 02 '18 05:04

Johnny Chiu


1 Answers

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'
like image 142
Venkatesh Wadawadagi Avatar answered Oct 19 '22 07:10

Venkatesh Wadawadagi