Skip to content

Commit

Permalink
Added tests.models.test_utils
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed Sep 9, 2020
1 parent b0bbedb commit 4feee5f
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions tests/models/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import re
import pytest
from pydantic import BaseModel
from optimade.models.utils import OptimadeField, StrictField, SupportLevel
from typing import List


def test_strict_field():
"""Test :class:`StrictField` creation for failure on bad keys, and
warnings with no description.
"""
detail = re.escape(
"Not creating StrictField ((Ellipsis,), {'random_key': 'disallowed'}) with forbidden keywords ['random_key']."
)
detail = "forbidden keywords"
with pytest.raises(RuntimeError, match=detail):

class BadModel(BaseModel):
bad_field: int = StrictField(..., random_key="disallowed")

detail = re.escape(
"No description provided for StrictField specified by (Ellipsis), {})"
)
detail = "No description"
with pytest.warns(UserWarning, match=detail):

class AnotherBadModel(BaseModel):
bad_field: int = StrictField(...)


def test_compatible_strict_optimade_field():
"""This test checks that OptimadeField and StrictField
produce the same schemas when given the same arguments.
"""

class CorrectModelWithStrictField(BaseModel):
# check that unit and uniqueItems are passed through
good_field: List[str] = StrictField(
...,
support=SupportLevel.MUST,
queryable=SupportLevel.MUST,
description="Unit test to make sure that StrictField allows through OptimadeField keys",
pattern="^structures$",
unit="stringiness",
uniqueItems=True,
sortable=True,
)

class CorrectModelWithOptimadeField(BaseModel):

good_field: List[str] = OptimadeField(
...,
# Only difference here is that OptimadeField allows case-insensitive
# strings to be passed instead of support levels directly
support="MUST",
queryable="MUST",
description="Unit test to make sure that StrictField allows through OptimadeField keys",
pattern="^structures$",
uniqueItems=True,
unit="stringiness",
sortable=True,
)

optimade_schema = CorrectModelWithOptimadeField.schema()
strict_schema = CorrectModelWithStrictField.schema()
strict_schema["title"] = optimade_schema["title"]
assert strict_schema == optimade_schema


def test_optimade_field():

with pytest.raises(RuntimeError, match="forbidden keywords"):

class BadModel(BaseModel):
field: int = OptimadeField(..., extra_garbage="garbage")

with pytest.warns(UserWarning, match="No description"):

class AnotherBadModel(BaseModel):
field: int = OptimadeField(...)

0 comments on commit 4feee5f

Please sign in to comment.