0
0

More than 1 year has passed since last update.

3つのファイルのDiffを取るときの備忘録

Last updated at Posted at 2022-07-25

概要

  • 3つのファイルのDiffを取って違った場合にFAILEDになるテストスクリプトを作りたい
  • 比較する3つのファイル名は同じである
  • 2つのファイルを比較する場合difflibモジュールを使用することができるが、今回は3つのファイルを比較したいためsubprocessモジュールを使用して、diff3コマンドを実行してみる

参考

環境

# Pythonのバージョンを確認
python --version
> Python 3.7.3

# pytestのインストール
> pip install pytest

# natsortのインストール
> pip install natsort

実装

diff_3_files.py
import os
import glob
from natsort import natsorted
import pytest
import subprocess


folder_1 = "/path/folder_1"
folder_2 = "/path/folder_2"
folder_3 = "/path/folder_3"

files_1 = natsorted(glob.glob(os.path.join(folder_1, "*.txt")))

def get_testdata():

    testdata = []
    testdata_ids = []
    for filename_with_path in files_1:
        filename = os.path.basename(filename_with_path)
        filename = filename.split('.')[0]
        testdata.append(filename_with_path)
        testdata_ids.append(f'{filename}')
    
    return [testdata, testdata_ids]

testdata = get_testdata()[0]
testdata_ids = get_testdata()[1]


@pytest.mark.parametrize("id", testdata_ids)
def test_compare(id):
    
    target_file_1 = f"{folder_1}/{id}.txt"
    target_file_2 = f"{folder_2}/{id}.txt"
    target_file_3 = f"{folder_3}/{id}.txt"

    if not os.path.exists(target_file_1) or not os.path.exists(target_file_2) or not os.path.exists(target_file_3):
        raise FileNotFoundError

    # check_output: 引数でコマンドを実行し、その出力を返す。
    results = subprocess.check_output(['diff3',target_file_1,target_file_2,target_file_3])
    print(results.decode())

    assert not results, f"{target_file_1}, {target_file_2}, {target_file_3} FAILED!!"


結果

==================================================================================== test session starts =====================================================================================
platform darwin -- Python 3.7.3, pytest-7.1.2, pluggy-0.13.1 -- 
cachedir: .pytest_cache
rootdir: /Users/test
plugins: cov-2.12.1, freezegun-0.4.2, Faker-5.3.0, mock-3.7.0
collected 2 items                                                                                                                                                                            

test_diff_3.py::test_diff_3[1] PASSED                                                                                                                                                 [ 50%]
test_diff_3.py::test_diff_3[2] FAILED   
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0