• Stars
    star
    183
  • Rank 210,154 (Top 5 %)
  • Language
    JavaScript
  • License
    GNU General Publi...
  • Created over 4 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A CLI module for npm that auto-generates tests based on user specified parameters.

A tool for autogenerating Node.js endpoint tests
Easier testing, happier devs 😎

Why Use Battletest?

Modern web APIs must be built to handle requests with any data type, including invalid ones. For instance, if a client sends a request with an extremely long string or -1 in the "ticker" field that should only contain a short string, will the server process fail?

Battletest.js will take in the shape of the intended request object, and generate many test requests that vary each field of the request object by a single unexpected value. By testing the backend as such, the developer can easily determine if there are any random test requests that might make the web API backend fail.

Built for Express.js & OpenAPI v3.03 ❀️

Battletest will read a configuration file ( battletest.config.js ) containing the shape of the expected HTTP request for each endpoint/method, and output for each endpoint/method a testing suite that leverages Mocha, Chai & Supertest to test how the server handles requests containing unexpected data types.

Battletest can also parse a express-js server file or a OpenAPI v3.03 document to prepopulate most (express-js server file) or all (OpenAPI document) of battletest.config.js .

Table of Content

Installation

$ npm install -g battletest

$ npm install --save-dev battletest

Install with the --save-dev flag in place of the -g flag for a local project-specific installation.

Getting Started

Initialize battletest.config.js

$ battletest init

$ battletest init <server.js>
$ battletest init <petstore.yaml>
$ battletest init <petstore.json>

This creates a new battletest.config.js in your project's root directory.

Battletest can optionally parse either an Express-js server.js file or OpenAPI specification to create a prepopulated battletest.config.js . If a file path is not specified, a skeleton configuration file will be created.

battletest.config.js generally follows OpenAPI v3.03 to define endpoints, methods and expected data type.

  • serverLocation: Path to the server.js file from the project's root directory. This path will be used for setup & teardown of the server during the test execution, as provided in testSetup.js .

  • expectedStatusCode: This is the status code the server should return if the server has correctly processed the client's malformed request, i.e. 400.

  • paths: This is an object that contains each Path available on the server as the key.

    • Operation: Each Path has one or more operation (or method) available to it, e.g., "get", "put", "post", etc. It contains a Parameters object and a RequestBody object.

    • Parameters: Array of objects, each specifying a parameter and a location. Possible locations are "path", "query", "get" and "cookie".

        parameters: [{
                name: "petID", // <-- field key
                in: "path", // <-- field location
                schema: {
                    type: "integer"
                },
            },
            {
                name: "lastVisitedDate",
                in: "cookie", // <-- field location
                schema: {
                    type: "string"
                },
            }
        ]
  • RequestBody: Object describing the body of a single request. It may have multiple Content-Types as keys. Only content-type "application-json" is currently supported.
        requestBody: {
            "application/json": {
                schema: {
                    type: "object",
                    properties: {
                        name: {
                            type: "string"
                        },
                        petType: {
                            type: "string"
                        },
                        favoriteFoods: {
                            type: "array",
                            items: {
                                type: "string"
                            }
                        }
                    }
                }
            },
            "text/html": {
                schema: {
                    type: "string"
                }
            }
        }

β†₯Back to top

Specifying Data Types

Possible data types include "array", "object", "integer", "number" and "string".

  • String, Integer, Number: These types can be specified as below.
    username: {
        type: "string"
    }
    userid: {
        type: "integer"
    }
    zipcode: {
        type: "number"
    }
  • Object: Object type needs to have the sibling key properties that specify the object's keys and the expected data type for each. Nested objects and arrays are permitted.
    // Specifying that request field "family" is an object, containing keys "mom"
    family: {
        type: "object",
        properties: {
            mom: {
                type: "string"
            },
            dad: {
                type: "string"
            },
            siblings: {
                type: "object",
                properties: {
                    sisters: {
                        type: "array",
                        items: {
                            type: "string"
                        }
                    },
                    brothers: {
                        type: "array",
                        items: {
                            type: "string"
                        }
                    },
                },
            },
        },
    },
  • Array: Array type needs to specify the data type of items as well. Array of nested objects is permitted.
    // Specifying that request field "favoriteFoods" expects property 
    favoriteFoods: {
        type: "array",
        items: {
            type: "string"
        }
    }

β†₯Back to top

Sample battletest.config.js

module.exports = {
    serverLocation: "server.js",
    serverURL: "http://localhost:8000",
    authorization_cookie: null,
    expectedStatusCode: 400,
    paths: {
        "/pet/:petID": {
            GET: { // <-- Operation 
                parameters: [{
                        name: "petID",
                        in: "path",
                        schema: {
                            type: "integer",
                        },
                    },
                    {
                        name: "lastVisitedDate",
                        in: "cookie",
                        schema: {
                            type: "string"
                        },
                    }
                ],
            },
        }
    }
}

For more sample battletest.config.js files, please see here.

β†₯Back to top

Using Express-js server file

Express-js server file must export "app" and "server" separately in order for Battletest's parsing logic to introspect the server code.

module.exports = {
    app,
    server
};

Resulting battletest.config.js will show the full shape of the request, with expected data types noted as "null". User needs to specify the expected data type for each request field, along with serverLocation and serverURL. Please see sample output here.

// sample Path object from battletest.config.js outputed from expressParser

module.exports = {
  serverLocation: null, // <-- user to specify
  serverURL: null, // <-- user to specify
  authorization_cookie: null, // <-- user to specify
  expectedStatusCode: 400, 
  paths: {

    "/postMessage": {
      post: {
        requestBody: {
          "application/json": {
            schema: {
              type: "object",
              properties: {
                post_message: {
                  type: null // <-- user to specify
                },
                post_password: {
                  type: null // <-- user to specify
                }
              }
            }
          }
        }
      }
    },

}

β†₯Back to top

Using an OpenAPI Document

Battletest uses SwaggerParser to validate & parse OpenAPI v3.03 documents. As OpenAPI documents specify the expected data type for each request field, resulting battletest.config.js will have been completedly populated other than serverLocation and serverURL for the dev server. Please see sample output here. Battletest does not currently support OpenAPI v2.0 documents.

// sample battletest.config.js output from an OpenAPI v.3.03 Document

module.exports = {
  serverLocation: null, // <-- user to specify
  serverURL: null, // <-- user to specify
  authorization_cookie: null, // <-- user to specify
  expectedStatusCode: 400,
  paths: {
    "/pets": {
      get: {
        parameters: [
          {
            name: "tags",
            in: "query",
            description: "tags to filter by",
            required: false,
            style: "form",
            schema: {
              type: "array",
              items: {
                type: "string"
              }
            }
          },
          {
            name: "limit",
            in: "query",
            description: "maximum number of results to return",
            required: false,
            schema: {
              type: "integer",
              format: "int32"
            }
          }
        ]
      },
    }
  }

β†₯Back to top

Generate Test Files

$ battletest generate

$ battletest generate <endpoint-name>

This will parse the newly created battletest.config.js and generate test files under __battletest__ in your project's directory. To only generate tests for a particular endpoint, pass in the endpoint name as an argument.

Sample test cases are as below:

  • Request where body.post_password is "undefined".

  • Request where body.post_password is "null".

  • Request where body.post_password is "false".

For sample test files, please see here.

Running Tests

$ battletest start

$ battletest start <test-file-name>

Please ensure that your server file exports the server using module.exports = { server } . This ensures that testSetup.js can launch and close the server.

This will instruct Mocha to run all tests contained in __battletest__ folder. To run a specific test file only, pass the test file path as an argument.

A .json file containing the result of each testing suite will be saved to __battletest__/__result__ once a test file has run. Each .json file will contain information on:

  • Full details of the request that was sent to the test server
  • Full details of the response that was received from the server
  • Whether the test passed or failed -- boolean
  • Time taken for the request-response cycle to complete

View Test Results

To Be Updated

How the Test Data is Generated

For each endpoint/operation, battletest will generate (i) base scenario that contains data that conform to proper data types, and (ii) other test scenarios that replace a single field in a base scenario with invalid data type or random data.

For instance, invalid data to be tested for a number field includes, among others:

  • null
  • 0
  • undefined
  • false
  • empty string
  • empty object
  • empty array
  • positive infinity
  • negative infinity
  • random string

For details on how the random test data is generated, please see the relevant code here.

β†₯Back to top

Testing

We use Travis-CI to run our testing suites. In a local machine, please use npm run test to execute the testing suite.

β†₯Back to top

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. For an overview diagram for the codebase, please see here. For full API documentation, please see here

β†₯Back to top

Credits

Binta Kinteh @BintaKinteh | Duygu Yigitsoy @dyigitsoy | Kevin Luo @LuoKevin | Soobin Kim @soobinkim1 | Yula Ko @yulako

β†₯Back to top

More Repositories

1

sapling

Sapling - A convenient way to traverse your React app in VS Code
JavaScript
489
star
2

Kafka-Sprout

πŸš€ Web GUI for Kafka Cluster Management
Java
429
star
3

GraphQuill

Real-time GraphQL API Exploration in VS Code
TypeScript
395
star
4

protographql

ProtoGraphQL is a prototyping tool that empowers developers to build and visualize GraphQL schemas and queries without writing any code.
JavaScript
360
star
5

seeql

see your database in a new way
TypeScript
344
star
6

Realize

A React component tree visualizer
JavaScript
327
star
7

Allok8

⚑️A pretty swell Kubernetes visualization tool
JavaScript
273
star
8

ReactRTC

NPM package that simplifies set-up of WebRTC as importable React components
JavaScript
270
star
9

svend3r

Interactive plug and play charting library for Svelte
JavaScript
267
star
10

aether

All-in-One Memory Leak Testing Solution
JavaScript
250
star
11

Yodelay

Your preferred gRPC endpoint testing tool. Making sure your outbound πŸ—£οΈ β€˜yodelay’ returns the β€˜IiiOoo’ πŸ“£ that you expect
TypeScript
228
star
12

ReactRPC

Full feature integration library for gRPC-Web into React
JavaScript
224
star
13

atomos

Atomos is an open source dev tool for Recoil that provides real-time visualization of the component tree and atom-selector relationships to facilitate debugging of a React application.
JavaScript
218
star
14

Dockter

A low-overhead, open-source Docker log management tool
TypeScript
217
star
15

svelte-sight

A Svelte dev tool for visualizing component hierarchy, state, and props of your application
Svelte
215
star
16

KUR8

A visual overview of Kubernetes architecture and Prometheus metrics
JavaScript
213
star
17

OpticQL

Developer tool focused on streamlining the performance testing and optimization of GraphQL API
JavaScript
212
star
18

connext-js

A middleware and route handling solution for Next.js.
JavaScript
210
star
19

hypnos

The best way to test GraphQL calls to RESTful APIs.
JavaScript
205
star
20

Equa11y

A stream-lined command line tool for developers to easily run accessibility testing locally through axe-core and puppeteer.
TypeScript
204
star
21

preducks

React/Redux/Typescript Application Prototyping & Smart Boilerplate Generation Tool
TypeScript
199
star
22

drawql

an OSS tool for designing a graphql endpoint in Apollo
CSS
195
star
23

kubermetrics

JavaScript
194
star
24

TotalRecoilJS

TotalRecoilJS is a tool created to help developers visualize/debug and track their Recoil state via a Chrome extension.
JavaScript
193
star
25

Horus

🎯 A gRPC-Node Distributed Tracing and Monitoring Tool.
JavaScript
187
star
26

PostQL

Web app to visualize your GraphQL metrics and provide historical analytics
TypeScript
186
star
27

Ahoy

Ahoy! is a GUI tool for DevOps engineers which distills the many functions of Helm into a user-friendly interface.
JavaScript
183
star
28

Deno-Redlock

Deno's first lightweight, secure distributed lock manager utilizing the Redlock algorithm
TypeScript
182
star
29

ReactMonitor

Quickly visualize React's component tree and its performance
JavaScript
181
star
30

Osiris

An Electron based desktop application for generating components, building pages, and storing them in a UI library.
JavaScript
177
star
31

protostar-relay

Open-source iteration of the official Relay devtool.
JavaScript
171
star
32

TorchQL

A tool to quickly generate GraphQL schemas and resolvers from a relational database
JavaScript
171
star
33

trydent

testing tamed
TypeScript
170
star
34

genesisQL

rapid schema-prototyping tool for GraphQL applications
JavaScript
169
star
35

FilamentQL

GraphQL query and caching solution
JavaScript
168
star
36

GatsbyHub

Access everything Gatsby has to offer without ever leaving Visual Studio Code. This VSCode Extension allows you to generate a new Gatsby site using a starter, browse Gatsby plugins, and develop a server all with a click of a button.
TypeScript
163
star
37

aditum

Accessibility components for managing focus in React SPAs
JavaScript
162
star
38

watchmo

JavaScript
162
star
39

react-chronoscope

Developer tool to monitor React performance
JavaScript
162
star
40

navigate

A Kubernetes cluster visualizer for DevOps engineers - network policies, aggregated scheduler logs, deployments and pods before your cluster is running!
TypeScript
161
star
41

TrunQ

NPM package for easy client and/or server side graphQL caching.
JavaScript
160
star
42

onyx

Onyx is authentication middleware for Deno, inspired by Passport.js
TypeScript
159
star
43

BACE

JavaScript
159
star
44

MASH

Kafka visualizer and management suite
TypeScript
158
star
45

portara

Portara directive is a rate limiter / throttler for GraphQL
TypeScript
158
star
46

irisql

GraphQL prototyping tool to quickly mock-up Node API's and visualize where you can query from.
JavaScript
158
star
47

Interspect

An API mocking tool for testing data interoperability between microservices and secure HTTP endpoints
JavaScript
157
star
48

SMEE

JavaScript
154
star
49

ChaosQoaLa

Chaos Engineering meets GraphQL
JavaScript
153
star
50

VaaS

Modular Kubernetes Management System with OpenFaaS Support
TypeScript
153
star
51

tropicRPC

A VS Code extension that provides gRPC API endpoint testing.
TypeScript
153
star
52

dashport

Local and OAuth authentication middleware for Deno
TypeScript
151
star
53

anagraphql

JavaScript
151
star
54

Trinity

A VSCode extension for Cypher and Neo4j
TypeScript
150
star
55

DockerLocal

DockerLocal is a GUI application that allows you to keep an up-to-date version of the docker compose file for interconnected repositories while doing development work on a single repository.
TypeScript
150
star
56

giraffeQL

πŸ¦’ Developer tool to visualize relational databases and export schemas for GraphQL API's.
JavaScript
147
star
57

ProtoCAD

ProtoCAD is a prototyping tool that allows developers to build UI component tree structure based on GraphQL query results.
TypeScript
146
star
58

Trace

A lightweight GraphQL query performance monitoring GUI with real-time, resolver-level performance tracing metrics and error logging.
TypeScript
146
star
59

StratosDB

β˜„οΈ ☁️ An All-in-One GUI for Cloud SQL that can help users design and test their AWS RDS Instances
TypeScript
145
star
60

snAppy

snAppy is a VS Code extension coupled with an interactive view to support your React front-end delivery.
TypeScript
144
star
61

synapse

Realtime API Library
TypeScript
144
star
62

SpectiQL

GraphQL query, mutation, subscription test generator
JavaScript
143
star
63

starfleet

Command line tool to generate GraphQL services from Mongoose schemas with full CRUD functionality and deploy them to the cloud
JavaScript
143
star
64

pelican

Automated GUI canary testing for your kubernetes clusters
JavaScript
140
star
65

ProtoNative

A React Native prototyping tool for developers.
TypeScript
140
star
66

reactFLO

A Chrome DevTool built for developers to visualize the flow of state throughout their application.
TypeScript
140
star
67

ReactionTime

ReactionTime provides a simpler way to write tests for React's Experimental Concurrent Mode.
TypeScript
140
star
68

DacheQL

GraphQL caching tool
JavaScript
139
star
69

KuberOptic

An Electron app for developers to visualize their Kubernetes clusters in real-time
TypeScript
137
star
70

sono.land

Real-time Communication Library for Deno (WebSockets & WebRTC)
TypeScript
137
star
71

KubeScrape

KubeScrape: An open-source dev tool that provides an intuitive way to view the health, structure, and live metrics of your Kubernetes cluster
JavaScript
136
star
72

LucidQL

A developer tool and visualizer that generates a GraphQL schema from an established relational database.
JavaScript
135
star
73

Hookd

A cli tool and visualizer for converting React class components to functional components with hooks.
TypeScript
135
star
74

kr8s

Docker/Kubernetes Visualization Tool
JavaScript
133
star
75

Svelcro

Svelte DevTool with a focus on rendering
JavaScript
133
star
76

KnightOwl

An npm package of GraphQL middleware to protect you from malicious queries.
JavaScript
133
star
77

Palaemon

Palaemon is an open-source developer tool for monitoring health and resource metrics of Kubernetes clusters and analyzing Out of Memory (OOMKill) errors
TypeScript
133
star
78

SvelTable

Feature rich data table component.
Svelte
132
star
79

Ekkremis

A periscopic view into pending Kubernetes pods
TypeScript
132
star
80

kQ

TypeScript
131
star
81

fflow

fflow is an easy-to-use open-source tool for all developers to create their React application.
JavaScript
127
star
82

KlusterView

Get instant insights on your Kubernetes clusters with our lightweight, plug-and-play performance monitoring tool
TypeScript
125
star
83

Aqls-server

An intelligent full-stack GraphQL subscription and analytics module. Server-side analytics processing, self-auditing router, and resolver plugins.
JavaScript
123
star
84

kondo

JavaScript
123
star
85

periqles

React form library for Relay and Apollo
JavaScript
120
star
86

ThermaKube

A web application that monitors the health and performance of Kubernetes clusters with support for AWS EKS deployments
JavaScript
120
star
87

arteMetrics

Creating performance monitors for Apollo implementations of graphQL.
JavaScript
118
star
88

QLens

QLens is an electron app which dynamically generates GraphQL Schemas and Mongo Schema visualization. QLens significantly cuts development time by automating the formation of their GraphQL schemas based on information fetched from their non-relational database.
JavaScript
118
star
89

firecomm

A complete framework for gRPC-node.
JavaScript
117
star
90

Kafkasocks

JavaScript
114
star
91

ReaPer

Dev tool to analyze the performance of user interface and single-page applications based on the React frontend library
JavaScript
114
star
92

dangoDB

A MongoDB ODM for Deno
TypeScript
111
star
93

AtomicKafka

JavaScript
110
star
94

Bedrock

A modular authentication library for Deno.
TypeScript
110
star
95

Docklight

Metrics for your Docker containers
TypeScript
109
star
96

Neptune

A light-weight, simple, and straightforward learning tool for your Kubernetes cluster
JavaScript
109
star
97

ArtemisQL

ArtemisQL is a GraphQL migration tool and database visualizer that empowers developers to build and implement GraphQL with ease.
TypeScript
108
star
98

shipm8

JavaScript
108
star
99

ReacTree

ReacTree - VS Code extension that generates a hierarchy tree of React components with each node listing the passed down props, indicating whether it's connected the Redux store, and guiding you to the associated file with the click of a button
TypeScript
107
star
100

reactron

Reactron is a React component visualizer that allows you to traverse an app's fiber tree and render components individually.
JavaScript
105
star