Пример #1
0
def test_large_dict(sheraf_database):
    with sheraf.connection(commit=True) as c:
        c.root.dict = sheraf.types.LargeDict()
        for i in range(100):
            c.root.dict[i] = str(i)

    with sheraf.connection() as c:
        assert c.root.dict[50] == "50"
        with pytest.raises(KeyError):
            c.root.dict[-1]
        assert 25 in c.root.dict
        assert 100 == len(c.root.dict)

    with sheraf.connection() as c:
        assert list(c.root.dict[98:]) == ["98", "99"]
        assert list(c.root.dict[12:14]) == ["12", "13", "14"]
        assert list(c.root.dict[:4]) == ["0", "1", "2", "3", "4"]
        assert list(c.root.dict[:]) == [str(i) for i in range(100)]

    with sheraf.connection() as c:
        assert list(c.root.dict[98::-1]) == ["99", "98"]
        assert list(c.root.dict[:3:-1]) == ["3", "2", "1", "0"]
        assert list(c.root.dict[10:12:-1]) == ["12", "11", "10"]

        assert list(c.root.dict[90:94:2]) == ["90", "92", "94"]
Пример #2
0
def test_threading(self, sheraf_database):
    with sheraf.connection(commit=True) as c:
        c.root.list = sheraf.types.LargeList()

    class Writer(threading.Thread):
        def __init__(self, name):
            super().__init__()
            self.failed = False
            self.name = name

        def run(self):
            try:
                with sheraf.connection() as c:
                    for i in range(LENGTH):
                        sheraf.attempt(
                            lambda: c.root.list.append(self.name + str(i)),
                            attempts=10)
            except BaseException as ex:
                self.failed = ex

    writers = [Writer(i) for i in THREADS]
    [w.start() for w in writers]

    [w.join() for w in writers]
    for w in (w for w in writers if w.failed):
        assert not w.failed

    with sheraf.connection() as c:
        assert len(c.root.list) == len(THREADS) * LENGTH
        for name in THREADS:
            for i in range(LENGTH):
                assert str(name) + str(i) in c.root.list
Пример #3
0
def test_edit_a_not_single_instance_after_set_index_in_one_of_two_attributes(
    sheraf_database,
):
    class Model(tests.UUIDAutoModel):
        my_simple_attribute = sheraf.SimpleAttribute()
        my_other_attribute = sheraf.SimpleAttribute()

    with sheraf.connection(commit=True):
        m = Model.create(
            my_simple_attribute="foo_not_indexed", my_other_attribute="other1"
        )
        # Having more than one instance must prevent indexation
        Model.create(
            my_simple_attribute="foo_not_indexed2", my_other_attribute="other2"
        )

    class Model(tests.UUIDAutoModel):
        my_simple_attribute = sheraf.SimpleAttribute().index()

    with sheraf.connection(commit=True):
        m = Model.read(m.id)
        with warnings.catch_warnings(record=True) as warning_messages:
            m.my_other_attribute = "new_other1"
            m.my_simple_attribute = "bar_still_not_indexed"
            assert "my_simple_attribute will not be indexed." in str(
                warning_messages[0].message
            )

    with sheraf.connection() as conn:
        assert "my_simple_attribute" not in conn.root()["model"]
        assert "my_other_attribute" not in conn.root()["model"]
Пример #4
0
def test_healthcheck_attributes_index_non_primitive_with_key(
        sheraf_database, capsys):
    from .fixture1 import Model3k, DummyModel

    with sheraf.connection(commit=True) as conn:
        Model3k.create(simple="simple1",
                       obj_indexed=DummyModel.create(v="str1"))
        Model3k.create(simple="simple2",
                       obj_indexed=DummyModel.create(v="str2"))

        index_table = conn.root()["model3k_table"]["obj"]
        del index_table["str1"]

    with sheraf.connection() as conn:
        assert "str1" not in conn.root()["model3k_table"]["obj"]
        assert "str2" in conn.root()["model3k_table"]["obj"]

        health = check_health(fixture1,
                              instance_checks=[],
                              attribute_checks=["index"
                                                ])["check_attributes_index"]

        assert {
            "obj": {
                "ok": 1,
                "ko": 1
            }
        } == health["tests.health.fixture1.Model3k"]

        print_health(fixture1)
        stdout = capsys.readouterr().out
        assert re.search(r"tests.health.fixture1.Model3k[^\n]*1[^\n]*1",
                         stdout)
Пример #5
0
def test_healthcheck_attributes_index_when_instance_deleted(
        sheraf_database, capsys):
    from .fixture1 import Model2unique

    with sheraf.connection(commit=True) as conn:
        Model2unique.create(simple="simple1", str_indexed="str1")
        Model2unique.create(simple="simple1", str_indexed="str2")
        m = Model2unique.create(simple="simple2", str_indexed="str3")
        mmapping = sheraf.types.SmallDict(m.mapping)
        m.delete()
        index_table = conn.root()["model2unique_table"]["str_indexed"]
        index_table["str3"] = mmapping

    with sheraf.connection() as conn:
        kwargs = dict(model_checks=["index"],
                      instance_checks=[],
                      attribute_checks=[])

        assert "str1" in conn.root()["model2unique_table"]["str_indexed"]
        assert "str2" in conn.root()["model2unique_table"]["str_indexed"]
        health = check_health(fixture1, **kwargs)["check_model_index"]

        assert {
            "str_indexed": {
                "ok": 2,
                "ko": 1
            }
        } == health["tests.health.fixture1.Model2unique"]

        print_health(fixture1, **kwargs)
        stdout = capsys.readouterr().out
        assert re.search(r"tests.health.fixture1.Model2unique[^\n]*1[^\n]*2",
                         stdout)
Пример #6
0
def test_multiple_keys_index_update(sheraf_database, Model):
    with sheraf.connection(commit=True):
        mfoo = Model.create(my_attribute="bar")

    with sheraf.connection(commit=True):
        mfoo = Model.read(mfoo.id)
        mfoo.my_attribute = "foo"

    with sheraf.connection() as conn:
        index_table_key_1 = conn.root()[Model.table]["key_1"]
        index_table_key_2 = conn.root()[Model.table]["key_2"]
        assert {"foo"} == set(index_table_key_1)
        assert {mfoo.raw_identifier: mfoo.mapping} == dict(index_table_key_1["foo"])
        assert {"foo"} == set(index_table_key_2)
        assert {mfoo.raw_identifier: mfoo.mapping} == dict(index_table_key_2["foo"])

        with pytest.raises(sheraf.exceptions.MultipleIndexException):
            Model.read(key_1="foo")
        assert [mfoo] == list(Model.read_these(key_1=["foo"]))

        with pytest.raises(sheraf.exceptions.MultipleIndexException):
            Model.read(key_2="foo")
        assert [mfoo] == list(Model.read_these(key_2=["foo"]))

        # Model._read_multiple_index = mock.MagicMock(
        #    side_effect=Model._read_multiple_index
        # )
        assert [mfoo] == Model.filter(key_1="foo")
        # Model._read_multiple_index.assert_has_calls(
        #    [mock.call("foo", "key_1")]
        # )

        assert [mfoo] == Model.filter(key_2="foo")
Пример #7
0
def test_common_index_different_values_methods(sheraf_database, Model):
    assert Model.indexes["theindex"].details.values_funcs[Model.lower] == [
        [Model.attributes["foo"]]
    ]
    assert Model.indexes["theindex"].details.values_funcs[Model.upper] == [
        [Model.attributes["bar"]]
    ]
    assert Model.indexes["theindex"].details.values_funcs[None] == []
    assert Model.indexes["theindex"].details.default_values_func is None
    assert Model.indexes["theindex"].details.search_func is None

    with sheraf.connection(commit=True) as conn:
        m = Model.create(foo="FOo", bar="bAr")

    with sheraf.connection() as conn:
        index_table = conn.root()[Model.table]["theindex"]
        assert {"foo", "BAR"} == set(index_table)
        assert {m.raw_identifier: m.mapping} == dict(index_table["foo"])
        assert {m.raw_identifier: m.mapping} == dict(index_table["BAR"])

        assert [m] == list(Model.read_these(theindex=["foo"]))
        assert [m] == list(Model.read_these(theindex=["BAR"]))

        assert [m] == Model.search(theindex="foo")
        assert [m] == Model.search(theindex="BAR")

        assert [] == Model.search(theindex="FOo")
        assert [] == Model.search(theindex="bAr")
Пример #8
0
def test_generic_nominal_case(sheraf_database):
    class Model(tests.UUIDAutoModel):
        submodel = sheraf.ModelAttribute((Submodel1, Submodel2))

    with sheraf.connection(commit=True):
        s1 = Submodel1.create(name="foo")
        s2 = Submodel2.create(name="bar")

        m1 = Model.create(submodel=s1)
        m2 = Model.create(submodel=s2)

        assert (Submodel1.table, s1.id) == m1.mapping["submodel"]
        assert (Submodel2.table, s2.id) == m2.mapping["submodel"]

        assert "foo" == m1.submodel.name
        assert "bar" == m2.submodel.name

    with sheraf.connection():
        m1 = Model.read(m1.id)
        m2 = Model.read(m2.id)

        assert isinstance(m1.submodel, Submodel1)
        assert isinstance(m2.submodel, Submodel2)

        assert "foo" == m1.submodel.name
        assert "bar" == m2.submodel.name
Пример #9
0
def test_update_no_addition(sheraf_database):
    class Model(tests.UUIDAutoModel):
        inlines = sheraf.LargeDictAttribute(
            sheraf.InlineModelAttribute(DictInlineModel))

    with sheraf.connection(commit=True):
        model = Model.create(inlines={"a": {"name": "a"}})

    with sheraf.connection(commit=True):
        model.edit(value={"inlines": {"b": {"name": "b"}}}, addition=True)

        assert isinstance(model.mapping["inlines"], sheraf.types.LargeDict)
        assert isinstance(model.inlines["b"], DictInlineModel)
        assert isinstance(model.inlines["b"].mapping, sheraf.types.SmallDict)
        assert "a" == model.inlines["a"].name
        assert "b" == model.inlines["b"].name

    with sheraf.connection():
        model = Model.read(model.id)

        assert isinstance(model.mapping["inlines"], sheraf.types.LargeDict)
        assert isinstance(model.inlines["b"], DictInlineModel)
        assert isinstance(model.inlines["b"].mapping, sheraf.types.SmallDict)
        assert "a" == model.inlines["a"].name
        assert "b" == model.inlines["b"].name
Пример #10
0
def test_update_edition(sheraf_database, attribute, list_type):
    class Model(tests.UUIDAutoModel):
        inlines = attribute(sheraf.InlineModelAttribute(ListInlineModel))

    with sheraf.connection(commit=True):
        model = Model.create(inlines=[{"name": "c"}, {"name": "c"}])

    with sheraf.connection(commit=True):
        model.edit(value={"inlines": [{
            "name": "a"
        }, {
            "name": "b"
        }]},
                   edition=True)

        assert isinstance(model.mapping["inlines"], list_type)
        assert isinstance(model.inlines[0], ListInlineModel)
        assert isinstance(model.inlines[1], ListInlineModel)
        x, y = list(model.inlines)
        assert "a" == x.name
        assert "b" == y.name

    with sheraf.connection():
        model = Model.read(model.id)

        assert isinstance(model.mapping["inlines"], list_type)
        assert isinstance(model.inlines[0], ListInlineModel)
        assert isinstance(model.inlines[1], ListInlineModel)
        x, y = list(model.inlines)
        assert "a" == x.name
        assert "b" == y.name
Пример #11
0
def test_update_no_addition(sheraf_database, attribute, list_type):
    class Model(tests.UUIDAutoModel):
        inlines = attribute(sheraf.InlineModelAttribute(ListInlineModel))

    with sheraf.connection(commit=True):
        model = Model.create(inlines=[{"name": "a"}])

    with sheraf.connection(commit=True):
        model.edit(value={"inlines": [{
            "name": "a"
        }, {
            "name": "b"
        }]},
                   addition=False)

        assert isinstance(model.mapping["inlines"], list_type)
        assert "a" == model.inlines[0].name
        assert len(model.inlines) == 1

    with sheraf.connection():
        model = Model.read(model.id)

        assert isinstance(model.mapping["inlines"], list_type)
        assert "a" == model.inlines[0].name
        assert len(model.inlines) == 1
Пример #12
0
def test_update_edition(sheraf_database):
    class Model(tests.UUIDAutoModel):
        models = sheraf.LargeDictAttribute(sheraf.ModelAttribute(AModel))

    with sheraf.connection(commit=True):
        model = Model.create(models={"a": {"name": "c"}, "b": {"name": "c"}})
        last_sub_id = model.models["a"].id

    with sheraf.connection(commit=True):
        model.edit(value={"models": {"a": {"name": "a"}, "b": {"name": "b"}}})

        assert isinstance(model.models["a"], AModel)
        assert isinstance(model.models["b"], AModel)
        assert "a" == model.models["a"].name
        assert "b" == model.models["b"].name
        assert last_sub_id == model.models["a"].id

    with sheraf.connection():
        model = Model.read(model.id)

        assert isinstance(model.models["a"], AModel)
        assert isinstance(model.models["b"], AModel)
        assert "a" == model.models["a"].name
        assert "b" == model.models["b"].name
        assert last_sub_id == model.models["a"].id
Пример #13
0
def test_update_replacement(sheraf_database):
    class Model(tests.UUIDAutoModel):
        models = sheraf.LargeDictAttribute(sheraf.ModelAttribute(AModel))

    with sheraf.connection(commit=True):
        model = Model.create(models={"a": {"name": "c"}, "b": {"name": "c"}})
        last_sub_id = model.models["a"].id

    with sheraf.connection(commit=True):
        old_submapping = model.models["a"].mapping
        model.edit(
            value={"models": {"a": {"name": "a"}, "b": {"name": "b"}}},
            edition=True,
            replacement=True,
        )
        new_submapping = model.models["a"].mapping

        assert isinstance(model.mapping["models"], sheraf.types.LargeDict)
        assert isinstance(model.models["a"], AModel)
        assert isinstance(new_submapping, sheraf.types.SmallDict)
        assert "a" == model.models["a"].name
        assert "b" == model.models["b"].name
        assert old_submapping is not new_submapping
        assert last_sub_id != model.models["a"].id

    with sheraf.connection():
        model = Model.read(model.id)

        assert isinstance(model.mapping["models"], sheraf.types.LargeDict)
        assert isinstance(model.models["a"], AModel)
        assert isinstance(new_submapping, sheraf.types.SmallDict)
        assert "a" == model.models["a"].name
        assert "b" == model.models["b"].name
        assert old_submapping is not new_submapping
        assert last_sub_id != model.models["a"].id
Пример #14
0
def test_rebuild_all_models_one_index(sheraf_zeo_database):
    with sheraf.connection(commit=True) as conn:
        bar = CliModel.create(foo="bar", boo="bar")
        baz = CliModel.create(foo="baz", boo="baz")
        del conn.root()[CliModel.table]["foo"]
        del conn.root()[CliModel.table]["boo"]

    runner = CliRunner()
    result = runner.invoke(
        cli,
        [
            f"{sheraf_zeo_database.uri}&database_name=cli",
            "rebuild",
            "tests.test_cli",
            "--indexes",
            "foo",
        ],
    )
    assert result.exit_code == 0, result.output

    with sheraf.connection() as conn:
        assert "foo" in conn.root()[CliModel.table]
        assert "boo" not in conn.root()[CliModel.table]
        assert bar in CliModel.search(foo="bar")
        assert baz in CliModel.search(foo="baz")
Пример #15
0
def test_common_index_complex(sheraf_database):
    class Model(tests.IntAutoModel):
        foo = sheraf.SimpleAttribute()
        bar = sheraf.SimpleAttribute()
        theindex = sheraf.Index(foo, bar)

        @theindex.values
        def values(self, value):
            return {value.lower(), value.upper()}

    with sheraf.connection(commit=True) as conn:
        m = Model.create(foo="foo", bar="bar")
        assert {"foo", "bar", "FOO", "BAR"} == set(conn.root()[Model.table]["theindex"])

        m.bar = "baz"
        assert {"foo", "baz", "FOO", "BAZ"} == set(conn.root()[Model.table]["theindex"])

    with sheraf.connection(commit=True) as conn:
        m = Model.read(m.id)
        assert {"foo", "baz", "FOO", "BAZ"} == set(conn.root()[Model.table]["theindex"])

        m.foo = "OOF"
        assert {"oof", "baz", "OOF", "BAZ"} == set(conn.root()[Model.table]["theindex"])

        del m.foo
        assert {"baz", "BAZ"} == set(conn.root()[Model.table]["theindex"])
Пример #16
0
def test_datetime_lastupdate_datetime(sheraf_database):
    sheraf_database.reset()

    class Model(tests.UUIDAutoModel):
        pass

    with libfaketime.fake_time("2014-08-04 02:00:00") as fk:
        with sheraf.connection(commit=True) as conn:
            m = Model.create()
            fk.tick()
            assert m.last_update_datetime() is None
            conn.transaction_manager.commit()
            assert datetime.datetime(2014, 8, 4, 2, 0,
                                     1) == m.last_update_datetime()

    with sheraf.connection():
        m = Model.read(m.id)
        assert datetime.datetime(2014, 8, 4, 2, 0,
                                 1) == m.last_update_datetime()

    with libfaketime.fake_time("2014-08-04 08:00:00") as fk:
        with sheraf.connection(commit=True) as conn:
            m = Model.read(m.id)
            m.save()
            fk.tick()
            assert datetime.datetime(2014, 8, 4, 2, 0,
                                     1) == m.last_update_datetime()
            conn.transaction_manager.commit()
            assert datetime.datetime(2014, 8, 4, 8, 0,
                                     1) == m.last_update_datetime()
Пример #17
0
def test_index_table_rebuild(sheraf_database):
    class Model(tests.UUIDAutoModel):
        foo = sheraf.SimpleAttribute()
        bar = sheraf.SimpleAttribute()

    with sheraf.connection(commit=True):
        Model.create(foo="bar", bar="bar")
        Model.create(foo="baz", bar="bor")

    class Model(tests.UUIDAutoModel):
        foo = sheraf.SimpleAttribute().index()
        bar = sheraf.SimpleAttribute().index()

    with sheraf.connection(commit=True):
        with warnings.catch_warnings(record=True) as warns:
            Model.create(foo="foobar", bar="bur")
            assert warns[0].category is sheraf.exceptions.IndexationWarning
            assert warns[1].category is sheraf.exceptions.IndexationWarning

    with sheraf.connection(commit=True):
        Model.index_table_rebuild()

    with sheraf.connection(commit=True):
        assert 3 == Model.count()

        with warnings.catch_warnings(record=True) as warns:
            Model.create(foo="foobar", bar="boo")
            assert not warns
Пример #18
0
def test_time_attribute(sheraf_database):
    class Model(tests.UUIDAutoModel):
        time = sheraf.TimeAttribute()

    with sheraf.connection(commit=True):
        m = Model.create()
        assert m.time is None

        m.time = datetime.time(12, 13, 14)
        assert m.mapping["time"] == 43994000000
        assert m.time == datetime.time(12, 13, 14)

    with sheraf.connection():
        m = Model.read(m.id)

        m.time = datetime.time(12, 13, 14)
        assert m.mapping["time"] == 43994000000
        assert m.time == datetime.time(12, 13, 14)

    with sheraf.connection(commit=True):
        m = Model.read(m.id)
        m.time = None

        assert m.time is None
        assert m.mapping["time"] == -1

    with sheraf.connection():
        m = Model.read(m.id)

        assert m.time is None
        assert m.mapping["time"] == -1
Пример #19
0
def test_custom_indexation_method(sheraf_database, Model):
    with sheraf.connection(commit=True):
        m = Model.create(foo="FOO", bar="BAR")
        func = Model.indexes["foo"].details.default_values_func
        assert func is not None
        assert {"foo"} == Model.indexes["foo"].details.get_values(
            m, [Model.attributes["foo"]], func
        )

    with sheraf.connection() as conn:
        index_table = conn.root()[Model.table]["foo"]
        assert {"foo"} == set(index_table)
        assert m.mapping == index_table["foo"]

        assert [m] == list(Model.filter(foo="foo"))
        assert [] == list(Model.filter(foo="FOO"))

        assert [m] == list(Model.filter(foo="foo", bar="BAR"))
        assert [] == list(Model.filter(foo="foo", bar="bar"))

        assert [m] == list(Model.search(foo="foo"))
        assert [m] == list(Model.search(foo="FOO"))

        assert [m] == list(Model.search(foo="foo", bar="BAR"))
        assert [m] == list(Model.search(foo="FOO", bar="BAR"))

        assert [] == list(Model.search(foo="foo", bar="bar"))
        assert [] == list(Model.search(foo="FOO", bar="bar"))

    with sheraf.connection():
        with pytest.raises(sheraf.exceptions.UniqueIndexException):
            Model.create(foo="FOO")
Пример #20
0
def test_date_attribute(sheraf_database):
    class Model(tests.UUIDAutoModel):
        date = sheraf.DateAttribute()

    with sheraf.connection(commit=True):
        m = Model.create()
        assert m.date is None

        m.date = datetime.date(1971, 1, 1)
        assert m.mapping["date"] == 365
        assert m.date == datetime.date(1971, 1, 1)

    with sheraf.connection():
        m = Model.read(m.id)

        m.date = datetime.date(1971, 1, 1)
        assert m.mapping["date"] == 365
        assert m.date == datetime.date(1971, 1, 1)

    with sheraf.connection(commit=True):
        m = Model.read(m.id)
        m.date = None

        assert m.date is None
        assert m.mapping["date"] == -1

    with sheraf.connection():
        m = Model.read(m.id)

        assert m.date is None
        assert m.mapping["date"] == -1
Пример #21
0
def test_healthcheck_attributes_index_with_key(sheraf_database, capsys):
    from .fixture1 import Model2kunique

    with sheraf.connection(commit=True) as conn:
        Model2kunique.create(simple="simple1", str_indexed="str1")
        Model2kunique.create(simple="simple2", str_indexed="str2")
        index_table = conn.root()["model2kunique_table"]["str"]
        del index_table["str1"]

    with sheraf.connection() as conn:
        kwargs = dict(instance_checks=[], attribute_checks=["index"])

        assert "str1" not in conn.root()["model2kunique_table"]["str"]
        assert "str2" in conn.root()["model2kunique_table"]["str"]
        health = check_health(fixture1, **kwargs)["check_attributes_index"]

        assert {
            "str": {
                "ok": 1,
                "ko": 1
            }
        } == health["tests.health.fixture1.Model2kunique"]

        print_health(fixture1, **kwargs)
        stdout = capsys.readouterr().out
        assert re.search(r"tests.health.fixture1.Model2kunique[^\n]*1[^\n]*1",
                         stdout)
Пример #22
0
def test_make_id(sheraf_database, db2):
    class Model(tests.UUIDAutoModel):
        pass

    class ModelWithProposeId(Model):
        table = "modelwithproposeid"
        id = sheraf.IntegerAttribute(default=lambda m: m.count()).index(primary=True)

    with sheraf.connection(commit=True):
        m0 = ModelWithProposeId.create()
        m1 = ModelWithProposeId.create()
        assert m0.id == 0
        assert m1.id == 1

    class Model(tests.UUIDAutoModel):
        database_name = "db2"

    class ModelWithProposeId(Model):
        table = "modelwithproposeid"
        id = sheraf.IntegerAttribute(default=lambda m: m.count()).index(primary=True)

    with sheraf.connection() as conn:
        root1 = conn.root()
        root2 = conn.get_connection("db2").root()

        m2 = ModelWithProposeId.create()
        m3 = ModelWithProposeId.create()
        assert m2.id == 2
        assert m3.id == 3

        assert root1["modelwithproposeid"]["id"][m1.id] is m1.mapping
        assert root2["modelwithproposeid"]["id"][m2.id] is m2.mapping
Пример #23
0
def test_multiple_healthcheck_attributes_index_when_instance_deleted(
        sheraf_database, capsys):
    from .fixture1 import Model2

    with sheraf.connection(commit=True) as conn:
        Model2.create(simple="simple1", str_indexed="str1")
        index_table = conn.root()["model2_table"]["str_indexed"]
        m21 = Model2.create(simple="simple21", str_indexed="str2")
        m22 = Model2.create(simple="simple22", str_indexed="str2")
        m21_deletedmapping = sheraf.types.SmallDict(m21.mapping)
        assert dict(index_table["str2"]) == {
            m21.raw_identifier: m21.mapping,
            m22.raw_identifier: m22.mapping,
        }
        m21.delete()
        index_table["str2"] = {
            m21.raw_identifier: m21_deletedmapping,
            m22.raw_identifier: m22.mapping,
        }

    with sheraf.connection() as conn:
        kwargs = dict(model_checks=["index"],
                      instance_checks=[],
                      attribute_checks=[])

        assert "str1" in conn.root()["model2_table"]["str_indexed"]
        assert "str2" in conn.root()["model2_table"]["str_indexed"]
        health = check_health(fixture1, **kwargs)["check_model_index"]

        assert {
            "str_indexed": {
                "ok": 1,
                "ko": 1
            }
        } == health["tests.health.fixture1.Model2"]
Пример #24
0
def test_model_create_in_default_connection(sheraf_database, db2):
    class Model(tests.UUIDAutoModel):
        pass

    class MyDefaultModel(tests.UUIDAutoModel):
        database_name = "unnamed"

    class MyDB2Model(tests.UUIDAutoModel):
        database_name = "db2"

    with sheraf.connection(commit=True) as connection:
        rootd = connection.root()
        m = Model.create()
        md = MyDefaultModel.create()
        m2 = MyDB2Model.create()

    with sheraf.connection() as connection:
        rootd = connection.root()
        root2 = connection.get_connection("db2").root()

        assert m.id in rootd[Model.table]["id"]
        assert md.id in rootd[MyDefaultModel.table]["id"]
        assert m2.id in root2[MyDB2Model.table]["id"]

        assert Model.table not in root2
        assert MyDefaultModel.table not in root2
        assert MyDB2Model.table not in rootd
Пример #25
0
def check_conflict_resolution():
    """
    Checks wether sheraf object conflicts resolutions are possible.
    When this is KO, it is generally because sheraf is not installed in the ZEO
    environnement, so ZEO cannot solve sheraf object conflicts.
    """
    table_name = "__conflict_resolution_test_model__"
    nestable = sheraf.Database.get().nestable
    sheraf.Database.get().nestable = True

    class TestModel(sheraf.Model):
        table = table_name
        counter = sheraf.CounterAttribute(default=0)

    with sheraf.connection(commit=True):
        m = TestModel.create()

    try:
        with sheraf.connection(commit=True):
            TestModel.read(m.identifier).counter.increment(1)

            with sheraf.connection(commit=True):
                TestModel.read(m.identifier).counter.increment(15)

    except ZODB.POSException.ConflictError:  # pragma: no cover
        return False

    else:
        return True

    finally:
        with sheraf.connection(commit=True) as conn:
            del conn.root()[table_name]

        sheraf.Database.get().nestable = nestable
Пример #26
0
def test_model_with_database_name_specified(sheraf_database, db2):
    class Db2Model(tests.UUIDAutoModel):
        database_name = "db2"

    with sheraf.connection(commit=True):
        m = Db2Model.create()
        n = Db2Model.create()

    with sheraf.connection() as connection:
        assert m.id not in connection.root().get(Db2Model.table, {})

        connection_2 = connection.get_connection("db2")
        assert connection_2.root()[Db2Model.table]["id"][m.id] is m.mapping
        assert Db2Model.read(m.id) == m
        assert Db2Model.count() == 2
        assert m in Db2Model.all()
        assert n in Db2Model.all()

        m.delete()
        assert m.id not in connection_2.root()[Db2Model.table]["id"]
        assert Db2Model.count() == 1

        n.delete()
        assert Db2Model not in connection_2.root()
        assert Db2Model.count() == 0
Пример #27
0
def test_edit_a_not_single_instance_when_two_indexes_with_key_afterwards(
    sheraf_database,
):
    class Model(tests.UUIDAutoModel):
        my_simple_attribute = sheraf.SimpleAttribute()

    with sheraf.connection(commit=True):
        m = Model.create(my_simple_attribute="foo_not_indexed")
        Model.create(my_simple_attribute="foo_not_indexed2")

    class Model(tests.UUIDAutoModel):
        my_simple_attribute = (
            sheraf.SimpleAttribute()
            .index(key="key1")
            .index(key="key2", values=lambda x: x)
        )

    with sheraf.connection(commit=True):
        m = Model.read(m.id)
        with warnings.catch_warnings(record=True) as warning_messages:
            m.my_simple_attribute = "bar_still_not_indexed"
            assert any(
                "key1 will not be indexed." in str(w.message) for w in warning_messages
            )

    with sheraf.connection() as conn:
        assert "key1" not in conn.root()["model"]
        assert "key2" not in conn.root()["model"]
Пример #28
0
def test_nested(sheraf_database, persistent_type, subattribute):
    class Model(tests.UUIDAutoModel):
        list = sheraf.ListAttribute(
            attribute=sheraf.ListAttribute(attribute=subattribute,
                                           persistent_type=persistent_type),
            persistent_type=persistent_type,
        )

    with sheraf.connection(commit=True):
        m = Model.create(list=[[0, 1], [2, 3]])

        assert 0 == m.list[0][0]
        assert 1 == m.list[0][1]
        assert 2 == m.list[1][0]
        assert 3 == m.list[1][1]
        assert isinstance(m.mapping["list"], persistent_type)
        assert isinstance(m.mapping["list"][0], persistent_type)
        assert [0, 1] == list(m.list[0])

    with sheraf.connection(commit=True):
        m = Model.read(m.id)

        assert 0 == m.list[0][0]
        assert 1 == m.list[0][1]
        assert 2 == m.list[1][0]
        assert 3 == m.list[1][1]
        assert isinstance(m.mapping["list"], persistent_type)
        assert isinstance(m.mapping["list"][0], persistent_type)
        assert [0, 1] == list(m.list[0])
Пример #29
0
def test_multiprocessing_float_conflict_resolution(sheraf_zeo_database):
    class FloatModel(tests.UUIDAutoModel):
        counter = sheraf.CounterAttribute(default=0.5)

    def process(uri, model_id, barrier, addition):
        sheraf.Database(uri)

        with sheraf.connection(commit=True):
            m = FloatModel.read(model_id)
            barrier.wait()
            m.counter.increment(addition)

    with sheraf.connection(commit=True):
        m = FloatModel.create()

    nb_process = 3
    barrier = multiprocessing.Barrier(nb_process)
    processes = [
        multiprocessing.Process(target=process,
                                args=(sheraf_zeo_database.uri, m.id, barrier,
                                      i + 0.5)) for i in range(0, nb_process)
    ]

    for process in processes:
        process.start()

    for process in processes:
        process.join(timeout=10)
        assert 0 == process.exitcode

    with sheraf.connection():
        m = FloatModel.read(m.id)
        assert 0.5 + sum(i + 0.5 for i in range(0, nb_process)) == m.counter
Пример #30
0
def test_integer_tuple(sheraf_database):
    with sheraf.connection(commit=True) as c:
        c.root.dict = sheraf.types.LargeDict()
        for x in range(10):
            for y in range(10):
                c.root.dict[(x, y)] = str(x) + "-" + str(y)

    with sheraf.connection() as c:
        assert c.root.dict[(5, 0)] == "5-0"
        with pytest.raises(KeyError):
            c.root.dict[(100, 100)]
        assert (2, 5) in c.root.dict
        assert 100 == len(c.root.dict)

    with sheraf.connection() as c:
        assert list(c.root.dict[(9, 8):]) == ["9-8", "9-9"]
        assert list(c.root.dict[(1, 2):(1, 4)]) == ["1-2", "1-3", "1-4"]
        assert list(c.root.dict[:(0,
                                  4)]) == ["0-0", "0-1", "0-2", "0-3", "0-4"]
        assert list(c.root.dict[:]) == [
            str(x) + "-" + str(y) for x in range(10) for y in range(10)
        ]

    with sheraf.connection() as c:
        assert list(c.root.dict[(9, 8)::-1]) == ["9-9", "9-8"]
        assert list(c.root.dict[:(0, 3):-1]) == ["0-3", "0-2", "0-1", "0-0"]
        assert list(c.root.dict[(1, 0):(1, 2):-1]) == ["1-2", "1-1", "1-0"]
        assert list(c.root.dict[(9, 0):(9, 4):2]) == ["9-0", "9-2", "9-4"]