예제 #1
0
    def shadow():
        schema = Dict.named(u'dict_name').of(String.named(u'name'),
                                             String.named(u'u'))

        element = schema({u'name': u'string name', u'u': u'string u'})
        element.set_prefix(u'top')
        return {'top': element, 'bound': element.bind}
예제 #2
0
def test_update_object():
    class Obj(object):
        def __init__(self, **kw):
            for (k, v) in kw.items():
                setattr(self, k, v)

    schema = Dict.of(String.named(u'x'), String.named(u'y'))

    o = Obj()
    assert not hasattr(o, 'x')
    assert not hasattr(o, 'y')

    def updated_(obj_factory, initial_value, wanted=None, **update_kw):
        el = schema(initial_value)
        obj = obj_factory()
        update_kw.setdefault('key', asciistr)
        el.update_object(obj, **update_kw)
        if wanted is None:
            wanted = dict((asciistr(k), v) for k, v in initial_value.items())
        have = dict(obj.__dict__)
        assert have == wanted

    updated_(Obj, {u'x': u'X', u'y': u'Y'})
    updated_(Obj, {u'x': u'X'}, {'x': u'X', 'y': None})
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {'x': u'X', 'y': None})
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {
        'x': u'X',
        'y': u'Y'
    },
             omit=('y', ))
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {'y': u'Y'}, include=(u'z', ))
    updated_(Obj, {u'x': u'X'}, {'y': None, 'z': u'X'}, rename=(('x', 'z'), ))
예제 #3
0
파일: test_tags.py 프로젝트: dag/flatland
def user_filter_form(values=None):
    schema = Dict.of(
        String.named(u'field1').using(optional=True),
        String.named(u'field2'))
    if values is None:
        values = {
            u'field1': u'val',
            }
    el = schema(values)
    el[u'field2'].errors.append(u'Missing')

    def label_filter(tag, attrs, stream, context, el):
        from genshi import QName
        if el is None:
            return tag, attrs, stream
        content = stream.render()
        if not content:
            label = el.label
            if not el.optional:
                label += ' *'
            stream = label
        if not el.optional:
            css = (attrs.get(u'class', u'') + u' required').strip()
            attrs |= [(QName(u'class'), css)]
        return tag, attrs, stream
    label_filter.tags = (u'label',)

    return dict(form=el, label_filter=label_filter)
예제 #4
0
def user_filter_form(values=None):
    schema = Dict.of(
        String.named(u'field1').using(optional=True), String.named(u'field2'))
    if values is None:
        values = {
            u'field1': u'val',
        }
    el = schema(values)
    el[u'field2'].errors.append(u'Missing')

    def label_filter(tag, attrs, stream, context, el):
        from genshi import QName
        if el is None:
            return tag, attrs, stream
        content = stream.render()
        if not content:
            label = el.label
            if not el.optional:
                label += ' *'
            stream = label
        if not el.optional:
            css = (attrs.get(u'class', u'') + u' required').strip()
            attrs |= [(QName(u'class'), css)]
        return tag, attrs, stream

    label_filter.tags = (u'label', )

    return dict(form=el, label_filter=label_filter)
예제 #5
0
파일: test_dicts.py 프로젝트: dag/flatland
def test_update_object():

    class Obj(object):

        def __init__(self, **kw):
            for (k, v) in kw.items():
                setattr(self, k, v)

    schema = Dict.of(String.named(u'x'), String.named(u'y'))

    o = Obj()
    assert not hasattr(o, 'x')
    assert not hasattr(o, 'y')

    def updated_(obj_factory, initial_value, wanted=None, **update_kw):
        el = schema(initial_value)
        obj = obj_factory()
        update_kw.setdefault('key', asciistr)
        el.update_object(obj, **update_kw)
        if wanted is None:
            wanted = dict((asciistr(k), v) for k, v in initial_value.items())
        have = dict(obj.__dict__)
        assert have == wanted

    updated_(Obj, {u'x': u'X', u'y': u'Y'})
    updated_(Obj, {u'x': u'X'}, {'x': u'X', 'y': None})
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {'x': u'X', 'y': None})
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {'x': u'X', 'y': u'Y'},
             omit=('y',))
    updated_(lambda: Obj(y=u'Y'), {u'x': u'X'}, {'y': u'Y'},
             include=(u'z',))
    updated_(Obj, {u'x': u'X'}, {'y': None, 'z': u'X'},
             rename=(('x', 'z'),))
예제 #6
0
def test_path():
    schema = Dict.named(u'root').of(
        String.named(u'element'),
        Dict.named(u'dict').of(String.named(u'dict_element')))
    element = schema()

    eq_(list(element.find_one([u'dict', u'dict_element']).path),
        [element, element[u'dict'], element[u'dict'][u'dict_element']])
예제 #7
0
def test_path():
    schema = Dict.named('root').of(
        String.named('element'),
        Dict.named('dict').of(String.named('dict_element')))
    element = schema()

    assert (list(element.el(['dict', 'dict_element']).path) ==
            [element, element['dict'], element['dict']['dict_element']])
예제 #8
0
def test_path():
    schema = Dict.named('root').of(
        String.named('element'),
        Dict.named('dict').of(String.named('dict_element')))
    element = schema()

    eq_(list(element.el(['dict', 'dict_element']).path),
        [element, element['dict'], element['dict']['dict_element']])
예제 #9
0
def test_naming_bogus():
    e = String(name=u's')

    assert e.el(u'.') is e
    assert_raises(LookupError, e.el, u'')
    assert_raises(TypeError, e.el, None)
    assert_raises(LookupError, e.el, ())
    assert_raises(LookupError, e.el, iter(()))
    assert_raises(TypeError, e.el)
예제 #10
0
def test_naming_bogus():
    e = String(name=u's')

    assert e.el(u'.') is e
    assert_raises(LookupError, e.el, u'')
    assert_raises(TypeError, e.el, None)
    assert_raises(LookupError, e.el, ())
    assert_raises(LookupError, e.el, iter(()))
    assert_raises(TypeError, e.el)
예제 #11
0
    def shadow():
        schema = Dict.named(u'dict_name').of(
            String.named(u'name'),
            String.named(u'u'))

        element = schema({u'name': u'string name',
                          u'u': u'string u'})
        element.set_prefix(u'top')
        return {'top': element, 'bound': element.bind}
예제 #12
0
    def elements():
        from flatland import Dict, String
        anon = Dict.of(String.named(u'anon_field'))()
        named = Dict.named(u'named').of(String.named(u'named_field'))()
        prefixed = Dict.named(u'prefixed').of(String.named(u'prefixed_field'))()
        prefixed.set_prefix(u'three.levels.down')

        return {'form': anon,
                'forms': {'named': named },
                'three': {'levels': {'down': prefixed}}}
예제 #13
0
def test_set_flat_doubly_anonymous_dict():
    pairs = ((u'0_x', u'x0'), (u'0_y', u'y0'),
             (u'1_x', u'x1'), (u'1_y', u'y1'),
             (u'2_x', u'x2'), )

    schema = List.of(String.named(u'x'), String.named(u'y'))
    el = schema.from_flat(pairs)

    eq_(len(el), 3)
    eq_(el[0].value, dict((k[-1], v) for k, v in pairs[0:2]))
    eq_(el[1].value, dict((k[-1], v) for k, v in pairs[2:4]))
    eq_(el[2].value, {u'x': u'x2', u'y': None})
예제 #14
0
파일: validation.py 프로젝트: steel-ne/moin
def subscription_validator(element, state):
    """
    a subscription
    """
    try:
        keyword, value = element.value.split(":", 1)
    except ValueError:
        element.add_error("Subscription must contain colon delimiters.")
        return False

    if keyword in (keys.ITEMID, ):
        value_element = String(value)
        valid = uuid_validator(value_element, state)
    elif keyword in (
            keys.NAME,
            keys.TAGS,
            keys.NAMERE,
            keys.NAMEPREFIX,
    ):
        try:
            namespace, value = value.split(":", 1)
        except ValueError:
            element.add_error("Subscription must contain 2 colon delimiters.")
            return False
        namespace_element = String(namespace)
        if not namespace_validator(namespace_element, state):
            element.add_error("Not a valid namespace value.")
            return False
    else:
        element.add_error("Subscription must start with one of the keywords: "
                          "'{0}', '{1}', '{2}', '{3}' or '{4}'.".format(
                              keys.ITEMID, keys.NAME, keys.TAGS, keys.NAMERE,
                              keys.NAMEPREFIX))
        return False

    value_element = String(value)
    if keyword == keys.TAGS:
        valid = tag_validator(value_element, state)
    elif keyword in (
            keys.NAME,
            keys.NAMEPREFIX,
    ):
        valid = name_validator(value_element, state)
    elif keyword == keys.NAMERE:
        try:
            re.compile(value, re.U)
            valid = True
        except re.error:
            valid = False
    if not valid:
        element.add_error("Subscription has invalid value.")
    return valid
예제 #15
0
def test_corrupt_all_children():
    # Ensure all_children won't spin out if the graph becomes cyclic.
    schema = List.of(String)
    el = schema()

    el.append(String(u'x'))
    el.append(String(u'y'))
    dupe = String(u'z')
    el.append(dupe)
    el.append(dupe)

    assert list(_.value for _ in el.children) == list(u'xyzz')
    assert list(_.value for _ in el.all_children) == list(u'xyz')
예제 #16
0
def test_validator_validated():
    sentinel = []

    def listener(**kw):
        sentinel.append(kw)

    signals.validator_validated.connect(listener)

    schema = String.using(validators=[Present(),
                                      Converted(),
                                      NoLongerThan(5)])
    el = schema()
    assert not el.validate()
    eq_(sentinel, [dict(sender=schema.validators[0],
                        element=el,
                        state=None,
                        result=False)])
    del sentinel[:]
    el = schema(value='abcd')
    assert el.validate()
    assert len(sentinel) == 3
    assert sentinel[-1]['result']

    del sentinel[:]
    el = schema('squiznart')
    assert not el.validate()
    assert len(sentinel) == 3
    assert not sentinel[-1]['result']

    s2 = String.using(optional=False)

    del sentinel[:]
    el = s2()
    assert not el.validate()
    eq_(sentinel, [dict(sender=NotEmpty, element=el,
                        state=None, result=False)])

    del sentinel[:]
    el = s2('squiznart')
    assert el.validate()
    eq_(sentinel, [dict(sender=NotEmpty, element=el,
                        state=None, result=True)])

    del listener
    del sentinel[:]
    el = schema('squiznart')
    assert not el.validate()
    assert not sentinel

    signals.validator_validated._clear_state()
예제 #17
0
    def form():
        schema = Dict.named(u'field0').of(
            String.named(u'field1'), String.named(u'field2'),
            List.named(u'field3').of(String.named(u'field4')),
            List.named(u'field5').of(
                List.named(u'field6').of(String.named(u'field7'))))

        element = schema({
            u'field1': u'val1',
            u'field2': u'val2',
            u'field3': [u'val3'],
            u'field5': [[u'val4']]
        })
        element.set_prefix(u'form')
        return {'form': element, 'bound': element.bind}
예제 #18
0
    def form():
        schema = Dict.named(u'field0').of(
            String.named(u'field1'),
            String.named(u'field2'),
            List.named(u'field3').of(String.named(u'field4')),
            List.named(u'field5').of(
                List.named(u'field6').of(String.named(u'field7'))))

        element = schema(
            {u'field1': u'val1',
             u'field2': u'val2',
             u'field3': [u'val3'],
             u'field5': [[u'val4']]})
        element.set_prefix(u'form')
        return {'form': element, 'bound': element.bind}
예제 #19
0
def test_naming_shallow():
    root = String(name=u's')
    assert root.fq_name() == u'.'
    assert root.flattened_name() == u's'
    assert root.el(u'.') is root

    root = String(name=None)
    assert root.fq_name() == u'.'
    assert root.flattened_name() == u''
    assert root.el(u'.') is root
    assert_raises(LookupError, root.el, ())
    assert root.el([Root]) is root
예제 #20
0
class PersonSchema(Form):

    name = String

    age = Integer.using(validators=[
        ValueAtLeast(minimum=18),
        ValueAtMost(maximum=120)
    ])

    weight = Integer.using(validators=[
        ValueAtLeast(minimum=0),
        ValueAtMost(maximum=300)
    ])
    weight.render_options = dict(
        style='slider'
    )

    friendly = Boolean

    address = String.using()
    address.render_options = dict(
        style='multiline'
    )

    happy = Boolean.using()
    happy.render_options = dict(
        style='toggle'
    )
예제 #21
0
    def _populate_app_fields(self):
        with WindowServiceProxy(59000) as w:
            self.video_mode_map = w.get_video_mode_map()
            if self.video_mode_map:
                self._video_available = True
            else:
                self._video_available = False
            self.video_mode_keys = sorted(self.video_mode_map.keys())
            if self._video_available:
                self.device_key, self.devices = w.get_video_source_configs()

        field_list = [
            Integer.named('overlay_opacity').using(default=50, optional=True),
            Directory.named('device_directory').using(default='', optional=True),
            String.named('transform_matrix').using(default='', optional=True,
                                                properties={'show_in_gui':
                                                            False}), ]

        if self._video_available:
            video_mode_enum = Enum.named('video_mode').valued(
                *self.video_mode_keys).using(default=self.video_mode_keys[0],
                                             optional=True)
            video_enabled_boolean = Boolean.named('video_enabled').using(
                default=False, optional=True, properties={'show_in_gui': True})
            recording_enabled_boolean = Boolean.named('recording_enabled').using(
                default=False, optional=True, properties={'show_in_gui': False})
            field_list.append(video_mode_enum)
            field_list.append(video_enabled_boolean)
            field_list.append(recording_enabled_boolean)
        return Form.of(*field_list)
예제 #22
0
class PersonForm(FormView):

    schema_type = Dict.of(
        String.named('name'),
        Integer.named('age'),
        Boolean.named('friendly'),
    )
예제 #23
0
def test_naming_dict():
    for name, root_flat, leaf_flat in ((u'd', u'd', u'd_s'),
                                       (None, u'', u's')):
        schema = Dict.named(name).of(String.named(u's'))
        root = schema()
        leaf = root[u's']

        assert root.fq_name() == u'.'
        assert root.flattened_name() == root_flat
        assert root.el(u'.') is root

        assert leaf.fq_name() == u'.s'
        assert leaf.flattened_name() == leaf_flat
        assert root.el(u'.s') is leaf
        assert root.el(u's') is leaf
        assert leaf.el(u'.s') is leaf
        with pytest.raises(LookupError):
            leaf.el(u's')
        assert leaf.el(u'.') is root

        assert root.el([Root]) is root
        assert root.el([u's']) is leaf
        assert root.el([Root, u's']) is leaf
        assert root.el(iter([u's'])) is leaf
        assert root.el(iter([Root, u's'])) is leaf
예제 #24
0
def small_form(values=None):

    SmallForm = Dict.of(String.named(u'field1'), String.named(u'field2'),
                        Boolean.named(u'toggle1'), Boolean.named(u'toggle2'),
                        Array.named(u'multi').of(String),
                        DateYYYYMMDD.named(u'date1'))

    if values is None:
        values = {
            u'field1': u'val',
            u'toggle2': True,
            u'multi': [u'a', u'b'],
            u'date1': datetime.date(1999, 12, 31),
        }
    el = SmallForm(values)
    return {'form': el}
예제 #25
0
def test_joined_string():
    el = JoinedString(u'abc')
    assert el.value == u'abc'
    assert [child.value for child in el] == [u'abc']

    el = JoinedString(u'abc,def')
    assert el.value == u'abc,def'
    assert [child.value for child in el] == [u'abc', u'def']

    el = JoinedString([u'abc', u'def'])
    assert el.value == u'abc,def'
    assert [child.value for child in el] == [u'abc', u'def']

    el = JoinedString(u' abc,,ghi ')
    assert el.value == u'abc,ghi'
    assert [child.value for child in el] == [u'abc', u'ghi']

    el = JoinedString(u'abc,,ghi', prune_empty=False)
    assert el.value == u'abc,,ghi'
    assert [child.value for child in el] == [u'abc', u'', u'ghi']

    # The child (String) strips by default
    el = JoinedString(u' abc ,, ghi ', strip=False)
    assert el.value == u'abc,ghi'
    assert [child.value for child in el] == [u'abc', u'ghi']

    # Try with a non-stripping String
    el = JoinedString(u' abc ,, ghi ',
                      strip=False,
                      member_schema=String.using(strip=False))
    assert el.value == u' abc , ghi '
    assert [child.value for child in el] == [u' abc ', u' ghi ']
예제 #26
0
def test_compose_abstract_fixme():
    with pytest.raises(TypeError):
        # really it'd be nice if serialize simply wasn't inherited. would
        # have to rejigger the hierarchy, not sure its worth it.
        schema = Compound.using(field_schema=[String.named(u'y')])
        el = schema()
        schema.serialize(el, u'abc')
예제 #27
0
    class MyCompound5(Compound):
        field_schema = [String.named(u'x')]

        @classmethod
        def __compound_init__(cls):
            assert isinstance(cls, type)
            canary.append(cls)
예제 #28
0
def test_joined_string():
    el = JoinedString(u'abc')
    assert el.value == u'abc'
    assert [child.value for child in el] == [u'abc']

    el = JoinedString(u'abc,def')
    assert el.value == u'abc,def'
    assert [child.value for child in el] == [u'abc', u'def']

    el = JoinedString([u'abc', u'def'])
    assert el.value == u'abc,def'
    assert [child.value for child in el] == [u'abc', u'def']

    el = JoinedString(u' abc,,ghi ')
    assert el.value == u'abc,ghi'
    assert [child.value for child in el] == [u'abc', u'ghi']

    el = JoinedString(u'abc,,ghi', prune_empty=False)
    assert el.value == u'abc,,ghi'
    assert [child.value for child in el] == [u'abc', u'', u'ghi']

    # The child (String) strips by default
    el = JoinedString(u' abc ,, ghi ', strip=False)
    assert el.value == 'abc,ghi'
    assert [child.value for child in el] == [u'abc', u'ghi']

    # Try with a non-stripping String
    el = JoinedString(u' abc ,, ghi ',
                      strip=False,
                      member_schema=String.using(strip=False))
    assert el.value == ' abc , ghi '
    assert [child.value for child in el] == [u' abc ', u' ghi ']
예제 #29
0
def test_naming_list_list():
    # make sure nested Slots-users don't bork
    for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_l2_0_s'),
                                       (None, u'', u'0_l2_0_s')):
        schema = List.named(name).of(List.named(u'l2').of(String.named(u's')))

        root = schema([u'x'])
        leaf = root[0][0]

        assert root.fq_name() == u'.'
        assert root.flattened_name() == root_flat
        assert root.el(u'.') is root

        assert leaf.fq_name() == u'.0.0'
        assert leaf.flattened_name() == leaf_flat
        assert root.el(u'.0.0') is leaf
        assert root.el(u'0.0') is leaf
        assert leaf.el(u'.0.0') is leaf
        with pytest.raises(LookupError):
            leaf.el(u'0')
        with pytest.raises(LookupError):
            leaf.el(u's')
        assert leaf.el(u'.') is root

        assert root.el([u'0', u'0']) is leaf
예제 #30
0
class ZmqHubPlugin(SingletonPlugin, AppDataController):
    """
    This class is automatically registered with the PluginManager.
    """
    implements(IPlugin)
    plugin_name = 'wheelerlab.zmq_hub_plugin'
    '''
    AppFields
    ---------

    A flatland Form specifying application options for the current plugin.
    Note that nested Form objects are not supported.

    Since we subclassed AppDataController, an API is available to access and
    modify these attributes.  This API also provides some nice features
    automatically:
        -all fields listed here will be included in the app options dialog
            (unless properties=dict(show_in_gui=False) is used)
        -the values of these fields will be stored persistently in the microdrop
            config file, in a section named after this plugin's name attribute
    '''
    AppFields = Form.of(
        String.named('hub_uri').using(optional=True, default='tcp://*:31000'),
        Enum.named('log_level').using(default='info', optional=True).valued(
            'debug', 'info', 'warning', 'error', 'critical'),
    )

    def __init__(self):
        self.name = self.plugin_name
        self.hub_process = None

    def on_plugin_enable(self):
        """
        Handler called once the plugin instance is enabled.

        Note: if you inherit your plugin from AppDataController and don't
        implement this handler, by default, it will automatically load all
        app options from the config file. If you decide to overide the
        default handler, you should call:

            AppDataController.on_plugin_enable(self)

        to retain this functionality.
        """
        super(ZmqHubPlugin, self).on_plugin_enable()
        app_values = self.get_app_values()
        self.hub_process = Process(
            target=run_hub,
            args=(MicroDropHub(app_values['hub_uri'], self.name),
                  getattr(logging, app_values['log_level'].upper())))
        self.hub_process.start()

    def on_plugin_disable(self):
        """
        Handler called once the plugin instance is disabled.
        """
        if self.hub_process is not None:
            self.hub_process.terminate()
            self.hub_process = None
예제 #31
0
def test_el():
    schema = Array.of(String.named(u's'))
    element = schema(u'abc')
    eq_(list(element.value), [u'a', u'b', u'c'])

    eq_(element.el(u'0').value, u'a')
    eq_(element.el(u'2').value, u'c')
    assert_raises(KeyError, element.el, u'a')
예제 #32
0
    class MyCompound(Compound):
        field_schema = [String.named(u'x')]
        attr = 'value'

        def __init__(self, value='sentinel', abc=1):
            # __new__'s value= should not trump this one
            assert value == 'sentinel'
            self.abc = abc
예제 #33
0
def test_validator_validated():
    sentinel = []

    def listener(**kw):
        sentinel.append(kw)

    signals.validator_validated.connect(listener)

    schema = String.using(validators=[Present(), Converted(), NoLongerThan(5)])
    el = schema()
    assert not el.validate()
    eq_(sentinel, [
        dict(sender=schema.validators[0], element=el, state=None, result=False)
    ])
    del sentinel[:]
    el = schema(value='abcd')
    assert el.validate()
    assert len(sentinel) == 3
    assert sentinel[-1]['result']

    del sentinel[:]
    el = schema('squiznart')
    assert not el.validate()
    assert len(sentinel) == 3
    assert not sentinel[-1]['result']

    s2 = String.using(optional=False)

    del sentinel[:]
    el = s2()
    assert not el.validate()
    eq_(sentinel,
        [dict(sender=NotEmpty, element=el, state=None, result=False)])

    del sentinel[:]
    el = s2('squiznart')
    assert el.validate()
    eq_(sentinel, [dict(sender=NotEmpty, element=el, state=None, result=True)])

    del listener
    del sentinel[:]
    el = schema('squiznart')
    assert not el.validate()
    assert not sentinel

    signals.validator_validated._clear_state()
예제 #34
0
def test_tuple_plural():
    catalog = GetTextish()
    schema = Dict.of(
        String.named(u'name').using(validators=[LocalizedShort(2)]))

    data = schema(dict(name=u'xxx'))
    data.validate(catalog)
    assert data[u'name'].errors == [u'plural NAME 2']
예제 #35
0
def test_tuple_single():
    catalog = GetTextish()
    schema = Dict.of(
        String.named('name').using(validators=[LocalizedShort(1)]))

    data = schema(dict(name='xxx'))
    data.validate(catalog)
    assert data['name'].errors == [u'single NAME 1']
예제 #36
0
def test_find():
    schema = Array.of(String.named(u's'))
    element = schema(u'abc')
    eq_(list(element.value), [u'a', u'b', u'c'])

    eq_(element.find_one(u'0').value, u'a')
    eq_(element.find_one(u'2').value, u'c')
    assert_raises(LookupError, element.find_one, u'a')
예제 #37
0
파일: test_i18n.py 프로젝트: mbr/flatland0
def test_tuple_plural():
    catalog = GetTextish()
    schema = Dict.of(String.named('name').
                     using(validators=[LocalizedShort(2)]))

    data = schema(dict(name='xxx'))
    data.validate(catalog)
    assert data['name'].errors == [u'plural NAME 2']
예제 #38
0
def test_el():
    schema = Array.of(String.named(u's'))
    element = schema(u'abc')
    assert list(element.value) == [u'a', u'b', u'c']

    assert element.el(u'0').value == u'a'
    assert element.el(u'2').value == u'c'
    with pytest.raises(KeyError):
        element.el(u'a')
예제 #39
0
    class MyCompound(Compound):
        name = u'abc'
        field_schema = [String.named(u'x')]

        def __new__(cls, *args, **kw):
            canary.append('new')
            return Compound.__new__(cls, *args, **kw)

        def __init__(self, *args, **kw):
            canary.append('init')
예제 #40
0
파일: test_dicts.py 프로젝트: dag/flatland
def test_slice():
    schema = Dict.of(String.named(u'x'), String.named(u'y'))

    def same_(source, kw):
        el = schema(source)

        sliced = el.slice(**kw)
        wanted = dict(keyslice_pairs(el.value.items(), **kw))

        eq_(sliced, wanted)
        eq_(set(type(_) for _ in sliced.keys()),
            set(type(_) for _ in wanted.keys()))

    yield same_, {u'x': u'X', u'y': u'Y'}, {}
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(key=asciistr)
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(include=[u'x'])
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(omit=[u'x'])
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(omit=[u'x'],
                                                rename={u'y': u'z'})
예제 #41
0
def test_values_equal_resolution():
    v = ValuesEqual('x', '/sub/xx')
    el = form(dict(x='a', sub=dict(xx='a')))
    assert v.validate(el, None)

    v = ValuesEqual('/x', 'xx')
    el = form(dict(x='a', sub=dict(xx='a')))
    assert v.validate(el['sub'], None)

    # unhashable
    v = ValuesEqual('a', 'b')
    schema = Dict.of(List.named('a').of(String.named('x')),
                     List.named('b').of(String.named('x')))

    el = schema(dict(a=['a', 'b'], b=['a', 'b']))
    assert v.validate(el, None)

    el = schema(dict(a=['a', 'b'], b=['x', 'y']))
    assert not v.validate(el, None)
예제 #42
0
def test_values_equal_resolution():
    v = ValuesEqual('x', '/sub/xx')
    el = form(dict(x='a', sub=dict(xx='a')))
    assert v.validate(el, None)

    v = ValuesEqual('/x', 'xx')
    el = form(dict(x='a', sub=dict(xx='a')))
    assert v.validate(el['sub'], None)

    # unhashable
    v = ValuesEqual('a', 'b')
    schema = Dict.of(List.named('a').of(String.named('x')),
                     List.named('b').of(String.named('x')))

    el = schema(dict(a=['a', 'b'], b=['a', 'b']))
    assert v.validate(el, None)

    el = schema(dict(a=['a', 'b'], b=['x', 'y']))
    assert not v.validate(el, None)
예제 #43
0
def test_slice():
    schema = Dict.of(String.named(u'x'), String.named(u'y'))

    def same_(source, kw):
        el = schema(source)

        sliced = el.slice(**kw)
        wanted = dict(keyslice_pairs(el.value.items(), **kw))

        eq_(sliced, wanted)
        eq_(set(type(_) for _ in sliced.keys()),
            set(type(_) for _ in wanted.keys()))

    yield same_, {u'x': u'X', u'y': u'Y'}, {}
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(key=asciistr)
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(include=[u'x'])
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(omit=[u'x'])
    yield same_, {u'x': u'X', u'y': u'Y'}, dict(omit=[u'x'],
                                                rename={u'y': u'z'})
예제 #44
0
 def adapt(self, value):
     value = String.adapt(self, value)
     if value is not None:
         try:
             value = import_string(str(value))
         except ImportError, e:
             msg = "Warning, failed to import %r, %s" % (value, e)
             print msg
             raise AdaptationError(msg)
         return value
예제 #45
0
파일: test_arrays.py 프로젝트: dag/flatland
def test_set_flat_pruned():
    sub = String.named(u's')
    pairs = [(u's', u'val0'), (u's', ''), (u's', u'val1'), (u's', u'')]
    wanted = [u'val0', u'val1']

    for schema in Array.of(sub), Array.of(sub).using(prune_empty=True):
        el = schema.from_flat(pairs)

        eq_(len(el), len(wanted))
        eq_(el.value, wanted)
예제 #46
0
def test_set_flat_pruned():
    sub = String.named(u's')
    pairs = [(u's', u'val0'), (u's', u''), (u's', u'val1'), (u's', u'')]
    wanted = [u'val0', u'val1']

    for schema in Array.of(sub), Array.of(sub).using(prune_empty=True):
        el = schema.from_flat(pairs)

        eq_(len(el), len(wanted))
        eq_(el.value, wanted)
예제 #47
0
    def elements():
        from flatland import Dict, String
        anon = Dict.of(String.named(u'anon_field'))()
        named = Dict.named(u'named').of(String.named(u'named_field'))()
        prefixed = Dict.named(u'prefixed').of(
            String.named(u'prefixed_field'))()
        prefixed.set_prefix(u'three.levels.down')

        return {
            'form': anon,
            'forms': {
                'named': named
            },
            'three': {
                'levels': {
                    'down': prefixed
                }
            }
        }
예제 #48
0
파일: test_tags.py 프로젝트: dag/flatland
def small_form(values=None):

    SmallForm = Dict.of(
        String.named(u'field1'),
        String.named(u'field2'),
        Boolean.named(u'toggle1'),
        Boolean.named(u'toggle2'),
        Array.named(u'multi').of(String),
        DateYYYYMMDD.named(u'date1'))

    if values is None:
        values = {
            u'field1': u'val',
            u'toggle2': True,
            u'multi': [u'a', u'b'],
            u'date1': datetime.date(1999, 12, 31),
            }
    el = SmallForm(values)
    return {'form': el}
예제 #49
0
def test_regular_gettext():
    catalog = GetTextish()

    # translators placed at the top of the form
    schema = Dict.of(String.named(u'age').using(validators=[Converted()])).\
             using(ugettext=catalog.ugettext,
                   ungettext=catalog.ungettext)

    data = schema()
    data.validate()
    assert data[u'age'].errors == [u'reg AGE']
예제 #50
0
def test_multivalue_roundtrip():
    schema = MultiValue.of(String.named(u's'))
    data = [u'abc', u'def']
    el = schema(data)
    assert [e.value for e in el] == data

    flat = el.flatten()
    assert flat == [(u's', u'abc'), (u's', u'def')]
    restored = schema.from_flat(flat)
    assert restored.value == u'abc'
    assert [e.value for e in restored] == data
예제 #51
0
파일: test_arrays.py 프로젝트: dag/flatland
def test_multivalue_roundtrip():
    schema = MultiValue.of(String.named(u's'))
    data = [u'abc', u'def']
    el = schema(data)
    eq_([e.value for e in el], data)

    flat = el.flatten()
    eq_(flat, [(u's', u'abc'), (u's', u'def')])
    restored = schema.from_flat(flat)
    eq_(restored.value, u'abc')
    eq_([e.value for e in restored], data)
예제 #52
0
    class AltNewReturn(Compound):
        name = u'abc'
        field_schema = [String.named(u'x')]

        def __new__(cls, *args, **kw):
            canary.append('new')
            self = {}
            return self

        def __init__(self, *args, **kw):
            canary.append('init')
예제 #53
0
파일: test_i18n.py 프로젝트: mbr/flatland0
def test_local_gettext():
    catalog = GetTextish()

    # translators placed on a specific form element
    schema = Dict.of(String.named('age').using(validators=[Converted()],
                                               ugettext=catalog.ugettext,
                                               ungettext=catalog.ungettext))

    data = schema()
    data.validate()
    assert data['age'].errors == [u'reg AGE']
예제 #54
0
def test_multivalue_roundtrip():
    schema = MultiValue.of(String.named(u's'))
    data = [u'abc', u'def']
    el = schema(data)
    eq_([e.value for e in el], data)

    flat = el.flatten()
    eq_(flat, [(u's', u'abc'), (u's', u'def')])
    restored = schema.from_flat(flat)
    eq_(restored.value, u'abc')
    eq_([e.value for e in restored], data)
예제 #55
0
파일: test_i18n.py 프로젝트: mbr/flatland0
def test_regular_gettext():
    catalog = GetTextish()

    # translators placed at the top of the form
    schema = Dict.of(String.named('age').using(validators=[Converted()])).\
             using(ugettext=catalog.ugettext,
                   ungettext=catalog.ungettext)

    data = schema()
    data.validate()
    assert data['age'].errors == [u'reg AGE']
예제 #56
0
def test_mixed_all_children():
    data = {u'A1': u'1',
            u'A2': u'2',
            u'A3': {u'A3B1': {u'A3B1C1': u'1',
                              u'A3B1C2': u'2'},
                    u'A3B2': {u'A3B2C1': u'1'},
                    u'A3B3': [[u'A3B3C0D0', u'A3B3C0D1'],
                             [u'A3B3C1D0', u'A3B3C1D1'],
                             [u'A3B3C2D0', u'A3B3C2D1']]}}

    schema = (
        Dict.named(u'R').of(
            String.named(u'A1'),
            String.named(u'A2'),
            Dict.named(u'A3').of(
                Dict.named(u'A3B1').of(
                    String.named(u'A3B1C1'),
                    String.named(u'A3B1C2')),
                Dict.named(u'A3B2').of(
                    String.named(u'A3B2C1')),
                List.named(u'A3B3').of(
                    List.named(u'A3B3Cx').of(
                        String.named(u'A3B3x'))))))

    top = schema(data)

    names = list(e.name for e in top.all_children)

    assert set(names[0:3]) == set([u'A1', u'A2', u'A3'])
    assert set(names[3:6]) == set([u'A3B1', u'A3B2', u'A3B3'])
    assert set(names[6:12]) == set([u'A3B1C1', u'A3B1C2',
                                    u'A3B2C1', u'A3B3Cx'])
    assert set(names[12:]) == set([u'A3B3x'])
    assert len(names[12:]) == 6
예제 #57
0
파일: test_arrays.py 프로젝트: dag/flatland
def test_set_default():
    schema = Array.of(String).using(default=[u'x', u'y'])
    el = schema()

    eq_(el.value, [])
    el.set_default()
    eq_(el.value, [u'x', u'y'])

    el.append(u'z')
    eq_(el.value, [u'x', u'y', u'z'])
    el.set_default()
    eq_(el.value, [u'x', u'y'])

    defaulted_child = String.using(default='not triggered')
    schema = Array.of(defaulted_child).using(default=[u'x'])

    el = schema.from_defaults()
    eq_(el.value, [u'x'])

    schema = Array.of(String.using(default=u'x'))
    el = schema.from_defaults()
    eq_(el.value, [])
예제 #58
0
파일: test_i18n.py 프로젝트: mbr/flatland0
def test_state_gettext():
    catalog = GetTextish()

    schema = Dict.of(String.named('age').using(validators=[Converted()]))

    # if state has ugettext or ungettext attributes, those will be used
    data = schema()
    data.validate(catalog)
    assert data['age'].errors == [u'reg AGE']

    # also works if state is dict-like
    data = schema()
    state = dict(ugettext=catalog.ugettext, ungettext=catalog.ungettext)
    data.validate(state)
    assert data['age'].errors == [u'reg AGE']