检查一个函数是否在另一个函数内部被调用 [英] Check if a function is called inside another function

查看:53
本文介绍了检查一个函数是否在另一个函数内部被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个功能

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

如何检查 mean 函数是否被调用?

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.

为了更清楚,我再举一个例子.让我们考虑这个函数:

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

read_data 的目的是读取 CVS 文件并对其进行验证.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.

我想测试这两个函数,但我不想在 read_data 的情况下复制我为 validate_data 编写的相同测试.无论如何,我必须检查后一个函数是否已在 read_data 中调用,因此我想编写一个测试来为我执行此操作.

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.

推荐答案

You can trace mean:

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.

这篇关于检查一个函数是否在另一个函数内部被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆