Beispiel #1
0
async def test_repo_loads_from_db():
    """Измененная таблица сохраняется в базу данных один раз из нескольких репо."""
    session = FakeSession([outer.TableTuple(*TABLE_NAME, DF, TIMESTAMP)])
    store = repo.Repo(session)
    table = await store.get_table(TABLE_NAME)

    assert isinstance(table, model.Table)
    assert table.name == TABLE_NAME
    pd.testing.assert_frame_equal(table.df, DF)
    assert table.timestamp == TIMESTAMP
Beispiel #2
0
    async def get(self,
                  table_name: outer.TableName) -> Optional[outer.TableTuple]:
        """Извлекает документ из коллекции."""
        collection, name = _collection_and_name(table_name)
        doc = await self._db[collection].find_one({"_id": name})

        if doc is None:
            return None

        df = pd.DataFrame(**doc["data"])
        return outer.TableTuple(*table_name, df=df, timestamp=doc["timestamp"])
Beispiel #3
0
        outer.DIVIDENDS: _DIVIDENDS,
        outer.CPI: _CPI,
        outer.SECURITIES: _SECURITIES,
        outer.INDEX: _INDEX,
        outer.QUOTES: _QUOTES,
    }, )


def create_table(name: outer.TableName) -> model.Table:
    """Создает пустую новую таблицу."""
    return model.Table(name=name, desc=_TABLES_REGISTRY[name.group])


def recreate_table(table_tuple: outer.TableTuple) -> model.Table:
    """Создает таблицу на основе данных и обновляет ее."""
    name = outer.TableName(table_tuple.group, table_tuple.name)
    return model.Table(name, _TABLES_REGISTRY[name.group], table_tuple.df,
                       table_tuple.timestamp)


def convent_to_tuple(table: model.Table) -> outer.TableTuple:
    """Конвертирует таблицу в кортеж."""
    group, name = table.name
    if (timestamp := table.timestamp) is None:
        raise outer.DataError(
            f"Попытка сериализации пустой таблицы {table.name}")
    return outer.TableTuple(group=group,
                            name=name,
                            df=table.df,
                            timestamp=timestamp)
Beispiel #4
0
"""Тесты для фабрик по созданию таблиц и их сериализации."""
from datetime import datetime

import pandas as pd
import pytest

from poptimizer.data.domain import factories, model
from poptimizer.data.ports import outer

TABLE_NAME = outer.TableName(outer.QUOTES, "VSMO")
TABLE_VARS = outer.TableTuple(
    TABLE_NAME.group,
    TABLE_NAME.name,
    pd.DataFrame([1]),
    datetime.utcnow(),
)


def test_create_table():
    """У новой таблицы не должно быть данных и времени обновления."""
    table = factories.create_table(TABLE_NAME)

    assert isinstance(table, model.Table)
    assert table.df is None
    assert table.timestamp is None


def test_recreate_table():
    """У таблицы должны быть переданные значения данных и времени обновления.

    Данные должны возвращаться копией.
Beispiel #5
0
import pytest

from poptimizer.data.adapters import db
from poptimizer.data.config import resources
from poptimizer.data.ports import outer

DF = pd.DataFrame(
    [[5, 6], [6, 7]],
    columns=["s", "f"],
    index=["r", "g"],
)
TIMESTAMP = datetime.utcnow()
TIMESTAMP = TIMESTAMP.replace(microsecond=(TIMESTAMP.microsecond // 1000) *
                              1000)
TABLE_NAME = outer.TableName(outer.SECURITIES, outer.SECURITIES)
TABLE_TUPLE = outer.TableTuple(outer.SECURITIES, outer.SECURITIES, DF,
                               TIMESTAMP)

NAME_CASES = (
    [
        outer.TableTuple(outer.QUOTES, "VTBR", DF, TIMESTAMP), outer.QUOTES,
        "VTBR"
    ],
    [outer.TableName(outer.QUOTES, "HYDR"), outer.QUOTES, "HYDR"],
    [TABLE_TUPLE, db.MISC, outer.SECURITIES],
    [TABLE_NAME, db.MISC, outer.SECURITIES],
)


@pytest.mark.parametrize("table_name, collection, name", NAME_CASES)
def test_collection_and_name(table_name, collection, name):
    """Тестирование комбинации двух пар случаев.