Skip to content

Commit

Permalink
Fix printing when show called on invalid variable or constraint (#3763)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow committed May 31, 2024
1 parent 99ab0b2 commit 56b186f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/print.jl
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,9 @@ julia> function_string(MIME("text/plain"), 2 * x + 1)
```
"""
function function_string(mode::MIME"text/plain", v::AbstractVariableRef)
if !is_valid(owner_model(v), v)
return "InvalidVariableRef"
end
var_name = name(v)
if isempty(var_name)
return anonymous_name(mode, v)
Expand All @@ -744,6 +747,9 @@ function function_string(mode::MIME"text/plain", v::AbstractVariableRef)
end

function function_string(mode::MIME"text/latex", v::AbstractVariableRef)
if !is_valid(owner_model(v), v)
return "InvalidVariableRef"
end
var_name = name(v)
if isempty(var_name)
return anonymous_name(mode, v)
Expand Down Expand Up @@ -1038,6 +1044,9 @@ julia> constraint_string(MIME("text/plain"), c)
```
"""
function constraint_string(mode::MIME, ref::ConstraintRef; in_math_mode = false)
if !is_valid(owner_model(ref), ref)
return "InvalidConstraintRef"
end
return constraint_string(
mode,
name(ref),
Expand Down
24 changes: 24 additions & 0 deletions test/test_print.jl
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ function JuMP.add_constraint(
)
end

function JuMP.is_valid(
model::M,
con_ref::ConstraintRef{M,CustomIndex},
) where {M<:GenericModel}
return 1 <= con_ref.index.value <= length(model.ext[:custom_constraints])
end

function JuMP.constraint_object(cref::ConstraintRef{Model,CustomIndex})
return cref.model.ext[:custom_constraints][cref.index.value]
end
Expand Down Expand Up @@ -1070,4 +1077,21 @@ function test_print_omit_vector()
return
end

function test_invalid_references()
model = Model()
@variable(model, x[1:2])
@constraint(model, c[i in 1:2], x[i] <= i)
delete(model, c[1])
delete(model, x[1])
mime = MIME("text/plain")
@test sprint(show, mime, x[1]) == "InvalidVariableRef"
@test occursin("InvalidVariableRef", sprint(show, mime, x))
@test sprint(show, mime, c[1]) == "InvalidConstraintRef"
@test occursin("InvalidConstraintRef", sprint(show, mime, c))
mime = MIME("text/latex")
@test sprint(show, mime, x[1]) == "\$ InvalidVariableRef \$"
@test sprint(show, mime, c[1]) == "InvalidConstraintRef"
return
end

end # TestPrint

0 comments on commit 56b186f

Please sign in to comment.