Skip to content

Commit

Permalink
feat: support MessagePact with a string as a content #1619
Browse files Browse the repository at this point in the history
  • Loading branch information
rholshausen committed Nov 25, 2022
1 parent 68dd07f commit e256c0c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -205,4 +205,19 @@ class MessagePactBuilderSpec extends Specification {
then:
generators.categories[category] == ['$.DT': new DateTimeGenerator("yyyy-MM-dd'T'HH:mm:ss")]
}

@Issue('#1619')
def 'support non-json text formats'() {
when:
def pact = new MessagePactBuilder()
.consumer('MessagePactBuilderSpec')
.expectsToReceive('a message with text contents')
.withContent('a=b&c=d', 'application/x-www-form-urlencoded')
.toPact()
Message message = pact.interactions.first()

then:
message.contents.valueAsString() == 'a=b&c=d'
message.contents.contentType.toString() == 'application/x-www-form-urlencoded'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ import au.com.dius.pact.core.model.messaging.MessagePact
/**
* PACT DSL builder for v3 specification
*/
class MessagePactBuilder(
class MessagePactBuilder @JvmOverloads constructor(
/**
* The consumer for the pact.
*/
private var consumer: Consumer,
private var consumer: Consumer = Consumer(),

/**
* The provider for the pact.
Expand All @@ -38,7 +38,6 @@ class MessagePactBuilder(
*/
private var messages: MutableList<Message> = mutableListOf()
) {

/**
* Name the provider that the consumer has a pact with.
*
Expand Down Expand Up @@ -198,6 +197,24 @@ class MessagePactBuilder(
return this
}

/**
* Adds the text as the message contents
*/
@JvmOverloads
fun withContent(contents: String, contentType: String = "text/plain"): MessagePactBuilder {
if (messages.isEmpty()) {
throw InvalidPactException("expectsToReceive is required before withMetaData")
}

val message = messages.last()
message.metaData["contentType"] = contentType

val ct = ContentType(contentType)
message.contents = OptionalBody.body(contents.toByteArray(ct.asCharset()), ct)

return this
}

/**
* Convert this builder into a Pact
*/
Expand Down

0 comments on commit e256c0c

Please sign in to comment.