Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python unittest ModuleNotFound用于从同一模块导入_Python_Python 3.x_Python Import_Python Unittest - Fatal编程技术网

Python unittest ModuleNotFound用于从同一模块导入

Python unittest ModuleNotFound用于从同一模块导入,python,python-3.x,python-import,python-unittest,Python,Python 3.x,Python Import,Python Unittest,当我试图在我的模块上创建单元测试时,我不断发现模块出错。 这是我的文件夹结构 - mod1/ - __init__.py - file1.py - numbers.py - tests/ - __init__.py - test_file1.py 问题出在file1.py中,有一条语句来自数字导入5 file1.py from numbers import five def five_plus_one(): return five()+1 test_file1.

当我试图在我的模块上创建单元测试时,我不断发现模块出错。 这是我的文件夹结构

- mod1/
  - __init__.py
  - file1.py
  - numbers.py
- tests/
  - __init__.py
  - test_file1.py
问题出在
file1.py
中,有一条语句
来自数字导入5

file1.py

from numbers import five

def five_plus_one():
    return five()+1
test_file1.py

import unittest
from mod1.file1 import five_plus_one

class MyTestCase(unittest.TestCase):
    @unittest.mock.patch('mod1.file1.five')
    def test_five_plus_one(self, five_mock):
        five_mock.return_value = 7
        self.assert_true(8, five_plus_one())
使用nosetest,这将生成此错误

ModuleNotFoundError: No module named 'numbers'
通过讨论多个stackoverflow问题,下面是如果尝试的话会发生什么

  • 删除和添加
    \uuuu init\uuuuu.py

    我试着在两个地方都删除一个,并且两个都删除了,但这并没有改变错误

  • @unittest.mock.patch('numbers.five')
    @unittest.mock.patch('mod1.numbers.five')

  • file1.py中使用
    import numbers
    而不是
    from numbers import five

  • 使用本地导入,但会产生此错误

    ModuleNotFoundError: No module named 'numbers'
    
  • 我对python非常陌生,不太了解名称空间及其导入方式


    注意。我将无法修改PYTHONPATH或此代码的运行方式。

    file1.py
    中,用以下内容替换当前导入:

    从mod1.5导入五个编号


    老实说,我也不知道它是怎么工作的。对于多文件夹项目始终必须这样做,而且从未真正质疑过它。

    我这样做了,但正常运行它会导致错误
    modulenofounderror:没有名为“mod1”的模块。
    ImportError: attempted relative import with no known parent package