Skip to content

Commit

Permalink
Merge pull request #239 from emmo-repo/cwa/close-220-tidy-up-tests
Browse files Browse the repository at this point in the history
Ensure all produced files from tests are in a temp dir.

Add pytest fixtures for loading EMMO, as this is done in several
tests.
Add fixture for location to repo_dir, instantiating it only once per
pytest session.
Add a yield-fixture for creating a temporary directory that lives for
the lifetime of the test function.

This removes the possibility to check through the generated files
from the tests, keeping the unit tests being just that: unit tests.
However, I guess the generated files should be tested more now?

In short, the unit tests here should never rely on human inspection,
hence, they shouldn't produce any permanent files.

If examples are the motive for the tests (as it is explicitly stated for
one of them) it should be added to the examples/ folder and be
part of the documentation.
  • Loading branch information
CasperWA authored Sep 29, 2021
2 parents 179f78f + b4961ef commit 92cd815
Show file tree
Hide file tree
Showing 14 changed files with 213 additions and 236 deletions.
5 changes: 0 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ __pycache__
MANIFEST
dist
build
old
test_graph2

*.pdf
*.xml

# Documentation
site/
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ recursive-exclude examples/emmodoc old/** genfigs/** *.pdf *.html *~
recursive-include demo *
recursive-exclude demo old __pycache__ *~ *.pyc *.off

recursive-include emmo/factpluspluswrapper/java *
recursive-include ontopy/factpluspluswrapper/java **
10 changes: 0 additions & 10 deletions tests/.gitignore

This file was deleted.

34 changes: 34 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Pytest fixtures and setup functions."""
from pathlib import Path
from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
from ontopy.ontology import Ontology


@pytest.fixture(scope="session")
def repo_dir() -> Path:
"""Absolute path to the repository directory."""
return Path(__file__).parent.parent.resolve()


@pytest.fixture
def emmo() -> "Ontology":
"""Load and return EMMO."""
from emmopy import get_emmo

emmo = get_emmo()

return emmo


@pytest.fixture
def tmpdir() -> Path:
"""Create a temporary directory that lasts the runtime of the test."""
from tempfile import TemporaryDirectory

res = TemporaryDirectory()
yield Path(res.name)
res.cleanup()
49 changes: 20 additions & 29 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
def test_basic() -> None:
import sys
import os
import itertools
from typing import TYPE_CHECKING

# Add emmo to sys path
thisdir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(1, os.path.abspath(os.path.join(thisdir, '..')))
from ontopy import get_ontology # noqa: E402, F401
if TYPE_CHECKING:
from ontopy.ontology import Ontology

import owlready2 # noqa: E402, F401

def test_basic(emmo: "Ontology") -> None:
from ontopy import get_ontology

emmo = get_ontology()
emmo.load()
emmo.sync_reasoner()


onto = get_ontology('onto.owl')
onto.imported_ontologies.append(emmo)
onto.base_iri = 'http://emmo.info/examples/test#'
Expand All @@ -27,7 +20,7 @@ def test_basic() -> None:

# Add entity using python classes
class Oxygen(emmo.Atom):
pass
"""Oxygen atom."""

class H2O(emmo.Molecule):
"""Water molecule."""
Expand All @@ -37,19 +30,17 @@ class H2O(emmo.Molecule):
# Create some
H1 = onto.Hydrogen()
H2 = onto.Hydrogen()
O = Oxygen() # noqa: E741
w = H2O()
w.hasSpatialDirectPart = [H1, H2, O]

onto.sync_attributes(name_policy='sequential', name_prefix='myonto_')
assert onto.base_iri + 'myonto_0' in onto
assert onto.base_iri + 'myonto_6' in onto

onto.sync_attributes(name_policy='uuid', name_prefix='onto_')
assert w.name.startswith('onto_')
assert len(w.name) == 5 + 36

# Remove all traces of onto such that they do not mess up other tests
# when running pytest
for e in itertools.chain(onto.classes(), onto.individuals()):
owlready2.destroy_entity(e)
O = Oxygen()
water = H2O()
water.hasSpatialDirectPart = [H1, H2, O]

name_prefix = "myonto_"
onto.sync_attributes(name_policy='sequential', name_prefix=name_prefix)
assert f"{onto.base_iri}{name_prefix}0" in onto
assert f"{onto.base_iri}{name_prefix}6" in onto

name_prefix = "onto_"
onto.sync_attributes(name_policy='uuid', name_prefix=name_prefix)
assert water.name.startswith('onto_')
# A UUID is 32 chars long + 4 `-` chars = 36 chars
assert len(water.name) == len(name_prefix) + 36
70 changes: 33 additions & 37 deletions tests/test_catalog.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
def test_catalog() -> None:
import sys
import os

# Add emmo to sys path
thisdir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(1, os.path.abspath(os.path.join(thisdir, '..')))
from ontopy.utils import read_catalog, ReadCatalogError # noqa: E402, F401
from ontopy.utils import write_catalog # noqa: E402, F401


ontodir = os.path.join(thisdir, 'testonto')
d_expected = {
'http://emmo.info/testonto/0.1.0': os.path.join(
ontodir, 'testonto.ttl'),
'http://emmo.info/testonto/0.1.0/models': os.path.join(
ontodir, 'models.ttl'),
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from pathlib import Path


def test_catalog(repo_dir: "Path", tmpdir: "Path") -> None:
from ontopy.utils import read_catalog, ReadCatalogError, write_catalog

ontodir = repo_dir / "tests" / 'testonto'
catalog_expected = {
'http://emmo.info/testonto/0.1.0': str(ontodir / 'testonto.ttl'),
'http://emmo.info/testonto/0.1.0/models': str(ontodir / 'models.ttl'),
}

d = read_catalog(os.path.join(ontodir, 'catalog-v001.xml'))
assert d == d_expected
catalog = read_catalog(str(ontodir / 'catalog-v001.xml'))
assert catalog == catalog_expected

d = read_catalog(ontodir)
assert d == d_expected
catalog = read_catalog(str(ontodir))
assert catalog == catalog_expected

d = read_catalog(ontodir, recursive=True)
assert d == d_expected
catalog = read_catalog(str(ontodir), recursive=True)
assert catalog == catalog_expected

d, p = read_catalog(ontodir, return_paths=True)
assert d == d_expected
assert p == set([ontodir])
catalog, catalog_paths = read_catalog(str(ontodir), return_paths=True)
assert catalog == catalog_expected
assert catalog_paths == set([str(ontodir)])

d = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master/'
catalog = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master/'
'catalog-v001.xml')
assert any(v.endswith('/emmo.ttl') for v in d.values())
assert any(_.endswith('/emmo.ttl') for _ in catalog.values())

d = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master')
assert any(v.endswith('/emmo.ttl') for v in d.values())
catalog = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master')
assert any(_.endswith('/emmo.ttl') for _ in catalog.values())

try:
read_catalog(
Expand All @@ -46,17 +42,17 @@ def test_catalog() -> None:
assert False, 'expected ReadCatalogError'

try:
read_catalog(os.path.join(ontodir, 'does-not-exists'))
read_catalog(str(ontodir / 'does-not-exists'))
except ReadCatalogError:
pass
else:
assert False, 'expected ReadCatalogError'

d = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master/'
catalog = read_catalog('https://raw.githubusercontent.com/emmo-repo/EMMO/master/'
'catalog-v001.xml', baseuri='/abc')
assert '/abc/emmo.ttl' in d.values()

assert '/abc/emmo.ttl' in catalog.values()

write_catalog(d, 'tmp-catalog.xml')
d2 = read_catalog('tmp-catalog.xml')
assert d2 == d
tmp_catalog_path = tmpdir / "tmp-catalog.xml"
write_catalog(catalog, output=tmp_catalog_path)
tmp_catalog = read_catalog(str(tmp_catalog_path))
assert tmp_catalog == catalog
48 changes: 21 additions & 27 deletions tests/test_graph.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
def test_graph() -> None:
import sys
import os
from typing import TYPE_CHECKING

# Add emmo to sys path
thisdir = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(1, os.path.abspath(os.path.join(thisdir, '..')))
from ontopy import get_ontology # noqa: E402, F401
if TYPE_CHECKING:
from pathlib import Path

from ontopy.ontology import Ontology

emmo = get_ontology()
emmo.load()
def test_graph(emmo: "Ontology", tmpdir: "Path") -> None:
graph = emmo.get_dot_graph(relations='is_a')
graph.write_svg(tmpdir / 'taxonomy.svg')
graph.write_pdf(tmpdir / 'taxonomy.pdf')

graph = emmo.get_dot_graph(relations='is_a')
graph.write_svg('taxonomy.svg')
graph.write_pdf('taxonomy.pdf')
entity_graph = emmo.get_dot_graph('EMMO')
entity_graph.write_svg(tmpdir / 'taxonomy2.svg')

entity_graph = emmo.get_dot_graph('EMMO')
entity_graph.write_svg('taxonomy2.svg')
substrate_graph = emmo.get_dot_graph('Item', relations=True,
leafs=('Physical'), parents='Item',
style='uml')
substrate_graph.write_svg(tmpdir / 'merotopology_graph.svg')

substrate_graph = emmo.get_dot_graph('Item', relations=True,
leafs=('Physical'), parents='Item',
style='uml')
substrate_graph.write_svg('merotopology_graph.svg')
property_graph = emmo.get_dot_graph('Property')
property_graph.write_svg(tmpdir / 'property_graph.svg')

property_graph = emmo.get_dot_graph('Property')
property_graph.write_svg('property_graph.svg')
# Update the default style
emmo._default_style['graph']['rankdir'] = 'BT'


# Update the default style
emmo._default_style['graph']['rankdir'] = 'BT'

relations_graph = emmo.get_dot_graph('EMMORelation')
relations_graph.write_pdf('relation_graph.pdf')
relations_graph.write_png('relation_graph.png')
relations_graph = emmo.get_dot_graph('EMMORelation')
relations_graph.write_pdf(tmpdir / 'relation_graph.pdf')
relations_graph.write_png(tmpdir / 'relation_graph.png')
Loading

0 comments on commit 92cd815

Please sign in to comment.