pytest에서 difflib을 사용해 보았습니다. (예시 첨부)

10218 단어 pytest

소개하다.


처음 Qita 기사를 쓰는데 잘 부탁드립니다.
저는 평소에 EC시스템을 맡고 있습니다. 저희 팀은 테스트를 잘 쓰기로 결정했기 때문에pytest를 가져오고 싶습니다.이번에 가져온 항목은 메일 템플릿 API입니다.여기의 메일 템플릿 API는 EC 웹 사이트에서 주문한 후 고객에게 메일의 내용을 생성하여 처리하는 API입니다.
이전에 bash에서 이루어진 메일 내용 생성 처리를 파이톤의 API로 옮깁니다.
  • pythhon 전이 테스트에 다음과 같은 문제가 존재합니다
  • 응답 항목 중 하나인 메일 내용에 대한 결단이 필요하지만 내용이 길기 때문에 assert를 사용하면 결과가 보기 어렵다
  • 우편 내용은 주문점(Yahoo, Amazon...등)과 우편 종류(주문 확인, 발송...등)의 조합에 따라 여러 종류가 있어 모든 조합에 대한 테스트 용례 마련이 어렵다
  • 다음과 같은 방법으로 각 과제를 해결하였다.
  • 메일의 결단에서 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.txt
    xxx様
    
    この度は「店舗」をご利用いただき、誠にありがとうございます。
    
    ご注文内容は下記の通りです。test
    
    商品発送後、改めて『商品の発送のお知らせ』メールを送信させていただきます。
    

    코드


    test_message.py
    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
    
    

    결실



    메일의 차이를 볼 수 있습니다!

    좋은 웹페이지 즐겨찾기