0

I know theres heaps of questions and answers for this, I tried multitude stackoverflow links but none of these seem to help.

My project structure is:

volume_price_analysis/
  README.md
  TODO.md
  build/
  docs/
  requirements.txt
  setup.py
  vpa/
    __init__.py
    database_worker.py
    utils.py
    test/
      __init__.py
      test_utils.py
      input/
        input_file.txt

I want to load utils.py inside test_utils.py

my test_utils.py is:

import unittest
import logging
import os

from .vpa import utils

class TestUtils(unittest.TestCase):

    def test_read_file(self):
        input_dir = os.path.join(os.path.join(os.getcwd()+"/test/input"))
        file_name = "input_file.txt"

        with open(os.path.join(input_dir+"/"+file_name)) as f:
            file_contents = f.read()
        f.close()

        self.assertEqual(file_contents, "Hello World!\n")

if __name__ == '__main__':
    unittest.main()

I want to run (say inside test folder):

python3 -m test_utils.py

I can not do that, I get a bunch of errors regarding imports of utils (tried many iterations of . , no ., from this import that etc.. etc..

Why is this so bloody complicated?

I am using Python 3.7 if that helps.

user3674993
  • 129
  • 1
  • 9

2 Answers2

0

As per this answer, you can do it using importlib,

in spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") ,instead of path/to/file, you can use ../utils.py. Also, since you are already importing a package named utils (from importlib), you should call one of them by other name, ie. dont keep module.name as utils or import importlib.utils as something else.

SajanGohil
  • 960
  • 13
  • 26
0

I figured it out, turns out python prefers you to run your code from top level folder, in my case volume_price_analysis folder, all I had to do was make a shell script that calls

python3 -m unittest vpa.test.test_utils

And inside test_utils I can import whatever I want as long as I remember that I am executing the code from main folder so loading utils.py would be

from vpa import utils inside test_utils

user3674993
  • 129
  • 1
  • 9