首页 > 解决方案 > 机器人框架和 Python - 检查文件是否存在

问题描述

我有一个命令行工具,可以将名为exportedfile.txt 的文本文件导出到Windows 系统中的C:\Temp 位置,其想法是在工具运行后检查导出的文件是否存在。

如果直接在具有 Robot Framework 和 Python 的 Windows 环境中运行,则以下示例有效:

Windows环境下的工作解决方案:

*** Settings ***
Library    OperatingSystem

*** Variables ***
${filePath}     C:\\Temp\\exportedfile.txt

*** Test Cases ***
TC01
    Check File Exists

*** Keywords ***
Check File Exists
    File Should Exist   ${filePath}

Linux/Windows 环境中发生的问题作为容器运行:

然而,由于在实际环境中,Robot Framework 作为以 Linux 为主机的容器运行,但导出文本文件的工具在 Windows 容器中运行,因此上述解决方案会导致此问题,因为它会尝试在 Linux 上查找文件:

File '/robot/C:\Temp\exportedfile.txt' does not exist.

尝试使用 Robot Framework 和 Python 的解决方案:

尝试结合使用 Robot Framework 和自定义 Python 库来做到这一点,如下所示:

文件.py

import os
from robot.api import logger

def file_exists(file):
    logger.info("Checking if file exists".format(), also_console=True)
    return os.path.isfile(file)

套件机器人

*** Settings ***
Library    ../../../libraries/tools/file.py

*** Test Cases ***
Playground
    Test File Exists

*** Keywords ***
Test File Exists
    ${fileExists}=    File Exists    suite.robot
    Run Keyword If    ${fileExists}    Log To Console    File Exists!

起初我实际上试图检查测试用例文件“suite.robot”本身是否存在,只是为了看看这种组合是否有效。

目前的结果是,当我检查机器人日志时,它显示为已通过,但对于关键字“测试文件存在”,可以在那里看到,${fileExists} = False因此由于某种原因,这个测试用例文件本身并没有像我认为的那样存在。

在实际版本中,我想检查 C:\Temp\exportedfile.txt 是否存在(我已经可以手动看到文件被命令行工具导出)。

标签: pythonrobotframework

解决方案


推荐阅读