MCP HubMCP Hub
스킬 목록으로 돌아가기

test-shiny-app

pjt222
업데이트됨 6 days ago
10 조회
17
2
17
GitHub에서 보기
테스팅testing

정보

이 스킬은 개발자가 샤이니 애플리케이션을 테스트하는 데 도움을 줍니다. end-to-end 브라우저 테스트에는 shinytest2를, 모듈 로직의 단위 테스트에는 testServer()를 사용합니다. 스냅샷 테스트, CI 통합, 외부 서비스 모킹을 다루며, 기존 앱에 테스트를 추가하거나 새 프로젝트의 테스트 환경을 설정할 때, 리팩토링 전 회귀 테스트를 작성할 때, CI/CD 파이프라인에 테스트를 통합할 때 활용할 수 있습니다.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/test-shiny-app

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

測試 Shiny 應用

以 shinytest2(端對端)與 testServer()(單元測試)為 Shiny 應用設立全面測試。

適用時機

  • 為既有 Shiny 應用加測試
  • 為新 Shiny 專案設立測試策略
  • 重構 Shiny 碼前寫回歸測試
  • 將 Shiny 應用測試整合入 CI/CD 管道

輸入

  • 必要:Shiny 應用之路徑
  • 必要:測試範圍(單元測試、端對端,或兩者)
  • 選擇性:是否用快照測試(預設:e2e 為 yes)
  • 選擇性:CI 平台(GitHub Actions、GitLab CI)
  • 選擇性:欲獨立測之模組

步驟

步驟一:安裝測試依賴

install.packages("shinytest2")

# For golem apps, add as a Suggests dependency
usethis::use_package("shinytest2", type = "Suggests")

# Set up testthat infrastructure if not present
usethis::use_testthat(edition = 3)

預期: shinytest2 已裝且 testthat 目錄結構就位。

失敗時: shinytest2 需 chromote(無頭 Chrome)。於系統裝 Chrome/Chromium。WSL 上:sudo apt install -y chromium-browser。以 chromote::find_chrome() 驗。

步驟二:為模組寫 testServer() 單元測試

tests/testthat/test-mod_dashboard.R

test_that("dashboard module filters data correctly", {
  testServer(dataFilterServer, args = list(
    data = reactive(iris),
    columns = c("Species", "Sepal.Length")
  ), {
    # Set inputs
    session$setInputs(column = "Species")
    session$setInputs(value_select = "setosa")
    session$setInputs(apply = 1)

    # Check output
    result <- filtered()
    expect_equal(nrow(result), 50)
    expect_true(all(result$Species == "setosa"))
  })
})

test_that("dashboard module handles empty data", {
  testServer(dataFilterServer, args = list(
    data = reactive(iris[0, ]),
    columns = c("Species")
  ), {
    # Module should not error on empty data
    expect_no_error(session$setInputs(column = "Species"))
  })
})

關鍵模式:

  • testServer() 無瀏覽器測模組伺服器邏輯
  • 透過 args 列表傳反應參數
  • session$setInputs() 模擬用戶互動
  • 直接以名存取反應回值
  • 測邊界情況:空資料、NULL 輸入、無效值

預期: 模組測試以 devtools::test() 通過。

失敗時:testServer() 報錯「不為模組伺服器函式」,確保函式內部用 moduleServer()。若 session$setInputs() 不觸發反應,於設輸入後加 session$flushReact()

步驟三:寫 shinytest2 端對端測試

tests/testthat/test-app-e2e.R

test_that("app loads and displays initial state", {
  # For golem apps
  app <- AppDriver$new(
    app_dir = system.file(package = "myapp"),
    name = "initial-load",
    height = 800,
    width = 1200
  )
  on.exit(app$stop(), add = TRUE)

  # Wait for app to load
  app$wait_for_idle(timeout = 10000)

  # Check that key elements exist
  app$expect_values()
})

test_that("filter interaction updates the table", {
  app <- AppDriver$new(
    app_dir = system.file(package = "myapp"),
    name = "filter-interaction"
  )
  on.exit(app$stop(), add = TRUE)

  # Interact with the app
  app$set_inputs(`filter1-column` = "cyl")
  app$wait_for_idle()

  app$set_inputs(`filter1-apply` = "click")
  app$wait_for_idle()

  # Snapshot the output values
  app$expect_values(output = "table")
})

關鍵模式:

  • AppDriver$new() 於無頭 Chrome 啟應用
  • 永遠用 on.exit(app$stop()) 清理
  • 模組輸入 ID 用 "moduleId-inputId" 格式
  • app$expect_values() 建/比對快照檔
  • app$wait_for_idle() 確反應更新完成

預期: 端對端測試於 tests/testthat/_snaps/ 建快照檔。

失敗時: 若找不到 Chrome,將 CHROMOTE_CHROME 環境變數設為 Chrome 二進位之路徑。若快照於 CI 失敗而本機過,檢平台依賴之渲染差——對資料快照用 app$expect_values(),而非對視覺者用 app$expect_screenshot()

步驟四:互動式錄製測試(選擇性)

shinytest2::record_test("path/to/app")

此於含錄製面板之瀏覽器中開應用。與應用互動,再點「Save test」自動產生測試碼。

預期: 一測試文件於 tests/testthat/ 中產生,含所錄互動。

失敗時: 若錄製器不開,先檢應用以 shiny::runApp() 成功執。錄製器需可運作之應用。

步驟五:設立快照管理

對快照測試,管理預期值:

# Accept new/changed snapshots after review
testthat::snapshot_accept("test-app-e2e")

# Review snapshot differences
testthat::snapshot_review("test-app-e2e")

將快照目錄加入版本控制:

tests/testthat/_snaps/    # Committed — contains expected values

預期: 快照檔於 git 中追蹤以供回歸偵測。

失敗時: 若快照意外變化,跑 testthat::snapshot_review() 看差。以 testthat::snapshot_accept() 接受意圖之變。

步驟六:與 CI 整合

加入 .github/workflows/R-CMD-check.yaml 或建專屬工作流:

- name: Install system dependencies
  run: |
    sudo apt-get update
    sudo apt-get install -y chromium-browser

- name: Set Chrome path
  run: echo "CHROMOTE_CHROME=$(which chromium-browser)" >> $GITHUB_ENV

- name: Run tests
  run: |
    Rscript -e 'devtools::test()'

對 golem 應用,確應用套件於測前已裝:

- name: Install app package
  run: Rscript -e 'devtools::install()'

預期: 測試於 CI 中以無頭 Chrome 通過。

失敗時: 常見 CI 問題:Chrome 未裝(加 apt-get 步驟)、顯示伺服器缺(shinytest2 預設用無頭模式故通常非問題)、慢執行器逾時(增 AppDriver$new()timeout)。

驗證

  • devtools::test() 無錯執所有測試
  • testServer() 測試含模組伺服器邏輯
  • shinytest2 測試含關鍵用戶工作流
  • 快照檔已提交至版本控制
  • 測試於 CI 環境中通過
  • 邊界情況已測(空資料、NULL 輸入、錯誤狀態)

常見陷阱

  • 測 UI 渲染而非邏輯:邏輯優先用 testServer(),資料用 app$expect_values()。僅當視覺外觀重要時用 app$expect_screenshot()——截圖跨平台脆弱。
  • e2e 測試中之模組 ID 格式:透過 AppDriver 設模組輸入時,用 "moduleId-inputId" 格式(連字符分隔),非 "moduleId.inputId"
  • 時序不穩:永遠於 app$set_inputs() 後叫 app$wait_for_idle()。否則斷言可能於反應更新完成前執。
  • 快照漂移:勿提交於不同平台(Mac vs Linux)所產之快照。將 CI 平台標準化為快照產生平台。
  • CI 缺 Chrome:shinytest2 需 Chrome/Chromium。永遠於 CI 工作流中含安裝步驟。

相關技能

  • build-shiny-module — 建可測之具清晰介面之模組
  • scaffold-shiny-app — 設立含測試基礎建設之應用結構
  • write-testthat-tests — R 套件之一般 testthat 模式
  • setup-github-actions-ci — R 套件(golem 應用)之 CI/CD 設立

GitHub 저장소

pjt222/agent-almanac
경로: i18n/wenyan-lite/skills/test-shiny-app
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

evaluating-llms-harness

테스팅

이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.

스킬 보기

cloudflare-cron-triggers

테스팅

이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.

스킬 보기

webapp-testing

테스팅

이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.

스킬 보기

finishing-a-development-branch

테스팅

이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.

스킬 보기