我是机器人框架的新手,我正在尝试使用机器人框架自动化 API 测试,
框架如下所示,
我有一种情况,我需要使用一个测试用例到其他测试用例的变量(两个测试用例都在 TC1_api.robot 内部),
TC1_api.robot,
*** 设置***
Library RequestsLibrary
Library Collections
Variables ../config/variables.py
Library JSONLibrary
*** 测试用例***
Testcase1
code ...
# Extract ID from response
${response_json}= Convert String To Json ${response.content}
${id}= Get Value From Json ${response_json} message
Log To Console Created ID: ${id}
Set Suite Variable ${created_id} ${id}
Testcase2
code ....
${response}= GET On Session session /api/${created_id} headers=${headers}
Testcase3
.....
错误日志,
Test Cases
------------
[ WARN ] Keyword 'RequestsLibrary.To Json' is deprecated. Please use ${resp.json()} instead. Have a look at the improved HTML output as pretty printing replacement.
Get a single id details | FAIL |
Resolving variable '${{created_id}}' failed: Evaluating expression 'created_id' failed: NameError: name 'created_id' is not defined nor importable as module
-----------
Test Cases | FAIL |
1 test, 0 passed, 1 failed
要求:
请为此提供建议和示例
首先,如果你在套件中定义变量肯定不会有什么坏处——毕竟,它具有套件级别的作用域;执行此操作的位置位于“变量”部分(通常在设置和测试用例之间):
*** Variables ***
${created_id} not_set_failure_condition # it doesn't hurt setting some meaningful initial value, that will tip you off it hasn't been set to what you expect
然后,您使用它的方式严格依赖于以确切的顺序运行案例 - “Testcase1”必须始终在“Testcase2”之前运行,或者任何其他可能需要该变量的案例。这从来都不是一个好主意 - 测试用例应该是独立的,它应该自行验证 SUT 的功能。
在这些情况下,您显然需要该 ID - 必须对其进行设置,以便稍后使用。 在这种情况下,我建议您将其逻辑单独放入关键字中,
*** Keywords ***
Initialize The Objects # obviously, a name relevant for your use case
# the code that will get the value from where it is needed
Set Suite Variable ${created_id} ${id}
,然后在您的测试用例中您将调用关键字
*** Test Cases ***
Testcase2
# code ....
Initialize The Objects
${response}= GET On Session session /api/${created_id} headers=${headers}
或者,如果变量的值实际上每次运行只设置一次 - 例如它不会改变 b/n 情况,您可以在
Suite Setup
中调用该关键字(在“设置”部分中定义),
*** Setttings ***
Suite Setup Initialize The Objects
,从那时起 - 您不必在每种情况下都调用它。