2

I'm trying to run a unittest but my test_fruit.py couldn't find my main script called whatis.py. All __init__.py files are empty and the full path of this sample project is /home/user/unittest_test.

I always get this error: ModuleNotFoundError: No module named 'x'. And if I use the relative import, I always get this message: ValueError: attempted relative import beyond top-level package.

# python tests/test_fruit.py
Traceback (most recent call last):
File "tests/test_fruit.py", line 2, in <module>
    from app.whatis import whatis
ModuleNotFoundError: No module named 'app'
# python tests/test_fruit.py
Traceback (most recent call last):
File "tests/test_fruit.py", line 2, in <module>
    from ..app.whatis import whatis
ValueError: attempted relative import beyond top-level package
#

Here's the directory structure:

unittest_test
├── app
│   ├── __init__.py
│   └── whatis.py
├── env
│   ├── bin
│   ├── include
│   ├── lib
│   └── pip-selfcheck.json
└── tests
    ├── __init__.py
    └── test_fruit.py

6 directories, 5 files

Here's the code in unittest_test/app/whatis.py:

import sys


def whatis(fruit):
    if fruit == 'apple':
        print('APPLE!')
        return 'apple'
    else:
        print('Sorry, I only return "apple".')
        sys.exit(1)


if __name__ == "__main__":
    try:
        fruit = sys.argv[1].lower()
    except IndexError:
        print('Please provide a name of fruit.')
        sys.exit(1)
    else:
        whatis(fruit)

Here's the code in unittest_test/tests/test_fruit.py:

import unittest
from app.whatis import whatis


class FruitTest(unittest.TestCase):
    def test_fruit(self):
        self.assertEqual(whatis('apple'), 'apple')

if __name__ == '__main__':
    unittest.main()
devxvda1
  • 442
  • 2
  • 8
  • 18
  • 1
    Recently answered a similar question: http://stackoverflow.com/a/43859946/723891 Take a look. It should help you understand how imports work in python – Igonato May 14 '17 at 06:55
  • I used pytest instead. Everything is working fine now. – devxvda1 May 18 '17 at 02:17

1 Answers1

0

Simply replace from app.whatis import whatis with from .app.whatis import whatis

Pdubbs
  • 1,967
  • 2
  • 11
  • 20