Giter Club home page Giter Club logo

agreed-core's Introduction

agreed-core

Build Status codecov

agreed is Consumer Driven Contract tool with JSON mock server.

agreed has 3 features.

  1. Create contract file as json(json5/yaml/etc) file
  2. mock server for frontend development.
  3. test client for backend development

agreed-core is a library to create test client and mock server. agreed-core provide the following features.

  1. json5/yaml require hook, you can write require('foo.json5') / require('bar.yaml') using agreed-core/register.
  2. server middleware, agreed-core provides express/pure node http middleware.
  3. test client, agreed-core provides response check.

Install

$ npm install agreed-core --dev

Usage

Usage as Frontend Mock Server

  • Create agreed file (this file is used as a contract between frontend and backend)
module.exports = [
  {
    request: {
      path: '/user/:id',
      method: 'GET',
      query: {
        q: '{:someQueryStrings}',
        index: '{:index}',
      },
      values: {
        id: 'yosuke',
        someQueryStrings: 'bye',
        index: 2,
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token', 
      },
      body: {
        // hello yosuke bye
        message: '{:greeting} {:id} {:someQueryStrings}',
        // http://example.com/baz.jpg 
        image: '{:images[:index]}',
        themes: [
          // { name: 'green' }
          {
            name: '{:themes.0.name}'
          },
          // { name: 'blue' }, { name: 'red' }
          '{:themes.1-last}'
        ],
      },
      // you can write json schema
      // schema: {
      //   type: 'object',
      //   properties: {
      //     message: { type: 'string' },
      //     image: { type: 'string' },
      //     themes: { 
      //       type: 'array',
      //       items: { 
      //         type: 'object',
      //         properties: {
      //           name: { type: 'string' }
      //         }
      //       }
      //     }
      //   }
      // },
      values: {
        greeting: 'hello',
        images: [
          'http://example.com/foo.jpg',
          'http://example.com/bar.jpg',
          'http://example.com/baz.jpg',
        ],
        themes: [
          {
            name: 'green',
          },
          {
            name: 'blue',
          },
          {
            name: 'red',
          },
        ]
      }
    },
  },
]
  • Create server

We support express, pure node.js and any other frameworks can use agreed.

'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const Agreed = require('agreed-core');
const agreed = new Agreed();
const app = express();

app.use(bodyParser.json());

app.use(agreed.middleware({
  path: './agreed/file/agreed.js',
}));

app.use((err, req, res, next) => {
  res.statusCode = 500;
  res.send(`Error is occurred : ${err}`);
});
app.listen(3000);
$ node server.js
  • call server from client
$ curl http://localhost:3000/user/alice?q=foo
{ 
  "message": "hello alice foo",
  "images": [
    "http://example.com/foo.jpg",
    "http://example.com/bar.jpg"
  ],
  "themes": {
    "name": "green",
  },
}

Usage as Backend test client

agreed can be test client.

  • Reuse agreed file
module.exports = [
  {
    request: {
      path: '/user/:id',
      method: 'GET',
      query: {
        q: '{:someQueryStrings}',
      },
      values: {
        id: 'yosuke',
        someQueryStrings: 'foo'
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token', 
      },
      body: {
        message: '{:greeting} {:id} {:someQueryStrings}',
        images: '{:images}',
        themes: '{:themes}',
      },
      values: {
        greeting: 'hello',
        images: [
          'http://example.com/foo.jpg',
          'http://example.com/bar.jpg',
        ],
        themes: {
          name: 'green',
        },
      }
    },
  },
]
  • Create test client
'use strinct';
const Agreed = require('agreed-core');
const agreed = new Agreed();
const client = agreed.createClient({
  path: './agreed/file/agreed.js',
  host: 'example.com',
  port: 12345,
});

// Get Agreements as array.
const agrees = client.getAgreement();

// request to servers.
// in this case, GET example.com:12345/user/yosuke?q=foo
const responses = client.executeAgreement(agrees);

// Check response object.
client.checkResponse(responses, agrees).then((diffs) => {
  // if the response is mismatched to agreed response,
  // you can get diff.
  // but if no difference, you can get empty object {}
  diffs.forEach((diff) => {
    if (Object.keys(diff).length > 0) {
      console.error('your request does not matched: ', diff);
    }
  });
});

APIs

Agreement

how to define API specs

Agreement file can be written in JSON5/YAML/JavaScript format. You can choose your favorite format.

  • JSON5 example
[
  {
    "request": {
      "path": '/hoge/fuga',
      "method": 'GET',
      // you can write query
      "query": {
        "q": 'foo',
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token', 
      },
      body: {
        message: 'hello world',
      },
    },
  },
  {
    "request": {
      // you can write regexp path, 
      // match /users/yosuke
      "path": '/users/:id',
      "method": 'GET',
    },
    response: {
      // embed path :id to your response body 
      // if request path /users/yosuke
      // return { "message": "hello yosuke" }
      body: {
        message: 'hello {:id}',
      },
    },
  },
  // you can write json file
  // see test/agrees/hoge/foo.json
  './hoge/foo.json',
  // you can write yaml file
  // see test/agrees/foo/bar.yaml
  './foo/bar.yaml',
  // you can separate request/response json
  {
    request: './qux/request.json',
    response: './qux/response.json',
  },
  {
    request: {
      path: '/path/:id',
      method: 'POST',
      // query embed data, any query is ok.
      query: {
        meta: "{:meta}",
      },
      body: {
        message: "{:message}"
      },
      // value for test client
      values: {
        id: 'yosuke',
        meta: true,
        message: 'foobarbaz'
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token', 
      },
      body: {
        // :id is for request value
        message: 'hello {:id}, {:meta}, {:message}',
      },
    },
  },
  {
    request: {
      path: '/images/:id',
      method: 'GET',
      query: {
        q: '{:someQueryStrings}',
      },
      values: {
        id: 'yosuke',
        someQueryStrings: 'foo'
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token', 
      },
      body: {
        message: '{:greeting} {:id} {:someQueryStrings}',
        images: '{:images}',
        themes: '{:themes}',
      },
      values: {
        greeting: 'hello',
        images: [
          'http://example.com/foo.jpg',
          'http://example.com/bar.jpg',
        ],
        themes: {
          name: 'green',
        },
      }
    },
  },
  {
    request: {
      path: '/useschema/:index',
      method: 'GET',
      values: {
        index: 1
      }
    },
    response: {
      body: {
        result : '{:list[:index]}'
      },
      // you can write json schema
      schema: {
        type: 'object',
        properties: {
          result: {
            type: 'string'
          }
        },
      },
      values: {
        list: [
          'hello',
          'hi',
          'dunke',
        ]
      }
    },
  },
]

agreed-core's People

Contributors

akito0107 avatar k-minemoto avatar kt3k avatar mkamakura avatar orisano avatar renovate-bot avatar shootaroo avatar yassh avatar yosuke-furukawa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

agreed-core's Issues

send "null" as text when starting as a client

my agreed.js is here.

module.exports = [
  {
    request: {
      path: '/foo',
      method: 'GET',
      body: null,
    },
    response: {
      status: 200,
    },
  }
]

execute client

$ NODE_DEBUG=http agreed-client --host localhost --port 8080 --path ./agreed.js

and debug message

HTTP 17395: call onSocket 0 0
HTTP 17395: createConnection localhost:8080: { servername: 'localhost',
  port: 8082,
  host: 'localhost',
  headers:
   { 'Content-Length': 4,
     'Content-Type': 'application/json' },
  method: 'GET',
  path: null,
  _agentKey: 'localhost:8082:' }
HTTP 17395: sockets localhost:8080: 1
HTTP 17395: write ret = false
HTTP 17395: outgoing message end.
HTTP 17395: AGENT incoming response!
HTTP 17395: AGENT isHeadResponse false
HTTP 17395: AGENT socket.destroySoon()

'Content-Length' is 4 and send body "null" as text.

jsonschema does not work?

my agreed.js is here. (just copied example)

// save as agreed.js
module.exports = [
  {
    request: {
      path: '/user/:id',
      method: 'GET',
      query: {
        q: '{:someQueryStrings}',
      },
      values: {
        id: 'yosuke',
        someQueryStrings: 'foo'
      },
    },
    response: {
      headers: {
        'x-csrf-token': 'csrf-token',
      },
      body: {
        message: '{:greeting} {:id} {:someQueryStrings}',
        images: '{:images}',
        themes: '{:themes}',
      },
      schema: {
        type: 'object',
        required: [
          'messages',
          'images',
          'themes'
        ],
        properties: {
          message: { type: 'number' }, // should fail here
          image: { type: 'string' },
          themes: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                name: { type: 'string' }
              }
            }
          }
        }
      },
      values: {
        greeting: 'hello',
        images: [
          'http://example.com/foo.jpg',
          'http://example.com/bar.jpg',
        ],
        themes: {
          name: 'green',
        },
      }
    },
  },
]

I activated jsonschema to fail on message , but it works without jsonschema validation.

$ agreed-server --path ./agreed.js --port 3010
$ curl 'http://localhost:3010/user/yosuke?q=foo'
{"message":"hello yosuke foo","images":["http://example.com/foo.jpg","http://example.com/bar.jpg"],"themes":{"name":"green"}}

Content-type was duplicated when starting as a client

my agreed.js is here.

const { resolve } = require('path')
const { readFileSync } = require('fs')

const content = readFileSync(resolve(__dirname, './data.csv'), { encoding: 'utf-8' })
const boundary = '------------------------cafebabe'
const sep = '\r\n'

module.exports = [
  {
    request: {
      path: '/api/csv/import',
      method: 'POST',
      headers: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`,
      },
      body: [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="data.csv"',
        'Content-Type: text/csv; charset=utf-8',
        '',
        content,
        `--${boundary}--`,
      ].join(sep),
    },
    response: {
      status: 200,
    },
  }
]

execute client

$ NODE_DEBUG=http agreed-client --host localhost --port 8080 --path ./agreed.js

and debug message

HTTP 17395: call onSocket 0 0
HTTP 17395: createConnection localhost:8080: { servername: 'localhost',
  port: 8080,
  host: 'localhost',
  headers:
   { 'content-type': 'multipart/form-data; boundary=------------------------cafebabe',
     'Content-Length': 1099,
     'Content-Type': 'application/json' },
  method: 'POST',
  path: null,
  _agentKey: 'localhost:8080:' }
HTTP 17395: sockets localhost:8080: 1
HTTP 17395: write ret = false
HTTP 17395: outgoing message end.
HTTP 17395: AGENT incoming response!
HTTP 17395: AGENT isHeadResponse false
HTTP 17395: AGENT socket.destroySoon()

'content-type' is duplicated.
API Server received request as a 'Content-Type: application/json'.

because, header-key 'Content-Type' mismatch after completion.

https://github.com/recruit-tech/agreed-core/blob/master/lib/client.js#L65

const completedAgrees = this.completion(agrees); // 1. completion
const requests = completedAgrees.map((agree) => {
  const setting = this.setup(agree); // 2. setup
  return this.createRequest(setting);
});

https://github.com/recruit-tech/agreed-core/blob/master/lib/check/completion.js#L66

agree.request.headers = toLowerCaseKeys(agree.request.headers); // convert lowerKey

https://github.com/recruit-tech/agreed-core/blob/master/lib/client.js#L43

options.headers['Content-Type'] = (agree.request.headers && agree.request.headers['Content-Type']) || 'application/json';

レスポンスステータスのみを返すAPIのステータスが異なっていてもfailしない

// agreed.js
module.exports = [
{
  request: {
    path: '/api/sample/:id',
    method: 'PUT',
    body: [
      {value:'test'}
    ],
    values: {
      id: 1,
    },
  },
  response: {
    status: 204,
  },
}]

クライアントテストの実行

$ agreed-client --host localhost --port 8080 --path ./agreed.js

この時、実際のサーバーステータスが200で戻ってきても、テスト結果がOKとなります。

https://github.com/recruit-tech/agreed-client/blob/master/lib/reporter.js#L15
を見る限りではdiffかschemaErrorsのどちらかにデータがあるとfailするようになってますが、この時のresultの中身は

{ body: '', diff: {}, status: [ 204, 200 ] }

となっており、failと判定されません(※isEmpty(result)は、diffが存在するので常にfalseです)。
よって詰め込む側がdiffに入れるかreporter側がstatusの有無を見るかになりますが、単純にclientのcheckResponseの処理でdiffに入れ損ねているように見えます。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.