[@liaoPythonImport2020] 指出 import 常常遇到的問題
[@loongProjectStructure2021] Python project structure 寫的非常好,本文直接引用作爲自己參考。
testing:
由於 Python 簡單易用,很多開始使用 Python 的人都是從一個 script 檔案開始,逐步形成多個 Python 檔案組成的程序。
在脫離 Python 幼幼班準備建立稍大型的專案的時候,學習如何組織化 Python 專案是一大要點。分成三個部分:
- 檔案放在同一個 directory 形成一個 package 打包。對應下面的簡單結構。
- 不同的 sub-packages 再用一個 (src) directory. 之後一起打包。對應下面的 src 結構的 src directory.
- Testing 非常重要,但是一般放在分開的 tests directory, 避免被打包。對應下面的 src 結構的 tests directory.
這裏討論 Testing.
Unittest
Pytest 的特點
-
會自動辨識 tests directory, test_xxx.py, 以及 def test_xxx module!
-
使用 assert 語法
-
可以直接在 command window 執行,或是在 vs code 執行。
-
如果在 command window 執行 python program, 例如 pytest:
在 PC Windows 10 PowerShell (PS), 必須這樣設定 PYTHONPATH:
1
$env:PYTHONPATH = ".\src"
在 Mac OS, 可以這樣設定 PYTHONPATH:
1
$export PYTHONPATH='./src'
-
如果在 vs code 執行 python program, 有兩種設定方式
- 直接在 launch.json 設定如下。此處是相當于設定 PYTHONPATH = “./src” 也就是 VS Code {workspaceRoot/src} folder.
- 第二種方法是 VS code default 會 load {workspaceRoot}/.env. 也可以用 launch.json 的 envFile 設定 path (這裡也是 ./.env)
1 |
|
.env file content 就只有一行:
1 |
|
好像第二種方法比較不會有問題?
phone_benchmark + pytest 爲例
首先看 tree structure:
1 |
|
src/phone_benchmark/gfxsql.py
先看 gfxsql.py 目的是輸入 gfxbench.html, parse and output to benchmark.db.
原則上每一個 function, 包含main, 都可以被測試。不過一般還是以主要的 function 爲主。
例如 parse_gfxbench_html().
1 |
|
tests/test_gfxsql.py
我們看 test_gfxsql.py
1 |
|
直接在 command window 執行 pytest : evoke tests\test_gfxsql.py
其中的兩項 test: test_main() and test_parse_gfxbench_html()
1 |
|