测试与R包中的用户的交互 [英] Test interaction with users in R package

查看:88
本文介绍了测试与R包中的用户的交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个R包,其中一个功能是通过readline通过标准输入实现与用户的交互.我现在想知道如何测试此功能的行为,最好使用testthat库.

I am developing an R package and one of the function implements interaction with users through standard input via readline. I now wonder how to test the behavior of this function, preferably with testthat library.

似乎test_that函数假定用户输入的答案是"".我希望我可以测试用户可以输入的各种答案的行为条件.

It seems test_that function assumes the answer is "" for user-input. I wish I could test the behavior conditional of various answers users may type in.

下面是一个小的示例代码.在实际的开发中,marryme函数是在单独的文件中定义的,并导出到名称空间. devtools::test()在最后一行给我一个错误,因为答案永远不会变成是.我想测试用户键入"y"时函数是否正确返回true.

Below is a small example code. In the actual development, the marryme function is defined in a separate file and exported to the namespace. devtools::test() gets me an error on the last line because the answer never becomes yes. I would like to test if the function correctly returns true when user types "y".

library(testthat)

test_that("input", {
  marryme <- function() {
    ans <- readline("will you marry me? (y/n) > ")
    return(ans == "y")
  }

  expect_false(marryme())  # this is good
  expect_true(marryme())   # this is no good
})

推荐答案

通过自定义连接使用readLines()

通过使用readLines()而不是readline(),您可以定义连接,从而可以使用全局选项自定义连接.

Use readLines() with a custom connection

By using readLines() instead of readline(), you can define the connection, which allows you to customize it using global options.

您需要执行两个步骤:

  1. 在包中的zzz.R中设置一个默认选项,该选项指向stdin:

  1. set a default option in your package in zzz.R that points to stdin:

.onAttach <- function(libname, pkgname){
  options(mypkg.connection = stdin())
}

  • 在您的函数中,将readline更改为readLines(n = 1)并将readLines()中的连接设置为getOption("mypkg.connection")

  • In your function, change readline to readLines(n = 1) and set the connection in readLines() to getOption("mypkg.connection")

    示例

    基于您的MWE:

    Example

    Based on your MWE:


        library(testthat)
    
        options(mypkg.connection = stdin())
    
        marryme <- function() {
          cat("will you marry me? (y/n) > ")
          ans <- readLines(con = getOption("mypkg.connection"), n = 1)
          cat("\n")
          return(ans == "y")
        }
    
        test_that("input", {
    
          f <- file()
          options(mypkg.connection = f)
          ans <- paste(c("n", "y"), collapse = "\n") # set this to the number of tests you want to run
          write(ans, f)
    
          expect_false(marryme())  # this is good
          expect_true(marryme())   # this is no good
          # reset connection
          options(mypkg.connection = stdin())
          # close the file
          close(f)
        })
    #> will you marry me? (y/n) > 
    #> will you marry me? (y/n) >
    

    这篇关于测试与R包中的用户的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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