1

我正在使用 chromote R 包,并且正在使用闪亮的应用程序对其进行测试。我正在尝试单击应该复制几个选择元素的图标。但是当我截屏时,我所拥有的只是工具提示,如果我打开浏览器,它会冻结 R 进程。

这是我的代码:

#' Run shiny in background - based on shinytest source code
#' @export
shiny.bg <- function(path, loadTimeout = 10000, shinyOptions = list()) {
  tempfile_format <- tempfile("%s-", fileext = ".log")
  p <- callr::r_bg(function(path, shinyOptions) {
    do.call(shiny::runApp, c(path, shinyOptions))
  },
  args = list(
      path = normalizePath(path),
      shinyOptions = shinyOptions
    ),
    stdout = sprintf(tempfile_format, "shiny-stdout"),
    stderr = sprintf(tempfile_format, "shiny-stderr"),
    supervise = TRUE
  )
  if (! p$is_alive()) {
    abort(paste0(
      "Failed to start shiny. Error: ",
      strwrap(readLines(p$get_error_file()))
    ))
  }
  ## Try to read out the port. Try 5 times/sec, until timeout.
  max_i <- loadTimeout / 1000 * 5
  for (i in seq_len(max_i)) {
    err_lines <- readLines(p$get_error_file())

    if (!p$is_alive()) {
      abort(paste0(
        "Error starting application:\n", paste(err_lines, collapse = "\n")
      ))
    }
    if (any(grepl("Listening on http", err_lines))) break

    Sys.sleep(0.2)
  }
  if (i == max_i) {
    abort(paste0(
      "Cannot find shiny port number. Error:\n", paste(err_lines, collapse = "\n")
    ))
  }

  line <- err_lines[grepl("Listening on http", err_lines)]
  m <- rematch::re_match(text = line, "https?://(?<host>[^:]+):(?<port>[0-9]+)")
  
  url <- sub(".*(https?://.*)", "\\1", line)
  
  list(
    process = p,
    url = url
  )
}

#' Run shiny application and Chromeote instance
chromote.shiny <- function() {
  chr <- chromote::ChromoteSession$new()
  app <- shiny.bg('.')
  
  chr$Page$navigate(app$url)
  chr$Page$loadEventFired()
  chr$screenshot()
  
  list(
    chr = chr,
    app = app
  )
}

#' kill browser and R shiny process
cleanUp <- function(obj) {
  obj$chr$Browser$close()
  obj$app$process$kill()
}

#' click on the element
chromote.click <- function(chromote, selector) {
  doc = chromote$DOM$getDocument()
  node = chromote$DOM$querySelector(doc$root$nodeId, selector)
  box <- chromote$DOM$getBoxModel(node$nodeId)
  left <- box$model$content[[1]]
  top <- box$model$content[[2]]
  x <- left + (box$model$width / 2)
  y <- top + (box$model$height / 2)
  chromote$Input$dispatchMouseEvent(type = "mousePressed", x = x, y = y, button="left")
  chromote$Input$dispatchMouseEvent(type = "mouseReleased", x = x, y = y, button="left")
}

tmp <- chromote.shiny()
chromote.click(tmp$chr, ".clone-pair")
tmp$chr$screenshot()

我不知道如何调试它,也没有太多关于如何点击的信息,我在 GitHub repo for chromote 中发现 dispatchMouseEvent 有问题。

回购链接https://github.com/rstudio/chromote

我想使用 chromote 的原因是我想为我的应用程序创建单元/集成测试,而 shinytest 已经过时了,它使用了几年前被遗弃的 phantomJS(所以你需要使用非常旧的 JavaScript,否则 pantomJS 会抛出错误并进行测试将失败)并且RSelenium也不再维护。

4

1 回答 1

0

有同样的问题。。

我发现这个库使用 chromote,但有许多来自 RSelenium 的函数(GetElement、Click)。

install.packages("remotes") 遥控器::install_github("rundel/hayalbaz")

于 2021-03-31T09:37:42.287 回答