Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@pact-foundation/pact-cli

Package Overview
Dependencies
Maintainers
0
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pact-foundation/pact-cli

Broker CLI for @pact-foundation/pact

  • 16.0.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Pact CLI

Pact CLI Tools

This package wraps the Pact Standalone Tools so that they are available to node scripts in package.json, and linked binaries in the standard NPM installation directory (e..g. ./node_modules/.bin).

For example:

"scripts": {
  "pactPublish": "pact-broker publish ./pacts --consumer-app-version=$\(git describe\) --broker-base-url=$BROKER_BASE_URL --broker-username=$BROKER_USERNAME --broker-password=BROKER_PASSWORD"`
}

Or:

 
```sh
# Example can-i-deploy check
./node_modules/.bin/pact-broker can-i-deploy --pacticipant "Banana Service" --broker-base-url https://test.pact.dius.com.au --latest --broker-username dXfltyFMgNOFZAxr8io9wJ37iUpY42M --broker-password O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1

Computer says no ¯\_(ツ)_/¯

CONSUMER       | C.VERSION | PROVIDER       | P.VERSION | SUCCESS?
---------------|-----------|----------------|-----------|---------
Banana Service | 1.0.0     | Fofana Service | 1.0.0     | false

The verification between the latest version of Banana Service (1.0.0) and version 1.0.0 of Fofana Service failed

The following are the binaries currently made available:

  • pact-mock-service
  • pact-broker
  • pact-stub-service
  • pact-message
  • pact-provider-verifier
  • pact

Pact-CLI API

A wrapper for the Pact CLI Tools.

Installation

npm install @pact-foundation/pact-cli --save-dev

Do Not Track

In order to get better statistics as to who is using Pact, we have an anonymous tracking event that triggers when Pact installs for the first time. To respect your privacy, anyone can turn it off by simply adding a 'do not track' flag within their package.json file:

{
 "name": "some-project",
 ...
 "config": {
  "pact_do_not_track": true
 },
 ...
}

Which Library/Package should I use?

pact-js for core contract testing functionality pact-cli for broker client tools, either standalone or as a JavaScript API.

Usage

Simply require the library and call the create function to start the mock service

var pact = require("@pact-foundation/pact-cli");
var server = pact.createServer({ port: 9999 });
server.start().then(function() {
 // Do your testing/development here
});

Or if you're using Typescript instead of plain old Javascript

import pact from "@pact-foundation/pact-cli";
const server = pact.createServer({ port: 9999 });
server.start().then(() => {
 // Do your testing/development here
});

Or you can also use the CLI

$# pact mock --port 9999

To see the list commands possible with the CLI, simply ask for help $# pact --help

Documentation

Set Log Level

var pact = require("@pact-foundation/pact-cli");
pact.logLevel("debug");

or you can set it via an environment variable

LOG_LEVEL=debug

Pact Broker Publishing

var pact = require('@pact-foundation/pact-core');
var opts = {
 ...
};

pact.publishPacts(opts).then(function () {
 // do something
});

Options:

ParameterRequired?TypeDescription
pactFilesOrDirstruearrayArray of local Pact files or directories containing them. Required.
pactBrokertruestringURL of the Pact Broker to publish pacts to. Required.
consumerVersiontruestringA string containing a semver-style version e.g. 1.0.0. Required.
pactBrokerUsernamefalsestringUsername for Pact Broker basic authentication. Optional
pactBrokerPasswordfalsestringPassword for Pact Broker basic authentication. Optional
pactBrokerTokenfalsestringBearer token for Pact Broker authentication. Optional
tagsfalsearrayAn array of Strings to tag the Pacts being published. Optional
branchfalsestringThe branch to associate with the published pacts. Optional but recommended
autoDetectVersionPropertiesfalsebooleanAutomatically detect the repository branch from known CI environment variables or git CLI. Supports Buildkite, Circle CI, Travis CI, GitHub Actions, Jenkins, Hudson, AppVeyor, GitLab, CodeShip, Bitbucket and Azure DevOps. Optional
buildUrlfalsestringThe build URL that created the pact. Optional
verbosefalsebooleanEnables verbose output for underlying pact binary.

Pact Broker Deployment Check

var pact = require('@pact-foundation/pact-core');
var opts = {
 ...
};

pact.canDeploy(opts)
 .then(function (result) {
  // You can deploy this
    // If output is not specified or is json, result describes the result of the check.
    // If outout is 'table', it is the human readable string returned by the check
 })
 .catch(function(error) {
  // You can't deploy this
    // if output is not specified, or is json, error will be an object describing
    // the result of the check (if the check failed),
    // if output is 'table', then the error will be a string describing the output from the binary,

    // In both cases, `error` will be an Error object if something went wrong during the check.
 });

Options:

ParameterRequired?TypeDescription
pacticipantstrue[]objectsAn array of version selectors in the form `{ name: String, latest?: string
specify a tag, use the tagname with latest. Specify one of these per pacticipant
that you want to deploy
pactBrokertruestringURL of the Pact Broker to query about deployment. Required.
pactBrokerUsernamefalsestringUsername for Pact Broker basic authentication. Optional
pactBrokerPasswordfalsestringPassword for Pact Broker basic authentication. Optional
pactBrokerTokenfalsestringBearer token for Pact Broker authentication. Optional
outputfalsejson,tableSpecify output to show, json or table. Optional, Defaults to json.
verbosefalsebooleanEnables verbose output for underlying pact binary.
retryWhileUnknownfalsenumberThe number of times to retry while there is an unknown verification result. Optional
retryIntervalfalsenumberThe time between retries in seconds, use with retryWhileUnknown. Optional
tofalsestringThe tag that you want to deploy to (eg, 'prod')

Mock Servers

Mock servers are used by Pact to record interactions and create pact contracts.

Create Mock Server
var pact = require('@pact-foundation/pact-cli');
var server = pact.createServer({
 ...
});

Options:

ParameterRequired?TypeDescription
portfalsenumberPort number that the server runs on, defaults to random available port
hostfalsestringHost on which to bind the server on, defaults to 'localhost'. Supports '0.0.0.0' to bind on all IPv4 addresses on the local machine.
logfalsestringFile to log output on relative to current working directory, defaults to none
logLevelfalseLogLevel (string)Log level to pass to the pact core. One of "DEBUG", "ERROR", "WARN", "INFO", can be set by LOG_LEVEL env var
sslfalsebooleanCreate a self-signed SSL cert to run the server over HTTPS , defaults to false
sslcertfalsestringPath to a custom self-signed SSL cert file, 'ssl' option must be set to true to use this option, defaults to none
sslkeyfalsestringPath a custom key and self-signed SSL cert key file, 'ssl' option must be set to true to use this, defaults to none
corsfalsebooleanAllow CORS OPTION requests to be accepted, defaults to 'false'
dirfalsestringDirectory to write the pact contracts relative to the current working directory, defaults to none
specfalsenumberThe pact specification version to use when writing pact contracts, defaults to '1'
consumerfalsestringThe name of the consumer to be written to the pact contracts, defaults to none
providerfalsestringThe name of the provider to be written to the pact contracts, defaults to none
pactFileWriteModefalseoverwrite OR update OR mergeControl how the pact file is created. Defaults to "overwrite"
formatfalsejson OR xmlFormat to write the results as, either in JSON or XML, defaults to JSON
outfalsestringWrite output to a file instead of returning it in the promise, defaults to none
timeoutfalsenumberHow long to wait for the mock server to start up (in milliseconds). Defaults to 30000 (30 seconds)
List Mock Servers

If you ever need to see which servers are currently created.

var pact = require("@pact-foundation/pact-cli");
var servers = pact.listServers();
console.log(JSON.stringify(servers));
Remove All Mock Servers

Remove all servers once you're done with them in one fell swoop.

var pact = require("@pact-foundation/pact-cli");
pact.removeAllServers();
Start a Mock Server

Start the current server.

var pact = require("@pact-foundation/pact-cli");
pact.createServer()
 .start()
 .then(function() {
  // Do something after it started
 });
Stop a Mock server

Stop the current server.

var pact = require("@pact-foundation/pact-cli");
pact.createServer()
 .stop()
 .then(function() {
  // Do something after it stopped
 });
Delete a Mock server

Stop the current server and deletes it from the list.

var pact = require("@pact-foundation/pact-cli");
pact.createServer()
 .delete()
 .then(function() {
  // Do something after it was killed
 });
Check if a Mock server is running
var pact = require("@pact-foundation/pact-cli");
pact.createServer().running;
Mock Server Events

There's 3 different events available, 'start', 'stop' and 'delete'. They can be listened to the same way as an EventEmitter.

var pact = require("@pact-foundation/pact-cli");
var server = pact.createServer();
server.on("start", function() {
 console.log("started");
});
server.on("stop", function() {
 console.log("stopped");
});
server.on("delete", function() {
 console.log("deleted");
});

Stub Servers

Stub servers create runnable APIs from existing pact files.

The interface is comparable to the Mock Server API.

Create Stub Server
var pact = require('@pact-foundation/pact-cli');
var server = pact.createStub({
 ...
});

Options:

ParameterRequired?TypeDescription
pactUrlstruearrayList of local Pact files to create the stub service from
portfalsenumberPort number that the server runs on, defaults to random available port
hostfalsestringHost on which to bind the server on, defaults to 'localhost'. Supports '0.0.0.0' to bind on all IPv4 addresses on the local machine.
logfalsestringFile to log output on relative to current working directory, defaults to none
logLevelfalseLogLevel (string)Log level to pass to the pact core. One of "DEBUG", "ERROR", "WARN", "INFO", can be set by LOG_LEVEL env var
sslfalsebooleanCreate a self-signed SSL cert to run the server over HTTPS , defaults to 'false'
sslcertfalsestringPath to a custom self-signed SSL cert file, 'ssl' option must be set to true to use this option. Defaults false
sslkeyfalsestringPath a custom key and self-signed SSL cert key file, 'ssl' option must be set to true to use this option false. Defaults to none
corsfalsebooleanAllow CORS OPTION requests to be accepted, defaults to 'false'
timeoutfalsenumberHow long to wait for the stub server to start up (in milliseconds). Defaults to 30000 (30 seconds)

Message Pacts

Create Message Pacts
var pact = require('@pact-foundation/pact-cli');
var message = pact.createMessage({
 ...
});

Options:

ParameterRequired?TypeDescription
dirtruestringDirectory to write the pact contracts relative to the current working directory, defaults to none
consumertruestringThe name of the consumer to be written to the pact contracts, defaults to none
providertruestringThe name of the provider to be written to the pact contracts, defaults to none
pactFileWriteModefalse`"overwrite""update"
Example
const messageFactory = messageFactory({
 consumer: "consumer",
 provider: "provider",
 dir: dirname(`${__filename}/pacts`),
 content: `{
  "description": "a test mesage",
  "content": {
   "name": "Mary"
  }
 }`
});

messageFactory.createMessage();

Windows Issues

Enable Long Paths

Windows has a default path length limit of 260 causing issues with projects that are nested deep inside several directory and with how npm handles node_modules directory structures. To fix this issue, please enable Windows Long Paths in the registry by running regedit.exe, find the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled and change the value from 0 to 1, then reboot your computer. Pact should now work as it should, if not, please raise an issue on github.

Contributing

To develop this project, simply install the dependencies with npm install --ignore-scripts, and run npm run watch to for continual development, linting and testing when a source file changes.

Testing

Running npm test will execute the tests that has the *.spec.js pattern.

Questions?

Please search for potential answers or post question on our official Pact StackOverflow.

Keywords

FAQs

Package last updated on 12 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc