Skip to content

3. Response mocksing

Yauheni Abramovich edited this page Sep 22, 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.

Fake data generation

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

Object definition

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

Where:

  • - The seed for generator to freeze generated value
  • <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": "amparobogan@hauck.org",
  "first-name": "Kyla",
  "last-name": "Tromp",
  "phones": [
    "646-197-4242",
    "1-849-783-9215",
    "1-953-147-0257"
  ]
}

Array definition

type: array
seed: <randomizing-seed>
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>
seed: <randomizing-seed>
options:
  <param1>: <param1-value>
  <param2>: <param2-value>
  <param3>: <param3-value>

Where:

  • - The key of function generator
  • - The seed for generator to freeze generated value
  • <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 Return Type Example
city Part of a country with significant population, often a central hub for culture and commerce - string Marcelside
country Nation with its own government and defined territory - string United States of America
countryabr Shortened 2-letter form of a country's name - string US
latitude Geographic coordinate specifying north-south position on Earth's surface - float -73.534056
longitude Geographic coordinate indicating east-west position on Earth's surface - float -147.068112
state Governmental division within a country, often having its own laws and government - string Illinois
stateabr Shortened 2-letter form of a country's state - string IL
street Public road in a city or town, typically with houses and buildings on each side - string 364 East Rapidsborough
streetname Name given to a specific road or street - string View
streetnumber Numerical identifier assigned to a street - string 13645
streetprefix Directional or descriptive term preceding a street name, like 'East' or 'Main' - string Lake
streetsuffix Designation at the end of a street name indicating type, like 'Avenue' or 'Street' - string land
zip Numerical code for postal address sorting, specific to a geographic area - string 13645

Auth

Type Description Options Return Type Example
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
string EEP+wwpk 4lU-eHNXlJZ4n K9%v&TZ9e
username Unique identifier assigned to a user for accessing an account or system - string Daniel1364

Color

Type Description Options Return Type Example
color Hue seen by the eye, returns the name of the color like red or blue - string MediumOrchid
hexcolor Six-digit code representing a color in the color model - string #a99fb4
rgbcolor Color defined by red, green, and blue light values - []int [85, 224, 195]

Company

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

Emoji

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

Finance

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

Internet

Type Description Options Return Type Example
chromeuseragent The specific identification string sent by the Google Chrome web browser when making requests on the internet - string Mozilla/5.0 (X11; Linux i686) AppleWebKit/5312 (KHTML, like Gecko) Chrome/39.0.836.0 Mobile Safari/5312
domainname Human-readable web address used to identify websites on the internet - string centraltarget.biz
domainsuffix The part of a domain name that comes after the last dot, indicating its type or purpose - string org
firefoxuseragent The specific identification string sent by the Firefox web browser when making requests on the internet - string Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_8_3 rv:7.0) Gecko/1900-07-01 Firefox/37.0
httpmethod Verb used in HTTP requests to specify the desired action to be performed on a resource - string HEAD
httpstatuscode Random http status code - int 200
httpstatuscodesimple Three-digit number returned by a web server to indicate the outcome of an HTTP request - int 404
httpversion Number indicating the version of the HTTP protocol used for communication between a client and a server - string HTTP/1.1
ipv4address Numerical label assigned to devices on a network for identification and communication - string 222.83.191.222
ipv6address Numerical label assigned to devices on a network, providing a larger address space than IPv4 for internet communication - string 2001:cafe:8898:ee17:bc35:9064:5866:d019
loglevel Classification used in logging to indicate the severity or priority of a log entry - string error
macaddress Unique identifier assigned to network interfaces, often used in Ethernet networks - string cb:ce:06:94:22:e9
operauseragent The specific identification string sent by the Opera web browser when making requests on the internet - string Opera/8.39 (Macintosh; U; PPC Mac OS X 10_8_7; en-US) Presto/2.9.335 Version/10.00
safariuseragent The specific identification string sent by the Safari web browser when making requests on the internet - string Mozilla/5.0 (iPad; CPU OS 8_3_2 like Mac OS X; en-US) AppleWebKit/531.15.6 (KHTML, like Gecko) Version/4.0.5 Mobile/8B120 Safari/6531.15.6
url Web address that specifies the location of a resource on the internet - string http://www.principalproductize.biz/target
useragent String sent by a web browser to identify itself when requesting web content - string Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5362 (KHTML, like Gecko) Chrome/37.0.834.0 Mobile Safari/5362

Language

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

Misc

Type Description Options Return Type Example
bool Data type that represents one of two possible values, typically true or false - bool true
uuid 128-bit identifier used to uniquely identify objects or entities in computer systems - string 590c1440-9888-45b0-bd51-a817ee07c3f2

Number

Type Description Options Return Type Example
float32 Data type representing floating-point numbers with 32 bits of precision in computing - float32 3.1128167e+37
float32range Float32 value between given range min (float) - Minimum float32 value
max (float) - Maximum float32 value
float32 914774.6
float64 Data type representing floating-point numbers with 64 bits of precision in computing - float64 1.644484108270445e+307
float64range Float64 value between given range min (float) - Minimum float64 value
max (float) - Maximum float64 value
float64 914774.5585333086
int Signed integer - int 14866
int16 Signed 16-bit integer, capable of representing values from 32,768 to 32,767 - int16 2200
int32 Signed 32-bit integer, capable of representing values from -2,147,483,648 to 2,147,483,647 - int32 -1072427943
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 - int64 -8379641344161477543
int8 Signed 8-bit integer, capable of representing values from -128 to 127 - int8 24
intn Integer value between 0 and n n (int) - Maximum int value int 32783
number Mathematical concept used for counting, measuring, and expressing quantities or values min (int) - Minimum integer value
max (int) - Maximum integer value
int 14866
uint Unsigned integer - uint 14866
uint16 Unsigned 16-bit integer, capable of representing values from 0 to 65,535 - uint16 34968
uint32 Unsigned 32-bit integer, capable of representing values from 0 to 4,294,967,295 - uint32 1075055705
uint64 Unsigned 64-bit integer, capable of representing values from 0 to 18,446,744,073,709,551,615 - uint64 843730692693298265
uint8 Unsigned 8-bit integer, capable of representing values from 0 to 255 - uint8 152
uintn Unsigned integer between 0 and n n (uint) - Maximum uint value uint 32783

Payment

Type Description Options Return Type Example
achaccount A bank account number used for Automated Clearing House transactions and electronic transfers - string 491527954328
achrouting Unique nine-digit code used in the U.S. for identifying the bank and processing electronic transactions - string 513715684
bitcoinaddress Cryptographic identifier used to receive, store, and send Bitcoin cryptocurrency in a peer-to-peer network - string 1lWLbxojXq6BqWX7X60VkcDIvYA
bitcoinprivatekey Secret, secure code that allows the owner to access and control their Bitcoin holdings - string 5vrbXTADWJ6sQBSYd6lLkG97jljNc0X9VPBvbVqsIH9lWOLcoqg
creditcardcvv Three or four-digit security code on a credit card used for online and remote transactions - string 513
creditcardexp Date when a credit card becomes invalid and cannot be used for transactions - string 01/21
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
string 4136459948995369
creditcardtype Classification of credit cards based on the issuing company - string Visa
currencylong Complete name of a specific currency used for official identification in financial transactions - string United States Dollar
currencyshort Short 3-letter word used to represent a specific currency - string USD
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
float64 92.26

Person

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

String

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

Time

Type Description Options Return Type Example
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 string 2006-01-02T15:04:05Z07:00
daterange Random date between two ranges startdate (string) - Start date time string
enddate (string) - End date time string
format (string) - Date time string format
string 2006-01-02T15:04:05Z07:00
day 24-hour period equivalent to one rotation of Earth on its axis - int 12
futuredate Date that has occurred after the current moment in time - time 2107-01-24 13:00:35.820738079 +0000 UTC
hour Unit of time equal to 60 minutes - int 8
minute Unit of time equal to 60 seconds - int 34
month Division of the year, typically 30 or 31 days long - string 1
monthstring String Representation of a month name - string September
nanosecond Unit of time equal to One billionth (10^-9) of a second - int 196446360
pastdate Date that has occurred before the current moment in time - time 2007-01-24 13:00:35.820738079 +0000 UTC
second Unit of time equal to 1/60th of a minute - int 43
timezone Region where the same standard time is used, based on longitudinal divisions of the Earth - string Kaliningrad Standard Time
timezoneabv Abbreviated 3-letter word of a timezone - string KST
timezonefull Full name of a timezone - string (UTC+03:00) Kaliningrad, Minsk
timezoneoffset The difference in hours from Coordinated Universal Time (UTC) for a specific region - float32 3
timezoneregion Geographic area sharing the same standard time - string America/Alaska
weekday Day of the week excluding the weekend - string Friday
year Period of 365 days, the time Earth takes to orbit the Sun - int 1900

Word

Type Description Options Return Type Example
adjective Word describing or modifying a noun - string genuine
adjectivedemonstrative Adjective used to point out specific things - string this
adjectivedescriptive Adjective that provides detailed characteristics about a noun - string brave
adjectiveindefinite Adjective describing a non-specific noun - string few
adjectiveinterrogative Adjective used to ask questions - string what
adjectivepossessive Adjective indicating ownership or possession - string my
adjectiveproper Adjective derived from a proper noun, often used to describe nationality or origin - string Afghan
adjectivequantitative Adjective that indicates the quantity or amount of something - string a little
adverb Word that modifies verbs, adjectives, or other adverbs - string smoothly
adverbdegree Adverb that indicates the degree or intensity of an action or adjective - string intensely
adverbfrequencydefinite Adverb that specifies how often an action occurs with a clear frequency - string hourly
adverbfrequencyindefinite Adverb that specifies how often an action occurs without specifying a particular frequency - string occasionally
adverbmanner Adverb that describes how an action is performed - string stupidly
adverbplace Adverb that indicates the location or direction of an action - string east
adverbtimedefinite Adverb that specifies the exact time an action occurs - string now
adverbtimeindefinite Adverb that gives a general or unspecified time frame - string already
connective Word used to connect words or sentences - string such as
connectivecasual Connective word used to indicate a cause-and-effect relationship between events or actions - string an outcome of
connectivecomparative Connective word used to indicate a comparison between two or more things - string in addition
connectivecomplaint Connective word used to express dissatisfaction or complaints about a situation - string besides
connectiveexamplify Connective word used to provide examples or illustrations of a concept or idea - string then
connectivelisting Connective word used to list or enumerate items or examples - string firstly
connectivetime Connective word used to indicate a temporal relationship between events or actions - string finally
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
string Quia quae repellat consequatur quidem nisi quo qui voluptatum accusantium quisquam amet. Quas et ut non dolorem ipsam aut enim assumenda mollitia harum ut. Dicta similique veniam nulla voluptas at excepturi non ad maxime at non. Eaque hic repellat praesentium voluptatem qui consequuntur dolor iusto autem velit aut. Fugit tempore exercitationem harum consequatur voluptatum modi minima aut eaque et et.

Aut ea voluptatem dignissimos expedita odit tempore quod aut beatae ipsam iste. Minus voluptatibus dolorem maiores eius sed nihil vel enim odio voluptatem accusamus. Natus quibusdam temporibus tenetur cumque sint necessitatibus dolorem ex ducimus iusto ex. Voluptatem neque dicta explicabo officiis et ducimus sit ut ut praesentium pariatur. Illum molestias nisi at dolore ut voluptatem accusantium et fugiat et ut.

Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta quia et quia. Aut veniam voluptas consequatur placeat sapiente non eveniet voluptatibus magni velit eum. Nobis vel repellendus sed est qui autem laudantium quidem quam ullam consequatur. Aut iusto ut commodi similique quae voluptatem atque qui fugiat eum aut. Quis distinctio consequatur voluptatem vel aliquid aut laborum facere officiis iure tempora.
loremipsumsentence Sentence of the Lorem Ipsum placeholder text used in design and publishing wordcount (int) - Number of words in a sentence string Quia quae repellat consequatur quidem.
loremipsumword Word of the Lorem Ipsum placeholder text used in design and publishing - string quia
noun Person, place, thing, or idea, named or referred to in a sentence - string aunt
nounabstract Ideas, qualities, or states that cannot be perceived with the five senses - string confusion
nouncollectiveanimal Group of animals, like a 'pack' of wolves or a 'flock' of birds - string party
nouncollectivepeople Group of people or things regarded as a unit - string body
nouncollectivething Group of objects or items, such as a 'bundle' of sticks or a 'cluster' of grapes - string hand
nouncommon General name for people, places, or things, not specific or unique - string part
nounconcrete Names for physical entities experienced through senses like sight, touch, smell, or taste - string snowman
nouncountable Items that can be counted individually - string neck
noununcountable Items that can't be counted individually - string seafood
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
string Interpret context record river mind press self should compare property outcome divide. Combine approach sustain consult discover explanation direct address church husband seek army. Begin own act welfare replace press suspect stay link place manchester specialist. Arrive price satisfy sign force application hair train provide basis right pay. Close mark teacher strengthen information attempt head touch aim iron tv take.
phrase A small group of words standing together - string time will tell
preposition Words used to express the relationship of a noun or pronoun to other words in a sentence - string other than
prepositioncompound Preposition that can be formed by combining two or more prepositions - string according to
prepositiondouble Two-word combination preposition, indicating a complex relation - string before
prepositionsimple Single-word preposition showing relationships between 2 parts of a sentence - string out
pronoun Word used in place of a noun to avoid repetition - string me
pronoundemonstrative Pronoun that points out specific people or things - string this
pronouninterrogative Pronoun used to ask questions - string what
pronounobject Pronoun used as the object of a verb or preposition - string it
pronounpersonal Pronoun referring to a specific persons or things - string it
pronounpossessive Pronoun indicating ownership or belonging - string mine
pronounreflective Pronoun referring back to the subject of the sentence - string myself
pronounrelative Pronoun that introduces a clause, referring back to a noun or pronoun - string as
question Statement formulated to inquire or seek clarification - string Roof chia echo?
quote Direct repetition of someone else's words - string "Roof chia echo." - Lura Lockman
sentence Set of words expressing a statement, question, exclamation, or command wordcount (int) - Number of words in a sentence string Interpret context record river mind.
verb Word expressing an action, event or state - string release
verbaction Verb Indicating a physical or mental action - string close
verbhelping Auxiliary verb that helps the main verb complete the sentence - string be
verblinking Verb that Connects the subject of a sentence to a subject complement - string was
word Basic unit of language representing a concept or thing, consisting of letters and having meaning - string man