Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix printing when show called on invalid variable or constraint #3763

Merged
merged 3 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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
Loading