Skip to content

3. Response mocking

Evgeny Abramovich edited this page Dec 26, 2024 · 3 revisions

The mocks configuration section in each mapping allows you to define specific endpoints to be mocked, including the response data and other parameters. It provides filters such as path, method, queries, and headers, which utilize the gorilla/mux route matching system.

Each endpoint mock requires a path parameter to define the URL path for the endpoint. Additionally, you can use the method parameter to specify a specific HTTP method for the endpoint.

The queries and headers parameters can be used to define more detailed URLs that will be mocked. The queries parameter allows you to specify specific query parameters for the URL, while the headers parameter allows you to define specific HTTP headers.

Here is the structure of the mock configuration:

mappings:
  - from: ...
    to: ...
    mocks:
      - path: /example-endpoint
        method: POST
        queries:
          param1: value1
          param2: value2
        headers:
          Content-Type: application/json
        response:
          code: 201
          headers:
            Content-Type: application/json
          delay: 10s
          raw: `{ "ok": true }`
          file: /path/to/file.json

Mock matching

path (required) - This property is used to define the URL path that should be mocked. The value should be a string, such as /example. The path can also include variables, denoted by curly braces ({}), such as /users/{id}. This variable path segment will match any URL that starts with /users/ and has a variable id in it. For example, a request to /users/123 will match the path /users/{id}.

method (optional) - This property is used to define the HTTP method that should be mocked. The value should be a string representing the desired HTTP method, such as GET, POST, PUT, etc. If this property is not specified, the mock will match any HTTP method, allowing the mock to be used for requests with any method.

queries (optional) - This property is used to define specific query parameters that should be matched against the request URL. The value should be a mapping (key-value pairs) of query parameters and their expected values, such as {"param1": "value1", "param2": "value2"}. If this property is not specified, the mock will match any query parameter, allowing the mock to be used for requests with any query parameter combination.

headers (optional): This property is used to define specific HTTP headers that should be matched against the request headers. The value should be a mapping (key-value pairs) of header names and their expected values, such as {"Content-Type": "application/json"}. If this property is not specified, the mock will match any HTTP header, allowing the mock to be used for requests with any header combination.

Mock response

When setting up mock configurations, you can define the response that should be returned when a mock is triggered. The selection responce with following properties are used to configure the mock response:

code (optional) - This property is used to define the HTTP status code that should be returned in the mock response. The value should be an integer representing the desired status code, such as 200 or 404. If this property is not specified, the mock will default to a 200 OK status code.

headers (optional) - This property is used to define specific HTTP headers that should be returned in the mock response. The value should be a mapping (key-value pairs) of header names and their corresponding values, such as {"Content-Type": "application/json"}. If this property is not specified, the mock response will not include any additional headers.

delay (optional) - This property is used to define a delay before sending the mock response. The value should be a string in the format <number><unit> <number><unit> ..., where <number> is a positive integer and <unit> represents a time unit. Valid time units are ns (nanoseconds), us or µs (microseconds), ms (milliseconds), s ( seconds), m (minutes), and h (hours).

For example, 1m 30s would delay the response by 1 minute and 30 seconds.

If this property is not specified, the mock response will be sent immediately without any delay.

raw (required if file or fake is not set) - This property is used to define the raw content that should be returned in the mock response. The value should be a string representing the desired content, such as "Hello, world!".

file (required if raw or fake is not set) - This property is used to define the path to a file that contains the mock response content. The content of the specified file will be used as the response content. The value should be a string that specifies the file path, such as ~/mocks/example.json.

fake (required if file or raw is not set) - This property is used to define the fake data that should be returned in the mock response.

seed (optional) - This property is used to define the seed for the random generator to freeze the generated value. The value should be a unsigned integer.

Fake data generation

UNCORS allow sending random JSON data based on configuration. The configuration follows a JSON Schema-like structure.

Object definition

type: object
properties:
  <property1-name>: <property1-value>
  <property2-name>: <property2-value>
  <property3-name>: <property3-value>

Where:

  • <property1-name>, <property2-name>, etc - The names of the object properties.
  • <property1-value>, <property1-value>, etc - The node definition (it can be object definition, array definition or primitive types) for the corresponding properties.

For example the following configuration:

fake:
  type: object
  properties:
    first-name:
      type: firstname
    last-name:
      type: lastname
    email:
      type: email
    phones:
      type: array
      item:
        type: phoneformatted
      count: 3

will produce next data (pay attention response was formatter for better readability):

{
  "email": "[email protected]",
  "first-name": "Kyla",
  "last-name": "Tromp",
  "phones": ["646-197-4242", "1-849-783-9215", "1-953-147-0257"]
}

Array definition

type: array
item: <item-definition>
count: <items-count>

Where:

For example the following configuration:

type: array
item:
  type: object
  properties:
    first-name:
      type: firstname
    last-name:
      type: lastname
    about:
      type: sentence
      options:
        wordcount: 15
count: 3

will produce next data (pay attention response was formatter for better readability):

[
  {
    "about": "Of most now summation whom pretty yet about scary thing shirt those an that within.",
    "first-name": "Sheila",
    "last-name": "Auer"
  },
  {
    "about": "Whom fight sufficient my lately then been generally these knit quarterly of his there could.",
    "first-name": "Precious",
    "last-name": "Dicki"
  },
  {
    "about": "Finnish Caesarian goal anybody tomorrow itself then entirely whale behind German regularly within boots this.",
    "first-name": "Kody",
    "last-name": "Larson"
  }
]

Primitive types

To configure a concrete primitive type you can use folofing structure:

type: <data-type>
options:
  <param1>: <param1-value>
  <param2>: <param2-value>
  <param3>: <param3-value>

Where:

  • - The key of function generator
  • <param1>, <param2>, etc - The keys of options for <data-type> function.
  • <param1-value>, <param2-value>, etc - The values of the corresponding parameters for the generator function.

Example of configuration for sentence data:

type: sentence
options:
  wordcount: 15

That will provide value like this:

"Themselves sock are fly noisily over before secondly nest theirs next is bunch his alternatively."

Following you can found table with information about available types, their options and return types.

Address

Type Description Options
city Part of a country with significant population, often a central hub for culture and commerce -
country Nation with its own government and defined territory -
countryabr Shortened 2-letter form of a country's name -
latitude Geographic coordinate specifying north-south position on Earth's surface -
longitude Geographic coordinate indicating east-west position on Earth's surface -
state Governmental division within a country, often having its own laws and government -
stateabr Shortened 2-letter form of a country's state -
street Public road in a city or town, typically with houses and buildings on each side -
streetname Name given to a specific road or street -
streetnumber Numerical identifier assigned to a street -
streetprefix Directional or descriptive term preceding a street name, like 'East' or 'Main' -
streetsuffix Designation at the end of a street name indicating type, like 'Avenue' or 'Street' -
zip Numerical code for postal address sorting, specific to a geographic area -

Auth

Type Description Options
password Secret word or phrase used to authenticate access to a system or account lower (bool) - Whether or not to add lower case characters
upper (bool) - Whether or not to add upper case characters
numeric (bool) - Whether or not to add numeric characters
special (bool) - Whether or not to add special characters
space (bool) - Whether or not to add spaces
length (int) - Number of characters in password
username Unique identifier assigned to a user for accessing an account or system -

Color

Type Description Options
color Hue seen by the eye, returns the name of the color like red or blue -
hexcolor Six-digit code representing a color in the color model -
rgbcolor Color defined by red, green, and blue light values -

Company

Type Description Options
blurb Brief description or summary of a company's purpose, products, or services -
bs Random bs company word -
buzzword Trendy or overused term often used in business to sound impressive -
company Designated official name of a business or organization -
companysuffix Suffix at the end of a company name, indicating business structure, like 'Inc.' or 'LLC' -
jobdescriptor Word used to describe the duties, requirements, and nature of a job -
joblevel Random job level -
jobtitle Specific title for a position or role within a company or organization -
slogan Catchphrase or motto used by a company to represent its brand or values -

Emoji

Type Description Options
emoji Digital symbol expressing feelings or ideas in text messages and online chats -
emojialias Alternative name or keyword used to represent a specific emoji in text or code -
emojicategory Group or classification of emojis based on their common theme or use, like 'smileys' or 'animals' -
emojidescription Brief explanation of the meaning or emotion conveyed by an emoji -
emojitag Label or keyword associated with an emoji to categorize or search for it easily -

Finance

Type Description Options
cusip Unique identifier for securities, especially bonds, in the United States and Canada -
isin International standard code for uniquely identifying securities worldwide -

Internet

Type Description Options
chromeuseragent The specific identification string sent by the Google Chrome web browser when making requests on the internet -
domainname Human-readable web address used to identify websites on the internet -
domainsuffix The part of a domain name that comes after the last dot, indicating its type or purpose -
firefoxuseragent The specific identification string sent by the Firefox web browser when making requests on the internet -
httpmethod Verb used in HTTP requests to specify the desired action to be performed on a resource -
httpstatuscode Random http status code -
httpstatuscodesimple Three-digit number returned by a web server to indicate the outcome of an HTTP request -
httpversion Number indicating the version of the HTTP protocol used for communication between a client and a server -
ipv4address Numerical label assigned to devices on a network for identification and communication -
ipv6address Numerical label assigned to devices on a network, providing a larger address space than IPv4 for internet communication -
loglevel Classification used in logging to indicate the severity or priority of a log entry -
macaddress Unique identifier assigned to network interfaces, often used in Ethernet networks -
operauseragent The specific identification string sent by the Opera web browser when making requests on the internet -
safariuseragent The specific identification string sent by the Safari web browser when making requests on the internet -
url Web address that specifies the location of a resource on the internet -
useragent String sent by a web browser to identify itself when requesting web content -

Language

Type Description Options
language System of communication using symbols, words, and grammar to convey meaning between individuals -
languageabbreviation Shortened form of a language's name -

Misc

Type Description Options
bool Data type that represents one of two possible values, typically true or false -
uuid 128-bit identifier used to uniquely identify objects or entities in computer systems -

Number

Type Description Options
float32 Data type representing floating-point numbers with 32 bits of precision in computing -
float32range Float32 value between given range min (float) - Minimum float32 value
max (float) - Maximum float32 value
float64 Data type representing floating-point numbers with 64 bits of precision in computing -
float64range Float64 value between given range min (float) - Minimum float64 value
max (float) - Maximum float64 value
int Signed integer -
int16 Signed 16-bit integer, capable of representing values from 32,768 to 32,767 -
int32 Signed 32-bit integer, capable of representing values from -2,147,483,648 to 2,147,483,647 -
int64 Signed 64-bit integer, capable of representing values from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807 -
int8 Signed 8-bit integer, capable of representing values from -128 to 127 -
intn Integer value between 0 and n n (int) - Maximum int value
number Mathematical concept used for counting, measuring, and expressing quantities or values min (int) - Minimum integer value
max (int) - Maximum integer value
uint Unsigned integer -
uint16 Unsigned 16-bit integer, capable of representing values from 0 to 65,535 -
uint32 Unsigned 32-bit integer, capable of representing values from 0 to 4,294,967,295 -
uint64 Unsigned 64-bit integer, capable of representing values from 0 to 18,446,744,073,709,551,615 -
uint8 Unsigned 8-bit integer, capable of representing values from 0 to 255 -
uintn Unsigned integer between 0 and n n (uint) - Maximum uint value

Payment

Type Description Options
achaccount A bank account number used for Automated Clearing House transactions and electronic transfers -
achrouting Unique nine-digit code used in the U.S. for identifying the bank and processing electronic transactions -
bitcoinaddress Cryptographic identifier used to receive, store, and send Bitcoin cryptocurrency in a peer-to-peer network -
bitcoinprivatekey Secret, secure code that allows the owner to access and control their Bitcoin holdings -
creditcardcvv Three or four-digit security code on a credit card used for online and remote transactions -
creditcardexp Date when a credit card becomes invalid and cannot be used for transactions -
creditcardnumber Unique numerical identifier on a credit card used for making electronic payments and transactions types ([]string) - A select number of types you want to use when generating a credit card number
bins ([]string) - Optional list of prepended bin numbers to pick from
gaps (bool) - Whether or not to have gaps in number
creditcardtype Classification of credit cards based on the issuing company -
currencylong Complete name of a specific currency used for official identification in financial transactions -
currencyshort Short 3-letter word used to represent a specific currency -
price The amount of money or value assigned to a product, service, or asset in a transaction min (float) - Minimum price value
max (float) - Maximum price value

Person

Type Description Options
email Electronic mail used for sending digital messages and communication over the internet -
firstname The name given to a person at birth -
gender Classification based on social and cultural norms that identifies an individual -
hobby An activity pursued for leisure and pleasure -
lastname The family name or surname of an individual -
middlename Name between a person's first name and last name -
name The given and family name of an individual -
nameprefix A title or honorific added before a person's name -
namesuffix A title or designation added after a person's name -
phone Numerical sequence used to contact individuals via telephone or mobile devices -
phoneformatted Formatted phone number of a person -
ssn Unique nine-digit identifier used for government and financial purposes in the United States -

String

Type Description Options
digit Numerical symbol used to represent numbers -
digitn string of length N consisting of ASCII digits count (uint) - Number of digits to generate
letter Character or symbol from the American Standard Code for Information Interchange (ASCII) character set -
lettern ASCII string with length N count (uint) - Number of digits to generate
string Sentence of the Lorem Ipsum placeholder text used in design and publishing wordcount (int) - Number of words in a sentence

Time

Type Description Options
date Representation of a specific day, month, and year, often used for chronological reference format (string) - Date time string format output. You may also use golang time format or java time format
daterange Random date between two ranges startdate (string) - Start date time string
enddate (string) - End date time string
format (string) - Date time string format
day 24-hour period equivalent to one rotation of Earth on its axis -
futuredate Date that has occurred after the current moment in time -
hour Unit of time equal to 60 minutes -
minute Unit of time equal to 60 seconds -
month Division of the year, typically 30 or 31 days long -
monthstring String Representation of a month name -
nanosecond Unit of time equal to One billionth (10^-9) of a second -
pastdate Date that has occurred before the current moment in time -
second Unit of time equal to 1/60th of a minute -
timezone Region where the same standard time is used, based on longitudinal divisions of the Earth -
timezoneabv Abbreviated 3-letter word of a timezone -
timezonefull Full name of a timezone -
timezoneoffset The difference in hours from Coordinated Universal Time (UTC) for a specific region -
timezoneregion Geographic area sharing the same standard time -
weekday Day of the week excluding the weekend -
year Period of 365 days, the time Earth takes to orbit the Sun -

Word

Type Description Options
adjective Word describing or modifying a noun -
adjectivedemonstrative Adjective used to point out specific things -
adjectivedescriptive Adjective that provides detailed characteristics about a noun -
adjectiveindefinite Adjective describing a non-specific noun -
adjectiveinterrogative Adjective used to ask questions -
adjectivepossessive Adjective indicating ownership or possession -
adjectiveproper Adjective derived from a proper noun, often used to describe nationality or origin -
adjectivequantitative Adjective that indicates the quantity or amount of something -
adverb Word that modifies verbs, adjectives, or other adverbs -
adverbdegree Adverb that indicates the degree or intensity of an action or adjective -
adverbfrequencydefinite Adverb that specifies how often an action occurs with a clear frequency -
adverbfrequencyindefinite Adverb that specifies how often an action occurs without specifying a particular frequency -
adverbmanner Adverb that describes how an action is performed -
adverbplace Adverb that indicates the location or direction of an action -
adverbtimedefinite Adverb that specifies the exact time an action occurs -
adverbtimeindefinite Adverb that gives a general or unspecified time frame -
connective Word used to connect words or sentences -
connectivecasual Connective word used to indicate a cause-and-effect relationship between events or actions -
connectivecomparative Connective word used to indicate a comparison between two or more things -
connectivecomplaint Connective word used to express dissatisfaction or complaints about a situation -
connectiveexamplify Connective word used to provide examples or illustrations of a concept or idea -
connectivelisting Connective word used to list or enumerate items or examples -
connectivetime Connective word used to indicate a temporal relationship between events or actions -
loremipsumparagraph Paragraph of the Lorem Ipsum placeholder text used in design and publishing paragraphcount (int) - Number of paragraphs
sentencecount (int) - Number of sentences in a paragraph
wordcount (int) - Number of words in a sentence
paragraphseparator (string) - String value to add between paragraphs
loremipsumsentence Sentence of the Lorem Ipsum placeholder text used in design and publishing wordcount (int) - Number of words in a sentence
loremipsumword Word of the Lorem Ipsum placeholder text used in design and publishing -
noun Person, place, thing, or idea, named or referred to in a sentence -
nounabstract Ideas, qualities, or states that cannot be perceived with the five senses -
nouncollectiveanimal Group of animals, like a 'pack' of wolves or a 'flock' of birds -
nouncollectivepeople Group of people or things regarded as a unit -
nouncollectivething Group of objects or items, such as a 'bundle' of sticks or a 'cluster' of grapes -
nouncommon General name for people, places, or things, not specific or unique -
nounconcrete Names for physical entities experienced through senses like sight, touch, smell, or taste -
nouncountable Items that can be counted individually -
noununcountable Items that can't be counted individually -
paragraph Distinct section of writing covering a single theme, composed of multiple sentences paragraphcount (int) - Number of paragraphs
sentencecount (int) - Number of sentences in a paragraph
wordcount (int) - Number of words in a sentence
paragraphseparator (string) - String value to add between paragraphs
phrase A small group of words standing together -
preposition Words used to express the relationship of a noun or pronoun to other words in a sentence -
prepositioncompound Preposition that can be formed by combining two or more prepositions -
prepositiondouble Two-word combination preposition, indicating a complex relation -
prepositionsimple Single-word preposition showing relationships between 2 parts of a sentence -
pronoun Word used in place of a noun to avoid repetition -
pronoundemonstrative Pronoun that points out specific people or things -
pronouninterrogative Pronoun used to ask questions -
pronounobject Pronoun used as the object of a verb or preposition -
pronounpersonal Pronoun referring to a specific persons or things -
pronounpossessive Pronoun indicating ownership or belonging -
pronounreflective Pronoun referring back to the subject of the sentence -
pronounrelative Pronoun that introduces a clause, referring back to a noun or pronoun -
question Statement formulated to inquire or seek clarification -
quote Direct repetition of someone else's words -
sentence Set of words expressing a statement, question, exclamation, or command wordcount (int) - Number of words in a sentence
verb Word expressing an action, event or state -
verbaction Verb Indicating a physical or mental action -
verbhelping Auxiliary verb that helps the main verb complete the sentence -
verblinking Verb that Connects the subject of a sentence to a subject complement -
word Basic unit of language representing a concept or thing, consisting of letters and having meaning -