1

I have been reading this, this and this but i still can't figure out how to proper import so i can run coverage.

This is the structure of my app

package/
   app/
      services/
         __init__.py
         news_services.py
   test/
      news_test.py

This is the import

from ..app.services.news_services import NewsServices

This is the command that i run the file.

coverage run .\test\news_test.py

And this is the error that i get

ValueError: attempted relative import beyond top-level package

Sachihiro
  • 1,597
  • 2
  • 20
  • 46

1 Answers1

2

EDIT: here is an answer for an app/service

For testing within the same app/service I often use this pattern:

import inspect
import os
import sys

test_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
src_dir = os.path.join(test_dir, '..', 'app')
sys.path.append(src_dir)

from services.news_services import NewsServices

EDIT: Below is the original for packages but the question appears to relate to an app/service

Your best bet, and the one I use on a daily basis with packages that I maintain, is to install your own package and not use relative imports for this at all.

Your tests will find and import the package exactly as your users would.

Here is my install.sh which you only have to do once; the trick is installing it in an "editable" fashion which, in this context, will cause anything importing it from the environment to find it exactly in your working structure with all your local changes:

#!/bin/bash

python3 -m venv env/
source env/bin/activate

pip install --editable "."

Then, within your tests:

from app.services.news_services import NewsServices

This is also described in this answer:

https://stackoverflow.com/a/6466139/351084

mattbornski
  • 11,895
  • 4
  • 31
  • 25
  • i did all this and followed all the link that leads from this article but still i get `ModuleNotFoundError: No module named 'app'` – Sachihiro Sep 18 '19 at 19:05
  • I should mention that in this case you are using a venv, and you need to *enter* the venv before running your code in order to find this dependency. Something like `source env/bin/activate` and then `python myscript.py` – mattbornski Sep 18 '19 at 19:06
  • yes, i did activate venv it before i ran my script but still error. – Sachihiro Sep 18 '19 at 19:07
  • Okay, follow-up question: are you actually making a *package*? Do you have a setup.py? I am starting to believe (and probably should have guessed earlier, from the name `app`) that you are not making a package (such as could be re-used and imported by other code) and instead are making an application/service/script that is intended to be used but not re-used. I may have been misled by the top-level `package` folder. – mattbornski Sep 18 '19 at 19:11
  • I did create a `setup.py` and you are correct, I am not making a package for reuse. – Sachihiro Sep 18 '19 at 19:14