> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lagerdata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 您的第一个测试

> 用 Lager 测试设备的完整演练

本指南带您完成一个完整的测试流程，可以用 Python，也可以用 Rust。流程从连通性开始，到自动化测试结束。完成之后，您可以交互式地使用 CLI，并编写自己的 Lager 测试脚本。

<Note>
  请先完成 [入门](/source/zh/getting-started/overview) 指南。本教程假设您已经安装了 CLI、添加了 Box，并用 Net 配置好了仪器。
</Note>

***

## 第 1 部分：CLI 演练

我们先用一条条 CLI 命令走完一个典型的测试流程。这对临时测试、调试和熟悉您的配置很有帮助。

### 第 1 步：确认您的 Box 在线

```bash theme={null}
lager hello --box my-lager-box
```

**预期输出：**

```
Box: my-lager-box
IP: <BOX_IP>
Version: 0.47.0 (v0.47.0@<commit>)

my-lager-box is online and responding!
```

### 第 2 步：查看已连接的仪器

```bash theme={null}
lager instruments --box my-lager-box
```

这条命令显示 Box 能看到的所有仪器。请确认您的电源、调试探针和其他仪器都出现在列表中。

### 第 3 步：查看已配置的 Net

```bash theme={null}
lager nets --box my-lager-box
```

这条命令显示您在后续命令中要使用的命名 Net。请记下这些 Net 名称，下面会用到。

### 第 4 步：设置默认值以减少输入

```bash theme={null}
lager defaults add --box my-lager-box
lager defaults add --supply-net POWER
lager defaults add --debug-net DEBUG_NET
```

设置默认值之后，后续命令可以省略 `--box` 和 Net 名称。

### 第 5 步：烧录固件

```bash theme={null}
lager debug flash --hex firmware.hex
```

**预期输出：**

```
Flashing firmware.hex to target...
Flash complete. 32768 bytes written.
```

### 第 6 步：给您的设备上电

```bash theme={null}
# 设置电压和保护阈值
lager supply voltage 3.3 --ovp 3.6 --ocp 0.5 --yes

# 打开输出
lager supply enable --yes
```

### 第 7 步：进行一次测量

```bash theme={null}
lager adc SENSOR_1
```

**预期输出：**

```
ADC 'SENSOR_1': 2.450000 V
```

### 第 8 步：断电

```bash theme={null}
lager supply disable --yes
```

测试结束后，请始终关闭电源输出。

***

## 第 2 部分：您的第一个测试脚本

现在把上面的手动 CLI 步骤变成一个可重复的测试。脚本总是会自己清理，即使发生错误也会关闭电源。

您可以用 Python 编写，它通过 `lager python` 在 Box 上运行。您也可以用 Rust 编写：在您的固件仓库中作为一个普通的 `cargo test`，使用 [`lager-net` crate](/source/zh/reference/rust/overview)。下面两个版本都会烧录、上电、测量、断言并清理。

<CodeGroup>
  ```python my_first_test.py theme={null}
  from lager import Net, NetType

  def main():
      # 获取我们的 Net
      psu = Net.get('POWER', type=NetType.PowerSupply)
      debug = Net.get('DEBUG_NET', type=NetType.Debug)
      sensor = Net.get('SENSOR_1', type=NetType.ADC)

      try:
          # 烧录固件
          print("Flashing firmware...")
          debug.connect()
          debug.flash(['firmware.hex'])
          debug.reset()
          print("Flash complete.")

          # 给 DUT 上电
          print("Enabling power supply at 3.3V...")
          psu.set_voltage(3.3)
          psu.set_current(0.5)
          psu.enable()
          print("Power enabled.")

          # 进行一次测量
          voltage = sensor.input()
          print(f"Sensor reading: {voltage:.4f} V")

          # 检查结果
          if 2.0 <= voltage <= 3.0:
              print("PASS: Sensor voltage within expected range.")
          else:
              print(f"FAIL: Sensor voltage {voltage:.4f}V outside range [2.0, 3.0]")

      finally:
          # 始终清理，即使发生错误
          print("Disabling power supply...")
          psu.disable()
          print("Done.")

  if __name__ == '__main__':
      main()
  ```

  ```rust tests/my_first_test.rs theme={null}
  use lager::LagerBox;

  #[test]
  fn sensor_reads_in_range_after_boot() -> lager::Result<()> {
      // 从环境变量读取 LAGER_BOX_HOST。
      let lager = LagerBox::from_env()?;
      let psu = lager.supply("POWER");
      let debug = lager.debug("DEBUG_NET");
      let sensor = lager.adc("SENSOR_1");

      // 烧录固件
      println!("Flashing firmware...");
      debug.connect()?;
      debug.flash("firmware.hex")?;
      debug.reset(false)?;
      println!("Flash complete.");

      // 给 DUT 上电
      println!("Enabling power supply at 3.3V...");
      psu.set_voltage(3.3)?;
      psu.set_current(0.5)?;
      psu.enable()?;
      println!("Power enabled.");

      // 进行一次测量并检查结果；在断言之前先关闭电源，
      // 这样失败的测试不会让 DUT 一直带电。
      let voltage = sensor.read()?;
      println!("Sensor reading: {voltage:.4} V");
      psu.disable()?;

      assert!(
          (2.0..=3.0).contains(&voltage),
          "sensor voltage {voltage:.4} V outside range [2.0, 3.0]"
      );
      Ok(())
  }
  ```
</CodeGroup>

<Note>
  清理可以保护您的硬件，所以两个版本都做了清理。Python 版本使用 `try/finally`，即使发生错误也会关闭电源。Rust 版本在断言之前关闭电源。更早的 `?` 错误同样会结束测试，并且失败信息会显示电源的状态。
</Note>

***

## 第 3 部分：运行测试

在您的 Lager Box 上执行这个 Python 脚本：

```bash theme={null}
lager python my_first_test.py --box my-lager-box
```

或者从您的项目运行 Rust 测试（在 `[dev-dependencies]` 中加入 `lager = { package = "lager-net", version = "0.4" }`）：

```bash theme={null}
LAGER_BOX_HOST=<box-ip> cargo test
```

**预期输出（Python）：**

```
Flashing firmware...
Flash complete.
Enabling power supply at 3.3V...
Power enabled.
Sensor reading: 2.4500 V
PASS: Sensor voltage within expected range.
Disabling power supply...
Done.
```

如果您需要随脚本一起发送其他文件（固件二进制文件、配置文件），请使用 `--add-file`：

```bash theme={null}
lager python my_first_test.py --box my-lager-box --add-file firmware.hex
```

***

## 接下来做什么

您已经用 Lager 完成了第一个测试。以下是可以继续探索的方向：

* **[CLI 参考](/source/zh/reference/cli/overview)** -- 每条 CLI 命令的完整文档
* **[Python API](/source/zh/reference/python/overview)** -- 完整的 Python SDK 参考
* **[Rust API](/source/zh/reference/rust/overview)** -- 把您的 HIL 测试套件写成 `cargo test` 集成测试
* **[故障排除](/source/zh/getting-started/troubleshooting)** -- 出现问题时的解决方法
* **[术语表](/source/zh/getting-started/glossary)** -- 文档中技术术语的定义

[示例脚本](https://github.com/lagerdata/lager/blob/main/docs/examples/demo_script.py) 是一个更大的例子。它把机械臂控制、USB 集线器电源循环、调试探针烧录和 ADC 测量组合在一起。
