api: Add @validate.eq(field, value)
We already have @validate.is_in() for when there are multiple acceptable
values. Introducing @validate.eq(), for when there is only one
acceptable value.
Sample use case: ensuring that a common_pb2.Path is outside the chroot.
BUG=b:259445595
TEST=./run_tests
Change-Id: I424ceeb09827d5cf5e956bc33a85460b1a7d68ae
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/4375644
Reviewed-by: Alex Klein <saklein@chromium.org>
Tested-by: Greg Edelston <gredelston@google.com>
Commit-Queue: Greg Edelston <gredelston@google.com>
diff --git a/api/validate.py b/api/validate.py
index 744c024..f851554 100644
--- a/api/validate.py
+++ b/api/validate.py
@@ -13,7 +13,7 @@
import functools
import logging
import os
-from typing import Callable, Iterable, List, Optional, Union
+from typing import Any, Callable, Iterable, List, Optional, Union
from chromite.third_party.google.protobuf import message as protobuf_message
@@ -79,6 +79,39 @@
return decorator
+def eq(field: str, expected_value: Any):
+ """Validate |field| is set to |expected_value|.
+
+ Args:
+ field: The field being checked. May be a `.` separated field.
+ expected_value: The value to which the field must be equal.
+ """
+ assert field
+
+ def decorator(func):
+ @functools.wraps(func)
+ def _eq(input_proto, output_proto, config, *args, **kwargs):
+ if config.do_validation:
+ logging.debug(
+ "Validating %s is equal to %r", field, expected_value
+ )
+ actual_value = _value(field, input_proto)
+
+ if actual_value != expected_value:
+ cros_build_lib.Die(
+ "%s (%r) must be equal to %r",
+ field,
+ actual_value,
+ expected_value,
+ )
+
+ return func(input_proto, output_proto, config, *args, **kwargs)
+
+ return _eq
+
+ return decorator
+
+
def is_in(field: str, values: Iterable):
"""Validate |field| is an element of |values|.