From 59cc031a06fc448dd2211aef962b9fab34496dd3 Mon Sep 17 00:00:00 2001 From: Oscar Dowson Date: Thu, 7 Dec 2023 17:02:04 +1300 Subject: [PATCH] Fix error for unsupported objective sense (#3601) --- src/macros.jl | 22 ++++++++-------------- test/test_macros.jl | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/macros.jl b/src/macros.jl index 61d33046a88..2f710e9e8d8 100644 --- a/src/macros.jl +++ b/src/macros.jl @@ -1771,30 +1771,24 @@ In the last case, the expression throws an error using the `_error` function in case the value is not an `MOI.OptimizationSense`. """ function _moi_sense(_error::Function, sense) - if sense == :Min - expr = MIN_SENSE + expr = if sense == :Min + MIN_SENSE elseif sense == :Max - expr = MAX_SENSE + MAX_SENSE else - # Refers to a variable that holds the sense. - # TODO: Better document this behavior - expr = esc(sense) + esc(sense) end return :(_throw_error_for_invalid_sense($_error, $expr)) end function _throw_error_for_invalid_sense(_error::Function, sense) return _error( - "Unexpected sense `$value`. The sense must be an", - " `MOI.OptimizatonSense`, `Min` or `Max`.", + "unexpected sense `$sense`. The sense must be an " * + "`::MOI.OptimizatonSense`, or the symbol `:Min` or `:Max`.", ) end -function _throw_error_for_invalid_sense( - _error::Function, - sense::MOI.OptimizationSense, -) - return sense -end + +_throw_error_for_invalid_sense(::Function, sense::MOI.OptimizationSense) = sense """ _replace_zero(model::M, x) where {M<:AbstractModel} diff --git a/test/test_macros.jl b/test/test_macros.jl index 49f2583bcd7..25158c0d60c 100644 --- a/test/test_macros.jl +++ b/test/test_macros.jl @@ -2131,4 +2131,18 @@ function test_issue_3514() return end +function test_bad_objective_sense() + model = Model() + @variable(model, x) + @test_throws_strip( + ErrorException( + "In `@objective(model, :MinMax, x)`: unexpected sense `MinMax`. " * + "The sense must be an `::MOI.OptimizatonSense`, or the symbol " * + "`:Min` or `:Max`.", + ), + @objective(model, :MinMax, x), + ) + return +end + end # module