Import error while running specific test case - python

Before I say something, let me show the current project hierarchy. The app name is api.
── api
│   ├──
│   ├── admin.py
│   ├── apps.py
│   ├── init.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── 0002_wallet_customer_id.py
│   │   ├── 0003_auto_20201201_1103.py
│   │   ├── 0004_auto_20201203_0703.py
│   │   ├── 0005_auto_20201207_1355.py
│   │   ├── __init__.py
│   │ 
│   ├── models.py
│   ├── permissions.py
│   ├── serializers.py
│   ├── stellar.py
│   ├── te_s_ts_bk.py
│   ├── te_sts_2.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── debug.log
├── manage.py
└── myapp
├── __init__.py
├── asgi.py
├── settings-local.py
├── settings-remote.py
├── settings.py
├── urls.py
└── wsgi.py
As it was suggested here, I even removed __init__.py file from the api app folder, yet having the issue.
My TestCase Class look like below:
class CreateWalletTestCase(APITestCase):
app_id = 0
app = None
def test_create_wallet(self):
response = self.client.post(
'/wallets/',
data={'app_id': self.app_id, 'customer_id': 'A-001'},
**{'HTTP_api_key': 'test-api', 'HTTP_api_secret': 'test-api-password'}
)
data = json.loads(response.content)
self.assertEqual(data['status'], 'OK
When I run as python manage.py test api.CreateWalletTestCase.test_create_wallet or even python manage.py test CreateWalletTestCase.test_create_wallet, it generates the error:
ImportError: Failed to import test module: CreateWalletTestCase
Traceback (most recent call last):
File "/usr/local/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
ModuleNotFoundError: No module named 'api.CreateWalletTestCase'

The way to call the tests in python is very similar to the way you import things in that language. For example, if you want to import that TestCase in your file and assuming it is in the tests.py file, you should write import CreateWalletTestCase from api.tests in the elegant way. You can also write import api.tests.CreateWalletTestCase, to import it.
So, to call that specific test, you should write the command in the following way:
python manage.py test api.tests.CreateWalletTestCase.test_create_wallet
You can check the Django Documentation here about running tests.
It is not necessary to delete the __init__.py file.

Related

Django, error importing view from another app

I'm trying to import a view from one app to another in my project.
When using this:
from ..from ..KnownLocation.views import KnownLocationView
I get the following error:
ValueError: attempted relative import beyond top-level package
When trying to use:
from triangulationapi.KnownLocation.views import KnownLocationView
It's raising the following error.
ModuleNotFoundError: No module named 'triangulationapi.KnownLocation'
my Project tree:
├── find_second_gdt
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── second_GDT_finding
│   ├── serializers.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── __init__.py
├── KnownLocation
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── serializers.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── requirements.txt.
└── triangulationapi
├── asgi.py
├── __init__.py
├── __pycache__
├── settings.py
├── urls.py
└── wsgi.py
And, what's the diffrence between using .. and project.app.view...
I thought it is the same up until now.
Try this:
from .KnownLocation.views import KnownLocationView

How to import python function from another file into django views

I am trying to call a function from a python file that is located outside the django project directory from views.py. I have tried importing the python file but running the django server says "no module named xxxx".
Tree structure is given below.
├── auto_flash
│   ├── __init__.py
│   └── test.py
└── fireflash
├── detection_reports
│   ├── admin.py
│   ├── admin.pyc
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── __pycache__
│   │   └── __init__.cpython-35.pyc
│   ├── templates
│   │   └── detection_reports
│   │   └── home.html
│   ├── tests.py
│   ├── views.py
│   └── views.pyc
├── fireflash
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── __pycache__
│   │   ├── __init__.cpython-35.pyc
│   │   └── settings.cpython-35.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── ui_cgi.py
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
├── __init__.py
└── manage.py
Project name here is "fireflash" and there is an app in that project named "detection_reports". There is another directory named "auto_flash" that has same location as "fireflash". What I want to do is to import test.py file from "auto_flash" in detection_reports.views and call a function from views. Importing like this "from auto_flash import test" throws error "no module named auto_flash".
I have tried all of the above mentioned solutions, but the cleaner solution was to append the path for auto_flash to syspath and the issue was resolved. Thanks to all of you for the efforts.
Move auto_flash to fireflash
In detection_reports add from auto_flash import test.py

Python: AttributeError module x has no attribute y

I have a project with directory structure like below
.
├── Pipfile
├── Pipfile.lock
├── module
│   ├── __init__.py
│   ├── helpers
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── dynamo.py
│   │   └── logger.py
│   └── test.py
Relavant code
logger.py
import click
import sys
from tabulate import tabulate
def formatter(string, *rest):
return string.format(*rest)
def info(*rest):
"""Write text in blue color
"""
click.echo(click.style('☵ ' + formatter(*rest), fg='blue'))
test.py
import helpers
helpers.logger.info('Trying')
When I try to run using the command
python3 module/test.py
I get this error
Traceback (most recent call last):
File "module/test.py", line 4, in <module>
helpers.logger.info('Trying')
AttributeError: module 'helpers' has no attribute 'logger'
I have tried restructuring the code. Putting the helpers directory outside, in level with module directory. But still it didn't work, which it should not have, from what I have read. I tried researching a bit about __init__.py and python module system. The more I read, the more confusing it gets. But from whatever I learned, I created another sample project. With the following structure,
.
└── test
├── __init__.py
├── helpers
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── quote.cpython-36.pyc
│   └── quote.py
├── index.py
├── logger
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── info.cpython-36.pyc
│   └── info.py
Code is same as first project.
Here when I do,
python3 test/index.py
It works as expected. The only difference between the two projects:
In the first project, I used pipenv to install deps and create virtual environment.
Using your initial layout (with loggers as a submodule of the helpers package), you'd need to explicitely import loggers in helpers/__init__.py to expose it as an attribute of the helpers package:
# helpers/__init__.py
from . import logger
logger is module and not attribute and helpers.logger evalutes logger as attribute. Actually you should do as follow:
from helpers import logger
print(logger.info('Trying'))

Can not import class from custom django package

I am writing a custom Django module but I seem to have something wrong. I cannot import a class that lives in a certain file. I get the error
ValueError: Unable to configure handler 'admins': Cannot resolve 'myPackage.handlers.MyHandlerClass': No module named handlers
This is the directory structure. I believe I can import views and models with no problem.
myPackage
├── CHANGELOG.rst
├── myPackage
│   ├── handlers .py
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── 0001_initial.pyc
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   ├── models.py
│   ├── models.pyc
│   ├── tests.py
│   ├── views.py
│   └── views.pyc
├── myPackage.egg-info
│   ├── dependency_links.txt
│   ├── PKG-INFO
│   ├── requires.txt
│   ├── SOURCES.txt
│   └── top_level.txt
├── MANIFEST.in
├── README.rst
├── requirements.txt
└── setup.py
There is a space in the filename of handlers .py, so python can't find a module names handlers. Obviously the easiest fix is to correct the filename, but for anyone actually wanting a space in the filename, import name with spaces is a syntax error, so the only way to import such a name is using __import__. But this is really a very bad idea.

Python/Django: import weirdness

I've the following project setup
....
├── lira
│   ├── __init__.py
│   ├── admin.py
│   ├── ajax.py
│   ├── authentication.py
│   ├── context_processors.py
│   ├── fencoder
│   │   ├── __init__.py
│   │   ├── encoder.py
│   │   ├── ffmpeg_commands.py
│   │   ├── frames.py
│   │   ├── utils.py
│   │   └── video.py
│   ├── models.py
....
And when I try to import from lira.fencoder import encoder I get an error ImportError: cannot import name encoder.
What is wrong with the above project setup though this morning it was the same and it worked?
Sultan
If you want to debug import problems, sometimes a simple launch of
python -v -m path/to/python/module/to_start
will help you, it will show you all the imports done by the python interpreter and help detect cyclic imports.

Categories

Resources