def test_verify_key__str_list_values(): """If the type is list, the items inside should be strings.""" conf = Config() conf.foo = ["bar", 3.14, "baz"] conf._verify_key("foo", list) assert conf.foo == ["bar", "3.14", "baz"]
def test_verify_key__dict_types(): """If a dict is provided with types, the key/values should be coerced.""" conf = Config() conf.foo = {3.14: "500.123"} conf._verify_key("foo", {str: float}) assert conf.foo == {"3.14": 500.123}
def test_verify_key__failure_coerce(): """Should try to coerce values into their types when not list or dict.""" conf = Config() conf.foo = 3.14 conf._verify_key("foo", str) assert conf.foo == "3.14"
def test_verify_key__list_object(): """If an attribute should be a list, it should be listed.""" conf = Config() conf.foo = "not a list" conf._verify_key("foo", list) assert conf.foo == ["not a list"]
def test_verify_key__failure(): """If unable to coerce into the expected type, raise TypeError.""" conf = Config() conf.foo = "something" with pytest.raises(TypeError) as error: conf._verify_key("foo", float) assert error.value.args[0] == "foo should be a float, not str!"
def test_verify_key__dict_failure(): """Do not try to coerce something that should be a dict into one.""" conf = Config() conf.foo = "not a dict" with pytest.raises(TypeError) as error: conf._verify_key("foo", {}) assert error.value.args[0] == "foo should be a dict, not str!"
def test_verify_key__multiple__fallthrough(): """If the first coerce fails, try the second.""" conf = Config() conf.bar = mock.MagicMock(spec=False) conf.bar.__float__ = mock.Mock(side_effect=ValueError) conf.bar.__str__ = mock.Mock(return_value="mock str") conf._verify_key("bar", (float, str)) assert conf.bar == "mock str"
def test_verify_key__multiple__failure(): """When unable to coerce to any type, raise TypeError.""" conf = Config() conf.foo = mock.MagicMock(spec=False) conf.foo.__float__ = mock.Mock(side_effect=ValueError) conf.foo.__str__ = mock.Mock(side_effect=ValueError) with pytest.raises(TypeError) as err: conf._verify_key("foo", (float, str)) assert err.value.args[0] == "foo should be a float or str, not MagicMock!"
def test_verify_key__multiple__allowed(): """There are some keys where multiple types are allowed.""" conf = Config() conf.foo = 3.14 conf._verify_key("foo", (list, str)) assert conf.foo == [3.14] conf.foo = 3.14 conf._verify_key("foo", (str, list)) # assert order matters assert conf.foo == "3.14"