Stream: helpdesk (published)

Topic: Testing mutating function


view this post on Zulip Nils (Sep 18 2024 at 09:34):

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?

view this post on Zulip Nils (Sep 18 2024 at 09:40):

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)
(...)

view this post on Zulip Gunnar Farnebäck (Sep 19 2024 at 12:05):

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

view this post on Zulip Nils (Sep 19 2024 at 12:59):

It currently doesn't, although maybe there's no harm in letting it return the argument...

view this post on Zulip Gunnar Farnebäck (Sep 20 2024 at 08:33):

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