title: Python - ModuleNotFoundError: No module named 'x'
body: <p>I'm trying to run a <code>unittest</code> but my <code>test_fruit.py</code> couldn't find my main script called <code>whatis.py</code>. All <code>__init__.py</code> files are empty and the full path of this sample project is <code>/home/user/unittest_test</code>.</p>
  
  <p>I always get this error: <code>ModuleNotFoundError: No module named 'x'</code>. And if I use the relative import, I always get this message: <code>ValueError: attempted relative import beyond top-level package</code>.</p>
  
  <pre><code># python tests/test_fruit.py
  Traceback (most recent call last):
  File "tests/test_fruit.py", line 2, in &lt;module&gt;
      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 &lt;module&gt;
      from ..app.whatis import whatis
  ValueError: attempted relative import beyond top-level package
  #
  </code></pre>
  
  <p>Here's the directory structure:</p>
  
  <pre><code>unittest_test
  ├── app
  │   ├── __init__.py
  │   └── whatis.py
  ├── env
  │   ├── bin
  │   ├── include
  │   ├── lib
  │   └── pip-selfcheck.json
  └── tests
      ├── __init__.py
      └── test_fruit.py
  
  6 directories, 5 files
  </code></pre>
  
  <p>Here's the code in <code>unittest_test/app/whatis.py</code>:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Here's the code in <code>unittest_test/tests/test_fruit.py</code>:</p>
  
  <pre><code>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()
  </code></pre>