# End-to-end Shiny testing with shinytest2 and AppDriver # # Writes a Shiny application summarizing clinical trial safety subjects # (pharmaverseadam::adsl where SAFFL == "Y") by treatment arm, drives it # headlessly with shinytest2::AppDriver, asserts initial and updated output # values, and cleanly stops the application. # # Run with: # Rscript app-driver-demo.R #' Write the ADSL summary Shiny application to disk #' #' @param app_dir Directory where app.R will be written. #' @return The application directory path, invisibly. #' @export write_adsl_app <- function(app_dir) { if (!dir.exists(app_dir)) { dir.create(app_dir, recursive = TRUE) } app_code <- c( "library(shiny)", "", "ui <- fluidPage(", " titlePanel(\"Safety Population Summary\"),", " sidebarLayout(", " sidebarPanel(", " selectInput(", " inputId = \"arm\",", " label = \"Treatment Arm\",", " choices = c(\"Placebo\", \"Xanomeline High Dose\", \"Xanomeline Low Dose\"),", " selected = \"Placebo\"", " )", " ),", " mainPanel(", " h4(\"Safety Subjects (SAFFL == Y)\"),", " textOutput(\"subject_count\")", " )", " )", ")", "", "server <- function(input, output, session) {", " output$subject_count <- renderText({", " req(input$arm)", " saf <- subset(pharmaverseadam::adsl, SAFFL == \"Y\" & TRT01A == input$arm)", " as.character(nrow(saf))", " })", "}", "", "shinyApp(ui = ui, server = server)" ) writeLines(app_code, file.path(app_dir, "app.R")) invisible(app_dir) } #' Calculate expected safety subject count from ADSL #' #' @param arm Treatment arm (TRT01A). #' @return Integer subject count. #' @export compute_safety_count <- function(arm) { sum( pharmaverseadam::adsl$SAFFL == "Y" & pharmaverseadam::adsl$TRT01A == arm, na.rm = TRUE ) } #' Drive the ADSL application with AppDriver #' #' @param app_dir Directory containing the Shiny application. #' @return Named list with recorded values from AppDriver. #' @export run_app_driver_demo <- function(app_dir) { withr::local_envvar(NOT_CRAN = "true") app <- shinytest2::AppDriver$new(app_dir, name = "adsl-summary") withr::defer(app$stop()) initial_val <- app$get_value(output = "subject_count") app$set_inputs(arm = "Xanomeline High Dose") high_dose_val <- app$get_value(output = "subject_count") app$set_inputs(arm = "Xanomeline Low Dose") low_dose_val <- app$get_value(output = "subject_count") list( placebo = initial_val, high_dose = high_dose_val, low_dose = low_dose_val ) } # Run demo only when executed directly as a script. if (sys.nframe() == 0L) { message("Writing ADSL safety summary app to temporary directory...") demo_dir <- withr::local_tempdir() write_adsl_app(demo_dir) message( "Starting AppDriver and testing reactive outputs in headless Chrome..." ) results <- run_app_driver_demo(demo_dir) message("Initial (Placebo) count: ", results$placebo) message("Updated (High Dose) count: ", results$high_dose) message("Updated (Low Dose) count: ", results$low_dose) message("AppDriver stopped cleanly. Demo complete.") }