我的应用程序返回一个ggplot -或-一条消息给用户,说明为什么没有生成绘图
使用validate(need())
创建消息
我还没有能够弄清楚如何使这与shinytest 2工作
下面是来自Robust testing的示例,已更新以显示我正在尝试做的事情
应用程序文件:
# initial example from
# https://rstudio.github.io/shinytest2/articles/robust.html
# removed depreciated aes_string()
library(shiny)
library(ggplot2)
ui <- fluidPage(
numericInput("n", "Number of rows", 10, 1, nrow(cars)),
plotOutput("plot")
)
server <- function(input, output) {
dt <- reactive({
head(cars, input$n)
})
plot_obj <- reactive({
validate(need(input$n > 0, message = "n must be strictly positive"))
ggplot(dt(), aes(speed, dist)) + geom_point()
})
output$plot <- renderPlot({
plot_obj()
})
exportTestValues(
dt = dt(),
plot_obj = plot_obj()
)
}
plot_app <- shinyApp(ui = ui, server = server)
plot_app
测试文件:
# File: tests/testthat/test-export.R
library(shinytest2)
test_that("`export`ed `plot_obj` is updated by `n`", {
skip_if_not_installed("vdiffr")
app <- AppDriver$new(variant = platform_variant())
expect_n_and_plot <- function(n) {
# Verify `n` input equals `n`
n_val <- app$get_value(input = "n")
expect_equal(n_val, n, expected.label = n)
# Verify `dt()` data is first `n` lines of `cars`
dt <- app$get_value(export = "dt")
expect_equal(dt, head(cars, n), expected.label = paste0("head(cars, ", n, ")"))
# Verify `plot_obj()` data is `dt()`
plot_obj <- app$get_value(export = "plot_obj")
expect_equal(plot_obj$data, dt, info = paste0("n = ", n))
# Verify `plot_obj()` is consistent
vdiffr::expect_doppelganger(paste0("cars-points-", n), plot_obj)
}
expect_n_and_plot(10)
# Update `n` to 20
app$set_inputs(n = 20)
expect_n_and_plot(20)
# Update `n` to -1, expect message
app$set_inputs(n = -1)
expect_n_and_plot(-1)
})
理想情况下,回归测试会像标准输出一样捕获返回的消息
谢谢你考虑这个
1条答案
按热度按时间uqxowvwt1#
对
validate
函数的调用应该在renderXXX
函数中:然后你可以调用
app$get_values
或app$get_value(output = "plot")
:所以你可以先做
plot_value <- app$get_value(output = "plot")
,然后再做expect_equal(plot_value$message, "n must be strictly positive")
。编辑
对不起,实际上你也可以用你的代码做
app$get_value(output = "plot")
。但是app$get_value(export = "plot_obj")
会导致错误,因此app$get_values()
也会导致同样的错误。我向Shiny团队报告了这个问题。