0

I'm using Flask framework and would like to test a single class (not Flask app, and I've read the test documentation here)

My folder structure is like below picture, and init.py for each folder.

enter image description here

But I tried all below but none of them works.

from ... import grouper

or

import reporting.dashboard.helpers.grouper

or

import dashboard
from dashboard.helpers.grouper import Grouper

Could anyone please give me some hints on how to include

reporting/dashboard/helpers/grouper.py

in my test module located at

reporting/tests/helpers/helper-test.py

?

Thanks a lot.

keypoint
  • 2,268
  • 4
  • 31
  • 59
  • Did you try `from ...reporting.dashboard.helpers import grouper`? – BrenBarn Sep 18 '15 at 18:01
  • Does the `helpers` directory have an `__init__.py`? – thebjorn Sep 18 '15 at 18:03
  • @BrenBarn I tried but no luck, "ValueError: Attempted relative import in non-package" – keypoint Sep 18 '15 at 18:05
  • @thebjorn I just added one empty __init__.py under helps directory, but still not working... – keypoint Sep 18 '15 at 18:06
  • @keypoint: You're probably running `helper-test.py` directly. See [this question](http://stackoverflow.com/questions/11536764/attempted-relative-import-in-non-package-even-with-init-py) and others you can find by googling that error message. – BrenBarn Sep 18 '15 at 18:06
  • @BrenBarn oh yes you are right, I'm just running "python helper-test.py", I'll give it a try, thanks – keypoint Sep 18 '15 at 18:07
  • @BrenBarn I tried to run "python -m reporting.tests.helpers.helper-test.py" under directory reporting, but still no luck, "No module named reporting.tests.helpers.helper-test"... – keypoint Sep 18 '15 at 18:13
  • Is the parent directory of your top-level `reporting` directory on `sys.path`? – BrenBarn Sep 18 '15 at 18:13
  • @BrenBarn no...should I add it to sys.path ? – keypoint Sep 18 '15 at 18:16
  • @keypoint: Yes (add the *parent* of `reporting` to `sys.path`). You can't in general expect to be able to import anything that is not reachable from `sys.path`. – BrenBarn Sep 18 '15 at 18:19
  • @BrenBarn is there an alternative way to do this? sys.path seems a bit hacky...lol – keypoint Sep 18 '15 at 18:22

1 Answers1

0

I've identified the cause. It's because the __init__.py under folder "reporting" is not empty, but doing some initiation operations for Flask app. When I made this "__init__.py" a empty file, the import was successful using

from reporting.dashboard.helpers.grouper import Grouper

Also, python-2.6 may not recognize "from xxx import yyyClass", but only "import xxxModule"

reference reading: The import system

keypoint
  • 2,268
  • 4
  • 31
  • 59