Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 39 additions & 16 deletions _plotly_utils/basevalidators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1740,7 +1740,9 @@ class SubplotidValidator(BaseValidator):
}
"""

def __init__(self, plotly_name, parent_name, dflt=None, regex=None, **kwargs):
def __init__(
self, plotly_name, parent_name, dflt=None, regex=None, array_ok=False, **kwargs
):
if dflt is None and regex is None:
raise ValueError("One or both of regex and deflt must be specified")

Expand All @@ -1755,6 +1757,7 @@ def __init__(self, plotly_name, parent_name, dflt=None, regex=None, **kwargs):
self.base = re.match(r"/\^(\w+)", regex).group(1)

self.regex = self.base + r"(\d*)"
self.array_ok = array_ok

def description(self):
desc = """\
Expand All @@ -1763,31 +1766,51 @@ def description(self):
optionally followed by an integer >= 1
(e.g. '{base}', '{base}1', '{base}2', '{base}3', etc.)
""".format(plotly_name=self.plotly_name, base=self.base)

desc = """\
The '{plotly_name}' property is an identifier of a particular
subplot, of type '{base}', that may be specified as:
- the string '{base}'
optionally followed by an integer >= 1
(e.g. '{base}', '{base}1', '{base}2', '{base}3', etc.)""".format(
Comment thread
my-tien marked this conversation as resolved.
Outdated
plotly_name=self.plotly_name, base=self.base
)
if self.array_ok:
desc += """
- A tuple or list of the above"""
return desc

def validate_coerce(self, v):
if v is None:
pass
elif not isinstance(v, str):
self.raise_invalid_val(v)
else:
# match = re.fullmatch(self.regex, v)
match = fullmatch(self.regex, v)
def coerce(value, invalid_els):
if not isinstance(value, str):
invalid_els.append(value)
return value
match = fullmatch(self.regex, value)
if not match:
is_valid = False
invalid_els.append(value)
return value
else:
digit_str = match.group(1)
if len(digit_str) > 0 and int(digit_str) == 0:
is_valid = False
invalid_els.append(value)
return value
elif len(digit_str) > 0 and int(digit_str) == 1:
# Remove 1 suffix (e.g. x1 -> x)
v = self.base
is_valid = True
return self.base
else:
is_valid = True
return value
Comment thread
my-tien marked this conversation as resolved.
Outdated

if not is_valid:
self.raise_invalid_val(v)
if v is None:
pass
elif self.array_ok and is_simple_array(v):
invalid_els = []
v = [e for e in v if coerce(e, invalid_els)]
if invalid_els:
self.raise_invalid_elements(invalid_els[:10])
else:
invalid_els = []
v = coerce(v, invalid_els)
if invalid_els:
self.raise_invalid_val(self.base)
return v


Expand Down
53 changes: 53 additions & 0 deletions tests/test_plotly_utils/validators/test_subplotid_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,18 @@ def validator():
return SubplotidValidator("prop", "parent", dflt="geo")


@pytest.fixture()
def validator_aok():
return SubplotidValidator("prop", "parent", dflt="legend", array_ok=True)


# Tests

# Array not ok (default)

# Acceptance


@pytest.mark.parametrize("val", ["geo"] + ["geo%d" % i for i in range(2, 10)])
def test_acceptance(val, validator):
assert validator.validate_coerce(val) == val
Expand Down Expand Up @@ -43,3 +51,48 @@ def test_rejection_value(val, validator):
validator.validate_coerce(val)

assert "Invalid value" in str(validation_failure.value)


# Array ok

# Acceptance


@pytest.mark.parametrize(
"val", ["legend2", ["legend", "legend2"], ("legend1", "legend2")]
)
def test_acceptance_aok(val, validator_aok):
v = validator_aok.validate_coerce(val)
if isinstance(val, tuple):
assert val == tuple(v)
else:
assert val == v


# Rejection by type
@pytest.mark.parametrize("val", [23, [2, 3], {}, set(), np_inf(), np_nan()])
def test_rejection_type_aok(val, validator_aok):
with pytest.raises(ValueError) as validation_failure:
validator_aok.validate_coerce(val)

failure_msg = str(validation_failure.value)
assert "Invalid value" in failure_msg or "Invalid elements" in failure_msg


# Rejection by value
@pytest.mark.parametrize(
"val",
[
"", # Cannot be empty
"bogus", # Must begin with 'geo'
"legend0", # If followed by a number the number must be > 1,
["", "legend"],
("bogus", "legend2"),
],
)
def test_rejection_value_aok(val, validator_aok):
with pytest.raises(ValueError) as validation_failure:
validator_aok.validate_coerce(val)

failure_msg = str(validation_failure.value)
assert "Invalid value" in failure_msg or "Invalid elements" in failure_msg