在 JMeter 中继续从 UI 到 API 的会话

Continue Session from UI to API in JMeter

问题陈述:在我的应用程序中有一个令牌无法直接从 api 调用或其他方式生成它,因为它是使用 OAUTH 实现的。所以绕道而行,通过API实现了自动化。通过使用 Webdriver 采样器。使用以下脚本。

WDS.sampleResult.sampleStart()
WDS.browser.get('appurl');
java.lang.Thread.sleep(10000);
WDS.browser.findElement(org.openqa.selenium.By.id("details-button")).click();
WDS.browser.findElement(org.openqa.selenium.By.id("proceed-link")).click();
WDS.browser.findElement(org.openqa.selenium.By.id("i0116")).sendKeys("username"); //enter user name and password in login.microsoft.com
WDS.browser.findElement(org.openqa.selenium.By.id("idSIButton9")).click();
WDS.browser.findElement(org.openqa.selenium.By.id("i0118")).sendKeys("password");
WDS.browser.findElement(org.openqa.selenium.By.id("idSIButton9")).click();
WDS.browser.findElement(org.openqa.selenium.By.id("idSIButton9")).click();
//WDS.sampleResult.sampleEnd()

这很好用,我可以使用正则表达式提取器检索令牌。

在 API 调用中使用令牌并出现重试错误

JMeter 失败(获取 IO 错误超过重试次数 =,尝试了 20、50、200,现在是 500)

浏览器:

怀疑会话 ID 可能是我没有传输或者是否遗漏了什么(记住我没有终止浏览器会话)

我认为你需要复制 cookies from the browser to the HTTP Request 采样器

  1. HTTP Cookie Manager 添加到您的测试计划

  2. 将下一行添加到您的 WebDriver Sampler 代码中:

    WDS.vars.putObject('cookies', WDS.browser.manage().getCookies())
    
  3. 添加 JSR223 PreProcessor 作为 HTTP 请求采样器的子项,您希望从 UI 复制会话并将以下代码放入“脚本”区域:

    vars.getObject('cookies').each { cookie ->
        sampler.getCookieManager().add(new org.apache.jmeter.protocol.http.control.Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.secure, cookie.getExpiry().getTime()))
    }
    
  4. 就是这样,HTTP 请求采样器现在应该发送 cookie,您应该已经过身份验证

有关使用 Groovy 代码操作 cookie 的更多信息:Modifying Cookies in JMeter with Groovy

如果我处在你的位置,我应该会同意德米特里的回答。但是我们最近遇到了类似的问题,我们在 cookie 中发送 JSessionIdDead-SessionId。我们通过以下方式解决

  1. Http Cookie manager 添加到您的测试计划。

  2. 在UI采样器中请添加示例代码,

    WDS.vars.putObject('sessionCookies', WDS.browser.manage().getCookies())

  3. 使用以下脚本将 JSR223 PreProcessor 添加到您的 Http request

    vars.getObject('sessionCookies').each { scookie ->
    sampler.getCookieManager().add(new org.apache.jmeter.protocol.http.control.Cookie
    (scookie.getName(), 
    scookie.getValue(), 
    scookie.getDomain(), 
    scookie.getPath(), 
    scookie.secure, 
    System.currentTimeMillis() + 10000))
    

    }

在我们的例子中,我们没有发送给我们的到期时间

ERROR o.a.j.m.JSR223PreProcessor: Problem in JSR223 script, JSR223 PreProcessor javax.script.ScriptException: java.lang.NullPointerException: Cannot invoke method getTime() on null object at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:320) ~[groovy-jsr223-3.0.3.jar:3.0.3]

所以我们用System.currentTimeMillis() + 10000

替换了cookie.getExpiry().getTime()