Strobe_
Strobe_

Reputation: 515

ImportError: No module named app - Trying to run unit tests

So I have a folder structure like so.

└── myApp
    ├── app
    │   ├── __init__.py
    │   ├── core
    │   ├── db.py
    │   ├── schema.sql
    │   ├── static
    │   │   ├── fonts
    │   │   ├── images
    │   │   ├── js
    │   │   └── resources
    │   ├── templates
    │   ├── tests
    │   │   └── tests.py
    │   ├── utils.py
    │   ├── views.py
    │   ├── con.py
    ├── config.py
    ├── manifest.json
    ├── run.py
    ├── deps
    ├── store

As you can see my tests.py is in the app/tests folder.

app = Flask(__name__) is declared within init.py but whenever i try to run my tests my folder (which I do from myApp directory like so: python app/tests/tests.py) I get a ImportError: No module named app.

I'm not sure if this information is relevant, to run the app I normally run run.py which has app.run(debug = True, host='0.0.0.0') inside of it.

Thanks.

tests.py:

import os
import unittest
from app import app

class TestCase(unittest.TestCase):

    def setUp(self):
        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
        self.app = app.test_client()

    def tearDown(self):
        os.unlink(app.config['DATABASE'])

    def test_empty_db(self):
        rv = self.app.get('/index')
        assert b'No entries here so far' in rv.data

if __name__ == "__main__":
    unittest.main()

Upvotes: 0

Views: 1429

Answers (2)

jnsod
jnsod

Reputation: 66

You can look if the path to your module is already set by typing sys.path. If not, you have to set it, e.g. in the file with the unit tests with something like:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'app'))

Upvotes: 0

Matthias
Matthias

Reputation: 3890

Is it possible this is because the tests.py is inside the app? meaning python won't find the app because he isn't looking in directories above this one.

import os.path
import sys
newPath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
sys.path.append(newPath)
from app import app
sys.path.remove(newPath)
del newPath

this is a very ugly way to add a path to where python looks for imports. This example goes 2 directories up, which should bring it to the myApp directory.

If this is the problem, you could also consider moving the tests directory to the myApp folder or some other location. But I am no expert on python packaging/app etiquette. Might consider looking that up

Upvotes: 1

Related Questions