如何为文件复制Python脚本创建GitLab自动化测试?
实现GitLab自动测试你的文件复制Python脚本的步骤
第一步:调整脚本以支持自动化测试
你的原脚本用input()获取目标路径,这种交互式输入无法在自动化测试中运行。建议改用命令行参数接收目标路径,同时把复制逻辑封装成函数,方便测试调用:
修改后的脚本示例:
import shutil import os from pathlib import Path import argparse def copy_files(src_list, dest_path): dest = Path(dest_path.strip()) if not dest.exists(): dest.mkdir(parents=True) print("Directory was created") else: print("Existing directory was chosen") for item in src_list: dest_dir_name, src_path = item src = Path(src_path) target_dir = dest / dest_dir_name if src.is_dir(): shutil.copytree(src, target_dir) elif src.is_file(): if not target_dir.exists(): target_dir.mkdir(parents=True) shutil.copy(src, target_dir) else: print(f"Error: {src_path} is not a valid file or directory") print(item) print("All files and directories have been copied!") if __name__ == "__main__": # 示例源文件/目录配置 src = [ ["docs_dir", "./test_docs"], ["data_file", "./test_data.txt"] ] parser = argparse.ArgumentParser(description='Copy specified files/directories to target path') parser.add_argument('dest', help='Destination path for copying') args = parser.parse_args() copy_files(src, args.dest)
第二步:编写单元测试用例
用pytest(Python常用测试框架)编写测试,利用临时目录模拟文件和目录,避免修改真实系统文件。
- 安装pytest:
pip install pytest
- 创建测试文件
test_copy_script.py:
import tempfile from pathlib import Path from your_script_name import copy_files # 替换成你的脚本文件名 def test_copy_files(): # 创建临时目录作为测试环境 with tempfile.TemporaryDirectory() as temp_dir: temp_dir_path = Path(temp_dir) # 创建测试用的源文件和目录 src_dir = temp_dir_path / "source_dir" src_dir.mkdir() (src_dir / "file1.txt").write_text("test content 1") src_file = temp_dir_path / "source_file.txt" src_file.write_text("test content 2") # 定义测试用的src_list test_src = [ ["target_dir", str(src_dir)], ["target_file_dir", str(src_file)] ] # 目标路径 dest_path = temp_dir_path / "destination" # 执行复制函数 copy_files(test_src, str(dest_path)) # 验证复制结果 copied_dir = dest_path / "target_dir" assert copied_dir.exists() assert (copied_dir / "file1.txt").read_text() == "test content 1" copied_file_dir = dest_path / "target_file_dir" assert copied_file_dir.exists() assert (copied_file_dir / "source_file.txt").read_text() == "test content 2" def test_non_existent_source(): with tempfile.TemporaryDirectory() as temp_dir: dest_path = Path(temp_dir) / "dest" test_src = [["invalid", str(Path(temp_dir) / "non_existent")]] # 执行复制,验证错误处理逻辑 copy_files(test_src, str(dest_path))
第三步:配置GitLab CI/CD流水线
在仓库根目录创建.gitlab-ci.yml文件,定义每次推送时自动运行测试的流程:
stages: - test test_job: stage: test image: python:3.11-slim # 选择适配你脚本的Python版本镜像 before_script: - pip install pytest script: - pytest test_copy_script.py -v only: - pushes
最后一步:提交并推送代码
把修改后的脚本、测试文件和.gitlab-ci.yml提交到GitLab仓库,之后每次推送代码,GitLab都会自动执行测试,你可以在仓库的CI/CD页面查看测试结果。
内容的提问来源于stack exchange,提问作者PatrickRKa
相关产品推荐
相关产品推荐

