A repository to generate the fake json data from protobuf.

Overview

Mock Protobuf

A command-line tool to mock protobuf!


Table of Contents


Install

It’s handy to just use npm to install this tool:

npm i mock-pb-cli@latest -g

Or, you can build the source code on your own:

# Clone this repo
git clone [email protected]:JasonkayZK/mock-protobuf.js.git

# Install dependencies
npm i

# Compile the code
npm run c

# Install
npm i -g --force

Usage

Press mock-pb -h to get help:

$ mock-pb -h

Usage: mock-protobuf [options] [command]

A tool to mock protobuf

Options:
  -v, --version         output the version number
  -h, --help            display help for command

Commands:
  s|serve [options]     Create a mock server for the given protobuf
  g|generate [options]  Generate mock data for the given protobuf
  help [command]        display help for command

Their are two sub commands to mock:

  • Generate json mock data: mock-pb g or mock-pb generate
  • Generate mock server:mock-pb s or mock-pb serve

Generate Mock Data

The generate subcommand is used to generate the json mock data from proto.

For example:

$ mock-pb g

The command above will mock all the protobuf files under the current work directory (aka .) and print all the mock data to the terminal:

Mocked demo.BasicResponse:
{
    "status": 902735693509892,
    "message": "Vmucue hqxllqx oiloapzwp.",
    "resp": {}
}

Mocked demo.DemoRequest:
{
    "data": "Kqr gxxq."
}

Mocked demo.DemoResponse:
{
    "resp": {
        "status": -6061376970430480,
        "message": "Xpjzjyxrcq eqkmytjo.",
        "resp": {}
    },
    "resp_data": "Ryogd tswayqjsf."
}

The default searching protobuf files path is set to ., you can use -d to change it!

Such as:

  • mock-pb g -d ../test/proto

Output Directory

It’s easy to use -o the output the mock data to and directory:

$ mock-pb g -o ./mock-pb-output

And all the mock data will be output under mock-pb-output/:

$ tree
.
├── demo
│   ├── BasicResponse.json
│   ├── DemoRequest.json
│   └── DemoResponse.json
├── google.api
│   ├── CustomHttpPattern.json
│   ├── HttpBody.json
│   ├── Http.json
│   └── HttpRule.json
└── google.protobuf
    ├── Any.json
    ├── Api.json
		......
    ├── SourceContext.json
    ├── Type.json
    └── UninterpretedOption.json

The output directory is based on the protobuf package


Mock Server

Instead of generating the mock json data, you can also start a mock server locally to mock the whole service!

It’s easy to start a mock server:

$ mock-pb s

The command above will mock all the protobuf files under the current work directory (aka .) and mock the methods under the service:

Handling routePath: /Demo
Handling routePath: /demo/DemoServiceAnotherDemo
restify listening at http://[::]:3333

The default port is 3333, you can use -p to change the server’s port:

  • mock-pb s -p 13333

It will print the handling route path when starting the server.

When you defined the method’s route path via google.api.http, the server will use this path, such as:

service DemoService {
  rpc Demo(DemoRequest) returns (DemoResponse) {
    option (google.api.http) = {
      post: "/Demo"
      body: "*"
    };
  }
}

If not, the route path will be generated as {/{ProtobufPackageName}/{ProtobufMethodName}, such as:

service DemoService {
  rpc AnotherDemo(AnotherDemoRequest) returns (AnotherDemoResponse) {
  }
}

When serve is started, it’s easy to test:

$ curl localhost:3333/Demo
{"resp":{"status":8107764027207864,"message":"Vcinpb troqo neffhj ylve.","resp":{}},"resp_data":"Gpwsl nfq yvkyajlyk."}

$ curl localhost:3333/demo/DemoServiceAnotherDemo
{"resp":{"status":-843357854531144,"message":"Vzby.","resp":{}},"resp_data":"Kvia gfkcggmuo."}

Mock Server Data

Sometimes, you don’t want let mock.js generating the mock data, suck as:

{"resp":{"status":-843357854531144,"message":"Vzby.","resp":{}},"resp_data":"Kvia gfkcggmuo."}

But you need to let the server mock the specific response:

{"resp":{"status":200,"message":"ok"},"resp_data":{"Message":"This is a demo message"}}

It’s easy to declare your own mock data:

mock-protobuf.config.json

{
    "ResponseValue": [
        {
            "MethodName": "demo.Demo",
            "Data": {
                "Hello": "world"
            }
        },
        {
            "MethodName": "demo.AnotherDemo",
            "Data": {
                "resp": {
                    "status": 200,
                    "message": "ok"
                },
                "resp_data": {
                    "Message": "This is a demo message"
                }
            }
        }
    ]
}

The MethodName is the full name of the protobuf method (package.method);

Then use -c to declare the config file, such as -c ./mock-protobuf.config.json

The example is below:

$ npm run dev -- s -i demo -c ./mock-protobuf.config-demo.json

Then test:

$ curl localhost:3333/Demo
{"Hello":"world"}

$ curl localhost:3333/demo/DemoServiceAnotherDemo
{"resp":{"status":200,"message":"ok"},"resp_data":{"Message":"This is a demo message"}}

The response has changed!


Filter

Sometimes we don’t want to mock all the protobuf definitions. Some some filter is required!

There are two ways to filter:

  • Includes: -i <string> or --include;
  • Excludes: -e <string> or --exclude;

The <string> will be built as a RegExp, and will be matched as packageName.serviceName.methodName;

Include Filter

When using include, ONLY the matched data will be mocked.

For example:

$ mock-pb g -i demo

Mocked demo.BasicResponse:
{
    "status": -978663427598816,
    "message": "Iymo zomttydmb.",
    "resp": {}
}

Mocked demo.DemoRequest:
{
    "data": "Mdnbfxbvoq khrbwyu sxmkev jss."
}

Mocked demo.DemoResponse:
{
    "resp": {
        "status": 6207610394471496,
        "message": "Dkwse mmhmuhhunb.",
        "resp": {}
    },
    "resp_data": "Fqwkd noiefpr ntjbcfydl."
}

Mocked demo.AnotherDemoRequest:
{
    "name": "Puvujqy kyxl hshuysly.",
    "age": 175838119803604
}

Mocked demo.AnotherDemoResponse:
{
    "resp": {
        "status": -7659482750118844,
        "message": "Fygec kyzysqqga svimupy nbfrjt.",
        "resp": {}
    },
    "resp_data": "Mpgjtjsbr qfspgkb xmpji."
}

This will only generate the data that under the demo.* package;

For more particular:

$ mock-pb g -i demo.DemoRequest.*

Mocked demo.DemoRequest:
{
    "data": "Ewqzspj hjkfvvc froqdhkwe fkqsdg dytidwli."
}

This will only mock demo.DemoRequest message!


Exclude Filter

On the contray, -e will remove the matched messages.

For example:

$ mock-pb g -e demo.*,google.protobuf.* -o mock-pb-gen

$ tree
.
└── google.api
    ├── CustomHttpPattern.json
    ├── HttpBody.json
    ├── Http.json
    └── HttpRule.json

This will not mock the message under demo.* and google.protobuf.* package.

When you are using both include and exclude filter, the exclude filter will ALWAYS effect at the first time!

For example:

$ mock-pb g -i demo -e demo

Will generate nothing!


Known Issue

Because this tool is depending on node-restify and protobuf.js, some known issue can not be avoid!

  • Resitfy does not work under Node v18: according to the issue: #1888
  • Protobuf.js may have trouble parsing the protobuf files when it got comments in it: according to the issue: #1799 or #1616 or #1237 or …
You might also like...

JCS (JSON Canonicalization Scheme), JSON digests, and JSON Merkle hashes

JSON Hash This package contains the following JSON utilties for Deno: digest.ts provides cryptographic hash digests of JSON trees. It guarantee that d

Sep 2, 2022

Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

Mar 29, 2022

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Dec 6, 2022

A JavaScript library built on top of the Faker.JS library. It generates massive amounts of fake data in the browser and node.js.

Blaver - generate massive amounts of fake data in the browser and node.js Blaver is a JavaScript library built on top of the Faker.JS library. It gene

Dec 30, 2022

All the Fake Data for All Your Real Needs 🙂

All the Fake Data for All Your Real Needs 🙂

All the Fake Data for All Your Real Needs 🙂 Run it on Stackblitz Installation npm i @ngneat/falso yarn add @ngneat/falso Methods randT(arr: T[]):

Dec 29, 2022

A set of javascript packages that generates fake data for you.

Faker A set of javascript packages that generates fake data for you. Install $ npm install --save @fakerjs/faker Usage import faker from '@fakerjs/fa

Apr 18, 2022

Jetcap is a free online REST API that you can use whenever you need some fake data ✨

Jetcap Jetcap is a simple fake REST API for testing and prototyping. When to use ✨ Jetcap is a free online REST API that you can use whenever you need

Nov 13, 2022

Tool to sign data with a Cardano-Secret-Key // verify data with a Cardano-Public-Key // generate CIP-8 & CIP-36 data

Tool to sign data with a Cardano-Secret-Key // verify data with a Cardano-Public-Key // generate CIP-8 & CIP-36 data

Tool to sign data with a Cardano-Secret-Key // verify data with a Cardano-Public-Key // generate CIP-8 & CIP-36 data

Dec 21, 2022

Pretty-print-json - 🦋 Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

Pretty-print-json - 🦋 Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

pretty-print-json Pretty-print JSON data into HTML to indent and colorize (written in TypeScript) 1) Try It Out Interactive online tool to format JSON

Dec 30, 2022
Owner
Jasonkay
SCUT18(修士&卒業)/Open-Source Supporter/英語と日本語がすき/EE-->CS/アニメ→SAOが大好き/音楽→Mr.children/社会の初心者/はじめまして(笑)
Jasonkay
JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Aykut Saraç 20.6k Jan 4, 2023
faker.js - generate massive amounts of fake data in the browser and node.js

faker.js - generate massive amounts of fake data in the browser and node.js

Wanderson Camargo 2 Jan 7, 2022
Generate massive amounts of fake data in the browser and node.js

Faker Generate massive amounts of fake data in the browser and node.js. FAQ - What happened to the original faker.js? This project was originally crea

faker-js 8.4k Jan 2, 2023
Generate massive amounts of fake data in the browser and node.js

Faker Generate massive amounts of fake data in the Browser and Node.js. Installation Please replace your faker dependency with @faker-js/faker. This i

faker-js 8.4k Jan 4, 2023
✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo ?? https://jsfiddle.net/torrobin

Tor 7 Jul 31, 2022
Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku

Deploying Fake Back-End Server & DataBase Using JSON-SERVER, GitHub, and Heroku. In this article, we will create and host a fake server that we can de

Israel David 0 Sep 5, 2022
simple PWA catalogue with vanilla javascript and json-server as a fake server

simple PWA catalogue with vanilla javascript and json-server as a fake server

bagher musavi 2 Mar 12, 2022
Generate in-memory fake files with custom size

File generator Generate fake in-memory files for varying sizes This package allows you generate fake in-memory files for varying sizes. The generated

Poppinss 19 Nov 4, 2022
Generate convincing fake tweet images

Fake Tweet Generator Description With the Fake Tweet Generator tool you can create convincing fake tweet images. This tool is completely customizable

Shashikanth Reddy 29 Dec 26, 2022
A GitHub action to generate a stackaid.json file based on your repository's dependency graph

generate-stackaid-json A GitHub action to generate a stackaid.json file based on your repository's dependency graph This action is primarily intended

StackAid 5 Sep 15, 2022