amarchin
amarchin

Reputation: 2114

Check if a function is called inside another function

Let say I have the function

mean_wrapper <- function(x) {
  mean(x)
}

How can I check if the mean function is called?

An use case is for instance If I want to check this behavior in a unit test.

EDIT:

I make another exampe to be clearer. Let consider this function:

library(readr)
library(magrittr)

read_data <- function(file_name) {
  read_csv(file_name) %>%
    validate_data()
}

The aim of read_data is to read a CVS file and validate it. validate_data performs some checks on the data. It raises an error if one of them fail, otherwise returns the input object.

I want to test both functions but I don't want replicate the same tests I wrote for validate_data in the case of read_data. Anyway I have to check that the latter function has been called in read_data, so I wolud like to write a test that does this for me.

Upvotes: 2

Views: 520

Answers (1)

Roland
Roland

Reputation: 132706

You could trace mean:

trace(mean, tracer = quote(message("mean was called")))
mean_wrapper(3)
#Tracing mean(x) on entry 
#mean was called
#[1] 3
untrace(mean)
#Untracing function "mean" in package "base"

Instead of a message you can use anything (e.g., assignment to a variable in the enclosing environment) as tracer.

Upvotes: 2

Related Questions