"""FeatureVariantForceRule model.""" from features import filters class FeatureVariantForceRule: """Feature Variant Force Rule. Feature variant force rule is used to ensure a user will be active for a given feature variant. """ @classmethod def from_context(cls, variant_name, context): """Create a variant override from a request context. Args: name (str): the name of the variants. context (dict): context of the request. Yields: FeatureVariantForceRule: the feature variant force rule. """ # Only use the first key-value pair because we're lazy. filter_name = list(context.keys())[0] filter_method = filters.get_from_context(filter_name) value = context[filter_name] return cls(variant_name, filter_method, [value]) def __init__(self, variant_name, filter_method, values): """Create a rule to force a feature variant. Args: variant_name (str): name of the variant. filter_method (callable): the callable. This takes two parameters: values (list) and context (dict) and returns boolean. values (list): the different values for the filter. """ self.variant_name = variant_name self.filter = filter_method self.values = [str(val) for val in values] def matches(self, context): """Check if the context matches the force rule. Args: context (dict): the context (same context is passed to the Feature.) Return: boolean: whether or not the override takes place. """ return self.filter(self.values, context or dict())