Пример #1
0
def test_model_context_pass_to_type():
    from schematics.types import BaseType
    from schematics.datastructures import Context

    class CustomType(BaseType):

        def to_native(self, value, context=None):
            suffix = context.suffix
            return str(value) + suffix

        def to_primitive(self, value, context=None):
            suffix = context.suffix
            return value[:-len(suffix)]

    class Thing(Model):
        x = CustomType()

    context = {'suffix': 'z'}
    input = {'x': 'thingie'}
    thing = Thing(input, context=context)
    assert thing.x == 'thingiez'
    assert thing.to_primitive(context=context) == {'x': 'thingie'}
    # try it with a Context object
    model_context = Context(suffix='z!')
    thing2 = Thing(input, context=model_context)
    assert thing2.x == 'thingiez!'
    export_context = Context(suffix='z!')
    assert thing2.to_primitive(context=export_context) == {'x': 'thingie'}
    with pytest.raises(AttributeError):
        # can't reuse the same Context object as was used for model
        # TODO this may be unexpected to the uninitiated; a custom exception
        #      could explain it better.
        thing2.to_primitive(context=model_context)
Пример #2
0
def test_multilingual_string_should_accept_lists_of_locales():
    strings = {
        'en_US': 'snake',
        'fr_FR': 'serpent',
        'es_MX': 'serpiente',
    }

    mls = MultilingualStringType(default_locale=['foo', 'fr_FR', 'es_MX'])

    assert mls.to_primitive(strings) == 'serpent'
    assert mls.to_primitive(strings, context=Context(app_data={'locale': ['es_MX', 'bar']})) == 'serpiente'

    mls = MultilingualStringType()

    assert mls.to_primitive(strings, context=Context(app_data={'locale': ['foo', 'es_MX', 'fr_FR']})) == 'serpiente'
Пример #3
0
def test_multilingual_string_without_matching_locale_should_explode():
    mls = MultilingualStringType()

    with pytest.raises(ConversionError):
        mls.to_primitive({'fr_FR': 'serpent'})

    with pytest.raises(ConversionError):
        mls.to_primitive({'en_US': 'snake'}, context=Context(app_data={'locale': 'fr_FR'}))
Пример #4
0
def test_multilingual_string_should_emit_string_with_explicit_locale():
    mls = MultilingualStringType(default_locale='en_US')

    assert mls.to_primitive(
        {
            'en_US': 'snake',
            'fr_FR': 'serpent'
        },
        context=Context(app_data={'locale': 'fr_FR'})) == 'serpent'