cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
1,131 lines (1,116 loc) • 42.8 kB
TypeScript
import { Request as Request$1, RequestHandler, Express } from 'express';
import winston from 'winston';
import { IncomingMessage, ServerResponse, ClientRequest, Server } from 'http';
import { IAuthentication, ICredentials, Client, IResult, IFetchResponse, IResultList, IFetchOptions } from '@c8y/client';
import { FormatFn } from 'morgan';
/**
* Preprocessor for C8yPact objects. Use C8yPactPreprocessor to preprocess any
* Cypress.Response, C8yPactRecord or C8yPact. The preprocessor could be used to
* obfuscate or remove sensitive data from the pact objects. It is called on save
* and load of the pact objects.
*/
interface C8yPactPreprocessor {
/**
* Configuration options used by the preprocessor.
*/
readonly options?: C8yPactPreprocessorOptions;
/**
* Applies the preprocessor to the given object.
*
* @param obj Object to preprocess.
* @param options Preprocessor options.
*/
apply: (obj: Partial<Cypress.Response<any> | C8yPactRecord | C8yPact>, options?: C8yPactPreprocessorOptions) => void;
}
/**
* Configuration options for the C8yPactPreprocessor.
*/
interface C8yPactPreprocessorOptions {
/**
* Key paths to obfuscate.
*
* @example
* response.body.password
*/
obfuscate?: string[];
/**
* Key paths to remove.
*
* @example
* request.headers.Authorization
*/
ignore?: string[];
/**
* Key paths to pick. All other keys (children) of the object will
* be removed.
*
* @example
* response.headers: ["content-type"]
* ["request.headers", "response.headers"]
*/
pick?: {
[key: string]: string[];
} | string[];
/**
* Apply regex replace to the key path. The key is the key path and the value
* is the regex to apply, or an array of regexes to apply in sequence.
* Regex string should be in the format of `/regex/replace/flags`.
*/
regexReplace?: {
[key: string]: string | string[];
};
/**
* Obfuscation pattern to use. Default is ********.
*/
obfuscationPattern?: string;
/**
* Whether to ignore case when matching keys.
*/
ignoreCase?: boolean;
}
declare const C8yPactPreprocessorDefaultOptions: {
ignore: string[];
obfuscate: string[];
obfuscationPattern: string;
ignoreCase: boolean;
};
/**
* Default implementation of C8yPactPreprocessor. Preprocessor for C8yPact objects
* that can be used to obfuscate or remove sensitive data from the pact objects.
* Use C8ypactPreprocessorOptions to configure the preprocessor.
*
* Removes cookies and set-cookie headers by appending the key to the `cookie` or `set-cookie`
* key as for example `headers.cookie.authorization` or `headers.set-cookie.authorization`.
*/
declare class C8yDefaultPactPreprocessor implements C8yPactPreprocessor {
static defaultObfuscationPattern: string;
options?: C8yPactPreprocessorOptions;
protected reservedKeys: string[];
constructor(options?: C8yPactPreprocessorOptions);
apply(obj: Partial<Cypress.Response<any> | C8yPactRecord | C8yPact>, options?: C8yPactPreprocessorOptions): void;
private filterObjectByKeepPaths;
private applyKeepArray;
private handleObfuscation;
private handleRemoval;
private removeKey;
private removeSetCookie;
private removeCookie;
private filterValidKeys;
private obfuscateKey;
private obfuscateSetCookie;
private obfuscateCookie;
protected resolveOptions(options?: Partial<C8yPactPreprocessorOptions>): C8yPactPreprocessorOptions;
private hasKey;
private getCookieObject;
}
declare function parseRegexReplace(input: string): {
pattern: RegExp;
replacement: string;
};
declare function performRegexReplace(input: string | any, regexes: {
pattern: RegExp;
replacement: string;
}[] | {
pattern: RegExp;
replacement: string;
}): string | any;
interface C8yAuthOptions extends ICredentials {
sendImmediately?: boolean;
bearer?: (() => string) | string;
userAlias?: string;
type?: string;
xsrfToken?: string;
}
interface C8yPactAuthObject {
userAlias?: string;
user: string;
type?: string;
}
type C8yAuthentication = IAuthentication;
/**
* Matcher for matching objects against a schema. If the object does not match
* the schema an Error will be thrown.
*/
interface C8ySchemaMatcher {
/**
* Matches the given object against the given schema. Throws an error when
* schema does not match. Strict matching controls whether additional properties
* are allowed in the object.
*
* @param obj Object to match.
* @param schema Schema to match obj against.
* @param strictMatching If true, additional properties are not allowed.
*/
match(obj: any, schema: any, strictMatching?: boolean): boolean;
}
/**
* A C8ySchemaGenerator is used to generate json schemas from json objects.
*/
interface C8ySchemaGenerator {
/**
* Generates a json schema for the given object.
*
* @param obj The object to generate the schema for.
* @param options The options passed to the schema generator.
*/
generate: (obj: any, options?: any) => Promise<any>;
}
/**
* Tenant ID of a Cumulocity tenant.
* @example t123456
*/
type C8yTenant = string;
/**
* Base URL of a Cumulocity tenant.
* @example https://tenant.eu-latest.cumulocity.com
*/
type C8yBaseUrl = string;
declare global {
interface Response {
data?: string | any;
method?: string;
responseObj?: Partial<Cypress.Response<any>>;
requestBody?: string | any;
}
namespace Cypress {
interface Response<T> {
url?: string;
requestBody?: string | any;
method?: string;
$body?: any;
}
}
}
/**
* Options used to configure c8yclient command.
*/
type C8yClientOptions = Partial<Cypress.Loggable> & Partial<Cypress.Timeoutable> & Partial<Pick<Cypress.Failable, "failOnStatusCode">> & Partial<{
auth: IAuthentication;
baseUrl: C8yBaseUrl;
client: Client;
preferBasicAuth: boolean;
skipClientAuthentication: boolean;
failOnPactValidation: boolean;
ignorePact: boolean;
schema: any;
record: C8yPactRecord;
schemaMatcher: C8ySchemaMatcher;
strictMatching: boolean;
}>;
/**
* Wrapper for Client to pass auth and options without extending Client.
* Using underscore to avoid name clashes with Client and misunderstandings reading the code.
*/
interface C8yClient {
_auth?: C8yAuthentication;
_options?: C8yClientOptions;
_client?: Client;
}
/**
* Converts the given object to a Cypress.Response.
* @param obj The object to convert.
* @param duration The duration of the request.
* @param fetchOptions The fetch options used for the request.
* @param url The URL of the request.
* @param schema The schema of the response.
*/
declare function toCypressResponse(obj: IFetchResponse | IResult<any> | IResultList<any> | C8yPactRecord | Partial<Response>, duration?: number, fetchOptions?: IFetchOptions, url?: RequestInfo | URL, schema?: any): Cypress.Response<any> | undefined;
/**
* Checks if the given object is a window.Response.
* @param obj The object to check.
*/
declare function isWindowFetchResponse(obj: any): obj is Response;
/**
* Checks if the given object is an IResult.
* @param obj The object to check.
*/
declare function isIResult(obj: any): obj is IResult<any>;
/**
* Checks if the given object is a CypressError.
* @param error The object to check.
* @returns True if the object is a CypressError, false otherwise.
*/
declare function isCypressError(error: any): boolean;
declare const C8yPactModeValues: readonly ["record", "recording", "apply", "forward", "disabled", "mock"];
/**
* The pact mode is used to determine the behavior of the recording and mocking capabilities.
* - `record`: Records the requests and responses and stores them in a pact file.
* - `apply`: Mocks or matches the requests and responses from the recorded pact file.
* - `disabled`: Disables the pact recording and mocking (same as undefined).
* - `forward`: Forward requests without recording or mocking (might not be supported in all contexts).
* - `recording` (deprecated): same as `record`, use `record` instead.
* - `mock`: Mock responses for requests. Same as `apply`, but `apply` could also mean matching the requests and responses depending on the context.
*/
type C8yPactMode = (typeof C8yPactModeValues)[number];
declare const C8yPactRecordingModeValues: readonly ["refresh", "append", "new", "replace"];
/**
* The pact recording mode is used to determine how or if requests and responses are recorded.
* - `refresh` (default): Recreates the pact file with the all requests and responses.
* - `append`: Appends the new requests and responses to the existing pact file.
* - `new`: Only creates a new pact file if no pact file exists. If pact file exists, only new requests and responses are added.
* - `replace`: Overwrites existing records of a pact with new request and response in the order of occurence. Other records are kept as is.
*/
type C8yPactRecordingMode = (typeof C8yPactRecordingModeValues)[number];
/**
* ID representing a pact object. Should be unique.
* @example api__get__permission_failure_tests
*/
type C8yPactID = string;
interface C8yPactRequestMatchingOptions {
ignoreUrlParameters?: string[];
baseUrl?: C8yBaseUrl;
}
interface C8yPactConfigOptions {
/**
* ID representing a pact object.
*/
id?: C8yPactID;
/**
* Use to enable additional logging.
*/
log?: boolean;
/**
* Information describing the producer of the pact. Includes name and version information
*/
producer?: {
name: string;
version?: string;
} | string;
/**
* Information describing the consumer of the pact. Includes name and version information
*/
consumer?: {
name: string;
version?: string;
} | string;
/**
* Tags describing the pact.
*/
tags?: string[];
/**
* Description of the pact.
*/
description?: string;
/**
* Use ignore to disable the pact for the current test case.
*/
ignore?: boolean;
/**
* Use failOnMissingPacts to disable failing the test if no pact or no next record
* is found for the current test case.
*/
failOnMissingPacts?: boolean;
/**
* Use strictMatching to enable strict matching of the pact records. If strict matching
* is enabled, all properties of the pact records must match and tests fail if a property
* is missing. Default is false.
*/
strictMatching?: boolean;
/**
* If strictMocking is enabled, an error will be thrown if no pact record matches the
* current request. If disabled, the request will be passed through to the configured baseUrl.
*/
strictMocking?: boolean;
/**
* Options to configure the C8yPactPreprocessor.
*/
preprocessor?: C8yPactPreprocessorOptions;
/**
* Options to configure the C8yPact request matching.
*/
requestMatching?: C8yPactRequestMatchingOptions;
/**
* Recording mode for the pact. Default is `refresh`.
*/
recordingMode?: C8yPactRecordingMode;
}
type C8yPactConfigKeys = keyof C8yPactConfigOptions;
interface C8yPactEnv {
tenant?: C8yTenant;
loggedInUser?: string;
loggedInUserAlias?: string;
testTitlePath?: string[];
systemVersion?: string;
pluginVersion?: string;
pluginFolder?: string;
}
interface C8yPactObject {
/**
* Pact records containing the requests and responses as well as auth information,
* configuration options and created objects.
*/
records: C8yPactRecord[];
/**
* Meta information describing the pact.
*/
info: C8yPactInfo;
/**
* Unique id of the pact.
*/
id: C8yPactID;
}
declare const C8yPactObjectKeys: string[];
/**
* Pact object. Contains all information about a recorded pact, including
* the pact records with requests and responses as well as info object with
* meta data. A C8yPact objtect must have an unique id.
*/
interface C8yPact extends C8yPactObject {
/**
* Clears all records of the pact. Also resets all indexes internally used for
* iterating over the records.
*/
clearRecords(): void;
/**
* Appends a new record to the pact. If skipIfExists is true, the record is
* only appended if no record with the same request exists.
* @param record The record to add.
* @param skipIfExists If true, the record is only appended if no record for the same request exists.
* @returns True if the record was appended, false otherwise.
*/
appendRecord(record: C8yPactRecord, skipIfExists?: boolean): boolean;
/**
* Replaces an existing record with a new record. If no record with the same
* request exists, the record is appended.
* @param record The record to be replaced.
* @returns True if the record was replaced, false otherwise.
*/
replaceRecord(record: C8yPactRecord): boolean;
/**
* Returns the next pact record or null if no more records are available.
*/
nextRecord(): C8yPactRecord | null;
/**
* Returns the next pact record matching the given request. Request matching is
* based ob criteria like url and method. Returns null if no record is found.
*/
nextRecordMatchingRequest(request: Partial<Request> | {
url: string;
method: string;
}, baseUrl?: C8yBaseUrl): C8yPactRecord | null;
/**
* Returns an iterator for the pact records.
*/
[Symbol.iterator](): Iterator<C8yPactRecord | null>;
}
interface C8yPactInfoVersion {
system?: string;
c8ypact?: string;
runner?: string;
}
/**
* Meta information describing a pact and how it was recorded.
*/
interface C8yPactInfo extends C8yPactConfigOptions {
id: C8yPactID;
/**
* Version information of the system, runner and pact standard used to record the pact.
*/
version?: {
system?: string;
shell?: string;
shellName?: string;
c8ypact?: string;
runner?: string;
};
/**
* Title of the pact. Title is an array of suite and test titles.
*/
title?: string[];
/**
* Base URL when recording the pact.
*/
baseUrl: C8yBaseUrl;
/**
* Tenant when recording the pact.
*/
tenant?: C8yTenant;
}
/**
* The request stored in a C8yPactRecord.
*/
type C8yPactRequest = Partial<Cypress.RequestOptions> & {
$body?: any;
};
/**
* The response stored in a C8yPactRecord.
*/
interface C8yPactResponse<T> {
allRequestResponses?: any[];
body?: T;
duration?: number;
headers?: {
[key: string]: string | string[];
};
isOkStatusCode?: boolean;
status?: number;
statusText?: string;
method?: string;
$body?: any;
}
/**
* The C8yPactRecord contains all information about a recorded request. It contains
* the request and response as well as configuration options, auth information and
* the created object id.
*/
interface C8yPactRecord {
/**
* Request of the record.
*/
request: C8yPactRequest;
/**
* Response of the record.
*/
response: C8yPactResponse<any>;
/**
* Modified response returned by interception RouteHandler.
*/
modifiedResponse?: C8yPactResponse<any>;
/**
* Configuration options used for the request.
*/
options?: C8yClientOptions;
/**
* Auth information used for the request. Can be Basic or Cookie auth. Contains username and possibly alias.
*/
auth?: C8yPactAuthObject;
/**
* Id of an object created by the request. Used for mapping when running the recording.
*/
createdObject?: string;
/**
* Converts the C8yPactRecord to a Cypress.Response object.
*/
toCypressResponse(): Cypress.Response<any>;
/**
* Returns the date of the response.
*/
date(): Date | null;
/**
* Returns if the record has a request header with the given key. Comparison is case-insensitive.
*/
hasRequestHeader(key: string): boolean;
/**
* Returns the auth type of the record. Currently supports `BasicAuth`, `CookieAuth` or undefined.
*/
authType(): "BasicAuth" | "CookieAuth" | "BearerAuth" | undefined;
}
declare function isValidPactId(value: string): boolean;
/**
* Creates an C8yPactID for a given string or array of strings.
* @param value The string or array of strings to convert to a pact id.
* @returns The pact id.
*/
declare function pactId(value: string | string[]): C8yPactID | undefined;
/**
* Validate the given pact mode. Throws an error if the mode is not supported
* or undefined.
* @param mode The pact mode to validate.
*/
declare function validatePactMode(mode?: string): void;
/**
* Validate the given pact recording mode. Throws an error if the mode is not supported
* or undefined.
* @param mode The pact recording mode to validate.
*/
declare function validatePactRecordingMode(mode?: string): void;
/**
* Checks if the given object is a C8yPact. This also includes checking
* all records to be valid C8yPactRecord instances.
*
* @param obj The object to check.
* @returns True if the object is a C8yPact, false otherwise.
*/
declare function isPact(obj: any): obj is C8yPact;
/**
* Checks if the given object is a C8yPactRecord.
*
* @param obj The object to check.
* @returns True if the object is a C8yPactRecord, false otherwise.
*/
declare function isPactRecord(obj: any): obj is C8yPactRecord;
/**
* Checks if the given object is a Cypress.Response.
*
* @param obj The object to check.
* @returns True if the object is a Cypress.Response, false otherwise.
*/
declare function isCypressResponse(obj: any): obj is Cypress.Response<any>;
/**
* Checks if the given object is a C8yPactError. A C8yPactError is an error
* with the name "C8yPactError".
*
* @param error The object to check.
* @returns True if the object is a C8yPactError, false otherwise.
*/
declare function isPactError(error: any): boolean;
/**
* Converts a Cypress.Response to a C8yPactRequest.
*/
declare function toPactRequest(response: Cypress.Response<any> | Partial<Cypress.Response<any>>): C8yPactRequest | undefined;
/**
* Converts a Cypress.Response to a C8yPactResponse.
*/
declare function toPactResponse<T>(response: Cypress.Response<T> | Partial<Cypress.Response<T>>): C8yPactResponse<T> | undefined;
type C8yPactSaveKeys = "id" | "info" | "records";
/**
* Returns the value of the environment variable with the given name. The function
* tries to find the value in the global `process.env` or `Cypress.env()`. If `env`
* is provided, the function uses the given object as environment.
*
* The function tries to find the value in the following order:
* - `name`
* - `camelCase(name)`
* - `CYPRESS_name`
* - `name.replace(/^C8Y_/i, "")`
* - `CYPRESS_camelCase(name)`
* - `CYPRESS_camelCase(name.replace(/^C8Y_/i, ""))`
*
* @param name The name of the environment variable.
* @param env The environment object to use. Default is `process.env` or `Cypress.env()`
*
* @returns The value of the environment variable or `undefined` if not found.
*/
declare function getEnvVar(name: string, env?: {
[key: string]: string;
}): string | undefined;
declare function isOneOfStrings(value: string, values: string[]): boolean;
declare function getCreatedObjectId(response: Cypress.Response<any> | Partial<Cypress.Response<any>> | C8yPactResponse<any>): string | undefined;
/**
* Default implementation of C8yPact. Use C8yDefaultPact.from to create a C8yPact from
* a Cypress.Response object, a serialized pact as string or an object implementing the
* C8yPact interface. Note, objects implementing the C8yPact interface may not provide
* all required functions and properties.
*/
declare class C8yDefaultPact implements C8yPact {
records: C8yPactRecord[];
info: C8yPactInfo;
id: C8yPactID;
protected recordIndex: number;
protected iteratorIndex: number;
protected requestIndexMap: {
[key: string]: number;
};
static strictMatching: boolean;
constructor(records: C8yPactRecord[], info: C8yPactInfo, id: C8yPactID);
/**
* Creates a C8yPact from a Cypress.Response object, a serialized pact as string
* or an object containing the pact records and info object. Throws an error if
* the input can not be converted to a C8yPact.
* @param obj The Cypress.Response, string or object to create a pact from.
* @param info The C8yPactInfo object containing additional information for the pact.
* @param client The optional C8yClient for options and auth information.
*/
static from(...args: [obj: Cypress.Response<any>, info: C8yPactInfo, client?: C8yClient] | [obj: string | C8yPact]): C8yDefaultPact;
clearRecords(): void;
appendRecord(record: C8yPactRecord, skipIfExists?: boolean): boolean;
replaceRecord(record: C8yPactRecord): boolean;
/**
* Returns the next pact record or null if no more records are available.
*/
nextRecord(): C8yPactRecord | null;
nextRecordMatchingRequest(request: Partial<Request> | {
url: string;
method: string;
}, baseUrl?: C8yBaseUrl): C8yPactRecord | null;
protected getIndexForKey(key: string): number;
protected setIndexForKey(key: string, index: number): void;
protected indexMapKey(request: Partial<Request> | C8yPactRequest, baseUrl?: C8yBaseUrl): string | undefined;
protected normalizeUrl(url: string | URL, parametersToRemove?: string[], baseUrl?: C8yBaseUrl): string;
protected matchUrls(url1: string | URL, url2: string | URL, baseUrl?: C8yBaseUrl): boolean;
protected getRequesIndex(key: string): number;
/**
* Returns the pact record for the given request or null if no record is found.
* Currently only url and method are used for matching.
* @param req The request to use for matching.
*/
getRecordsMatchingRequest(req: Partial<Request> | C8yPactRequest, baseUrl?: C8yBaseUrl): C8yPactRecord[] | null;
/**
* Returns an iterator for the pact records to iterate records using `for (const record of pact) {...}`.
*/
[Symbol.iterator](): Iterator<C8yPactRecord | null>;
}
type C8yPactSerializeOptions = {
preprocessor?: C8yPactPreprocessor;
client?: C8yClient;
modifiedResponse?: Cypress.Response<any>;
schemaGenerator?: C8ySchemaGenerator;
loggedInUser?: string;
loggedInUserAlias?: string;
authType?: string;
baseUrl?: C8yBaseUrl;
};
declare function toSerializablePactRecord(response: Partial<Cypress.Response<any>>, options?: C8yPactSerializeOptions): C8yPactRecord;
declare function toPactSerializableObject(response: Partial<Cypress.Response<any>>, info: C8yPactInfo, options?: C8yPactSerializeOptions): Promise<Pick<C8yPact, C8yPactSaveKeys>>;
/**
* Default implementation of C8yPactRecord. Use C8yDefaultPactRecord.from to create
* a C8yPactRecord from a Cypress.Response object or an C8yPactRecord object.
*/
declare class C8yDefaultPactRecord implements C8yPactRecord {
request: C8yPactRequest;
response: C8yPactResponse<any>;
options?: C8yClientOptions;
auth?: C8yPactAuthObject;
createdObject?: string;
modifiedResponse?: C8yPactResponse<any>;
constructor(request: C8yPactRequest, response: C8yPactResponse<any>, options?: C8yClientOptions, auth?: C8yPactAuthObject, createdObject?: string, modifiedResponse?: C8yPactResponse<any>);
/**
* Creates a C8yPactRecord from a Cypress.Response or an C8yPactRecord object.
* @param obj The Cypress.Response<any> or C8yPactRecord object.
* @param client The C8yClient for options and auth information.
*/
static from(obj: Cypress.Response<any> | C8yPactRecord | Partial<Cypress.Response<any>>, auth?: C8yAuthOptions, client?: C8yClient): C8yPactRecord;
/**
* Returns the date of the response.
*/
date(): Date | null;
/**
* Converts the C8yPactRecord to a Cypress.Response object.
*/
toCypressResponse<T>(): Cypress.Response<T>;
hasRequestHeader(key: string): boolean;
authType(): "BasicAuth" | "CookieAuth" | undefined;
}
declare function createPactRecord(response: Partial<Cypress.Response<any>>, client?: C8yClient, options?: {
loggedInUser?: string;
loggedInUserAlias?: string;
authType?: string;
}): C8yPactRecord;
/**
* Matcher for C8yPactRecord objects. Use C8yPactMatcher to match any two
* records. Depending on the matcher implementation an Error will be thrown
* or boolean is returned.
*/
interface C8yPactMatcher {
/**
* Matches objectToMatch against objectPact. Returns false if objectToMatch
* does not match objectPact or throws an error with details on failing match.
*
* @param obj1 Object to match.
* @param obj2 Pact to match obj1 against.
* @param {C8yPactMatcherOptions} options The C8yPactMatcherOptions to use for matching.
*/
match: (objectToMatch: any, objectPact: any, options?: C8yPactMatcherOptions) => boolean;
}
interface C8yPactMatcherOptions {
strictMatching?: boolean;
matchSchemaAndObject?: boolean;
loggerProps?: {
[key: string]: any;
};
schemaMatcher?: C8ySchemaMatcher;
parents?: string[];
ignoreCase?: boolean;
}
/**
* Default implementation of C8yPactMatcher to match C8yPactRecord objects. Pacts
* are matched by comparing the properties of the objects using property matchers.
* If no property matcher is configured for a property, the property will be matched
* by equality. Disable Cypress.c8ypact.config.strictMatching to ignore properties that are
* missing in matched objects. In case objects do not match an C8yPactError is thrown.
*/
declare class C8yDefaultPactMatcher implements C8yPactMatcher {
propertyMatchers: {
[key: string]: C8yPactMatcher;
};
static schemaMatcher: C8ySchemaMatcher;
static matchSchemaAndObject: boolean;
constructor(propertyMatchers?: {
[key: string]: C8yPactMatcher;
});
match(obj1: any, obj2: any, options?: C8yPactMatcherOptions): boolean;
/**
* Returns the property matcher for the given property name.
* @param key The property name to get the matcher for.
* @param ignoreCase Whether to ignore the case of the property name.
*/
getPropertyMatcher(key: string, ignoreCase?: boolean): any;
/**
* Adds a new property matcher for the given property name.
*/
addPropertyMatcher(propertyName: string, matcher: C8yPactMatcher): void;
/**
* Removes the property matcher for the given property name.
*/
removePropertyMatcher(propertyName: string): void;
}
/**
* Extends C8yDefaultPactMatcher with default property matchers for Cumulocity
* response bodies. It has rules configured at least for the following properties:
* id, statistics, lastUpdated, creationTime, next, self, password, owner, tenantId
* and lastPasswordChange. It is registered for the properties body and requestBody.
*/
declare class C8yPactBodyMatcher extends C8yDefaultPactMatcher {
constructor(propertyMatchers?: {});
}
declare class C8yIdentifierMatcher implements C8yPactMatcher {
match(obj1: any, obj2: any): boolean;
}
declare class C8yNumberMatcher implements C8yPactMatcher {
match(obj1: any, obj2: any): boolean;
}
declare class C8yStringMatcher implements C8yPactMatcher {
match(obj1: any, obj2: any): boolean;
}
declare class C8yIgnoreMatcher implements C8yPactMatcher {
match(): boolean;
}
declare class C8ySameTypeMatcher implements C8yPactMatcher {
match(obj1: any, obj2: any): boolean;
}
declare class C8yISODateStringMatcher {
match(obj1: any, obj2: any): boolean;
}
declare function oauthLogin(auth: C8yAuthOptions, baseUrl?: C8yBaseUrl): Promise<C8yAuthOptions>;
/**
* Using C8yPactFileAdapter you can implement your own adapter to load and save pacts using any format you want.
* This allows loading pact objects from different sources, such as HAR files, pact.io, etc.
*
* The default adapter is C8yPactDefaultFileAdapter which loads and saves pact objects from/to
* json files using C8yPact objects. Default location is cypress/fixtures/c8ypact folder.
*/
interface C8yPactFileAdapter {
/**
* Loads all pact objects. The key must be the pact id used in C8yPact.id.
*/
loadPacts: () => {
[key: string]: C8yPact;
};
/**
* Loads a pact object by id from file.
*/
loadPact: (id: string) => C8yPact | null;
/**
* Saves a pact object.
*/
savePact: (pact: C8yPact) => void;
/**
* Deletes a pact object or file.
*/
deletePact: (id: string) => void;
/**
* Gets the folder where the pact files are stored.
*/
getFolder: () => string;
/**
* Checks if a pact exists for a given id.
*/
pactExists(id: string): boolean;
/**
* Provides some custom description of the adapter.
* @example C8yPactFileAdapter
*/
description(): string;
}
type LogFormat = "json" | "simple" | "combined" | "short" | "dev" | "tiny" | "common";
type C8yPactHttpResponse<T = any> = Pick<C8yPactResponse<T>, "status" | "statusText" | "body" | "headers">;
declare const C8yPactHttpControllerLogLevel: readonly ["info", "debug", "warn", "error"];
declare const C8yPactHttpControllerDefaultMode: C8yPactMode;
declare const C8yPactHttpControllerDefaultRecordingMode: C8yPactRecordingMode;
interface C8yPactHttpControllerOptions {
/**
* The resource path to use for the controller. Default is "/c8yctrl".
*/
resourcePath?: string;
/**
* Base URL of the target server to proxy requests to.
*/
baseUrl?: C8yBaseUrl;
/**
* Authentication options to use for authenticating against the target server.
*/
auth?: C8yAuthOptions;
/**
* Hostname to listen on. Default is localhost.
*/
hostname?: string;
/**
* Port to listen on. Default is 3000.
*/
port?: number;
/**
* Tenant id of the target server to proxy requests to.
*/
tenant?: C8yTenant;
/**
* Root folder for static files to serve.
*/
staticRoot?: string;
/**
* Adapter to use for loading and saving pact files.
*/
adapter: C8yPactFileAdapter;
/**
* Preprocessor to use for modifying requests and responses.
*/
preprocessor?: C8yPactPreprocessor;
/**
* Schema generator to use for generating schemas for response bodies. If not set, no schema is generated.
*/
schemaGenerator?: C8ySchemaGenerator;
/**
* Request matching options to use for matching requests to recorded responses.
*/
requestMatching?: C8yPactRequestMatchingOptions;
/**
* Enable strict mocking. If true, only recorded responses are returned.
*/
strictMocking?: boolean;
/**
* Mode the controller is running in.
*/
mode?: C8yPactMode;
/**
* Recording mode to use for recording requests and responses.
*/
recordingMode?: C8yPactRecordingMode;
/**
* Id of the pact to use for recording and mocking. Default is undefined.
*/
pactId?: C8yPactID;
/**
* Record to use for error responses when no mock is found.
*/
mockNotFoundResponse?: C8yPactHttpResponse | ((req: Request$1<any, any, any, any>) => C8yPactHttpResponse);
/**
* Logger to use for logging. Currently only winston is supported.
*/
logger?: winston.Logger;
/**
* RequestHandler to use for logging requests. Default is morgan.
*/
requestLogger?: RequestHandler[] | ((logger?: winston.Logger) => RequestHandler[]);
/**
* RequestHandler to use for logging errors. Default is morgan logger
* that logs error object with url, status, request and response details.
* Use "common", "combined", "dev", "short" or "tiny" to use predefined
* mporgan log formats.
*/
errorLogger?: RequestHandler | "common" | "combined" | "dev" | "short" | "tiny" | string;
/**
* Log level to use for logging. Default is info.
*/
logLevel?: (typeof C8yPactHttpControllerLogLevel)[number];
/**
* Log format to use for logging.
*/
logFormat?: LogFormat | string | FormatFn<IncomingMessage, ServerResponse<IncomingMessage>>;
/**
* The app names and version to use from static folder. E.g. "cockpit: 1020".
* The version must be a semver range.
* @example { "cockpit": ">1020.0.0", "dtm": "^1018.1.0" }
*/
appsVersions?: {
[key: string]: string;
};
/**
* Custom replacer function to use for JSON.stringify. Use for customization of JSON output.
* Default is to replace URLs in "self", "next", "initRequest" properties with hostname and
* port of the controller.
*/
stringifyReplacer?: (key: string, value: any) => any;
/**
* Callbacks for hooking into the controller lifecycle.
*/
on: C8yPactHttpControllerCallbackOptions;
}
interface C8yPactHttpControllerCallbackOptions {
/**
* Called before the controller is started.
* @param ctrl The controller instance.
* @param config The configuration used for the controller.
*/
beforeStart?: (ctrl: C8yPactHttpController, config?: C8yPactHttpControllerOptions) => void;
/**
* Called before a request is mocked. Use to modify or return custom response as mock. Also
* use to forward custom headers from the request to the response. By default, only the
* recorded `content-type` and `set-cookie` headers are forwarded. Any other recorded headers
* must be forwarded by adding them to the `response.headers` object.
*
* By returning null or undefined, the request is passed to the proxy handler without mocking.
*
* **Note**: return `record.response` to use the recorded response as mock.
*
* @param ctrl The controller instance.
* @param req The request to mock.
* @param record The record used for mocking.
* @returns A response to use as mock or null/undefined to pass the request to the proxy handler.
*/
mockRequest?: (ctrl: C8yPactHttpController, req: Request$1<any, any, any, any>, record: C8yPactRecord | undefined | null) => C8yPactHttpResponse | undefined | null;
/**
* Called when a request is not found in the recorded pacts. Use to return a custom response
* for the request or `undefined` if `mockNotFoundResponse` or default 404 response should
* be returned for the given request. To access the pact, the response was not found in, use
* `c8yctl.currentPact`.
* @param ctrl The controller instance.
* @param req The request to be mocked.
* @returns A response to use as mock for the request or `undefined` to use the default 404 response.
*/
mockNotFound?: (ctrl: C8yPactHttpController, req: Request$1) => C8yPactHttpResponse | undefined;
/**
* Called before a request is proxied. Use to modify the request before it
* is proxied, e.g. to add or remove headers, etc. or to abort the request
* by returning a custom or error response to send back to the client.
* @param ctrl The controller instance.
* @param proxyReq The proxy request.
* @param req The request to proxy.
* @returns A response to send back to the client to abort the request or undefined to continue.
*/
proxyRequest?: (ctrl: C8yPactHttpController, proxyReq: ClientRequest, req: Request$1<any, any, any, any>) => C8yPactHttpResponse | undefined | null;
/**
* Called after receiving the response for a proxied request. By returning false,
* the request and response are ignored and not processed and saved. Use to filter
* requests and responses from recording.
* @param ctrl The controller instance.
* @param req The proxied request.
* @param res The proxied response.
* @returns false if the request and response should be ignored, true otherwise.
*/
proxyResponse?: (ctrl: C8yPactHttpController, req: Request$1, res: C8yPactHttpResponse) => boolean;
/**
* Called before a request and its response are saved. By returning false, the
* request is ignored and not saved.
* @param ctrl The controller instance.
* @param req The C8yPact object to be saved.
* @returns true if the C8yPact should be saved, false otherwise.
*/
savePact?: (ctrl: C8yPactHttpController, pact: C8yPact) => boolean;
}
interface C8yPactHttpControllerConfig extends C8yPactHttpControllerOptions {
/**
* Folder to load and save pact files from and to.
*/
folder?: string;
/**
* Folder to save log files to.
*/
logFolder?: string;
/**
* Log file name to use for logging.
*/
logFilename?: string;
/**
* File to use for http access logging.
*/
accessLogFilename?: string;
/**
* User to login to the target server.
*/
user?: string;
/**
* Password to login to the target server.
*/
password?: string;
/**
* Enable or disable logging.
*/
log?: boolean;
}
type C8yCtrlHeader = "x-c8yctrl-type" | "x-c8yctrl-id" | "x-c8yctrl-count" | "x-c8yctrl-mode";
declare class C8yPactHttpController {
currentPact?: C8yDefaultPact;
readonly port: number;
readonly hostname: string;
protected _baseUrl?: C8yBaseUrl;
protected _staticRoot?: string;
readonly tenant?: C8yTenant;
adapter?: C8yPactFileAdapter;
protected _recordingMode: C8yPactRecordingMode;
protected _mode: C8yPactMode;
protected _isStrictMocking: boolean;
protected staticApps: {
[key: string]: string;
};
protected authOptions?: C8yAuthOptions;
protected server?: Server;
readonly app: Express;
readonly options: C8yPactHttpControllerOptions;
readonly resourcePath: string;
readonly logger: winston.Logger;
protected mockHandler?: RequestHandler;
protected proxyHandler?: RequestHandler;
constructor(options: C8yPactHttpControllerOptions);
/**
* Base URL of the target server to proxy requests to.
* @example "https://mytenant.eu-latest.cumulocity.com"
*/
get baseUrl(): string | undefined;
/**
* Root folder for static files to serve. The controller will serve static files from this folder.
* @example "/path/to/static/root"
*/
get staticRoot(): string | undefined;
get recordingMode(): C8yPactRecordingMode;
set recordingMode(mode: C8yPactRecordingMode);
get mode(): C8yPactMode;
set mode(mode: C8yPactMode);
isRecordingEnabled(): boolean;
isMockingEnabled(): boolean;
/**
* Starts the server. When started, the server listens on the configured port and hostname. If required,
* the server will try to login to the target server using the provided credentials. If authOptions have
* a bearer token, the server will use this token for authentication. To enforce BasicAuth, set the type
* property of the authOptions to "BasicAuth".
*/
start(): Promise<void>;
/**
* Stops the server.
*/
stop(): Promise<void>;
protected registerOpenAPIRequestHandler(): void;
protected registerStaticRootRequestHandler(): Promise<void>;
protected registerC8yctrlInterface(): void;
protected getStatus(): {
status: string;
uptime: number;
version: any;
adapter: string | null;
baseUrl: string | null;
tenant: string | null;
current: {
id: string | null;
};
static: {
root: string | null;
required: {
[key: string]: string;
} | null;
apps: {
[key: string]: string;
};
};
mode: "record" | "recording" | "apply" | "forward" | "disabled" | "mock";
supportedModes: readonly ["record", "recording", "apply", "forward", "disabled", "mock"];
recording: {
recordingMode: "replace" | "refresh" | "append" | "new";
supportedRecordingModes: readonly ["refresh", "append", "new", "replace"];
isRecordingEnabled: boolean;
};
mocking: {
isMockingEnabled: boolean;
strictMocking: boolean;
};
logger: {
level: string;
};
};
protected mockRequestHandler: RequestHandler;
protected stringifyReplacer: (key: string, value: any) => any;
getStringifyReplacer(): (key: string, value: any) => any;
stringify(obj?: any): string;
protected stringifyPact(pact: C8yDefaultPact | C8yPact | any): string;
protected producerForPact(pact: C8yPact): {
name: string;
version?: string;
} | undefined;
protected pactsForProducer(pacts: {
[key: string]: C8yDefaultPact;
}, producer: string | {
name: string;
version: string;
}, version?: string): C8yPact[];
savePact(response: Cypress.Response<any> | C8yPact, pactForId?: C8yPact): Promise<boolean>;
protected getObjectWithKeys(objs: any[], keys: string[]): any[];
}
export { C8yDefaultPact, C8yDefaultPactMatcher, C8yDefaultPactPreprocessor, C8yDefaultPactRecord, C8yISODateStringMatcher, C8yIdentifierMatcher, C8yIgnoreMatcher, C8yNumberMatcher, C8yPactBodyMatcher, C8yPactHttpController, C8yPactHttpControllerDefaultMode, C8yPactHttpControllerDefaultRecordingMode, C8yPactHttpControllerLogLevel, C8yPactModeValues, C8yPactObjectKeys, C8yPactPreprocessorDefaultOptions, C8yPactRecordingModeValues, C8ySameTypeMatcher, C8yStringMatcher, createPactRecord, getCreatedObjectId, getEnvVar, isCypressError, isCypressResponse, isIResult, isOneOfStrings, isPact, isPactError, isPactRecord, isValidPactId, isWindowFetchResponse, oauthLogin, pactId, parseRegexReplace, performRegexReplace, toCypressResponse, toPactRequest, toPactResponse, toPactSerializableObject, toSerializablePactRecord, validatePactMode, validatePactRecordingMode };
export type { C8yClient, C8yClientOptions, C8yCtrlHeader, C8yPact, C8yPactConfigKeys, C8yPactConfigOptions, C8yPactEnv, C8yPactHttpControllerCallbackOptions, C8yPactHttpControllerConfig, C8yPactHttpControllerOptions, C8yPactHttpResponse, C8yPactID, C8yPactInfo, C8yPactInfoVersion, C8yPactMatcher, C8yPactMatcherOptions, C8yPactMode, C8yPactObject, C8yPactPreprocessor, C8yPactPreprocessorOptions, C8yPactRecord, C8yPactRecordingMode, C8yPactRequest, C8yPactRequestMatchingOptions, C8yPactResponse, C8yPactSaveKeys, C8yPactSerializeOptions, C8ySchemaGenerator, C8ySchemaMatcher };