Dũng Nguyễn
Dũng Nguyễn

Reputation: 495

Django Unitest: Table doesn't exist

I created a simple test case like this:

from unittest import TestCase
import user_manager


class UserTest(TestCase):
    def test_register(self):
        email = "[email protected]"
        password = "123456"
        result, user = user_manager.setup_new_user(email, password)
        self.assertEqual(result, CodeID.SUCCESS)

Then I run the testcase:

python manage.py test users

And here is the log:

Creating test database for alias 'default'...
/Users/admin/Projects/MyApp/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py:112: Warning: Table 'mysql.column_stats' doesn't exist
  return self.cursor.execute(query, args)
Creating test database for alias 'myapp_log'...
.FE
======================================================================
ERROR: test_register (users.tests.UserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
...
ProgrammingError: (1146, "Table 'test_myapp.user' doesn't exist")

So it created a test database but seem like it didn't create the tables. Here is my DATABASES setting:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "myapp",
        'USER': "root",
        'PASSWORD': "",
        'HOST': '127.0.0.1',
        'PORT': '',
    },
    'myapp_log': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "myapp_log",
        'USER': "root",
        'PASSWORD': "",
        'HOST': '127.0.0.1',
        'PORT': '',
    },
}

And my model:

class User(BaseModel):
    uid = models.IntegerField(primary_key=True)
    email = models.CharField(max_length=200)
    password = models.CharField(max_length=200)
    create_time = models.IntegerField()
    update_time = models.IntegerField()
    status = models.IntegerField()
    social_token = models.CharField(max_length=200)
    social_app = models.IntegerField()

    class Meta:
        db_table = 'user'

Anyone know why the table 'user' is not created?

UPDATE:

user_manager from my testcase will do some query and add new record on table user.

And I thought when I run the testcase, Django will somehow read my models and create a test database with all the table from those models. Am I right about this?

Upvotes: 0

Views: 4782

Answers (2)

Dũng Nguyễn
Dũng Nguyễn

Reputation: 495

So I found out I need to put my models.py in my users' folder and add 'users' into the INSTALLED_APPS setting. Now it worked.

Upvotes: 1

Vaibhav Singh
Vaibhav Singh

Reputation: 942

Your test database needs to be different than your production database. Test databases are destroyed once the test cases are run. In your case the database was not created. You should go through this documentation for detailed information https://docs.djangoproject.com/en/1.10/topics/testing/overview/ Can you also add the snippet of your user_manager module

Upvotes: 0

Related Questions