1. 环境搭建与项目初始化

任务目标

本案例完成HIL(硬件在环)测试脚本开发的前置工作:搭建Python虚拟环境、安装必要依赖、创建标准化的项目目录结构,并初始化Git版本控制。完成后,你将获得一个可直接编写HIL测试脚本的工程骨架。

环境依赖

  • Python 3.9+(建议3.10或3.11)
  • Git 2.30+
  • 操作系统:Windows 10/11 或 Ubuntu 20.04+(本案例命令兼容两者,差异处已标注)

项目结构说明

采用分层结构区分测试用例、公共库与配置,便于后续案例扩展维护:


hil_test_project/
├── config/               # 配置文件目录
│   └── device_config.yaml
├── core/                 # 核心封装(硬件通信、日志等)
│   └── __init__.py
├── testcases/            # 测试用例目录
│   └── __init__.py
├── reports/              # 测试报告输出目录
├── requirements.txt      # 依赖清单
└── README.md

完整实现步骤

1. 创建项目目录结构(Windows PowerShell 或 Linux/macOS Terminal 执行):

mkdir hil_test_project
cd hil_test_project
mkdir config core testcases reports
type nul > config\device_config.yaml   # Windows
# Linux/macOS 使用: touch config/device_config.yaml
type nul > core\__init__.py            # Windows
# Linux/macOS 使用: touch core/__init__.py
type nul > testcases\__init__.py       # Windows
# Linux/macOS 使用: touch testcases/__init__.py
echo # HIL Test Project > README.md

2. 创建虚拟环境并激活:

python -m venv .venv
# Windows:
.venv\Scripts\activate
# Linux/macOS:
source .venv/bin/activate

3. 创建依赖清单文件 requirements.txt,内容如下:

pytest==7.4.0
pyyaml==6.0
python-can==4.3.1

4. 安装依赖:

pip install -r requirements.txt

5. 创建最小配置文件 config/device_config.yaml,用于后续案例读取硬件参数:

# HIL设备连接配置(示例值,实际使用时替换)
hardware:
  interface: "can"          # 通信接口类型
  channel: 0                # 通道号
  bitrate: 500000           # 波特率
  database: "path/to/dbc"   # DBC文件路径

6. 初始化Git版本控制:

git init
# 创建 .gitignore 文件,内容如下:
echo .venv/ > .gitignore
echo __pycache__/ >> .gitignore
echo reports/ >> .gitignore
echo *.pyc >> .gitignore

git add .
git commit -m "Initial HIL test project structure"

验证方法与通过标准

完成上述步骤后,依次执行以下命令验证环境就绪:

# 1. 确认虚拟环境已激活(命令行前缀出现 (.venv))
# 2. 确认依赖安装成功:
pip list | findstr "pytest pyyaml python-can"   # Windows
pip list | grep -E "pytest|pyyaml|python-can"   # Linux/macOS

# 3. 确认Git仓库状态干净:
git status

通过标准:

  • pip list 能同时看到 pytest、pyyaml、python-can 三个包及其版本号;
  • git status 输出 nothing to commit, working tree clean(或中文环境提示无待提交变更);
  • 项目目录结构与上文一致,config/device_config.yaml 文件存在且内容可读。

常见问题

  • pip安装缓慢或超时:可临时使用国内镜像源,如 pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple。
  • python-can安装失败(Windows):若提示缺少编译工具,请安装Microsoft C++ Build Tools,或改用预编译wheel包。
  • Git提交时提示用户信息未配置:先执行 git config --global user.email "you@example.com" 和 git config --global user.name "Your Name" 再重新提交。