简体   繁体   中英

Python unittest ModuleNotFound for import from same module

I kept getting ModuleNotFound error when trying to create unit test on my module. Here is my folder structure

- mod1/
  - __init__.py
  - file1.py
  - numbers.py
- tests/
  - __init__.py
  - test_file1.py

The problem is in file1.py there is this statement from numbers import five .

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())

Using nosetests, this will generate this error

ModuleNotFoundError: No module named 'numbers'

From going through multiple stackoverflow questions, here is what if tried.

  1. Removing and adding __init__.py

    I've tried removing one, in both places and removed both, and it doesn't change the error

  2. replace the patch with @unittest.mock.patch('numbers.five') or @unittest.mock.patch('mod1.numbers.five')

  3. using import numbers instead of from numbers import five in file1.py

  4. using local import, but it produces this error

AttributeError: <module 'mod1.file1' from '/mod1/file1.py'> does not have the attribute 'five'

The only time it ever worked is if I modify file1.py to have from.numbers import five but it caused this error when running the code regularly

ImportError: attempted relative import with no known parent package

I'm quite new to python and don't really understand the namespace and how it imports.

Note. I wouldn't be able to modify PYTHONPATH or the way this code is being ran.

In file1.py replace your current import with this:

from mod1.numbers import five

Honestly, I don't know how it works either. Always had to do this for multi-folder projects and never really questioned it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM