How to test a function in Julia

Hi.

I have familiarity with unit testing in Python but I couldn’t really figure out how to do it in Julia when it comes to functions.

function year_created(p, language::String)
	loc = findfirst(p[:,2] .== language)
	return p[loc,1]
end

Based on some guides I’ve seen, I tried to add @test at the beginning of the function but it threw a Test.FallbackTestSetException("There was an error during testing"). I know that the way I did was amateur. I just don’t know what the steps are to test an entire function in Julia.

julia> using Test
       @test year_created([1500 "Portuguese"],"Portuguese") == 1500
Test Passed


1 Like

Sorry but shouldn’t it be year_created(1500, "Portuguese")?

From what I understand of your function, p is as array in which the first column has the years, and the second column has the language name.

So my question is this. Do you have to test the function like this for every single entry in the dataframe?

Once you’ve written a decent unit test, then you will have tested your function. The test furnished by @lmiq should indicate that the basic functionality is correct, but it depends on what you intend. Do you want special behavior if a language appears more than once in the data, or is in lower case or all caps? Do you expect certain errors if data are not properly formatted? Where you “have to” test all of the desired features, or some meaningful subset, is up to you. Complete coverage of all possibilities is not always practical.

Your question about “every single entry in the dataframe” suggests you might have doubts about the integrity of data. That is a different matter, and might merit separate validation of data, not necessarily within year_created. Usually unit testing is used to refer to code, and not data, and once your code works, you expect it to do so for any data. But if you want to completely validate data, then probably you do have to write something to test every entry.

5 Likes

You can broadcast the function, but that is not directly related to the tests:

julia> data = [ 1500 "Portuguese"
                1200 "Italian" ] 
2×2 Matrix{Any}:
 1500  "Portuguese"
 1200  "Italian"

julia> year_created.(Ref(data),data[:,2]) # broadcasting (note the dot ".")
2-element Vector{Int64}:
 1500
 1200

julia> @test year_created.(Ref(data),data[:,2]) == [ 1500, 1200 ]
Test Passed

#or
julia> @test year_created.(Ref(data),data[:,2]) == data[:,1]
Test Passed

But how do you want to actually design the tests is up to you.

4 Likes