Unittest: Compare max_size with column size of database

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import unittest

from django.db import connection
from django.db.models.loading import get_models

class MaxLengthTest(unittest.TestCase):
    def testMaxLength(self):
        '''
        Compare max_length of model with size in the database.
        '''
        cursor=connection.cursor()
        errors=[]
        for cls in get_models():
            for field in cls._meta.fields:
                max_length=getattr(field, 'max_length', None)
                if not max_length:
                    continue
                column=field.db_column or field.column
                if not column:
                    continue
                cursor.execute('''SELECT "%s" from "%s" LIMIT 0''' % (column, cls._meta.db_table))
                for name, type_code, display_size, internal_size, precision, scale, null_ok in cursor.description:
                    if max_length!=internal_size:
                        errors.append('%s %s.%s Python Model max_length: %s Internal Size: %s' % (
                                cls, cls._meta.db_table, column, max_length, internal_size))
        if errors:
            raise Exception('\n'.join(errors))

More like this

  1. ImageField with specified maximum image size by virhilo 4 years, 1 month ago
  2. Query printer coroutine by fnl 4 years, 12 months ago
  3. ImageWithThumbsField by zenx 5 years, 3 months ago
  4. Unit Test Profiling by justquick 5 years, 2 months ago
  5. Simple file size from bytes to kb/mb/gb by bryanhelmig 4 years, 3 months ago

Comments

oggy (on August 18, 2008):

What database are you using there? That doesn't work in MySQL. First off, you can't use double quotes for quoting identifiers in MySQL (have to use backticks). Furthermore, even with that corrected, I always get internal_size to be reported 3x the max_length parameter.

But other than that, I like the idea :)

#

guettli (on September 17, 2008):

I use postgresql and psycopg2. I am sorry if it does not work for you. Since I don't have MySQL here, I can't update this snippet. Please send me a patch if you got it working for you.

#

(Forgotten your password?)