aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/tests/fields.py
blob: 840ed32000c3d5f6abf49b7fcebe30a1e973ce2a (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
General serializer field tests.
"""
from __future__ import unicode_literals
import datetime
from django.db import models
from django.test import TestCase
from django.core import validators
from rest_framework import serializers


class TimestampedModel(models.Model):
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)


class CharPrimaryKeyModel(models.Model):
    id = models.CharField(max_length=20, primary_key=True)


class TimestampedModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = TimestampedModel


class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = CharPrimaryKeyModel


class TimeFieldModel(models.Model):
    clock = models.TimeField()


class TimeFieldModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = TimeFieldModel


class BasicFieldTests(TestCase):
    def test_auto_now_fields_read_only(self):
        """
        auto_now and auto_now_add fields should be read_only by default.
        """
        serializer = TimestampedModelSerializer()
        self.assertEqual(serializer.fields['added'].read_only, True)

    def test_auto_pk_fields_read_only(self):
        """
        AutoField fields should be read_only by default.
        """
        serializer = TimestampedModelSerializer()
        self.assertEqual(serializer.fields['id'].read_only, True)

    def test_non_auto_pk_fields_not_read_only(self):
        """
        PK fields other than AutoField fields should not be read_only by default.
        """
        serializer = CharPrimaryKeyModelSerializer()
        self.assertEqual(serializer.fields['id'].read_only, False)

    def test_TimeField_from_native(self):
        f = serializers.TimeField()
        result = f.from_native('12:34:56.987654')

        self.assertEqual(datetime.time(12, 34, 56, 987654), result)

    def test_TimeField_from_native_datetime_time(self):
        """
        Make sure from_native() accepts a datetime.time instance.
        """
        f = serializers.TimeField()
        result = f.from_native(datetime.time(12, 34, 56))
        self.assertEqual(result, datetime.time(12, 34, 56))

    def test_TimeField_from_native_empty(self):
        f = serializers.TimeField()
        result = f.from_native('')
        self.assertEqual(result, None)

    def test_TimeField_from_native_invalid_time(self):
        f = serializers.TimeField()

        try:
            f.from_native('12:69:12')
        except validators.ValidationError as e:
            self.assertEqual(e.messages, ["'12:69:12' value has an invalid "
                                          "format. It must be a valid time "
                                          "in the HH:MM[:ss[.uuuuuu]] format."])
        else:
            self.fail("ValidationError was not properly raised")

    def test_TimeFieldModelSerializer(self):
        serializer = TimeFieldModelSerializer()
        self.assertTrue(isinstance(serializer.fields['clock'], serializers.TimeField))
>'" to have value="' + expected + '".'; }; var value; htmlParser(this.actual.html(), { start:function(tag, attrs){ value = attrs.value; }, end:noop, chars:noop }); return trim(value) == trim(expected); } }); }); it('should populate value attribute on OPTION', inject(function($rootScope, $compile) { var element = $compile('<select ng:model="x"><option>abc</option></select>')($rootScope) expect(element).toHaveValue('abc'); })); it('should ignore value if already exists', inject(function($rootScope, $compile) { var element = $compile('<select ng:model="x"><option value="abc">xyz</option></select>')($rootScope) expect(element).toHaveValue('abc'); })); it('should set value even if newlines present', inject(function($rootScope, $compile) { var element = $compile('<select ng:model="x"><option attr="\ntext\n" \n>\nabc\n</option></select>')($rootScope) expect(element).toHaveValue('\nabc\n'); })); it('should set value even if self closing HTML', inject(function($rootScope, $compile) { // IE removes the \n from option, which makes this test pointless if (msie) return; var element = $compile('<select ng:model="x"><option>\n</option></select>')($rootScope) expect(element).toHaveValue('\n'); })); }); it('should bind href', inject(function($rootScope, $compile) { var element = $compile('<a ng:href="{{url}}"></a>')($rootScope) expect(sortedHtml(element)).toEqual('<a ng:bind-attr="{"href":"{{url}}"}"></a>'); })); it('should bind disabled', inject(function($rootScope, $compile) { var element = $compile('<button ng:disabled="{{isDisabled}}">Button</button>')($rootScope) $rootScope.isDisabled = false; $rootScope.$digest(); expect(element.attr('disabled')).toBeFalsy(); $rootScope.isDisabled = true; $rootScope.$digest(); expect(element.attr('disabled')).toBeTruthy(); })); it('should bind checked', inject(function($rootScope, $compile) { var element = $compile('<input type="checkbox" ng:checked="{{isChecked}}" />')($rootScope) $rootScope.isChecked = false; $rootScope.$digest(); expect(element.attr('checked')).toBeFalsy(); $rootScope.isChecked=true; $rootScope.$digest(); expect(element.attr('checked')).toBeTruthy(); })); it('should bind selected', inject(function($rootScope, $compile) { var element = $compile('<select><option value=""></option><option ng:selected="{{isSelected}}">Greetings!</option></select>')($rootScope) jqLite(document.body).append(element) $rootScope.isSelected=false; $rootScope.$digest(); expect(element.children()[1].selected).toBeFalsy(); $rootScope.isSelected=true; $rootScope.$digest(); expect(element.children()[1].selected).toBeTruthy(); })); it('should bind readonly', inject(function($rootScope, $compile) { var element = $compile('<input type="text" ng:readonly="{{isReadonly}}" />')($rootScope) $rootScope.isReadonly=false; $rootScope.$digest(); expect(element.attr('readOnly')).toBeFalsy(); $rootScope.isReadonly=true; $rootScope.$digest(); expect(element.attr('readOnly')).toBeTruthy(); })); it('should bind multiple', inject(function($rootScope, $compile) { var element = $compile('<select ng:multiple="{{isMultiple}}"></select>')($rootScope) $rootScope.isMultiple=false; $rootScope.$digest(); expect(element.attr('multiple')).toBeFalsy(); $rootScope.isMultiple='multiple'; $rootScope.$digest(); expect(element.attr('multiple')).toBeTruthy(); })); it('should bind src', inject(function($rootScope, $compile) { var element = $compile('<div ng:src="{{url}}" />')($rootScope) $rootScope.url = 'http://localhost/'; $rootScope.$digest(); expect(element.attr('src')).toEqual('http://localhost/'); })); it('should bind href and merge with other attrs', inject(function($rootScope, $compile) { var element = $compile('<a ng:href="{{url}}" rel="{{rel}}"></a>')($rootScope) expect(sortedHtml(element)).toEqual('<a ng:bind-attr="{"href":"{{url}}","rel":"{{rel}}"}"></a>'); })); it('should bind Text with no Bindings', inject(function($compile) { var $rootScope; function newScope (){ return $rootScope = angular.injector('ng').get('$rootScope'); } forEach(['checked', 'disabled', 'multiple', 'readonly', 'selected'], function(name) { var element = $compile('<div ng:' + name + '="some"></div>')(newScope()) expect(element.attr('ng:bind-attr')).toBe('{"' + name +'":"some"}'); $rootScope.$digest(); expect(element.attr(name)).toBe(name); dealoc(element); }); var element = $compile('<div ng:src="some"></div>')(newScope()) $rootScope.$digest(); expect(sortedHtml(element)).toEqual('<div ng:bind-attr="{"src":"some"}" src="some"></div>'); dealoc(element); var element = $compile('<div ng:href="some"></div>')(newScope()) $rootScope.$digest(); expect(sortedHtml(element)).toEqual('<div href="some" ng:bind-attr="{"href":"some"}"></div>'); dealoc(element); })); it('should Parse Text With No Bindings', inject(function($rootScope, $compile) { var parts = parseBindings("a"); assertEquals(parts.length, 1); assertEquals(parts[0], "a"); assertTrue(!binding(parts[0])); })); it('should Parse Empty Text', inject(function($rootScope, $compile) { var parts = parseBindings(""); assertEquals(parts.length, 1); assertEquals(parts[0], ""); assertTrue(!binding(parts[0])); })); it('should Parse Inner Binding', inject(function($rootScope, $compile) { var parts = parseBindings("a{{b}}C"); assertEquals(parts.length, 3); assertEquals(parts[0], "a"); assertTrue(!binding(parts[0])); assertEquals(parts[1], "{{b}}"); assertEquals(binding(parts[1]), "b"); assertEquals(parts[2], "C"); assertTrue(!binding(parts[2])); })); it('should Parse Ending Binding', inject(function($rootScope, $compile) { var parts = parseBindings("a{{b}}"); assertEquals(parts.length, 2); assertEquals(parts[0], "a"); assertTrue(!binding(parts[0])); assertEquals(parts[1], "{{b}}"); assertEquals(binding(parts[1]), "b"); })); it('should Parse Begging Binding', inject(function($rootScope, $compile) { var parts = parseBindings("{{b}}c"); assertEquals(parts.length, 2); assertEquals(parts[0], "{{b}}"); assertEquals(binding(parts[0]), "b"); assertEquals(parts[1], "c"); assertTrue(!binding(parts[1])); })); it('should Parse Loan Binding', inject(function($rootScope, $compile) { var parts = parseBindings("{{b}}"); assertEquals(parts.length, 1); assertEquals(parts[0], "{{b}}"); assertEquals(binding(parts[0]), "b"); })); it('should Parse Two Bindings', inject(function($rootScope, $compile) { var parts = parseBindings("{{b}}{{c}}"); assertEquals(parts.length, 2); assertEquals(parts[0], "{{b}}"); assertEquals(binding(parts[0]), "b"); assertEquals(parts[1], "{{c}}"); assertEquals(binding(parts[1]), "c"); })); it('should Parse Two Bindings With Text In Middle', inject(function($rootScope, $compile) { var parts = parseBindings("{{b}}x{{c}}"); assertEquals(parts.length, 3); assertEquals(parts[0], "{{b}}"); assertEquals(binding(parts[0]), "b"); assertEquals(parts[1], "x"); assertTrue(!binding(parts[1])); assertEquals(parts[2], "{{c}}"); assertEquals(binding(parts[2]), "c"); })); it('should Parse Multiline', inject(function($rootScope, $compile) { var parts = parseBindings('"X\nY{{A\nB}}C\nD"'); assertTrue(!!binding('{{A\nB}}')); assertEquals(parts.length, 3); assertEquals(parts[0], '"X\nY'); assertEquals(parts[1], '{{A\nB}}'); assertEquals(parts[2], 'C\nD"'); })); it('should Has Binding', inject(function($rootScope, $compile) { assertTrue(hasBindings(parseBindings("{{a}}"))); assertTrue(!hasBindings(parseBindings("a"))); assertTrue(hasBindings(parseBindings("{{b}}x{{c}}"))); })); });