source: main/waeup.sirp/trunk/src/waeup/sirp/utils/tests/test_converters.py @ 6267

Last change on this file since 6267 was 6267, checked in by uli, 13 years ago

Prove that the converter can handle simple vocabularies.

File size: 10.2 KB
Line 
1##
2## test_converters.py
3## Login : <uli@pu.smp.net>
4## Started on  Tue May 31 08:34:44 2011 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2011 Uli Fouquet
8## This program is free software; you can redistribute it and/or modify
9## it under the terms of the GNU General Public License as published by
10## the Free Software Foundation; either version 2 of the License, or
11## (at your option) any later version.
12##
13## This program is distributed in the hope that it will be useful,
14## but WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16## GNU General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22"""
23Tests for converterts.
24"""
25import datetime
26import os
27import shutil
28import tempfile
29import unittest
30from zope import schema
31from zope.app.testing.functional import FunctionalTestCase
32from zope.component import provideUtility
33from zope.component.factory import Factory
34from zope.component.hooks import setSite, clearSite
35from zope.component.interfaces import IFactory
36from zope.formlib import form
37from zope.interface import (
38    Interface, implements, invariant, Invalid, implementedBy)
39from zope.interface.verify import verifyClass, verifyObject
40
41from waeup.sirp.app import University
42from waeup.sirp.testing import FunctionalLayer, doctestsuite_for_module
43from waeup.sirp.utils.converters import IObjectConverter
44from waeup.sirp.utils.helpers import attrs_to_fields
45from waeup.sirp.interfaces import SimpleWAeUPVocabulary
46
47colors = SimpleWAeUPVocabulary(
48    ('Red', u'red'),
49    ('Green', u'green'),
50    ('Blue', u'blue'),
51    )
52
53class IContact(Interface):
54    """Sample interface for sample content type used here in tests.
55    """
56    name = schema.TextLine(
57        title = u'Name',
58        default = u'Manfred'
59        )
60    age = schema.Int(
61        title = u'Age',
62        default = 23,
63        required = True,
64        )
65    city = schema.TextLine(
66        title = u'City',
67        required = True,
68        )
69    vip = schema.Bool(
70        title = u'Celebrity',
71        default = False,
72        required = True,
73        )
74    birthday = schema.Date(
75        title = u'Birthday',
76        default = None,
77        )
78    fav_color = schema.Choice(
79        title = u'Favourite color',
80        default = u'red',
81        vocabulary = colors,
82        )
83    @invariant
84    def kevinIsYoung(contact):
85        if contact.age > 16 and contact.name == 'Kevin':
86            raise Invalid('Kevins are age 16 or below.')
87
88class Contact(object):
89    """Sample content type.
90    """
91    implements(IContact)
92Contact = attrs_to_fields(Contact)
93
94form_fields_select = form.Fields(IContact).select('name', 'vip')
95form_fields_omit = form.Fields(IContact).omit('name', 'vip')
96
97class ContactFactory(object):
98    """A factory for faculty containers.
99    """
100    implements(IContact)
101
102    def __call__(self, *args, **kw):
103        return Faculty()
104
105    def getInterfaces(self):
106        return implementedBy(Faculty)
107
108class ConverterTests(FunctionalTestCase):
109
110    layer = FunctionalLayer
111
112    def setUp(self):
113        super(ConverterTests, self).setUp()
114
115        # Setup a sample site for each test
116        app = University()
117        self.dc_root = tempfile.mkdtemp()
118        app['datacenter'].setStoragePath(self.dc_root)
119
120        # Prepopulate the ZODB...
121        self.getRootFolder()['app'] = app
122        self.app = self.getRootFolder()['app']
123
124        self.workdir = tempfile.mkdtemp()
125
126        # Create a factory for contacts and register it as global utility
127        factory = Factory(Contact)
128        provideUtility(factory, IFactory, 'contact')
129        return
130
131    def tearDown(self):
132        super(ConverterTests, self).tearDown()
133        shutil.rmtree(self.workdir)
134        shutil.rmtree(self.dc_root)
135        clearSite()
136        return
137
138    def test_valid_data(self):
139        contact = Contact()
140        contact.age = 33
141        input_data = dict(name='Rudi', age='99')
142        converter = IObjectConverter(IContact) # a converter to IContact
143        err, inv_err, new_contact = converter.applyRowData(
144            input_data, contact)
145        assert new_contact is contact
146        assert contact.name == 'Rudi'
147        assert contact.age == 99
148        return
149
150    def test_bool(self):
151        contact1 = Contact()
152        contact2 = Contact()
153        input_data1 = dict(vip='on')
154        input_data2 = dict(vip='')
155        converter = IObjectConverter(IContact) # a converter to IContact
156        err1, inv_err1, new_contact1 = converter.applyRowData(
157            input_data1, contact1)
158        err2, inv_err2, new_contact2 = converter.applyRowData(
159            input_data2, contact2)
160        assert contact1.vip is True
161        assert contact2.vip is False
162
163    def test_int(self):
164        contact = Contact()
165        input_data = dict(age='99')
166        converter = IObjectConverter(IContact) # a converter to IContact
167        err, inv_err, new_contact = converter.applyRowData(
168            input_data, contact)
169        assert contact.age == 99
170        return
171
172    def test_int_invalid(self):
173        contact = Contact()
174        input_data = dict(age='sweet sixteen')
175        converter = IObjectConverter(IContact) # a converter to IContact
176        err, inv_err, new_contact = converter.applyRowData(
177            input_data, contact)
178        self.assertEqual(err, [('age', u'Invalid integer data')])
179        return
180
181    def test_textline(self):
182        contact = Contact()
183        input_data = dict(name='Rudi')
184        converter = IObjectConverter(IContact) # a converter to IContact
185        err, inv_err, new_contact = converter.applyRowData(
186            input_data, contact)
187        self.assertEqual(contact.name, u'Rudi')
188        assert isinstance(contact.name, unicode)
189        return
190
191    def test_invariant(self):
192        contact = Contact()
193        input_data = dict(name='Kevin', age='22')
194        converter = IObjectConverter(IContact) # a converter to IContact
195        err, inv_err, new_contact = converter.applyRowData(
196            input_data, contact)
197        self.assertEqual(inv_err, ['Kevins are age 16 or below.'])
198        return
199
200    def test_date(self):
201        contact = Contact()
202        converter = IObjectConverter(IContact) # a converter to IContact
203        err, inv_err, new_contact = converter.applyRowData(
204            dict(birthday='1945/12/23'), contact)
205        assert contact.birthday == datetime.date(1945, 12, 23)
206        assert isinstance(contact.birthday, datetime.date)
207
208        err, inv_err, new_contact = converter.applyRowData(
209            dict(birthday='1945/23/12'), contact)
210        assert contact.birthday == datetime.date(1945, 12, 23)
211
212        err, inv_err, new_contact = converter.applyRowData(
213            dict(birthday='23/12/1945'), contact)
214        assert contact.birthday == datetime.date(1945, 12, 23)
215
216        err, inv_err, new_contact = converter.applyRowData(
217            dict(birthday='23.12.1945'), contact)
218        assert contact.birthday == datetime.date(1945, 12, 23)
219
220        err, inv_err, new_contact = converter.applyRowData(
221            dict(birthday='23-12-1945'), contact)
222        assert contact.birthday == datetime.date(1945, 12, 23)
223        return
224
225    def test_date_invalid(self):
226        contact = Contact()
227        converter = IObjectConverter(IContact) # a converter to IContact
228        err, inv_err, new_contact = converter.applyRowData(
229            dict(birthday='not-a-date'), contact)
230        self.assertEqual(err, [('birthday', u'Invalid datetime data')])
231
232    def test_inject_formfields_select(self):
233        # We can use our own formfields and select only a subset of fields
234        contact = Contact()
235        converter = IObjectConverter(IContact) # a converter to IContact
236        input_data = dict(name='Bruno', age='99', vip='on')
237        err, inv_err, new_contact = converter.applyRowData(
238            input_data, contact, form_fields=form_fields_select)
239        self.assertEqual(contact.name, 'Bruno')
240        self.assertEqual(contact.age, 23)
241        self.assertEqual(contact.vip, True)
242        return
243
244    def test_inject_formfields_omit(self):
245        # We can use our own formfields and omit some fields
246        contact = Contact()
247        converter = IObjectConverter(IContact) # a converter to IContact
248        input_data = dict(name='Bruno', age='99', vip='on')
249        err, inv_err, new_contact = converter.applyRowData(
250            input_data, contact, form_fields=form_fields_omit)
251        self.assertEqual(contact.name, 'Manfred')
252        self.assertEqual(contact.age, 99)
253        self.assertEqual(contact.vip, False)
254        return
255
256    def test_factory(self):
257        # We can use factories to create a new object
258        #
259        # This way we turn a dict of strings and some string denoting
260        # the kind of object to be created (factory name) into a real object.
261        converter = IObjectConverter(IContact) # a converter to IContact
262        # pass string ``contact`` instead of a real object
263        err, inv_err, contact = converter.applyRowData(
264            dict(name='Gabi'), 'contact')
265        # we get an object...
266        assert isinstance(contact, Contact)
267        # ...with the values from the dict set.
268        self.assertEqual(contact.name, 'Gabi')
269        return
270
271    def test_choice_vocab(self):
272        # We can handle vocabularies
273        converter = IObjectConverter(IContact) # a converter to IContact
274        err, inv_err, contact = converter.applyRowData(
275            dict(fav_color='blue'), 'contact')
276        assert contact.fav_color == u'blue'
277        assert isinstance(contact.fav_color, unicode)
278        return
279
280    def test_choice_vocab_invalid_value(self):
281        # We can handle vocabularies
282        converter = IObjectConverter(IContact) # a converter to IContact
283        err, inv_err, contact = converter.applyRowData(
284            dict(fav_color='magenta'), 'contact')
285        self.assertEqual(err, [('fav_color', u'Invalid value')])
286        assert contact.fav_color == u'red'
287        return
288
289def test_suite():
290    suite = unittest.TestSuite()
291    for testcase in [
292        ConverterTests,
293        ]:
294        suite.addTest(unittest.TestLoader().loadTestsFromTestCase(
295                testcase
296                )
297        )
298    return suite
299
Note: See TracBrowser for help on using the repository browser.