Search code examples
pythonmysqldjangodjango-unittest

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?


Solution

  • 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.