def enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: choices = [(item, item) for item in data["enum"]] kwargs = {"choices": choices, "default": data.get("default", NO_DEFAULT)} return Choice(**kwargs)
def test_choice(): validator = Choice(choices=[("R", "red"), ("B", "blue"), ("G", "green")]) value, error = validator.validate_or_error(None) assert error == ValidationError(text="May not be null.", code="null") validator = Choice(choices=[("R", "red"), ("B", "blue"), ("G", "green")], allow_null=True) value, error = validator.validate_or_error(None) assert value is None assert error is None validator = Choice(choices=[("R", "red"), ("B", "blue"), ("G", "green")], allow_null=True) value, error = validator.validate_or_error("") assert value is None assert error is None validator = Choice(choices=[("R", "red"), ("B", "blue"), ("G", "green")]) value, error = validator.validate_or_error("Z") assert error == ValidationError(text="Not a valid choice.", code="choice") validator = Choice(choices=[("R", "red"), ("B", "blue"), ("G", "green")]) value, error = validator.validate_or_error("R") assert value == "R" validator = Choice( choices=[("", "empty"), ("R", "red"), ("B", "blue"), ("G", "green")], allow_null=True, ) value, error = validator.validate_or_error("") assert value == "" validator = Choice( choices=[("", "empty"), ("R", "red"), ("B", "blue"), ("G", "green")], allow_null=True, ) value, error = validator.validate_or_error(None) assert value is None