Example #1
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)
Example #2
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)
Example #3
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'), ))
Example #4
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}
Example #5
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'),))
Example #6
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']])
Example #7
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']])
Example #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']])
Example #9
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}
Example #10
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}}}
Example #11
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})
Example #12
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}
Example #13
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}
Example #14
0
class PersonForm(FormView):

    schema_type = Dict.of(
        String.named('name'),
        Integer.named('age'),
        Boolean.named('friendly'),
    )
    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)
Example #16
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
Example #17
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}
Example #18
0
    class MyCompound5(Compound):
        field_schema = [String.named(u'x')]

        @classmethod
        def __compound_init__(cls):
            assert isinstance(cls, type)
            canary.append(cls)
Example #19
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')
Example #20
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
Example #21
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
Example #22
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
Example #23
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']
Example #24
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')
Example #25
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']
Example #26
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')
Example #27
0
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']
Example #28
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')
Example #29
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')
Example #30
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)
Example #31
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}
Example #32
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'})
Example #33
0
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)
Example #34
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'})
Example #35
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
                }
            }
        }
Example #36
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)
Example #37
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)
Example #38
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']
Example #39
0
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']
Example #40
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
Example #41
0
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']
Example #42
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')
Example #43
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)
Example #44
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)
Example #45
0
def test_local_gettext():
    catalog = GetTextish()

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

    data = schema()
    data.validate()
    assert data[u'age'].errors == [u'reg AGE']
Example #46
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
Example #47
0
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']
Example #48
0
def test_state_gettext():
    catalog = GetTextish()

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

    # if state has ugettext or ungettext attributes, those will be used
    data = schema()
    data.validate(catalog)
    assert data[u'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[u'age'].errors == [u'reg AGE']
Example #49
0
def test_local_gettext_search_is_not_overeager():
    catalog = GetTextish()

    def poison(*a):
        assert False

    # if a translator is found on an element, its parents won't be searched
    schema = (Dict.of(
        String.named(u'age').using(validators=[Converted()],
                                   ugettext=catalog.ugettext,
                                   ungettext=catalog.ungettext)).using(
                                       ugettext=poison, ungettext=poison))

    data = schema()
    data.validate()
    assert data[u'age'].errors == [u'reg AGE']
Example #50
0
def test_set_default_int():

    def factory(count, **kw):
        return List.named(u'l').using(default=count, **kw).of(
            String.named(u's').using(default=u'val'))

    schema = factory(3)
    el = schema()
    eq_(len(el), 0)
    eq_(el.value, [])

    el = schema()
    el.set_default()
    eq_(len(el), 3)
    eq_(el.value, [u'val'] * 3)

    el.append(None)
    eq_(len(el), 4)
    eq_(el[-1].value, None)
    el[-1].set_default()
    eq_(el[-1].value, u'val')

    el = schema([u'a', u'b'])
    eq_(len(el), 2)
    eq_(el.value, [u'a', u'b'])
    el.set_default()
    eq_(len(el), 3)
    eq_(el.value, [u'val'] * 3)

    schema0 = factory(0)

    el = schema0()
    el.set_default()
    eq_(len(el), 0)
    eq_(el.value, [])

    def calculated_default(element):
        assert isinstance(element, List)
        return 2

    schemaf = List.named(u'l').using(default_factory=calculated_default).of(
        String.named(u's').using(default=u'val'))

    el = schemaf()
    el.set_default()
    eq_(len(el), 2)
    eq_(el.value, [u'val'] * 2)
Example #51
0
def test_local_gettext_search_is_not_overeager():
    catalog = GetTextish()

    def poison(*a):
        assert False

    # if a translator is found on an element, its parents won't be searched
    schema = (Dict.of(String.named('age').
                     using(validators=[Converted()],
                           ugettext=catalog.ugettext,
                           ungettext=catalog.ungettext)).
              using(ugettext=poison,
                    ungettext=poison))

    data = schema()
    data.validate()
    assert data['age'].errors == [u'reg AGE']
Example #52
0
def test_builtin_gettext():
    catalog = GetTextish()

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

    data = schema()

    try:
        # translators can go into the builtins
        from six.moves import builtins
        builtins.ugettext = catalog.ugettext
        builtins.ungettext = catalog.ungettext
        data.validate()
        assert data['age'].errors == [u'reg AGE']
    finally:
        del builtins.ugettext
        del builtins.ungettext
Example #53
0
def test_builtin_gettext():
    catalog = GetTextish()

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

    data = schema()

    try:
        # translators can go into the builtins
        import __builtin__
        __builtin__.ugettext = catalog.ugettext
        __builtin__.ungettext = catalog.ungettext
        data.validate()
        assert data[u'age'].errors == [u'reg AGE']
    finally:
        del __builtin__.ugettext
        del __builtin__.ungettext
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Mpeg2-Player")
        window.set_default_size(640, 500)
        window.connect("destroy", self.on_destroy)
        vbox = gtk.VBox()
        window.add(vbox)
        hbox = gtk.HBox()
        vbox.pack_start(hbox, expand=False)

        video_mode_enum = Enum.named('video_mode').valued(*self.video_mode_keys)
        form = Form.of(
            video_mode_enum.using(default=self.video_mode_keys[0]),
            Filepath.named('output_path').using(default=''),
            Integer.named('bitrate').using(default=150, validators=[ValueAtLeast(
                    minimum=25)], properties={'step': 25,
                            'label': 'Bitrate (KB/s)', }),
            String.named('transform_string').using(default='1,0,0,0,1,0,0,0,1'),
            Boolean.named('draw_cairo').using(default=False),
        )
        self.video_mode_form_view = create_form_view(form)
        for field in ['video_mode', 'output_path', 'bitrate',
                'transform_string', 'draw_cairo']:
            setattr(self, '%s_field' % field, self.video_mode_form_view.form\
                    .fields[field])
        self.video_mode_field.proxy.connect('changed', self._on_mode_changed)
        self.video_source = None
        hbox.add(self.video_mode_form_view.widget)
        self.button = gtk.Button("Start")
        hbox.pack_start(self.button, False)
        self.button.connect("clicked", self.start_stop)
        self.aframe = gtk.AspectFrame(xalign=0.5, yalign=1.0, ratio=4.0 / 3.0,
                obey_child=False)

        self.pipeline = None
        self._proxy = None

        vbox.pack_start(self.aframe, expand=True)
        self.movie_view = GtkVideoView()
        self.movie_window = self.movie_view.widget
        self.aframe.add(self.movie_window)
        window.show_all()
        self.window = window
Example #55
0
def test_naming_dict_dict():
    for name, root_flat, leaf_flat in ((u'd', u'd', u'd_d2_s'), (None, u'',
                                                                 u'd2_s')):
        schema = Dict.named(name).of(Dict.named(u'd2').of(String.named(u's')))
        root = schema()
        leaf = root[u'd2'][u's']

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

        assert leaf.fq_name() == u'.d2.s'
        assert leaf.flattened_name() == leaf_flat
        assert root.el(u'.d2.s') is leaf
        assert root.el(u'd2.s') is leaf
        assert leaf.el(u'.d2.s') is leaf
        assert_raises(LookupError, leaf.el, u'd2.s')
        assert leaf.el(u'.') is root

        assert root.el([u'd2', u's']) is leaf
Example #56
0
def test_naming_list():
    for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_s'),
                                       (None, u'', u'0_s')):
        schema = List.named(name).of(String.named(u's'))
        root = schema([u'x'])
        leaf = root[0]

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

        assert leaf.fq_name() == u'.0'
        assert leaf.flattened_name() == leaf_flat
        assert root.el(u'.0') is leaf
        assert root.el(u'0') is leaf
        assert leaf.el(u'.0') is leaf
        assert_raises(LookupError, leaf.el, u'0')
        assert_raises(LookupError, leaf.el, u's')
        assert leaf.el(u'.') is root

        assert root.el([u'0']) is leaf
Example #57
0
def test_naming_dict_dict():
    for name, root_flat, leaf_flat in ((u'd', u'd', u'd_d2_s'),
                                       (None, u'', u'd2_s')):
        schema = Dict.named(name).of(
            Dict.named(u'd2').of(String.named(u's')))
        root = schema()
        leaf = root[u'd2'][u's']

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

        assert leaf.fq_name() == u'.d2.s'
        assert leaf.flattened_name() == leaf_flat
        assert root.el(u'.d2.s') is leaf
        assert root.el(u'd2.s') is leaf
        assert leaf.el(u'.d2.s') is leaf
        assert_raises(LookupError, leaf.el, u'd2.s')
        assert leaf.el(u'.') is root

        assert root.el([u'd2', u's']) is leaf