如何为速度模板编写单元测试? [英] How can I write unit tests for velocity templates?

查看:21
本文介绍了如何为速度模板编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?

朋友们好.我正在使用 AWS AppSync + DynamoDB 构建应用程序,并且我开始拥有大量 解析器映射模板,所有这些都是使用 Apache Velocity 模板语言 (VTL) 编写的.

Hello friends. I'm in the process of building an application using AWS AppSync + DynamoDB and I'm starting to have quite a large pile of resolver mapping templates, all which are written using the Apache Velocity Template Language (VTL).

我开始担心的是,这些 vtl 文件对应用程序非常重要(因为它们定义了如何检索数据)并且其中一个可能造成严重破坏的错误.所以就像系统的任何关键部分一样......我想为他们编写一些自动化的单元测试.但我没有发现很多其他人这样做.

The concern I'm starting to have is that these vtl files are quite critical to the application (since they define how data is retrieved) and a bug in one of the could wreak havoc. So like any critical part of a system... I would like to write some automated unit tests for them. But I haven't found much about others doing this.

  1. 如果您使用 VTL(使用 AppSync 或 API Gateway),您如何测试它们?
  2. 甚至可以为速度模板编写自动化测试吗?
  3. 还是我走错了路,我应该只使用 Lambda 作为解析器?

提前致谢!

推荐答案

我自己花了一段时间才弄明白,但我找到了一种为我的 VTL 请求和响应模板编写单元测试的好方法.我使用了 amplify-appsync-simulator npm 包的 VelocityTemplate 类.到目前为止,我看到的唯一警告是您需要在 VTL 中使用 $context,模拟器 VTL 渲染器无法识别缩写的 $ctx.看看吧:

It took me a while to figure this out myself, but I found a good way to write unit tests for my VTL request and response templates. I used the amplify-appsync-simulator npm package's VelocityTemplate class. The only caveat I have seen so far is that you need to use $context in your VTL, the abbreviated $ctx is not recognized by the simulators VTL renderer. Check it out:

我的 VTL:

#set( $timeNow = $util.time.nowEpochMilliSeconds() )
{
    "version" : "2018-05-29",
    "operation" : "PutItem",
    "key": {
        "pk" : { "S" : "game#${util.autoId()}" },
        "sk" : { "S" : "meta#${timeNow}" }
    },
    "attributeValues" : {
        "players": { "L" : [
            { "M" : {   
                ## num and color added at start game             
                "player": $util.dynamodb.toDynamoDBJson($context.args.input.player)    
            }}                        
        ]},
        "createdBy": { "S": "${context.identity.sub}"},
        "gsipk": { "S": "${context.args.input.status}"},
        "gsisk": { "S": "${context.args.input.level}#${context.args.input.maxPlayers}"},
        "gsipk2": {"S": "game"},
        "turns": { "L": [] },
        "nextPlayerNum": { "N": 1 },
        "createdAt": { "N": ${timeNow} },
        "updatedAt": { "N": ${timeNow} }
    }
}

我的测试:

import { AmplifyAppSyncSimulator } from 'amplify-appsync-simulator'
import { VelocityTemplate } from "amplify-appsync-simulator/lib/velocity"
import { readFileSync } from 'fs'
import path from 'path';

const vtl = readFileSync(path.join(__dirname, '..', 'addGame-request-mapping-template.vtl'))
const template = {
  content: vtl
}
const velocity = new VelocityTemplate(template, new AmplifyAppSyncSimulator)

describe('valid user and request', () => {

  // This is the graphql input
  const validContext = {
    arguments: {
      input: {
        player: 'player#1234',
        maxPlayers: 4,
        status: 'new',
        level: 7
      }
    },
    source: {}
  }

  // This is a logged in user with a JWT
  const requestContext = {
    requestAuthorizationMode: 'OPENID_CONNECT',
    jwt: {
      sub: 'abcd1234'
    }
  }

  const info = {
    fieldNodes: []
  }

  it('works', () => {
    const result = velocity.render(validContext, requestContext, info)
    expect(result).toEqual({
      result: {
        version: "2018-05-29",
        operation: "PutItem",
        key: {
          pk: { S: expect.stringMatching(/^game#[a-f0-9-]*$/) },
          sk: { S: expect.stringMatching(/^meta#[0-9]*$/)}
        },
        attributeValues: {
          players: {
            L: [
              { M: { player: { S: validContext.arguments.input.player }}}
            ]
          },
          createdBy: { S: requestContext.jwt.sub },
          gsipk: { S: validContext.arguments.input.status },
          gsisk: { S: `${validContext.arguments.input.level}#${validContext.arguments.input.maxPlayers}`},
          gsipk2: { S: 'game' },
          turns: { L: [] },
          nextPlayerNum: { N: 1 },
          createdAt: { N: expect.any(Number) },
          updatedAt: { N: expect.any(Number) }
        }
      },
      stash: {},
      errors: [],
      isReturn: false
    })
  })
})

这篇关于如何为速度模板编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆