在 Linux 中使用 Bats 測試 Bash 指令碼


摘要

廣泛使用且有益的指令碼語言 bash 有無數的應用。儘管該語言本身被廣泛使用,但對其進行測試並不常見。這可能導致代價高昂的錯誤,並降低對程式碼的信任度。

在本文中,我們將瞭解如何在 Linux 中使用 Bats 測試 bash 指令碼。

注意 - Linux 命令區分大小寫。

什麼是 BATS?

Bash 自動化測試系統,有時稱為 BATS,是一個測試框架。在釋出 bash 程式之前,可以使用此自動化測試過程驗證它是否正常執行並達到其設計目標。正如我們將在本文中看到的,BATS 用於對 bash 指令碼執行測試,然後提供結果。

BATS 使程式設計師可以選擇使用 bash 指令碼和庫,並執行類似於 Python 或 Java 程式設計師使用的自動化測試過程。

如何設定 BATS?

假設您希望從 git 儲存庫啟動您的專案,我們應該首先在終端中安裝“git”(如果您尚未安裝)。

$ sudo apt update
$ sudo apt install git
$ git version

輸出

$ git version 2.34.1

要設定您的 git 儲存庫,請建立它或轉到專案目錄並執行以下命令。之後,透過將所需的儲存庫克隆為子模組來安裝 bats 及其庫。

$ git init
$ git submodule add https://github.com/bats-core/bats-core.git test/bats
$ git submodule add https://github.com/bats-core/bats-assert.git   test/test_helper/bats-files
$ git submodule add https://github.com/bats-core/bats-support.git test/test_helper/bats-support
$ git submodule add https://github.com/bats-core/bats-assert.git test/test_helper/bats-assert

配置您的 Bash 指令碼

首先使用以下程式碼建立一個新的 bash 檔案:

$ nano point.sh
#!/usr/bin/env bash

choice="Web Browser $1 over $2"
echo "$choice";echo "$choice" > $3
exit 0

先前命令的輸出顯示我們的 bash 指令碼接受三個引數,並在終端中輸出“choice”變數的值,以及建立一個具有相同輸出的文字檔案。讓我們將我們的程式付諸實踐以更好地理解。

script.txt   point.sh   firefox   Bing   log23.txt   google

輸出

Web Browser firefox over Bing

開始測試 Bash 指令碼

為了熟悉 BATS,最簡單的方法是進行簡單的測試。在測試目錄中,讓我們測試一個名為“tutorial.bats”的新檔案,其內容如下:

$ ./test/bats/bin/bats test/tutorial.bats

輸出

tutorial.bats
 ✗ can run our script
   (in test file test/tutorial.bats, line 2)
     './pointscript.sh' failed with status 127
   /home/etc/my_project/test/tutorial.bats: line 2: ./initproj.sh: No such file or directory
1 test, 1 failure

由於我們沒有同名檔案,因此測試顯然失敗了。因此,讓我們在 /tst 目錄中編寫一個基本的 bash 指令碼,如下所示:

$ mkdir tst/
$ echo '#!/usr/bin/bash' > initproj.sh
$ chmod a+x initproj.sh

執行下面顯示的命令以從根目錄執行我們之前的測試:

$ ./test/bats/bin/bats test/tutorial.bats
tutorial.bats
 ✓ can run our script
1 test, 0 failures

結論

在本教程中,我們學習瞭如何使用各種 bash 元件測試 bash 指令碼。我們學習瞭如何使用 Bats 庫測試 Bash 指令碼。我們學習瞭如何編寫自己的斷言,使用了庫提供的斷言工具,並建立了簡單的測試。

在決定對一個或多個 Bash 指令碼或庫應用測試規範後,BATS 提供了在其他軟體開發環境中看到的廣泛測試功能。

希望您發現這些命令示例有用。

更新於: 2023-03-23

473 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.