如何針對使用 Matplotlib 的程式碼編寫單元測試?


為了針對某一程式碼編寫單元測試用例,我們可以考慮一個以陣列作為 x 點的圖,並將其繪製為 y=x^2. 在測試期間,我們將針對 x 資料點提取 y_data

步驟

  • 建立方法,即 plot_sqr_curve(x),使用 plot() 方法繪製 x 和 x^2,並返回圖形。
  • 進行測試時,使用 unittest.TestCase.
  • 編寫 test_curve_sqr_plot() 方法,包括以下陳述。
    • 建立 x 的資料點以繪製曲線。
    • 使用上述 x 資料點,建立 y 資料點。
    • 使用 x 和 y 資料點,繪製曲線。
    • 使用 pt(來自步驟 5),提取 x 和 y 資料。
    • 檢查給定表示式是否為真。

示例

import unittest
import numpy as np
from matplotlib import pyplot as plt
def plot_sqr_curve(x):
   """
   Plotting x points with y = x^2.
   """
return plt.plot(x, np.square(x))
class TestSqrCurve(unittest.TestCase):
def test_curve_sqr_plot(self):
   x = np.array([1, 3, 4])
   y = np.square(x)
   pt, = plot_sqr_curve(x)
   y_data = pt.get_data()[1]
   x_data = pt.get_data()[0]
   self.assertTrue((y == y_data).all())
   self.assertTrue((x == x_data).all())
if __name__ == '__main__':
   unittest.main()

輸出

Ran 1 test in 1.587s
OK

更新於: 2021 年 5 月 15 日

518 次瀏覽

助力你的 事業

完成課程可獲得認證

開始學習
廣告