Permalink
Browse files

rework char, better tests

  • Loading branch information...
1 parent c3c72c6 commit ef698ce4e4b76b79e704f3ecb62d4dff1a894369 @sorl committed Jun 26, 2011
Showing with 24 additions and 17 deletions.
  1. +10 −10 arrayfields/fields.py
  2. +1 −1 tests/arrayfields_tests/models.py
  3. +13 −6 tests/arrayfields_tests/tests.py
View
@@ -1,16 +1,10 @@
import json
from abc import abstractproperty
from django.db import models
-from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
class ArrayFieldBase(models.Field):
- base_db_type = abstractproperty()
-
- def db_type(self, connection):
- return '%s[]' % self.base_db_type
-
def get_prep_value(self, value):
if value == '':
value = '{}'
@@ -36,22 +30,28 @@ class CharArrayField(ArrayFieldBase):
"""
A character varying array field for PostgreSQL
"""
- description = _('Character array')
- base_db_type = 'character varying'
+ description = _('Character varying array')
+ def db_type(self, connection):
+ if self.max_length is not None:
+ return 'character varying(%s)[]' % self.max_length
+ return 'character varying[]'
class TextArrayField(ArrayFieldBase):
"""
A text array field for PostgreSQL
"""
description = _('Text array')
- base_db_type = 'text'
+ def db_type(self, connection):
+ return 'text[]'
class IntegerArrayField(ArrayFieldBase):
"""
An integer array field for PostgreSQL
"""
description = _('Integer array')
- base_db_type = 'integer'
+
+ def db_type(self, connection):
+ return 'integer[]'
@@ -4,6 +4,6 @@
class Item(models.Model):
text = TextArrayField()
- char = CharArrayField()
+ char = CharArrayField(max_length=1)
integer = IntegerArrayField()
@@ -1,8 +1,9 @@
#coding=utf-8
+from django.core import serializers
+from django.db import DatabaseError
from django.test import TestCase
from .models import *
-
class SimpleTest(TestCase):
def setUp(self):
pass
@@ -18,10 +19,16 @@ def test_integer(self):
item = Item.objects.create(integer=[[1,2], [1,2]])
self.assertEqual(1, item.integer[1][0])
+ def test_character_max_length(self):
+ with self.assertRaisesRegexp(DatabaseError, 'value too long for type character varying'):
+ item = Item.objects.create(char=['opq'])
+
def test_serialization(self):
- item = Item.objects.create(char=['abc'])
- self.assertEqual(
- '["abc"]',
- item._meta.get_field('char').value_to_string(item)
- )
+ item = Item.objects.create(text=[['abc'],['xyz']])
+ s = serializers.serialize('json', list(Item.objects.all()))
+ item.delete()
+ s = s.replace('abc', 'def')
+ for obj in serializers.deserialize('json', s):
+ obj.save()
+ self.assertEqual(Item.objects.get().text, [['def'],['xyz']])

0 comments on commit ef698ce

Please sign in to comment.