• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zopefoundation / zc.form / 16248976557

21 Oct 2024 07:16AM UTC coverage: 82.759%. Remained the same
16248976557

push

github

icemac
Back to development: 2.2

126 of 180 branches covered (70.0%)

Branch coverage included in aggregate %.

786 of 922 relevant lines covered (85.25%)

0.85 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/src/zc/form/browser/tests/test_unittest.py
1
##############################################################################
2
#
3
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
4
# All Rights Reserved.
5
#
6
# This software is subject to the provisions of the Zope Public License,
7
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
8
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11
# FOR A PARTICULAR PURPOSE.
12
#
13
##############################################################################
14
"""tests of custom widgets defined in Schema"""
15
import doctest
1✔
16
import re
1✔
17
import unittest
1✔
18

19
import zope.component.testing
1✔
20
import zope.publisher.interfaces.browser
1✔
21
import zope.schema.interfaces
1✔
22
import zope.traversing.adapters
1✔
23
from zope import component
1✔
24
from zope.formlib.interfaces import ConversionError
1✔
25
from zope.formlib.interfaces import IInputWidget
1✔
26
from zope.formlib.textwidgets import IntWidget
1✔
27
from zope.formlib.textwidgets import TextWidget
1✔
28
from zope.publisher.browser import TestRequest
1✔
29
from zope.publisher.interfaces.browser import IBrowserRequest
1✔
30
from zope.schema import Int
1✔
31
from zope.schema import TextLine
1✔
32
from zope.schema.interfaces import IInt
1✔
33
from zope.schema.interfaces import ITextLine
1✔
34
from zope.schema.interfaces import ValidationError
1✔
35

36
import zc.form.browser
1✔
37
import zc.form.field
1✔
38
from zc.form.browser.exceptionviews import ValidationErrorView
1✔
39
from zc.form.browser.unionwidget import UnionWidget
1✔
40
from zc.form.field import Union
1✔
41

42

43
class TestUnionWidget(
1✔
44
        zope.component.testing.PlacelessSetup, unittest.TestCase):
45

46
    def setUp(self):
1✔
47
        super().setUp()
1✔
48
        # XXX cheating: should not rely on these. :-/
49
        component.provideAdapter(
1✔
50
            TextWidget, (ITextLine, IBrowserRequest), IInputWidget)
51
        component.provideAdapter(
1✔
52
            IntWidget, (IInt, IBrowserRequest), IInputWidget)
53
        from zc.form.browser.unionwidget import default_template
1✔
54
        component.provideAdapter(default_template, name='default')
1✔
55
        component.provideAdapter(
1✔
56
            zope.traversing.adapters.DefaultTraversable,
57
            [None],
58
        )
59

60
    def test_render(self):
1✔
61
        request = TestRequest()
1✔
62
        field = Union(
1✔
63
            (TextLine(title="Name", min_length=5),
64
             Int(title="Age", min=0)),
65
            title="Simple Identifier",
66
            __name__='identifier')
67
        widget = UnionWidget(field, request)
1✔
68
        widget.setPrefix('field')
1✔
69
        output = widget()
1✔
70
        self.assertIn('<table', output)
1✔
71
        self.assertIn('Age', output)
1✔
72
        self.assertIn('Name', output)
1✔
73
        self.assertRegex(output, r'''type=['"]radio['"]''')
1✔
74
        self.assertRegex(output, r'''name=['"]field.identifier['"]''')
1✔
75
        self.assertRegex(output, r'''id=["']field.identifier-00['"]''')
1✔
76
        self.assertRegex(output, r'''id=["']field.identifier-01['"]''')
1✔
77
        self.assertRegex(
1✔
78
            output, r'''name=["']field.identifier.unioned_00['"]''')
79
        self.assertRegex(
1✔
80
            output, r'''name=["']field.identifier.unioned_01['"]''')
81
        self.assertNotRegex(output, r'''id=["']field.identifier-02['"]''')
1✔
82
        self.assertNotRegex(output, r'''checked\s*=\s*['"]checked['"]''')
1✔
83
        field = Union(
1✔
84
            (TextLine(title="Name", min_length=5),
85
             Int(title="Age", min=0)),
86
            title="Simple Identifier",
87
            __name__='identifier',
88
            required=False)
89
        widget = UnionWidget(field, request)
1✔
90
        widget.setPrefix('field')
1✔
91
        output = widget()
1✔
92
        self.assertRegex(output, r'''id=["']field.identifier-02['"]''')
1✔
93
        self.assertRegex(output, r'''checked\s*=\s*['"]checked['"]''')
1✔
94

95
    def test_use_default_for_not_selected(self):
1✔
96
        # test use_default_for_not_selected = True
97
        request = TestRequest()
1✔
98
        # the default selection shoud be the the option field which has the
99
        # value of None
100
        field = Union(
1✔
101
            (zc.form.field.TextLine(
102
                title="New Password", missing_value='',
103
                default_getter=lambda x: 'secret password'),
104
             zc.form.field.Option(
105
                title="No Change", value='no change')),
106
            title="Change Password",
107
            missing_value='',
108
            use_default_for_not_selected=True,
109
            __name__='identifier')
110
        widget = UnionWidget(field, request)
1✔
111
        widget.setPrefix('field')
1✔
112
        output = widget()
1✔
113
        # remove double whitespaces
114
        normalized_output = " ".join(output.split())
1✔
115

116
        # the value of the textline field should be the default_getter's
117
        # result
118
        value_attr_of_textline = re.search(
1✔
119
            '<input.*id="field.identifier.unioned_00".*(value=".*").*></div>',
120
            normalized_output).groups()[0]
121
        self.assertIn('secret password', value_attr_of_textline)
1✔
122

123
        # the radio button of the option field should be selected
124
        radio_option_field = re.search(
1✔
125
            '<input.*id="field.identifier-01"(.*)/> </td>',
126
            normalized_output).groups()[0]
127
        self.assertIn('checked="checked"', radio_option_field)
1✔
128

129
    def test_evaluate(self):
1✔
130
        request = TestRequest()
1✔
131
        request.form.update({
1✔
132
            'field.identifier-marker': 'x',
133
            'field.identifier.unioned_00': 'Foo Bar',
134
            'field.identifier': '0'})
135
        field = Union(
1✔
136
            (TextLine(title="Name", min_length=5),
137
             Int(title="Age", min=0)),
138
            title="Simple Identifier",
139
            __name__='identifier')
140
        widget = UnionWidget(field, request)
1✔
141
        widget.setPrefix('field')
1✔
142
        self.assertEqual(widget.loadValueFromRequest(), 'Foo Bar')
1✔
143

144

145
class TestInterfaces(unittest.TestCase):
1✔
146
    """Testing interfaces import."""
147

148
    def test_interfaces__import__1(self):
1✔
149
        """zope.form.browser.interfaces can be imported"""
150
        import zc.form.browser.interfaces  # noqa: F401
1✔
151

152

153
class TestValidationErrorView(unittest.TestCase):
1✔
154
    """Testing .exceptionviews.ValidationErrorView."""
155

156
    def test_exceptionviews__ValidationErrorView__1(self):
1✔
157
        """It converts an invariant error to an html snippet."""
158
        err = ValidationError("Bad error!  Bad!")
1✔
159
        view = ValidationErrorView(err, None)
1✔
160
        self.assertEqual(
1✔
161
            view.snippet(), '<span class="error">Bad error!  Bad!</span>')
162

163
    def test_exceptionviews__ValidationErrorView__2(self):
1✔
164
        """It converts also unicode an html snippet."""
165
        err = ValidationError("Fälscher!")
1✔
166
        view = ValidationErrorView(err, None)
1✔
167
        self.assertEqual(
1✔
168
            view.snippet(), '<span class="error">Fälscher!</span>')
169

170
    def test_exceptionviews__ValidationErrorView__3(self):
1✔
171
        """It quotes HTML characters correctly."""
172
        err = ValidationError("The <error> & me.")
1✔
173
        view = ValidationErrorView(err, None)
1✔
174
        self.assertEqual(
1✔
175
            view.snippet(),
176
            '<span class="error">The &lt;error&gt; &amp; me.</span>')
177

178
    def test_exceptionviews__ValidationErrorView__4(self):
1✔
179
        """It converts the exception argument of an ConversionError as well."""
180
        err = ConversionError(ValidationError("not valid"))
1✔
181
        view = ValidationErrorView(err, None)
1✔
182
        self.assertEqual(
1✔
183
            view.snippet(), '<span class="error">not valid</span>')
184

185

186
def pageSetUp(test):
1✔
187
    zope.component.testing.setUp(test)
1✔
188
    component.provideAdapter(
1✔
189
        zope.traversing.adapters.DefaultTraversable,
190
        [None],
191
    )
192

193

194
optionflags = (
1✔
195
    doctest.NORMALIZE_WHITESPACE
196
    | doctest.ELLIPSIS
197
    | doctest.REPORT_NDIFF
198
    | doctest.IGNORE_EXCEPTION_DETAIL
199
    | doctest.REPORT_ONLY_FIRST_FAILURE
200
)
201

202

203
def test_suite():
1✔
204
    return unittest.TestSuite([
1✔
205
        unittest.defaultTestLoader.loadTestsFromName(__name__),
206
        doctest.DocFileSuite(
207
            '../combinationwidget.rst',
208
            optionflags=optionflags,
209
            setUp=pageSetUp,
210
            tearDown=zope.component.testing.tearDown),
211
    ])
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc