Skip to content

Commit

Permalink
adding tests for coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
ncilfone committed Apr 5, 2021
1 parent 5777db3 commit 0093d9b
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 91 deletions.
52 changes: 39 additions & 13 deletions spock/backend/attr/typed.py
Expand Up @@ -28,6 +28,21 @@ def __new__(cls, x):
return super().__new__(cls, x)


def _get_name_py_version(typed):
"""Gets the name of the type depending on the python version
*Args*:
typed: the type of the parameter
*Returns*:
name of the type
"""
return typed._name if hasattr(typed, '_name') else typed.__name__


def _extract_base_type(typed):
"""Extracts the name of the type from a _GenericAlias
Expand All @@ -43,10 +58,7 @@ def _extract_base_type(typed):
name of type
"""
if hasattr(typed, '__args__'):
if minor < 7:
name = typed.__name__
else:
name = typed._name
name = _get_name_py_version(typed=typed)
bracket_val = f"{name}[{_extract_base_type(typed.__args__[0])}]"
return bracket_val
else:
Expand Down Expand Up @@ -229,8 +241,6 @@ def _in_type(instance, attribute, value, options):
*Returns*:
"""
if type(options) not in [list, tuple, EnumMeta]:
raise TypeError(f'options argument must be of type List, Tuple, or Enum -- given {type(options)}')
if type(value) not in options:
raise ValueError(f'{attribute.name} must be in {options}')

Expand Down Expand Up @@ -348,18 +358,32 @@ def _handle_optional_typing(typed):
type_args = typed.__args__
# Optional[X] has type_args = (X, None) and is equal to Union[X, None]
if (len(type_args) == 2) and (typed == Union[type_args[0], None]):
# Since this is true we need to strip out the OG type
# Grab all the types that are not NoneType and collapse to a list
type_list = [val for val in type_args if val is not type(None)]
if len(type_list) > 1:
raise TypeError(f"Passing multiple subscript types to GenericAlias is not supported: {type_list}")
else:
typed = type_list[0]
typed = type_args[0]
# Set the optional flag to true
optional = True
return typed, optional


def _check_generic_recursive_single_type(typed):
"""Checks generics for the single types -- mixed types of generics are not allowed
*Args*:
typed: type
*Returns*:
"""
# Check if it has __args__ to look for optionality as it is a GenericAlias
if hasattr(typed, '__args__'):
if len(set(typed.__args__)) > 1:
type_list = [str(val) for val in typed.__args__]
raise TypeError(f"Passing multiple different subscript types to GenericAlias is not supported: {type_list}")
else:
for val in typed.__args__:
_check_generic_recursive_single_type(typed=val)


def katra(typed, default=None):
"""Public interface to create a katra
Expand All @@ -380,6 +404,8 @@ def katra(typed, default=None):
"""
# Handle optionals
typed, optional = _handle_optional_typing(typed)
# Check generic types for consistent types
_check_generic_recursive_single_type(typed)
# We need to check if the type is a _GenericAlias so that we can handle subscripted general types
# If it is subscript typed it will not be T which python uses as a generic type name
if isinstance(typed, _GenericAlias) and (not isinstance(typed.__args__[0], TypeVar)):
Expand Down
File renamed without changes.
Expand Up @@ -16,6 +16,11 @@ class StrChoice(Enum):
option_2 = 'option_2'


class FailedEnum(Enum):
str_type = 'hello'
float_type = 10.0


class IntChoice(Enum):
option_1 = 10
option_2 = 20
Expand Down
Expand Up @@ -8,7 +8,7 @@
import pytest
from spock.builder import ConfigArgBuilder
from spock.config import isinstance_spock
from tests.attr.attr_configs_test import *
from tests.attr_tests.attr_configs_test import *
import sys


Expand Down Expand Up @@ -456,6 +456,50 @@ def test_class_unknown(self, monkeypatch):
ConfigArgBuilder(TypeConfig, NestedStuff, NestedListStuff, desc='Test Builder')


class TestWrongRepeatedClass:
def test_class_unknown(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config',
'./tests/conf/yaml/test_incorrect_repeated_class.yaml'])
with pytest.raises(ValueError):
ConfigArgBuilder(TypeConfig, NestedStuff, NestedListStuff, desc='Test Builder')


class TestEnumMixedFail:
def test_enum_mixed_fail(self, monkeypatch):
with monkeypatch.context() as m:
with pytest.raises(TypeError):
@spock
class EnumFail:
choice_mixed: FailedEnum


class TestIncorrectType:
def test_incorrect_type(self, monkeypatch):
with monkeypatch.context() as m:
with pytest.raises(TypeError):
@spock
class TypeFail:
weird_type: lambda x: x


class TestEnumClassMissing:
def test_enum_class_missing(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config',
'./tests/conf/yaml/test_wrong_class_enum.yaml'])
with pytest.raises(ValueError):
ConfigArgBuilder(TypeConfig, NestedStuff, NestedListStuff, desc='Test Builder')


class TestMixedGeneric:
def test_mixed_generic(self, monkeypatch):
with monkeypatch.context() as m:
with pytest.raises(TypeError):
@spock
class GenericFail:
generic_fail: Tuple[List[int], List[int], int]

class TestConfigCycles:
"""Checks the raise for cyclical dependencies"""
def test_config_cycles(self, monkeypatch):
Expand Down
7 changes: 7 additions & 0 deletions tests/conf/yaml/test_incorrect_repeated_class.yaml
@@ -0,0 +1,7 @@
# include another file
config: [test.yaml]
NestedListStuff:
- foo: 10
two: hello
- foo: 20
two: bye
4 changes: 4 additions & 0 deletions tests/conf/yaml/test_wrong_class_enum.yaml
@@ -0,0 +1,4 @@
# include another file
config: [test.yaml]
# Class Enum
class_enum: WhoAmI
4 changes: 2 additions & 2 deletions tests/debug/debug.py
Expand Up @@ -7,7 +7,7 @@
from spock.builder import ConfigArgBuilder
from spock.config import isinstance_spock
from params.first import Test
from params.first import NestedListStuff, Stuff, OtherStuff
# from params.first import NestedListStuff, Stuff, OtherStuff
from spock.backend.attr.typed import SavePath
import pickle
from argparse import Namespace
Expand Down Expand Up @@ -102,7 +102,7 @@

def main():
attrs_class = ConfigArgBuilder(
Test, NestedListStuff,
Test,
desc='I am a description'
).save(user_specified_path='/tmp').generate()
# with open('/tmp/debug.pickle', 'wb') as fid:
Expand Down
20 changes: 9 additions & 11 deletions tests/debug/debug.yaml
Expand Up @@ -35,26 +35,24 @@
#fail: [[1, 2], [3, 4]]
#flipper: True
#nested_list: NestedListStuff
test: [ 1, 2 ]
#test: [ 1, 2 ]

Test:
# test: [ 1, 2 ]
# fail: [ [ 1, 2 ], [ 3, 4 ] ]
fail: [ [ 1, 2 ], [ 3, 4 ], 10]
# most_broken: Stuff
# one: 18
# flipper: false
nested_list: NestedListStuff
# nested_list: NestedListStuff
# ummm: 10
# does_not_exist: 10
# new_choice: pear

Gorf:
funny: 12

NestedListStuff:
- maybe: 10
more: hello
- maybe: 20
more: bye
#NestedListStuff:
# - maybe: 10
# more: hello
# - maybe: 20
# more: bye
# borken: RepeatStuff

##ccccombo_breaker: 10
Expand Down
128 changes: 64 additions & 64 deletions tests/debug/params/first.py
Expand Up @@ -7,67 +7,67 @@
from .second import Choice

#
class Choice(Enum):
"""Blah
Attributes:
pear: help pears
banana: help bananas
"""
pear = 'pear'
banana = 'banana'


@spock
class OtherStuff:
"""Other stuff class
Attributes:
three: heahadsf
four: asdfjhasdlkf
"""
three: int
four: str


@spock
class Stuff:
"""Stuff class
Attributes:
one: help
two: teadsfa
"""
one: int
two: str


class ClassStuff(Enum):
"""Class enum
Attributes:
other_stuff: OtherStuff class
stuff: Stuff class
"""
other_stuff = OtherStuff
stuff = Stuff


@spock
class NestedListStuff:
"""Class enum
Attributes:
maybe: some val
more: some other value
"""
maybe: int
more: str
# class Choice(Enum):
# """Blah
#
# Attributes:
# pear: help pears
# banana: help bananas
#
# """
# pear = 'pear'
# banana = 'banana'
#
#
# @spock
# class OtherStuff:
# """Other stuff class
#
# Attributes:
# three: heahadsf
# four: asdfjhasdlkf
#
# """
# three: int
# four: str
#
#
# @spock
# class Stuff:
# """Stuff class
#
# Attributes:
# one: help
# two: teadsfa
#
# """
# one: int
# two: str
#
#
# class ClassStuff(Enum):
# """Class enum
#
# Attributes:
# other_stuff: OtherStuff class
# stuff: Stuff class
#
# """
# other_stuff = OtherStuff
# stuff = Stuff
#
#
# @spock
# class NestedListStuff:
# """Class enum
#
# Attributes:
# maybe: some val
# more: some other value
#
# """
# maybe: int
# more: str


@spock
Expand All @@ -86,11 +86,11 @@ class Test:
nested_list: Repeated list of a class type
"""
# new_choice: Choice
# fail: Tuple[Tuple[int, int], Tuple[int, int]]
test: List[int]
# fail: Tuple[List[int], List[str]]
test: Optional[List[int]]
# fail: List[List[int]]
# flipper: bool
# most_broken: ClassStuff
# one: int
nested_list: List[NestedListStuff]
# nested_list: List[NestedListStuff]

0 comments on commit 0093d9b

Please sign in to comment.