pytest에서 difflib을 사용해 보았습니다. (예시 첨부)
10218 단어 pytest
소개하다.
처음 Qita 기사를 쓰는데 잘 부탁드립니다.
저는 평소에 EC시스템을 맡고 있습니다. 저희 팀은 테스트를 잘 쓰기로 결정했기 때문에pytest를 가져오고 싶습니다.이번에 가져온 항목은 메일 템플릿 API입니다.여기의 메일 템플릿 API는 EC 웹 사이트에서 주문한 후 고객에게 메일의 내용을 생성하여 처리하는 API입니다.
이전에 bash에서 이루어진 메일 내용 생성 처리를 파이톤의 API로 옮깁니다.
git diff
명령의 출력 결과 등에도 사용된 표준 라이브러리의 difflib를 관습적인 형식으로 차분 비교pytest
의parametetrize 근사ptest의 표준 test discovery 규칙
test_*.py
또는 *_test.py
Test
test_
Parametrizing
각종 파라미터를 테스트하고 싶을 때
@pytest.mark.parametrize
는 매우 편리하다.이 예에서 많은 그룹
店舗、メールタイプ、注文番号
을 테스트하고 싶어서 테스트 함수 하나만 만들면 OK.절차. # pytestインストール
$ pip install pytest
# pytestインストールできた確認
$ pytest --version
# pytestを実行
# -vは結果を詳細に表示する
$ pytest -v
입력
1_1_2xxx.txtxxx様
この度は「店舗」をご利用いただき、誠にありがとうございます。
ご注文内容は下記の通りです。test
商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。
코드
test_message.pyfrom pathlib import Path
import os
import difflib
import pytest
local_path = Path.cwd()
txt_dir = local_path.joinpath('data')
def get_testdata():
"""
`data`フォルダーにファイル名からテストデータを作る
Returns:
list: parametrizeのtestdataとids
"""
testdata = []
testdata_ids = []
for filename_with_path in txt_dir.glob('*_*_*.txt'):
filename = os.path.basename(filename_with_path)
mail_type = filename.split('_')[0]
order_shop = filename.split('_')[1]
order_no = filename.split('_')[2]
testdata.append(tuple((order_shop, mail_type, order_no)))
testdata_ids.append(f'{order_shop}_{mail_type}_{order_no}')
return [testdata, testdata_ids]
testdata = get_testdata()[0]
testdata_ids = get_testdata()[1]
@pytest.mark.parametrize('order_shop, mail_type, order_no',
testdata,
ids=testdata_ids)
def test_mail_message(order_shop: str, mail_type: str, order_no: str):
"""
shell作ったメールテンプレートとpythonのを比較する
Args:
order_shop (str): 店舗
mail_type (str): メールタイプ
order_no (str): 注文番号
"""
# このプログラミングで作成したメールテンプレートを読み込む
fromfile = '''xxx様
この度は「店舗」をご利用いただき、誠にありがとうございます。
ご注文内容は下記の通りです。
商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。'''
# shellで作成したメールテンプレートを読み込む
compare_file = local_path.joinpath('data').joinpath(
f'{order_shop}_{mail_type}_{order_no}')
if compare_file.is_file():
with open(compare_file) as f:
tofile = f.read()
# 比較を実施
diff = difflib.unified_diff(fromfile.splitlines(keepends=True),
tofile.splitlines(keepends=True),
fromfile='python-mail-api',
tofile='shell-mail-api')
diff_str = ''.join(diff)
print(diff_str)
assert not diff_str
결실
메일의 차이를 볼 수 있습니다!
Reference
이 문제에 관하여(pytest에서 difflib을 사용해 보았습니다. (예시 첨부)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/sam159247/items/b260e183136d2a1662fd
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
# pytestインストール
$ pip install pytest
# pytestインストールできた確認
$ pytest --version
# pytestを実行
# -vは結果を詳細に表示する
$ pytest -v
1_1_2xxx.txt
xxx様
この度は「店舗」をご利用いただき、誠にありがとうございます。
ご注文内容は下記の通りです。test
商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。
코드
test_message.pyfrom pathlib import Path
import os
import difflib
import pytest
local_path = Path.cwd()
txt_dir = local_path.joinpath('data')
def get_testdata():
"""
`data`フォルダーにファイル名からテストデータを作る
Returns:
list: parametrizeのtestdataとids
"""
testdata = []
testdata_ids = []
for filename_with_path in txt_dir.glob('*_*_*.txt'):
filename = os.path.basename(filename_with_path)
mail_type = filename.split('_')[0]
order_shop = filename.split('_')[1]
order_no = filename.split('_')[2]
testdata.append(tuple((order_shop, mail_type, order_no)))
testdata_ids.append(f'{order_shop}_{mail_type}_{order_no}')
return [testdata, testdata_ids]
testdata = get_testdata()[0]
testdata_ids = get_testdata()[1]
@pytest.mark.parametrize('order_shop, mail_type, order_no',
testdata,
ids=testdata_ids)
def test_mail_message(order_shop: str, mail_type: str, order_no: str):
"""
shell作ったメールテンプレートとpythonのを比較する
Args:
order_shop (str): 店舗
mail_type (str): メールタイプ
order_no (str): 注文番号
"""
# このプログラミングで作成したメールテンプレートを読み込む
fromfile = '''xxx様
この度は「店舗」をご利用いただき、誠にありがとうございます。
ご注文内容は下記の通りです。
商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。'''
# shellで作成したメールテンプレートを読み込む
compare_file = local_path.joinpath('data').joinpath(
f'{order_shop}_{mail_type}_{order_no}')
if compare_file.is_file():
with open(compare_file) as f:
tofile = f.read()
# 比較を実施
diff = difflib.unified_diff(fromfile.splitlines(keepends=True),
tofile.splitlines(keepends=True),
fromfile='python-mail-api',
tofile='shell-mail-api')
diff_str = ''.join(diff)
print(diff_str)
assert not diff_str
결실
메일의 차이를 볼 수 있습니다!
Reference
이 문제에 관하여(pytest에서 difflib을 사용해 보았습니다. (예시 첨부)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/sam159247/items/b260e183136d2a1662fd
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
from pathlib import Path
import os
import difflib
import pytest
local_path = Path.cwd()
txt_dir = local_path.joinpath('data')
def get_testdata():
"""
`data`フォルダーにファイル名からテストデータを作る
Returns:
list: parametrizeのtestdataとids
"""
testdata = []
testdata_ids = []
for filename_with_path in txt_dir.glob('*_*_*.txt'):
filename = os.path.basename(filename_with_path)
mail_type = filename.split('_')[0]
order_shop = filename.split('_')[1]
order_no = filename.split('_')[2]
testdata.append(tuple((order_shop, mail_type, order_no)))
testdata_ids.append(f'{order_shop}_{mail_type}_{order_no}')
return [testdata, testdata_ids]
testdata = get_testdata()[0]
testdata_ids = get_testdata()[1]
@pytest.mark.parametrize('order_shop, mail_type, order_no',
testdata,
ids=testdata_ids)
def test_mail_message(order_shop: str, mail_type: str, order_no: str):
"""
shell作ったメールテンプレートとpythonのを比較する
Args:
order_shop (str): 店舗
mail_type (str): メールタイプ
order_no (str): 注文番号
"""
# このプログラミングで作成したメールテンプレートを読み込む
fromfile = '''xxx様
この度は「店舗」をご利用いただき、誠にありがとうございます。
ご注文内容は下記の通りです。
商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。'''
# shellで作成したメールテンプレートを読み込む
compare_file = local_path.joinpath('data').joinpath(
f'{order_shop}_{mail_type}_{order_no}')
if compare_file.is_file():
with open(compare_file) as f:
tofile = f.read()
# 比較を実施
diff = difflib.unified_diff(fromfile.splitlines(keepends=True),
tofile.splitlines(keepends=True),
fromfile='python-mail-api',
tofile='shell-mail-api')
diff_str = ''.join(diff)
print(diff_str)
assert not diff_str
메일의 차이를 볼 수 있습니다!
Reference
이 문제에 관하여(pytest에서 difflib을 사용해 보았습니다. (예시 첨부)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/sam159247/items/b260e183136d2a1662fd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)