str*_*sus 6 groovy metaprogramming katalon-studio
我想知道是否可以检索变量的名称。
例如,如果我有一个方法:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
Run Code Online (Sandbox Code Playgroud)
如果我按如下方式调用此方法:
def ordinary = 58
printSomething(ordinary)
Run Code Online (Sandbox Code Playgroud)
我想得到:
ordinary is 58
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我这样调用这个方法:
def extraOrdinary = 67
printSomething(extraOrdinary)
Run Code Online (Sandbox Code Playgroud)
我想得到:
extraOrdinary is 67
Run Code Online (Sandbox Code Playgroud)
编辑
我需要变量名称,因为我有这段代码在Katalon Studio中的每个TestSuite之前运行,基本上它为您提供了使用 katalon.features 文件传递 GlobalVariables 的灵活性。这个想法来自:kazurayam/KatalonPropertiesDemo
@BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
Run Code Online (Sandbox Code Playgroud)
现在这只处理 1 个变量值,如果我对 20 个变量执行此操作,那就是很多重复代码,所以我想创建一个辅助函数:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我只是用 var.getName() 来解释我正在寻找的内容,这只是我假设的一种方法。
是的,这可以通过 ASTTransformations 或宏 (Groovy 2.5+) 实现。
我目前没有合适的开发环境,但这里有一些提示:
这并不是说这两个选项都不是微不足道的,我不会推荐 Groovy 新手,您必须做一些研究。如果我没记错的话,任一选项都需要与调用代码分开的构建/项目才能可靠工作。此外,它们中的任何一个都可能会给您带来模糊且难以调试的编译时错误,例如,当您的代码需要变量作为参数但传递了文字或方法调用时。所以:有龙。话虽这么说:我在这些事情上做了很多工作,它们真的很有趣;)
如果您使用的是 Groovy 2.5+,则可以使用宏。对于您的用例,请查看参考资料@Macro methods部分。您的方法将有两个参数:MacroContext macroContext, MethodCallExpression callExpression后者是有趣的参数。MethodCallExpression具有-Methods,它允许您访问作为参数传递给方法的抽象语法树节点。getArguments()在你的情况下,它应该是一个VariableExpression,它有getName()方法为你提供你正在寻找的名称。
这是更复杂的版本。您仍然会得到VariableExpression与宏方法相同的结果,但是到达那里会很乏味,因为您必须MethodCallExpression自己确定正确的方法。你从a开始ClassNode,然后努力达到你VariableExpression自己。我建议使用本地转换并创建注释。但确定正确的方法MethodCallExpression并非易事。
| 归档时间: |
|
| 查看次数: |
4897 次 |
| 最近记录: |