Skip to main content

Meta b2e - Module 與 Test

Module

模組可以包含函數、類和變數,也可以包含可執行的程式碼。使用模組可以幫助把程式碼組織成不同的部分,以便重用和管理。

import

在其他 python 檔案中,要引用 module 中的變數或函式是使用 import,如:

Import example
# 引入整個 module
import mymodule

# 引入 module 中特定項目
from mymodule import myfunction, MyClass

# 導入所有項目
from mymodule import *

以實際例子來看:

mymodule.py
def greet(name):
print(f"Hello, {name}!")
index.py
import mymodule

# "Hello, World!"
mymodule.greet("World")
tip

上述例子使用 print(f"Hello, {name}!"),其中 f 叫做 f-string (字面量格式化字符串),它允許我們在字串中代入變數。
熟悉 JavaScript 的可以想像這個 f-string 就相當於 Template literals (即雙反引號 ``)。

reload

reload 用在重新加載之前已經加載的 module。
主要應用在程式運行中時,修改了 module 中的內容,但不希望重新運行程式時使用。

from importlib import reload
reload(mymodule)

mymodule.greet("World")

Test

測試種類 - 依測試人員對軟體內部實現細節的了解程度

  1. 黑箱測試 (Black Box Testing):測試人員不需要了解軟體的內部實現細節,只需要知道輸入和輸出的關係。
  2. 白箱測試 (White Box Testing):測試人員需要了解軟體的內部實現細節,以便測試軟體的每一個部分。

測試種類 - 依測試目的

  1. 驗收測試 (Acceptance Testing):最終用戶或客戶進行的測試,以確保系統符合他們的需求和預期。
  2. 系統測試 (System Testing):對整個系統進行測試,以確保它符合需求並且達到預期的功能。
  3. 整合測試 (Integration Testing):對系統中的不同部分進行測試,以確保它們能夠正確地協同工作。
  4. 單元測試 (Unit Testing):對程式中的最小單元進行測試,以確保它們能夠正確地工作。

PyTest - Python 測試框架

  1. 安裝 pytest
pip install pytest
  1. 撰寫需要測試的程式
spellcheck.py
def word_count(sentence):
# Function to check the number of words. Returns the word count in string.
words = len(sentence.split())
print(words)
return words

def char_count(sentence):
# Function to check the number of characters. Returns the character count in string.
chars = len(sentence)
print(chars)
return chars

def first_char(sentence):
# Function to check the first character using the string index. Returns the first character in string.
first = sentence[0]
return first

def last_char(sentence):
# Function to check the last character using the string index. Returns the last character in string.
last = sentence[-1]
return last
  1. 撰寫測試的程式
test_spellcheck.py
### WRITE IMPORT STATEMENTS HERE
import pytest
from spellcheck import word_count, char_count, first_char, last_char
# String variables to be tested
alpha = "Checking the length & structure of the sentence."
beta = "This sentence should fail the test"

# 透過 fixture 來傳入測試資料
@pytest.fixture
def input_value():
input = alpha
return input

# First test function test_length()
def test_length(input_value):
assert word_count(input_value) < 10
assert char_count(input_value) < 50


# Second test function test_struc()
def test_struc(input_value):
assert first_char(input_value).isupper() == True
assert last_char(input_value) == '.'
  1. 執行測試:
python3 -m pytest test_spellcheck.py

Test-driven development (TDD)

TDD 是一種軟體開發方法,它要求在開發新功能或修改現有功能之前先撰寫測試。
通常流程是:

  1. 撰寫測試。
  2. 運行測試,確保它失敗。
  3. 實現功能。
  4. 運行測試,確保它通過。
  5. 重構程式碼。
  6. 重複上述步驟。
warning

為何第二點要確保測試失敗? 因為這確保了這項測試確實能夠檢驗希望實現的功能。
如果測試一開始就通過,那麼這個測試就沒有意義。

參考資料

  1. Meta Back-End Developer Professional Certificate
  2. TDD (Test-Driven Development) 測試驅動開發(入門篇)
  3. 一次搞懂單元測試、整合測試、端對端測試之間的差異