Skip to content

Commit

Permalink
feat: add uuid matcher function
Browse files Browse the repository at this point in the history
  • Loading branch information
Ronald Holshausen committed Jan 13, 2021
1 parent 0d474d2 commit 49c3da8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/v3/matchers.spec.ts
Expand Up @@ -487,4 +487,31 @@ describe("V3 Matchers", () => {
})
})
})

describe("#uuid", () => {
it("returns a JSON representation of an regex matcher for UUIDs", () => {
let result = MatchersV3.uuid('ba4bd1bc-5556-11eb-9286-d71bc5b507be')
expect(result).to.deep.equal({
"pact:matcher:type": "regex",
"regex": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
"value": "ba4bd1bc-5556-11eb-9286-d71bc5b507be"
})
})

it("throws an exception if the example value does not match the UUID regex", () => {
expect(() => MatchersV3.uuid('not a uuid')).to.throw()
expect(() => MatchersV3.uuid('ba4bd1bc-5556-11eb-9286')).to.throw()
expect(() => MatchersV3.uuid('ba4bd1bc-5556-11eb-9286-d71bc5b507be-1234')).to.throw()
})

it("if no example is provided, it sets up a generator", () => {
let result = MatchersV3.uuid()
expect(result).to.deep.equal({
"pact:matcher:type": "regex",
"pact:generator:type": "Uuid",
"regex": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
"value": "e2490de5-5bd3-43d5-b7c4-526e33f71304"
})
})
})
})
25 changes: 25 additions & 0 deletions src/v3/matchers.ts
Expand Up @@ -434,4 +434,29 @@ export namespace MatchersV3 {
value: exampleValue
}
}

/**
* Match a universally unique identifier (UUID). Random values will be used for examples if no example is given.
*/
export function uuid(example?: string): RegexMatcher {
const regexStr = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
if (example) {
const regex = new RegExp("^" + regexStr + "$")
if (!example.match(regex)) {
throw new Error(`regex: Example value '${example}' does not match the UUID regular expression '${regexStr}'`)
}
return {
"pact:matcher:type": "regex",
regex: regexStr,
value: example
}
} else {
return {
"pact:matcher:type": "regex",
regex: regexStr,
"pact:generator:type": "Uuid",
"value": "e2490de5-5bd3-43d5-b7c4-526e33f71304"
}
}
}
}

0 comments on commit 49c3da8

Please sign in to comment.