File: test_io_order.py

package info (click to toggle)
python-cobra 0.29.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,512 kB
  • sloc: python: 14,703; xml: 12,841; makefile: 137; sh: 32
file content (132 lines) | stat: -rw-r--r-- 4,133 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""Test functionalities of I/O in an usage order."""

import logging
from operator import attrgetter
from pathlib import Path
from random import sample
from typing import Iterable, List

import pytest

from cobra import DictList, Model
from cobra import io as cio


logger = logging.getLogger(__name__)


@pytest.fixture(scope="module")
def tmp_path_order(tmp_path_factory: Path) -> Path:
    """Temporary path for I/O order tests."""
    return tmp_path_factory.mktemp("model_order")


@pytest.fixture(scope="module")
def minimized_shuffle(small_model: Model) -> Model:
    """Generate a minimal shuffled model for I/O order tests."""
    model = small_model.copy()
    chosen = sample(list(set(model.reactions) - set(model.exchanges)), 10)
    new = Model("minimized_shuffle")
    new.add_reactions(chosen)
    logger.debug(
        f"'{new.id}' has {new.metabolites} metabolites, {new.reactions} reactions, and "
        f"{new.genes} genes."
    )
    return new


@pytest.fixture(scope="module")
def minimized_sorted(minimized_shuffle: Model) -> Model:
    """Generate a minimal sorted model for I/O order tests."""
    model = minimized_shuffle.copy()
    model.id = "minimized_sorted"
    model.metabolites = DictList(sorted(model.metabolites, key=attrgetter("id")))
    model.genes = DictList(sorted(model.genes, key=attrgetter("id")))
    model.reactions = DictList(sorted(model.reactions, key=attrgetter("id")))
    return model


@pytest.fixture(scope="module")
def minimized_reverse(minimized_shuffle: Model) -> Model:
    """Generate a minimal reversed model for I/O order tests."""
    model = minimized_shuffle.copy()
    model.id = "minimized_reverse"
    model.metabolites = DictList(
        sorted(model.metabolites, key=attrgetter("id"), reverse=True)
    )
    model.genes = DictList(sorted(model.genes, key=attrgetter("id"), reverse=True))
    model.reactions = DictList(
        sorted(model.reactions, key=attrgetter("id"), reverse=True)
    )
    return model


@pytest.fixture(
    scope="module",
    params=["minimized_shuffle", "minimized_reverse", "minimized_sorted"],
)
def template(
    request: pytest.FixtureRequest,
    minimized_shuffle: Model,
    minimized_reverse: Model,
    minimized_sorted: Model,
) -> Model:
    """Return the cobra Model instances found in the current local symbol table."""
    return locals()[request.param]


@pytest.fixture(scope="module", params=["metabolites", "reactions", "genes"])
def attribute(request: pytest.FixtureRequest) -> str:
    """Return the parameter passed."""
    return request.param


def _get_ids(iterable: Iterable) -> List[str]:
    """Get IDs for elements in `iterable`."""
    return [x.id for x in iterable]


@pytest.mark.parametrize(
    "read, write, ext",
    [
        ("read_sbml_model", "write_sbml_model", ".xml"),
        ("load_json_model", "save_json_model", ".json"),
        ("load_yaml_model", "save_yaml_model", ".yml"),
    ],
)
def test_io_order(
    attribute: str,
    read: str,
    write: str,
    ext: str,
    template: Model,
    tmp_path_order: Path,
) -> None:
    """Test loading and saving of models in order.

    Parameters
    ----------
    attribute : str
        The attribute of cobra Model to access.
    read : str
        The function name for loading model, defined as string.
    write : str
        The function name for saving model, defined as string.
    ext : str
        The extension of the file format for loading and saving model.
    template : cobra.Model
        The cobra Model instance to load and save.
    tmp_path_order : pathlib.Path
        The folder path for storing I/O order test files.

    """
    read = getattr(cio, read)
    write = getattr(cio, write)
    file_path = tmp_path_order / f"template{ext}"
    write(template, str(file_path.resolve()))
    model = read(str(file_path.resolve()))
    model_elements = _get_ids(getattr(model, attribute))
    template_elements = _get_ids(getattr(template, attribute))
    assert len(model_elements) == len(template_elements)
    assert set(model_elements) == set(template_elements)
    assert model_elements == template_elements