source: main/waeup.kofa/trunk/src/waeup/kofa/schema/tests/test_textlinechoice.py @ 9506

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

Rename all non-locales stuff from sirp to kofa.

  • Property svn:keywords set to Id
File size: 7.2 KB
Line 
1## $Id: test_textlinechoice.py 7811 2012-03-08 19:00:51Z uli $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""Test TextLineChoice
19"""
20import unittest
21from zope.interface import implements, directlyProvides
22from zope.schema import vocabulary
23from zope.schema.interfaces import (
24    InvalidValue, ValidationError,
25    IVocabulary, ISource, IContextSourceBinder,)
26from zope.schema.tests.test_strfield import TextLineTest
27from waeup.kofa.schema import TextLineChoice
28
29# Define some helper functions, classes, vars for tests
30class DummyRegistry(vocabulary.VocabularyRegistry):
31    def get(self, object, name):
32        v = SampleVocabulary()
33        v.object = object
34        v.name = name
35        return v
36
37class SampleTerm(object):
38    pass
39
40SAMPLE_VALUES = [u'a', u'b', u'c', u'd']
41class SampleVocabulary(object):
42    implements(IVocabulary)
43
44    def __iter__(self):
45        return iter([self.getTerm(x) for x in SAMPLE_VALUES])
46
47    def __contains__(self, value):
48        return value in SAMPLE_VALUES
49        return 0 <= value < 10
50
51    def __len__(self):
52        return len(SAMPLE_VALUES)
53
54    def getTerm(self, value):
55        if value in self:
56            t = SampleTerm()
57            t.value = value
58            t.upper = value.upper() #2 * value
59            return t
60        raise LookupError("no such value: %r" % value)
61
62class LetterASource(object):
63    # A source that contains all strings with letter 'a'
64    implements(ISource)
65    required_letter = 'a'
66    def __contains__(self, value):
67        return self.required_letter in value
68letter_a_source = LetterASource()
69
70def letter_source_binder(context):
71    source = LetterASource()
72    source.required_letter = context.req_letter
73    return source
74directlyProvides(letter_source_binder, IContextSourceBinder)
75
76class SampleContext(object):
77    req_letter = 'b'
78
79
80
81class TextLineChoiceAsTextLineTest(TextLineTest):
82    # Tests to guarantee TextLine like behaviour of TextLineChoice
83    # i.e. make sure that a TextLineChoice can everything a TextLine can
84    _Field_Factory = TextLineChoice
85
86class TextLineChoice_Values_Tests(unittest.TestCase):
87    # Tests to guarantee values support
88    def test_create_vocabulary(self):
89        choice = TextLineChoice(values=[1, 3])
90        self.assertEqual([term.value for term in choice.vocabulary], [1, 3])
91
92    def test_validate_string(self):
93        choice = TextLineChoice(values=[u'a', u'c'])
94        choice.validate(u'a')
95        #choice.validate('c')
96        choice.validate(u'c')
97        self.assertRaises(InvalidValue, choice.validate, u'd')
98
99    def test_validate_strings(self):
100        choice = TextLineChoice(values=[u'foo', u'bar'])
101        choice.validate(u'foo')
102        choice.validate(u'bar')
103        choice.validate(u'bar')
104        self.assertRaises(InvalidValue, choice.validate, u'baz')
105
106class TextLineChoice_Vocabulary_Tests(unittest.TestCase):
107    # Tests of the TextLineChoice Field using vocabularies.
108    # Most tests were copied (slightly modified) from zope.schema.tests.
109
110    def setUp(self):
111        vocabulary._clear()
112
113    def tearDown(self):
114        vocabulary._clear()
115
116    def check_preconstructed(self, cls, okval, badval):
117        v = SampleVocabulary()
118        field = cls(vocabulary=v)
119        self.assert_(field.vocabulary is v)
120        self.assert_(field.vocabularyName is None)
121        bound = field.bind(None)
122        self.assert_(bound.vocabulary is v)
123        self.assert_(bound.vocabularyName is None)
124        bound.default = okval
125        self.assertEqual(bound.default, okval)
126        self.assertRaises(ValidationError, setattr, bound, "default", badval)
127
128    def test_preconstructed_vocabulary(self):
129        self.check_preconstructed(TextLineChoice, u'a', u'z')
130
131    def check_constructed(self, cls, okval, badval):
132        vocabulary.setVocabularyRegistry(DummyRegistry())
133        field = cls(vocabulary="vocab")
134        self.assert_(field.vocabulary is None)
135        self.assertEqual(field.vocabularyName, "vocab")
136        o = object()
137        bound = field.bind(o)
138        self.assert_(isinstance(bound.vocabulary, SampleVocabulary))
139        bound.default = okval
140        self.assertEqual(bound.default, okval)
141        self.assertRaises(ValidationError, setattr, bound, "default", badval)
142
143    def test_constructed_vocabulary(self):
144        self.check_constructed(TextLineChoice, u'a', u'z')
145
146    def test_create_vocabulary(self):
147        vocabulary.setVocabularyRegistry(DummyRegistry())
148        field = TextLineChoice(vocabulary="vocab")
149        o = object()
150        bound = field.bind(o)
151        self.assertEqual([term.value for term in bound.vocabulary],
152                         SAMPLE_VALUES)
153
154    def test_undefined_vocabulary(self):
155        choice = TextLineChoice(vocabulary="unknown")
156        self.assertRaises(ValueError, choice.validate, u"value")
157
158class TextLineChoice_Source_Tests(unittest.TestCase):
159    # Tests of the TextLineChoice Field using sources.
160
161    def test_simple_source(self):
162        choice = TextLineChoice(__name__='astring', source=letter_a_source)
163        bound = choice.bind(object())
164        self.assertEqual(bound.vocabulary, letter_a_source)
165        return
166
167    def test_validate_simple_source(self):
168        choice = TextLineChoice(__name__='astring', source=letter_a_source)
169        bound = choice.bind(object())
170        bound.validate(u'string_with_letter_a')
171        self.assertRaises(
172            InvalidValue, bound.validate, u'other_string')
173        return
174
175    def test_contextual_source(self):
176        # make sure we can pass contextual sources
177        choice = TextLineChoice(__name__='astring', source=letter_source_binder)
178        bound = choice.bind(SampleContext()) # requires 'b' instead of 'a'
179        self.assertTrue(isinstance(bound.vocabulary, LetterASource))
180        self.assertTrue(bound.vocabulary is not letter_a_source)
181        return
182
183    def test_validate_contextual_source(self):
184        # make sure the values from context are considered
185        choice = TextLineChoice(__name__='astring', source=letter_source_binder)
186        bound = choice.bind(SampleContext()) # requires 'b' instead of 'a'
187        bound.validate(u'string_with_letter_b')
188        self.assertRaises(
189            InvalidValue, bound.validate, u'other_string') # no 'b'
190        return
191
192def test_suite():
193    # We must define a test suite as we do not want the imported
194    # TextLineTest to be collected by testrunner.
195    return unittest.TestSuite((
196        unittest.makeSuite(TextLineChoiceAsTextLineTest),
197        unittest.makeSuite(TextLineChoice_Values_Tests),
198        unittest.makeSuite(TextLineChoice_Vocabulary_Tests),
199        unittest.makeSuite(TextLineChoice_Source_Tests),
200        ))
Note: See TracBrowser for help on using the repository browser.