0

I am trying to get my unit test scripts to work no matter where they are invoked from and have looked into a dozen questions on relative import issues now. But relative paths in combination with the unittest module seem to add some extra complications.

My directory structure is this:

importtest
├── importtest
│   ├── importtest.py
│   └── __init__.py
└── test
    ├── data.txt
    ├── importtest_test.py
    └── __init__.py

the __init__.py files are empty, importtest.py contains

def func(filename):
    with open(filename) as f:
        return True

and importtest_test.py contains

import unittest
from importtest import importtest

class Test(unittest.TestCase):
    def test(self):
        self.assertEqual(importtest.func('data.txt'), True)

This works when I execute py -m unittest test/importtest_test.py from the root folder of the project (the top most importtest folder). But it does not work from any other directory.

Why is that and how can I fix this?

lo tolmencre
  • 3,804
  • 3
  • 30
  • 60
  • When you say any directory do you outside your project folder as well? – ikuamike Aug 18 '18 at 17:18
  • Yes. But it also does not work from inside any directory within the project folder other than the root foler. – lo tolmencre Aug 18 '18 at 17:23
  • That's an import issue, therefore if you want to run it in a folder that is in your project folder use `from ..foo import foo` the .. tells python to move up one directory when importing. Just like .. in bash – ikuamike Aug 18 '18 at 17:32
  • But I don't want to hardcode that. I want it to figure that out by itself. – lo tolmencre Aug 18 '18 at 17:33
  • checkout the answer to this question, might help https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – ikuamike Aug 18 '18 at 17:37

0 Answers0