Home > other >  create an other table during tests manually in django webapp
create an other table during tests manually in django webapp

Time:07-20

I'm creating some tests in my django web app with selenium. Django create a test database with all tables.

In my case however I have a model Users. I want that django create also users table when I run this command in terminal python3.9 manage.py test -v3

This command goes in error:

Running post-migrate handlers for application contenttypes
Adding content type 'contenttypes | contenttype'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Running post-migrate handlers for application sessions
Adding content type 'sessions | session'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Running post-migrate handlers for application pygiustizia
Adding content type 'pygiustizia | member'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
Adding permission 'Permission object (None)'
System check identified no issues (0 silenced).
test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase) ... nel costruttore model Users
ERROR

======================================================================
ERROR: test_login (pygiustizia.tests.test_views_topics.ViewsTopicsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/home/nicola/.local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute
    return self.cursor.execute(query, args)
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/cursors.py", line 148, in execute
    result = self._query(query)
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/cursors.py", line 310, in _query
    conn.query(q)
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 548, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 775, in _read_query_result
    result.read()
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 1156, in read
    first_packet = self.connection._read_packet()
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/connections.py", line 725, in _read_packet
    packet.raise_for_error()
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/protocol.py", line 221, in raise_for_error
    err.raise_mysql_exception(self._data)
  File "/home/nicola/.local/lib/python3.9/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'test_civiledb.users' doesn't exist")

EDIT I access to the table users that I want create manually for test by this model.

from django.db import models
from django.db import connection
import pymysql

class Users(models.Model):

    firstname=models.CharField(max_length=100)
    lastname=models.CharField(max_length=100) 
    username=models.CharField(max_length=50)
    password=models.CharField(max_length=255)
    admin=models.IntegerField()
    createdAt=models.DateTimeField(db_column="created_at")

    def __init__(self,*args, **kwargs):
        super().__init__(*args, **kwargs)
        print("nel costruttore model Users")

    def getAdmin(self):
        return self.admin

    class Meta:
        db_table = 'users'

    def getUser(self,username):
        cursor = connection.cursor()
        cursor.execute('''SELECT id, 
                            username, 
                            password,
                            admin,
                            firstname,
                            lastname,
                            created_at 
                            FROM users 
                            WHERE username = %s''',[username])

        result = cursor.fetchone()
                 
        return result

    def setPassword(self,userId,password):
        cursor = connection.cursor()
        
        try:
            cursor.execute('''UPDATE users  
                            SET password = %s 
                            WHERE id = %s''',[password,userId])
            connection.commit()
        except Exception as e:
            print(e)
            connection.rollback()
            return False
        finally:
            connection.close()
        
        return True

A solution is to create "sql create" schema run it in testcase in setUp and drop it on tearDown.

CodePudding user response:

I think the concept you are looking for here are unmanaged models. By setting the appropriate Meta option you can tell Django that it shouldn't handle the table lifecycle for you.

To answer your question, using SchemaEditor on test setup and teardown seems like a particularly clean way to achieve what you are looking for.

  • Related