Buffer in JS file isn't recognized (API tests automation with Karate Framework)

故事扮演 提交于 2020-05-24 04:47:26

问题


We're automating our test with karate framework. In one of our features we need to decode a token and get a scope in the response. Everything works well, except this code in js.

function(token) {
    return JSON.parse(new Buffer(token.split('.')[1],'base64').toString('ascii')).scope;
}

Error:

Caused by: <eval>:2 ReferenceError: "Buffer" is not defined
Caused by: jdk.nashorn.internal.runtime.ECMAException

In official tutorials it is said that javascript is 'native' to karate, so we don't understand why Buffer is not recognized? What we should do? Thanks for any help


回答1:


I'm pretty sure that Buffer is advanced / non-standard or NodeJS so it probably is not supported by the JVM JS engine (Nashorn).

Here's my recommendation. For this case, do the work using Java utilities.

For example, look at the Karate basic-auth example in the doc which uses Base64 encoding.

If it is really complex, simply create a Java static function, it will be much easier to test as a side-benefit. Hope this helps !




回答2:


I was able to successfully base64Decode a JWT token payload to JSON using the following code without the need for a Java method:

  Background:
    * def parseJwt =
  """
  function(token) {
      var base64Url = token.split('.')[1];
      var base64Str = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      var Base64 = Java.type('java.util.Base64');
      var decoded = Base64.getDecoder().decode(base64Str);
      var String = Java.type('java.lang.String')
      return new String(decoded)
  };
  """

  Scenario: JWT Token
    Given path  'jwt/authenticate'
    And header x-goog-authenticated-user-email = 'email'
    And request {}
    When method get
    Then status 200
    * json result = parseJwt(responseHeaders['Set-Cookie'][0])
    * match result == {permissions: [1,2,3], iss: "us", exp: "#number", email: "email"}

Note: It does seem to be required to use json rather than def as Karate does better if it parses the string to json itself. Also, you may obtain the token from a header rather than a cookie as in this example if so, just change the responseHeader that you are looking for.



来源:https://stackoverflow.com/questions/46450804/buffer-in-js-file-isnt-recognized-api-tests-automation-with-karate-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!