Exemple #1
0
def test_argument_and_explicit_converters_explicit():
    reg = ConverterRegistry()

    assert reg.argument_and_explicit_converters({'a': None},
                                                {'a': Converter(int)}) == {
                                                    'a': Converter(int)
                                                }
Exemple #2
0
def test_argument_and_explicit_converters_from_type():

    reg = ConverterRegistry()
    reg.register_converter(int, Converter(int))

    assert reg.argument_and_explicit_converters({'a': None}, {'a': int}) == {
        'a': Converter(int)
    }
Exemple #3
0
def test_argument_and_explicit_converters_explicit():
    class MyConverterRegistry(ConverterRegistry):
        def converter_for_type(self, t):
            return IDENTITY_CONVERTER

        def converter_for_value(self, v):
            return IDENTITY_CONVERTER

    reg = MyConverterRegistry()

    assert reg.argument_and_explicit_converters(
        {'a': None}, {'a': Converter(int)}) == {'a': Converter(int)}
Exemple #4
0
def test_traject_no_type_conflict_middle():
    traject = TrajectRegistry()

    class int_f(object):
        def __init__(self, x):
            self.x = x

    class int_f2(object):
        def __init__(self, x):
            self.x = x

    traject.add_pattern('a/{x}/y', int_f, converters=dict(x=Converter(int)))
    traject.add_pattern('a/{x}/z', int_f2, converters=dict(x=Converter(int)))
Exemple #5
0
def test_traject_consume_parameter():
    class app(morepath.App):
        pass

    dectate.commit(app)

    traject = app.config.path_registry

    class Model(object):
        def __init__(self, a):
            self.a = a

    get_param = ParameterFactory({'a': 0}, {'a': Converter(int)}, [])
    traject.add_pattern('sub', (Model, get_param))

    mount = app()

    found, request = consume(mount, 'sub?a=1')
    assert isinstance(found, Model)
    assert found.a == 1
    assert request.unconsumed == []
    found, request = consume(mount, 'sub')
    assert isinstance(found, Model)
    assert found.a == 0
    assert request.unconsumed == []
Exemple #6
0
def test_url_parameter_explicit_trumps_implicit():
    class app(morepath.App):
        pass

    class Model(object):
        def __init__(self, id):
            self.id = id

    @app.path(model=Model, path='/', converters=dict(id=Converter(int)))
    def get_model(id='foo'):
        return Model(id)

    @app.view(model=Model)
    def default(self, request):
        return "View: %s (%s)" % (self.id, type(self.id))

    @app.view(model=Model, name='link')
    def link(self, request):
        return request.link(self)

    c = Client(app())

    response = c.get('/?id=1')
    assert response.body in \
        (b"View: 1 (<type 'int'>)", b"View: 1 (<class 'int'>)")

    response = c.get('/link?id=1')
    assert response.body == b'http://localhost/?id=1'

    response = c.get('/?id=broken', status=400)

    response = c.get('/')
    assert response.body in \
        (b"View: foo (<type 'str'>)", b"View: foo (<class 'str'>)")
Exemple #7
0
def test_traject_type_conflict():
    traject = TrajectRegistry()

    class found_int(object):
        def __init__(self, x):
            self.x = x

    class found_str(object):
        def __init__(self, x):
            self.x = x

    traject.add_pattern('{x}', found_int, converters=dict(x=Converter(int)))
    with pytest.raises(TrajectError):
        traject.add_pattern('{x}',
                            found_str,
                            converters=dict(x=Converter(str)))
Exemple #8
0
def test_variable_path_explicit_converter():
    class app(morepath.App):
        pass

    class Model(object):
        def __init__(self, id):
            self.id = id

    @app.path(model=Model, path='{id}', converters=dict(id=Converter(int)))
    def get_model(id):
        return Model(id)

    @app.view(model=Model)
    def default(self, request):
        return "View: %s (%s)" % (self.id, type(self.id))

    @app.view(model=Model, name='link')
    def link(self, request):
        return request.link(self)

    c = Client(app())

    response = c.get('/1')
    assert response.body in \
        (b"View: 1 (<type 'int'>)", b"View: 1 (<class 'int'>)")

    response = c.get('/1/link')
    assert response.body == b'http://localhost/1'

    response = c.get('/broken', status=404)
Exemple #9
0
def test_decode_encode():
    class app(morepath.App):
        pass

    class Model(object):
        def __init__(self, id):
            self.id = id

    def my_decode(s):
        return s + 'ADD'

    def my_encode(s):
        return s[:-len('ADD')]

    @app.path(model=Model,
              path='/',
              converters=dict(id=Converter(my_decode, my_encode)))
    def get_model(id):
        return Model(id)

    @app.view(model=Model)
    def default(self, request):
        return "View: %s" % self.id

    @app.view(model=Model, name='link')
    def link(self, request):
        return request.link(self)

    c = Client(app())

    response = c.get('/?id=foo')
    assert response.body == b"View: fooADD"

    response = c.get('/link?id=foo')
    assert response.body == b'http://localhost/?id=foo'
Exemple #10
0
def test_url_parameter_list_explicit_converter():
    class app(morepath.App):
        pass

    class Model(object):
        def __init__(self, item):
            self.item = item

    @app.path(model=Model, path='/', converters={'item': [Converter(int)]})
    def get_model(item):
        return Model(item)

    @app.view(model=Model)
    def default(self, request):
        return repr(self.item)

    @app.view(model=Model, name='link')
    def link(self, request):
        return request.link(self)

    c = Client(app())

    response = c.get('/?item=1&item=2')
    assert response.body == b"[1, 2]"

    response = c.get('/link?item=1&item=2')
    assert response.body == b'http://localhost/?item=1&item=2'

    response = c.get('/link')
    assert response.body == b'http://localhost/'

    response = c.get('/?item=broken&item=1', status=400)

    response = c.get('/')
    assert response.body == b"[]"
Exemple #11
0
def test_traject_consume_parameter():
    class App(morepath.App):
        pass

    App.commit()

    traject = App.config.path_registry

    class Model(object):
        def __init__(self, a):
            self.a = a

    traject.add_pattern('sub',
                        Model,
                        defaults={'a': 0},
                        converters={'a': Converter(int)},
                        required=[])

    r = req('sub?a=1')
    obj = traject.consume(r)
    assert isinstance(obj, Model)
    assert obj.a == 1
    assert r.unconsumed == []

    r = req('sub')
    obj = traject.consume(r)
    assert isinstance(obj, Model)
    assert obj.a == 0
    assert r.unconsumed == []
Exemple #12
0
def test_converter_registry():
    r = ConverterRegistry()

    c = Converter(int, type(u""))
    r.register_converter(int, c)
    assert r.converter_for_type(int) is c
    assert r.converter_for_value(1) is c
    assert r.converter_for_value(None) is IDENTITY_CONVERTER
    with pytest.raises(DirectiveError):
        r.converter_for_value('s')
Exemple #13
0
def test_converter():
    step = Step("{foo}", converters=dict(foo=Converter(int)))
    assert step.discriminator_info() == "{}"

    variables = {}
    assert step.match("1", variables)
    assert variables == {"foo": 1}

    variables = {}
    assert not step.match("x", variables)
    assert not variables
Exemple #14
0
def test_converter():
    step = Step('{foo}', converters=dict(foo=Converter(int)))
    assert step.discriminator_info() == '{}'

    variables = {}
    assert step.match('1', variables)
    assert variables == {'foo': 1}

    variables = {}
    assert not step.match('x', variables)
    assert not variables
Exemple #15
0
def test_traject_with_converter():
    traject = TrajectRegistry()

    class found(object):
        def __init__(self, x):
            self.x = x

    traject.add_pattern('{x}', found, converters=dict(x=Converter(int)))

    obj = traject.consume(req('1'))
    assert obj.x == 1

    assert traject.consume(req('foo')) is None
Exemple #16
0
def test_class_path_extra_parameters_convert(info):
    app, r = info

    class Foo(object):
        pass

    r.register_inverse_path(model=Foo,
                            path='/foos',
                            factory_args=set(),
                            converters={'a': Converter(int)})
    info = app._get_class_path(Foo, {'extra_parameters': {'a': 1, 'b': 'B'}})
    assert info.path == 'foos'
    assert info.parameters == {'a': ['1'], 'b': ['B']}
def test_class_path_parameters_with_converters(info):
    app, r = info

    class Foo(object):
        def __init__(self, value):
            self.value = value
    r.register_inverse_path(model=Foo,
                            path='/foos',
                            factory_args=set(['value']),
                            converters={'value': Converter(int)})
    info = app._class_path(Foo, {'value': 1})
    assert info.path == 'foos'
    assert info.parameters == {'value': ['1']}
Exemple #18
0
def test_traject_type_conflict_middle_end():
    traject = TrajectRegistry()

    class int_f(object):
        def __init__(self, x):
            self.x = x

    class str_f(object):
        def __init__(self, x):
            self.x = x

    traject.add_pattern('a/{x}/y', int_f, converters=dict(x=Converter(int)))
    with pytest.raises(TrajectError):
        traject.add_pattern('a/{x}', str_f)
Exemple #19
0
def test_class_path_extra_parameters_convert(info):
    app, r = info

    class Foo(object):
        pass

    r.register_inverse_path(
        model=Foo,
        path="/foos",
        factory_args=set(),
        converters={"a": Converter(int)},
    )
    info = app._class_path(Foo, {"extra_parameters": {"a": 1, "b": "B"}})
    assert info.path == "foos"
    assert info.parameters == {"a": ["1"], "b": ["B"]}
Exemple #20
0
def test_class_path_parameters_with_converters(info):
    app, r = info

    class Foo(object):
        def __init__(self, value):
            self.value = value

    r.register_inverse_path(
        model=Foo,
        path="/foos",
        factory_args=set(["value"]),
        converters={"value": Converter(int)},
    )
    info = app._class_path(Foo, {"value": 1})
    assert info.path == "foos"
    assert info.parameters == {"value": ["1"]}
def test_path_conflict_with_variable_different_converters():
    class app(morepath.App):
        pass

    class A(object):
        pass

    class B(object):
        pass

    @app.path(model=A, path='a/{id}', converters=Converter(decode=int))
    def get_a(id):
        return A()

    @app.path(model=B, path='a/{id}')
    def get_b(id):
        return B()

    with pytest.raises(ConflictError):
        app.commit()
Exemple #22
0
def test_converter_registry_inheritance():
    r = ConverterRegistry()

    class Lifeform(object):
        def __init__(self, name):
            self.name = name

    class Animal(Lifeform):
        pass

    seaweed = Lifeform('seaweed')
    elephant = Animal('elephant')

    lifeforms = {
        'seaweed': seaweed,
        'elephant': elephant,
    }

    def lifeform_decode(s):
        try:
            return lifeforms[s]
        except KeyError:
            raise ValueError

    def lifeform_encode(l):
        return l.name

    c = Converter(lifeform_decode, lifeform_encode)
    r.register_converter(Lifeform, c)
    assert r.converter_for_type(Lifeform) is c
    assert r.converter_for_type(Animal) is c
    assert r.converter_for_value(Lifeform('seaweed')) is c
    assert r.converter_for_value(Animal('elephant')) is c
    assert r.converter_for_value(None) is IDENTITY_CONVERTER
    with pytest.raises(DirectiveError):
        assert r.converter_for_value('s') is None
    assert r.converter_for_type(Lifeform).decode(['elephant']) is elephant
    assert r.converter_for_type(Lifeform).encode(seaweed) == ['seaweed']
Exemple #23
0
def test_converter_equality():
    def decode():
        pass

    def encode():
        pass

    def other_encode():
        pass

    def other_decode():
        pass

    one = Converter(decode, encode)
    two = Converter(decode, encode)
    three = Converter(other_decode, other_encode)
    four = Converter(decode, other_encode)
    five = Converter(other_decode, encode)
    six = Converter(decode)

    l0 = ListConverter(one)
    l1 = ListConverter(one)
    l2 = ListConverter(two)
    l3 = ListConverter(three)

    assert one == two
    assert one != three
    assert one != four
    assert one != five
    assert one != six
    assert three != four
    assert four != five
    assert five != six

    assert one != l0
    assert l0 != one
    assert l0 == l1
    assert not l0 != l1
    assert l0 == l2
    assert l1 != l3
    assert not l1 == l3
Exemple #24
0
def test_single_parameter_int_default():
    get_parameters = ParameterFactory({"a": 0}, {"a": Converter(int)}, [])
    assert get_parameters(req("?a=1")) == {"a": 1}
    assert get_parameters(req("")) == {"a": 0}
    with pytest.raises(HTTPBadRequest):
        get_parameters(req("?a=A"))
Exemple #25
0
def test_single_parameter():
    get_parameters = ParameterFactory({"a": None}, {"a": Converter(str)}, [])
    assert get_parameters(req("?a=A")) == {"a": "A"}
    assert get_parameters(req("")) == {"a": None}
Exemple #26
0
 def date_converter():
     return Converter(date_decode, date_encode)
Exemple #27
0
def test_single_parameter():
    get_parameters = ParameterFactory({'a': None}, {'a': Converter(str)}, [])
    assert get_parameters(req('?a=A')) == {'a': 'A'}
    assert get_parameters(req('')) == {'a': None}
Exemple #28
0
 def get_converters():
     return dict(id=Converter(int))
Exemple #29
0
def test_single_parameter_int_default():
    get_parameters = ParameterFactory({'a': 0}, {'a': Converter(int)}, [])
    assert get_parameters(req('?a=1')) == {'a': 1}
    assert get_parameters(req('')) == {'a': 0}
    with pytest.raises(HTTPBadRequest):
        get_parameters(req('?a=A'))
Exemple #30
0
 def converter_for_type(self, t):
     return Converter(int)