我正在尝试通过.cmd文件自动化我使用测试套件制作的程序。

我可以通过%errorlevel%获取我运行的返回代码的程序。

我的程序针对每种类型的错误都有一定的返回码。

例如:

1 - 意味着因为这样的原因而失败

2 - 由于其他原因意味着失败

...

echo FAILED:测试用例失败,错误级别:%errorlevel%>> TestSuite1Log.txt

相反,我想以某种方式说:

echo FAILED:测试用例失败,错误原因:lookupError(%errorlevel%)>> TestSuite1Log.txt

这是否可以使用.bat文件?或者我是否必须转向像python / perl这样的脚本语言?

有帮助吗?

解决方案

您可以使用 ENABLEDELAYEDEXPANSION 选项完美地完成此操作。这允许您使用作为在之后计算的变量标记。

REM Turn on Delayed Expansion
SETLOCAL ENABLEDELAYEDEXPANSION

REM Define messages as variables with the ERRORLEVEL on the end of the name
SET MESSAGE0=Everything is fine
SET MESSAGE1=Failed for such and such a reason
SET MESSAGE2=Failed for some other reason

REM Set ERRORLEVEL - or run command here
SET ERRORLEVEL=2

REM Print the message corresponding to the ERRORLEVEL
ECHO !MESSAGE%ERRORLEVEL%!

在命令提示符下键入 HELP SETLOCAL HELP SET ,以获取有关延迟扩展的更多信息。

其他提示

您可以执行以下代码之类的操作。请注意,由于cmd怪癖,错误级别比较应按降序排列。

setlocal

rem Main script
call :LookupErrorReason %errorlevel%
echo FAILED Test case failed, error reason: %errorreason% >> TestSuite1Log.txt
goto :EndOfScript

rem Lookup subroutine
:LookupErrorReason
  if %%1 == 3 set errorreason=Some reason
  if %%1 == 2 set errorreason=Another reason
  if %%1 == 1 set errorreason=Third reason
goto :EndOfScript

:EndOfScript
endlocal

不完全是这样,使用子程序,但您可以使用转到解决方法。

如果你的这个测试套件使用更强大的语言增长很多,可能会更容易。 Perl甚至Windows Scripting Host都可以为您提供帮助。

是的,你可以使用电话。只需在新行上调用,并传递错误代码。这应该有效,但我还没有测试过。

C:\Users\matt.MATTLANT>help call
Calls one batch program from another.

CALL [drive:][path]filename [batch-parameters]

  batch-parameters   Specifies any command-line information required by the
                     batch program.

SEDIT:orry我可能误解了一下,但你也可以使用IF

以相反的顺序测试您的值,并使用 IF 的重载行为:

@echo off
myApp.exe
if errorlevel 2 goto Do2
if errorlevel 1 goto do1
echo Success
goto End

:Do2
echo Something when 2 returned
goto End

:Do1
echo Something when 1 returned
goto End

:End

如果你想要更强大,你可以尝试这样的事情(你需要用%errorlevel替换%1但是我更难测试)。您需要为您处理的每个错误级别添加标签:

@echo off
echo passed %1
goto Label%1

:Label
echo not matched!
goto end

:Label1
echo One
goto end

:Label2
echo Two
goto end

:end

这是一个测试:

C:\>test
passed
not matched!

C:\>test 9
passed 9
The system cannot find the batch label specified - Label9

C:\>test 1
passed 1
One

C:\>test 2
passed 2
Two

您可以使用'IF ERRORLEVEL'语句根据返回码执行不同的操作。

请参阅:

http://www.robvanderwoude.com/errorlevel.html

在回答第二个问题时,无论如何我会转而使用脚本语言,因为Windows批处理文件本质上是如此有限。 Perl,Python,Ruby等都有很棒的Windows发行版,所以没有理由不使用它们。我个人喜欢在Windows上进行Perl脚本编写。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top