Some checks failed
Test before pr merge / test-lint (pull_request) Failing after 9s
82 lines
1.9 KiB
Python
82 lines
1.9 KiB
Python
import pytest
|
|
from enum import Enum
|
|
from typing import List
|
|
from cpl.core.utils.cast import cast
|
|
|
|
|
|
class Color(Enum):
|
|
RED = "red"
|
|
GREEN = "green"
|
|
|
|
|
|
class Status(Enum):
|
|
OK = 200
|
|
ERROR = 500
|
|
|
|
|
|
def test_cast_none_returns_none():
|
|
assert cast(None, int) is None
|
|
|
|
|
|
def test_cast_bool_true_values():
|
|
assert cast("true", bool) is True
|
|
assert cast("YES", bool) is True
|
|
assert cast("1", bool) is True
|
|
assert cast("On", bool) is True
|
|
|
|
|
|
def test_cast_bool_false_values():
|
|
assert cast("false", bool) is False
|
|
assert cast("0", bool) is False
|
|
assert cast("no", bool) is False
|
|
assert cast("off", bool) is False
|
|
|
|
|
|
def test_cast_list_of_str_with_brackets():
|
|
assert cast("[a,b,c]", List[str]) == ["a", "b", "c"]
|
|
|
|
|
|
def test_cast_list_of_str_with_delimiter_no_brackets():
|
|
assert cast("a,b,c", List[str]) == ["a", "b", "c"]
|
|
|
|
|
|
def test_cast_list_of_int_with_brackets():
|
|
assert cast("[1,2,3]", List[int]) == [1, 2, 3]
|
|
|
|
|
|
def test_cast_list_custom_delimiter():
|
|
assert cast("1;2;3", List[int], list_delimiter=";") == [1, 2, 3]
|
|
|
|
|
|
def test_cast_list_without_brackets_or_delimiter_errors():
|
|
with pytest.raises(ValueError):
|
|
cast("abc", List[str])
|
|
|
|
|
|
def test_cast_enum_by_value_case_insensitive():
|
|
assert cast("red", Color) is Color.RED
|
|
assert cast("RED", Color) is Color.RED
|
|
assert cast("Green", Color) is Color.GREEN
|
|
|
|
|
|
def test_cast_enum_by_name_case_insensitive():
|
|
assert cast("OK", Status) is Status.OK
|
|
assert cast("ok", Status) is Status.OK
|
|
assert cast("ERROR", Status) is Status.ERROR
|
|
|
|
|
|
def test_cast_enum_invalid_raises():
|
|
with pytest.raises(ValueError) as e:
|
|
cast("unknown", Color)
|
|
assert "Cannot cast value 'unknown' to enum 'Color'" in str(e.value)
|
|
|
|
|
|
def test_cast_primitives():
|
|
assert cast("42", int) == 42
|
|
assert cast("3.14", float) == 3.14
|
|
assert cast("abc", str) == "abc"
|
|
|
|
|
|
def test_cast_list_without_subtype_defaults_to_str():
|
|
assert cast("a,b", list) == ["a", "b"]
|