Python接口自動化測試框架之封裝shutil目錄及文件操作類

現在的程序,尤其是代碼,沒有多少是自己寫的了,爲什麼這麼說?除了不去開發新的技術,其他的都是炒剩飯。

那麼我也是屬於這一類,大多數的代碼照着源碼封裝一次後,就不再去管,只有出了了問題才維護或者完善,甚至將封裝當成了很高深的東西,硬把已經很簡潔的源碼再次封裝,真是強扭啊~

#!/usr/bin/python3

import config
import shutil
import os
import difflib
import sys
from hashlib import md5
from utils.HandleLogging import log
from celery.utils.sysinfo import df


diffFile = os.path.join(config.report_path, '比較文件內容異同_diff.html')
backupDiffFile = os.path.join(config.report_path, '比較文件內容異同_diff_back.html')

class HandleDirFile(object):
    """
    處理文件(夾)的工具類,主要用到shutil第三方庫
    """
#     def __init__(self,src_path,dest_path):
#         self.srcPath=src_path
#         self.destPath=dest_path

    def read_json(self, filename):
        '''
        讀取json格式文件的數據,進行內容分割
        '''
        try:
            with open(filename, 'r', encoding='utf-8') as fileHandle:
                text = fileHandle.read().splitlines()
            return text
        except IOError as e:
            log.error("文件讀取失敗:" + e)
            sys.exit()


    def md5_file(self, filename):
        '''
                        比較兩個文件內容的md5值
        '''
        m = md5()
        try:
            with  open(filename, 'rb') as a_file:  # 需要使用二進制格式讀取文件內容
                m.update(a_file.read())
        except Exception as e:
            log.error("文件讀取失敗:" + e)
        return m.hexdigest()


    def diff_json(self, filename1, filename2):
        '''
        比較兩個文件內容的md5值;比較兩個文件並輸出到html文件中
        '''
        file1Md5 = self.md5_file(filename1)
        file2Md5 = self.md5_file(filename2)
    
        if file1Md5 != file2Md5:
#             log.info('兩個json數據文件md5不一樣:')
            text1_lines = self.read_json(filename1)
            text2_lines = self.read_json(filename2)
            d = difflib.HtmlDiff()
            # context=True時只顯示差異的上下文,默認顯示5行,由numlines參數控制,context=False顯示全文,差異部分顏色高亮,默認爲顯示全文
            result = d.make_file(text1_lines, text2_lines, filename1, filename2, context=True)
            
            # 內容保存到result.html文件中
            try:
                with open(diffFile, 'a', encoding='utf-8') as result_file:
                    result_file.write(result)
            except Exception as e:
                log.error("寫入文件失敗:" + e)
                

    def move_file(self, srcPath, destPath):
        '''
        move文件(夾)移動,可覆蓋
        srcPath:源文件(夾)路徑
        destPath:目標文件(夾)路徑
        return:
        '''
        try:
            shutil.move(srcPath, destPath)
        except Exception as e:
            raise e

    
    def copy_dir(self, srcPath, destPath):
        '''
        copytree:文件(夾)移動,不可覆蓋
        srcPath:源文件(夾)路徑
        destPath:目標文件(夾)路徑,必須不存在
        return: 
        '''
#         判斷目錄是否存在
        if os.path.isdir(destPath):
            log.info("{}存在則刪除".format(destPath))
            shutil.rmtree(destPath)
        try:
            shutil.copytree(srcPath, destPath)
        except Exception as e:
            raise e
    
    
    def copy_file(self, srcPath, destPath):
        '''
        srcPath:源文件(夾)路徑
        destPath:目標文件(夾)路徑,必須不存在
        return: 
        '''
        
        destfile = self.get_file_list(destPath)
        srcfile = self.get_file_list(srcPath)
        
        file_list = []
        for df in destfile:
            file_list.append(df.split("\\")[len(df.split("\\")) - 1])
        
        for sf in srcfile:
            if sf.split("\\")[len(sf.split("\\")) - 1] not in file_list:
                log.info("{}文件不存在於備份目錄才執行".format(sf.split("\\")[len(sf.split("\\")) - 1]))
#                 print(config.back_path + sf.split("\\")[len(sf.split("\\")) - 2] + '\\' + sf.split("\\")[len(sf.split("\\")) - 1])
                destDir=config.back_path + sf.split("\\")[len(sf.split("\\")) - 2]+"\\"
                if not os.path.exists(destDir):
                    os.makedirs(destDir)
                shutil.copyfile(sf, destDir+sf.split("\\")[len(sf.split("\\")) - 1])
                

    def diff_dir_file(self, srcPath, destPath):
        '''
        比較兩個文件夾及子目錄下的文件
        '''
        
        if os.path.isfile(diffFile):
            try:
#                 刪除文件前先備份文件
                shutil.copyfile(diffFile,backupDiffFile)
                os.remove(diffFile)
            except Exception as e:
                log.error("備份/刪除文件:%s,失敗!" % diffFile)
                raise e
        else:
            log.info("no such file:%s" % diffFile)
            
#         獲取目錄下的所有文件,返回list
        srcfile = self.get_file_list(srcPath)
        destfile = self.get_file_list(destPath)
        
        for sf in srcfile:
            for df in destfile:
                if sf.split("\\")[len(sf.split("\\")) - 1] == df.split("\\")[len(df.split("\\")) - 1]:
                    self.diff_json(sf, df)
#                     log.info("他們名字一樣,內容纔可以比較:{}=={}".format(sf.split("\\")[len(sf.split("\\"))-1],df.split("\\")[len(df.split("\\"))-1]))

    def get_file_list(self, filepath):
            '''
                        獲取文件夾下所有文件名
            filepath:文件路徑
            return:返回文件夾下及子目錄的所有文件
            '''
            filepath_list = []
            for root_dir, sub_dir, files in os.walk(filepath):
    #             print('root_dir:', root_dir)  # 當前目錄路徑
    #             print('sub_dirs:', sub_dir)  # 當前路徑下所有子目錄
                log.info(sub_dir)
    #             print('file_name:', files)  # 當前路徑下所有非目錄子文件
                for i in range(0, len(files)):
                    filepath_list.append(root_dir + "\\" + files[i])
                    
            return filepath_list
        
if __name__ == '__main__':
    file = HandleDirFile()
    file.copy_file(config.case_path, config.back_path)
    
        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章