pytest 的 ModuleNotFoundError 问题 [英] ModuleNotFoundError issue for pytest

查看:68
本文介绍了pytest 的 ModuleNotFoundError 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 pytest 对另一个名为 src 的文件夹中的脚本进行单元测试.这是我的目录结构:

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

但是,当我尝试通过命令行在 test 文件夹中运行 pytest 时,我看到了以下错误

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

从 script2 导入 fun2
E ModuleNotFoundError: 没有名为script2"的模块

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'

如何使用上面提供的目录运行 pytest?

How can I run pytest with the directory provided above?

推荐答案

导入文件时,Python 只搜索当前目录、运行入口点脚本的目录和 sys.path.

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

修改test_fun.py如下:

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'

这篇关于pytest 的 ModuleNotFoundError 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆