Skip to content

Commit 3f562e5

Browse files
committed
Stop parsing invalid multiplications with OGIP
Previously the OGIP unit parser accepted strings that contained units without a separator in between if the second unit was parenthesized, even though the OGIP standard forbids such strings. Now the OGIP parser raises a helpful error message instead.
1 parent 0d1c297 commit 3f562e5

3 files changed

Lines changed: 38 additions & 5 deletions

File tree

‎astropy/units/format/ogip.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,19 +216,27 @@ def p_unit_expression(p):
216216
f"The function '{p[1]}' is valid in OGIP, but not understood "
217217
"by astropy.units."
218218
)
219+
bad_multiplication_message = (
220+
"if '{0}{1}' was meant to be a multiplication, "
221+
"it should have been written as '{0} {1}'."
222+
)
219223

220224
if len(p) == 7:
221225
if p1_str == "sqrt":
222226
p[0] = p[3] ** (0.5 * p[6])
223227
else:
224-
p[0] = p[1] * p[3] ** p[6]
228+
raise ValueError(
229+
bad_multiplication_message.format(p[1], f"({p[3]})**{p[6]}")
230+
)
225231
elif len(p) == 6:
226232
p[0] = p[2] ** p[5]
227233
elif len(p) == 5:
228234
if p1_str == "sqrt":
229235
p[0] = p[3] ** 0.5
230236
else:
231-
p[0] = p[1] * p[3]
237+
raise ValueError(
238+
bad_multiplication_message.format(p[1], f"({p[3]})")
239+
)
232240
elif len(p) == 4:
233241
p[0] = p[2]
234242
else:

‎astropy/units/tests/test_format.py‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -270,9 +270,30 @@ def test_ogip_sqrt(string):
270270
assert u_format.OGIP.parse(string) == u.m ** Fraction(3, 2)
271271

272272

273-
@pytest.mark.parametrize("string", ["m(s)**2", "m(s)"])
274-
def test_ogip_invalid_multiplication(string):
275-
with pytest.raises(ValueError):
273+
@pytest.mark.parametrize(
274+
"string,message",
275+
[
276+
pytest.param(
277+
"m(s)**2",
278+
(
279+
r"^if 'm\(s\)\*\*2' was meant to be a multiplication, "
280+
r"it should have been written as 'm \(s\)\*\*2'.$"
281+
),
282+
id="m(s)**2",
283+
),
284+
pytest.param(
285+
"m(s)",
286+
(
287+
r"^if 'm\(s\)' was meant to be a multiplication, "
288+
r"it should have been written as 'm \(s\)'.$"
289+
),
290+
id="m(s)",
291+
),
292+
],
293+
)
294+
def test_ogip_invalid_multiplication(string, message):
295+
# Regression test for #16749
296+
with pytest.raises(ValueError, match=message):
276297
u_format.OGIP.parse(string)
277298

278299

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
The OGIP unit parser no longer accepts strings where a component unit is
2+
followed by a parenthesized unit without a separator in between, such as
3+
``'m(s)'`` or ``'m(s)**2'``.
4+
Such strings are not allowed by the OGIP standard.

0 commit comments

Comments
 (0)