pytestで、csvファイルからテストデータを読み込んで流し込んで実施してみた
目的
- pytestでのテスト時に、ソースコードにテストデータを書くのは効率が悪そう。
- excel等で生成したcsvデータを流し込めるようにしたい
試した環境
- python 3.6.1
- pytest 3.0.7
ソースコードと実行方法
フォルダ構成
テスト対象のソースコード
引数として与えられたリストに入っている数値の和を取ります。
# newFuncs.py
import numpy as np
def getSum(numbers):
arr = np.array(numbers)
return arr.sum()
テストデータ
5通りのデータをセットしています。
1行目は表のタイトル行です。
nums ans
1,2,3 6
3,4,5 12
3,4,5,8,6,5 31
3,4,5 12
3,4,5 12
テストコードのソースコード
地の部分にcsvの読み込み等を書いています。
# test_newFuncs.py
import numpy as np
import pandas as pd
import pytest
# テスト対象の関数を読み込む
from newFuncs import getSum
# テストデータをDataFrame形式で読み込む
datas = pd.read_csv("testDatas.csv", sep = " ")
# テストデータを1つずつリストにappendしていく
testDatas = []
for _, dat in datas.iterrows():
list = np.array(dat["nums"].split(","), dtype = np.int).tolist()
# データの形式は、[[nums1, ans1], [nums2, ans2], ...]
testDatas.append([list, dat.ans])
# デコレータでテストデータにセット
@pytest.mark.parametrize("nums, ans", testDatas)
def test_add(nums, ans):
# テストの実行
assert getSum(nums) == ans
init.pyには何も書いていません。
実行結果
この状態で、実行すると、以下のようになります。
各テスト結果を出力するよう、-vオプションを付けています。
> pytest -v
============================= test session starts =============================
platform win32 -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- C:\Users\miler\Anaconda3\python.exe
cachedir: .cache
rootdir: C:\py\pytest_study, inifile:
collected 5 items
tests/test_newFuncs.py::test_add[nums0-6] PASSED
tests/test_newFuncs.py::test_add[nums1-12] PASSED
tests/test_newFuncs.py::test_add[nums2-31] PASSED
tests/test_newFuncs.py::test_add[nums3-12] PASSED
tests/test_newFuncs.py::test_add[nums4-12] PASSED
========================== 5 passed in 0.62 seconds ===========================
テストデータにある通り、5通りのテストが実施できています。
Author And Source
この問題について(pytestで、csvファイルからテストデータを読み込んで流し込んで実施してみた), 我々は、より多くの情報をここで見つけました https://qiita.com/miler0528/items/0c86eba5352d84040415著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .