What's the best way of testing a mutating function? Say I've got function mutate!(X, args); (...); return nothing; end
which works differently for different argument types, then I do:
@testset "Test my mutating function" begin
X_test = [1 2; 3 4]
mutate!(X, first_test_argument)
@test X_test == [1 2; 3 5]
X_test = [1 2; 3 4]
mutate!(X, second_test_argument)
@test X_test == [1 4; 9 16]
(...)
end
which seems fairly boiler-platy with the repeated creation of X_test
, is there a better way to write this?
For now I'm doing
X₀ = [1 2; 3 4]
X_test = copy(X₀); mutate!(X_test, first_test_argument)
@test X_test == (...)
X_test = copy(X₀); mutate!(X_test, second_test_argument)
(...)
If it makes sense for your mutating function to also return the mutated argument you can just do
@test mutate!(copy(X), test_argument) == expected
It currently doesn't, although maybe there's no harm in letting it return the argument...
You have lots of precedents in Base functions, e.g. empty!
, filter!
and push!
. I've generally found it to be a good idea in my code, unless the return value is needed for something else, like it is for pop!
.
Last updated: Dec 28 2024 at 04:38 UTC