1

I have a series of tests that inherit from a base class, which looks like this:

class Test(TestCase):
    def setUp(self):
        module_dir = os.path.dirname(self.__module__.replace('.', '/'))
        self.payload_dir = os.path.join(settings.BASE_DIR, module_dir, 'payloads')

This works fine, but self.__module__.replace('.', '/') isn't very pythonic, and won't work on Windows.

Is there a better way to convert a module name into a relative path?

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80

1 Answers1

0

I think you just want the __file__ attribute here. This will return the path to this file, which seems to be your module (but that isn't quite clear).

Depending on where in the path this is called from you may or may not need the BASE_DIR adding. You get a relative path if your inside the part of your path that contains the module, or an absolute path if you're outside. See this answer for more details.

class Test(TestCase):
    def set_up(self):
        module_path = os.path.dirname(__file__)
        self.payload_dir = os.path.join(module_path, 'payloads')

If you are not in the current module I believe you can use the module’s __file__ attribute.

class Test(TestCase):
    def set_up(self):
        module_path = os.path.dirname(module_name.__file__)
        self.payload_dir = os.path.join(module_path, 'payloads')
Tim B
  • 3,033
  • 1
  • 23
  • 28
  • That doesn't work in my case because the class is inherited. So each child class will have a `__file__` that references the parent, instead of the file that they are in. – Lord Elrond Jul 27 '20 at 22:06
  • I’ve added a potential way to address this, I’m on mobile so can’t test it at the moment. – Tim B Jul 29 '20 at 05:52