0

I wrote my own module, let's call it mymodule. To improve whether it's working I wrote tests. So that's what the structure became:

django-mymodule
|-mymodule (.py files in here)
|-tests (.py files in here, they are unittests)
|-... (docs and this stuff)

When module is installed to my computer is has to use relative imports like this: from . import otherfile. When it is started as test, the imports have to look like this: import otherfile. So I will have to do something like this:

if is_run_as_test:
  import otherfile
else:
  from . import otherfile

How does this is_run_as_test looks? Or am I doing something really wrong?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Asqiir
  • 607
  • 1
  • 8
  • 23
  • 2
    How will you test your code if it runs differently when you aren't testing it? – Vasili Syrakis Mar 05 '17 at 08:15
  • It doesn't run different, it's only because there are different ways to import for using `python3 -m unittest tests/test_file1` (in the shell) and when I have installed the module - as explained here: http://stackoverflow.com/a/14132912/1622937 – Asqiir Mar 05 '17 at 08:18
  • 1
    You can use absolute imports if your code is in a python package format, then you could run the tests from the project root. – Vasili Syrakis Mar 05 '17 at 08:23
  • I didn't understand your second post in the beginning, but now when I know what to do it's really clear. Thank you for helping! – Asqiir Mar 05 '17 at 08:49

2 Answers2

1

You can achieve this by checking whether or not your testing framework has been imported.

It would be strange to have it imported in regular code, so one could assume that the code is being run during a test.

if 'unittest' in locals():
    print('I am being run within a test')
Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56
  • This looks good but didn't work to me. The imports (now) in `tests/file1`: `import unittest`, `import sys`, `sys.path.insert(0, '../mymodule')`, `import file1`. The imports in `file1`: `if 'unittest' in locals(): from links import RawTextLink, RenderedTextLink else: from .links import RenderedTextLink, RenderedTextLink` What did I make wrong? – Asqiir Mar 05 '17 at 08:27
0

I was completely wrong. What I have to do is importing the whole package to the pythonpath and then using absolute imports. (In the tests file, of course.)

That means:

  • there is no trouble with relative imports in my module
  • I don't have to mess up in my module just to be able to do tests (Which is no good idea as Vasili Syrakis said.
  • I can acces the module from within the tests

So I use from . import somefile in mymodule. To the tests I added this code:

import unittest
import sys
sys.path.insert(0, '../../django-mymodule')
from mymodule import file1

Thank you for the tipps!

Community
  • 1
  • 1
Asqiir
  • 607
  • 1
  • 8
  • 23