Source

rpy2 / test_r.py

Full commit
import py
import r


def test_class():
    class Test(r.RPyObject):
        x = r.attribute(int)
        y = r.attribute(float)

    t = Test()
    assert t.x == t.y == 0
    assert type(t.x) is int
    assert type(t.y) is float
    t.x = 5
    assert t.x == 5
    py.test.raises(r.RPythonTypeError, "t.x = 1.0")
    py.test.raises(r.RPythonTypeError, "t.x = 'abc'")
    t.y = 5.6
    assert t.y == 5.6
    py.test.raises(r.RPythonTypeError, "t.y = 1")
    py.test.raises(r.RPythonTypeError, "t.y = 'abc'")


def test_subclass():
    class Test(r.RPyObject):
        x = r.attribute(int)
        y = r.attribute(float)

    class Sub(Test):
        z = r.attribute(Test)

    s = Sub()
    t = s.z = Test()
    t.x = 1
    t.y = 1.2
    s.x = 2
    s.y = 2.3
    assert s.z.x == 1
    assert s.z.y == 1.2
    assert s.x == 2
    assert s.y == 2.3


def test_class_referencing_class():
    class A(r.RPyObject):
        x = r.attribute(int)

    class ASub(A):
        y = r.attribute(float)

    class B(r.RPyObject):
        a = r.attribute(A)

    b = B()
    assert b.a is None
    a = b.a = A()
    a.x = 1
    assert a is b.a
    assert b.a.x == 1
    py.test.raises(r.RPythonTypeError, "b.a = 1")
    b.a = ASub()
    b.a.y = 1.2
    assert b.a.y == 1.2


def test_class_and_none():
    class A(r.RPyObject):
        x = r.attribute(int)

    class B(r.RPyObject):
        a = r.attribute(A)

    b = B()
    assert b.a is None
    a = b.a = A()
    assert b.a is a
    b.a = None
    assert b.a is None


def test_multiple_inheritance():
    class A(r.RPyObject):
        pass

    class B(object):
        pass

    class C(object):
        pass

    class D(r.RPyObject):
        pass
    py.test.raises(r.RPythonTypeError, "class ABC(A, B, C): pass")

    py.test.raises(r.RPythonTypeError, "class AD(A, D): pass")


def test_mixins():
    class A(r.RPyObject):
        pass

    class B(object):
        _mixin_ = True

    class C(r.RPyObject):
        _mixin_ = True
        a = r.attribute(int)

    class AC(A, C):
        pass

    py.test.raises(r.RPythonTypeError, "class AB(A, B): pass")

    assert hasattr(AC(), 'a')


def test_default_value():
    class A(r.RPyObject):
        x = r.attribute(int, default_value=41)
    a = A()
    assert a.x == 41


def test_immutable_attribute():
    class A(r.RPyObject):
        x = r.immutable_attribute(int)
    a = A()
    a.x = 31
    assert a.x == 31
    py.test.raises(r.RPythonTypeError, "a.x = 1")


def test_rpy_tuple():
    ttyp = r.get_rpy_type((int, int))
    assert r.get_rpy_type((int, int)) is ttyp
    ttyp.type_check((1, 2))
    py.test.raises(r.RPythonTypeError, ttyp.type_check, (1, "abc"))


def test_rpy_mixed_tuple():
    ttyp = r.get_rpy_type((int, float))
    assert r.get_rpy_type((int, float)) is ttyp
    ttyp.type_check((1, 2.0))
    py.test.raises(r.RPythonTypeError, ttyp.type_check, (1, "abc"))