测试 通过测试代码, 自动生成 postman 文件

ThxFly · 2018年10月17日 · 最后由 suoha 回复于 2019年03月22日 · 814 次阅读

0 最终成果预览

1 实现思路

自动化接口测试的同时, 通过打日志的形式构建postman格式的文本文件

2. 编写rake任务

lib/postman.rake

namespace :postman do
  task admin: :environment do
    postman('doc/admin_postman.json', :admin_postman, '轻牛+后台管理接口')
  end
end

def postman(doc, method, name)
  header = <<~JSON
    {
      "variables": [],
      "info": {
        "name": "#{name}",
        "_postman_id": "bce94da3-8aa9-c38e-bdb5-fe8835715887",
        "description": "",
        "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
      },
      "item": [
  JSON
  File.write(doc, header)
  send(method)
  File.truncate(doc, File.size(doc) - 1)
  File.write(doc, "]\n}", File.size(doc))
end

def admin_postman
  ENV['GENERATE_POSTMAN'] = 'true'
  dir = 'test/controllers/admin/'
  order_controllers = %w[
    sessions_controller_test.rb
    managers_controller_test.rb
  ]
  order_controllers.each do |x|
    `rails test #{dir}#{x}`
  end
end

3.编写测试helper

require_relative 'base_helper'
require 'timecop'

Timecop.freeze(Time.new(2018, 6, 1, 20, 10, 59)) # 冻结测试时的时间

module AdminTestHelper
  def postman_logger
    @postman_logger = Logger.new("#{Rails.root}/doc/admin_postman.json")
    @postman_logger.formatter = proc do |_severity, _datetime, _progname, msg|
      msg.to_s
    end
    @postman_logger
  end

  # Add more helper methods to be used by all tests here...
  def send_request(method, url, params, generate_doc_flag: true, code: '200', login_flag: true)
    header = { 'authorization' => Register.generate_gw_token(auth_token: 'm2TfHdaADecAEscTT4FzJ48sz') } if login_flag
    send(method, url, params: params, headers: header)
    assert_equal '200', JSON.parse(@response.body)['code']
    generate_postman(method, params) if ENV['GENERATE_POSTMAN'] && generate_doc_flag
  end

  def generate_postman(method, params)
    action_name = I18n.t(@controller.action_name, scope: 'admin.action_name', locale: 'zh-CN')
    postman_logger.info JSON.pretty_generate(
      name: action_name,
      request: {
        url: {
          raw: @request.original_url.sub('http://www.example.com', '{{WEBSITE}}'),
          host: ['{{HOST}}'],
          port: '{{PORT}}',
          path: @request.path.split('/'),
          query: (method != :get ? [] : params.map { |k, v| { key: k, value: v.to_s, equals: true, description: '' } })
        },
        method: method.upcase,
        header: [
          { key: 'AUTHORIZATION', value: '{{token}}' },
          { key: 'Content-Type', value: 'application/x-www-form-urlencoded' }
        ],
        body:
        if method == :get
          {}
        else
          {
            mode: 'urlencoded',
            urlencoded: params.map { |k, v| { key: k, value: v.to_s, type: 'text', enabled: true } }
          }
        end,
        description: ''
      },
      response: []
    )
    postman_logger.info ','
  end
end
class Admin::BaseControllerTest < ActionDispatch::IntegrationTest
  include ::AdminTestHelper
end

4. 编写测试代码

require 'admin_test_helper'
class Admin::SessionsControllerTest < Admin::BaseControllerTest
  test 'admin_login' do
    send_request(:post, admin_login_admin_sessions_url, { username: managers(:one).username, '123456' })
  end
end

5.运行rake任务, 在postman里导入生成的postman.json

$ rake postman:admin

p.s 最后把文档导入Insomnia(更简洁的api工具,兼容postman), 不是postman

共收到 2 条回复

同用insomnia

熟悉ruby on rail 吗?3105759652

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册