Skip to content

Commit

Permalink
chore(pact-jvm-server): Converted Result and ServerState to kotlin
Browse files Browse the repository at this point in the history
  • Loading branch information
rholshausen committed Nov 18, 2024
1 parent 7ed2ee4 commit 36cf032
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 58 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package au.com.dius.pact.server

import au.com.dius.pact.core.model.IResponse

data class ServerState @JvmOverloads constructor(val state: Map<String, StatefulMockProvider> = mapOf())

data class Result(val response: IResponse, val newState: ServerState)
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ object Complete extends StrictLogging {
}

def apply(request: Request, oldState: ServerState): Result = {
def clientError = Result(new Response(400), oldState)
def clientError = new Result(new Response(400), oldState)
def pactWritten(response: Response, port: String) = {
val server = oldState(port)
val newState = oldState.filter(p => p._2 != server)
Result(response, newState)
val server = oldState.getState.asScala(port)
val newState = new ServerState(oldState.getState.asScala.filter(p => p._2 != server).asJava)
new Result(response, newState)
}

val result = for {
port <- getPort(JsonUtils.parseJsonString(request.getBody.valueAsString()))
mockProvider <- oldState.get(port)
mockProvider <- oldState.getState.asScala.get(port)
sessionResults = mockProvider.getSession.remainingResults
pact <- Option(mockProvider.getPact)
} yield {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ object Create extends StrictLogging {
val portEntry = port.toString -> server

// Not very scala...
val newState = (oldState + portEntry) ++
val newState = (oldState.getState.asScala + portEntry) ++
(for (
pathValue <- path
) yield (pathValue -> server))
Expand All @@ -48,12 +48,12 @@ object Create extends StrictLogging {

server.start(pact)

Result(new Response(201, (ResponseUtils.CrossSiteHeaders ++ Map("Content-Type" -> List("application/json").asJava)).asJava, body), newState)
new Result(new Response(201, (ResponseUtils.CrossSiteHeaders ++ Map("Content-Type" -> List("application/json").asJava)).asJava, body), new ServerState(newState.asJava))
}

def apply(request: Request, oldState: ServerState, config: Config): Result = {
def errorJson = OptionalBody.body("{\"error\": \"please provide state param and path param and pact body\"}".getBytes)
def clientError = Result(new Response(400, ResponseUtils.CrossSiteHeaders.asJava, errorJson),
def clientError = new Result(new Response(400, ResponseUtils.CrossSiteHeaders.asJava, errorJson),
oldState)

logger.debug(s"path=${request.getPath}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ object Publish extends StrictLogging {
def body: OptionalBody = OptionalBody.body(errorJson.getBytes())
response = new Response(500, ResponseUtils.CrossSiteHeaders.asJava, body)
}
Result(response, oldState)
new Result(response, oldState)
}

private def publishPact(consumer: String, consumerVersion: String, provider: String, broker: String, authToken: Option[String], tags: Option[::[String]]) = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import unfiltered.response.ResponseFunction
import scala.collection.immutable.Map

class ServerStateStore {
var state: ServerState = Map()
var state: ServerState = new ServerState()
}

@Sharable
Expand All @@ -21,8 +21,8 @@ case class RequestHandler(store: ServerStateStore, config: Config) extends cycle
def handle(request: HttpRequest[ReceivedMessage]): ResponseFunction[NHttpResponse] = {
val pactRequest = Conversions.unfilteredRequestToPactRequest(request)
val result = RequestRouter.dispatch(pactRequest, store.state, config)
store.state = result.newState
Conversions.pactToUnfilteredResponse(result.response)
store.state = result.getNewState
Conversions.pactToUnfilteredResponse(result.getResponse)
}
def intent = PartialFunction[HttpRequest[ReceivedMessage], ResponseFunction[NHttpResponse]](handle)
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import scala.collection.JavaConverters._
object RequestRouter extends StrictLogging {
def matchPath(request: Request, oldState: ServerState): Option[StatefulMockProvider] =
(for {
k <- oldState.keys if request.getPath.startsWith(k)
pact <- oldState.get(k)
k <- oldState.getState.asScala.keys if request.getPath.startsWith(k)
pact <- oldState.getState.asScala.get(k)
} yield pact).headOption

def handlePactRequest(request: Request, oldState: ServerState): Option[IResponse] =
Expand All @@ -19,7 +19,7 @@ object RequestRouter extends StrictLogging {
} yield pact.handleRequest(request)

def state404(request: Request, oldState: ServerState): String =
(oldState + ("path" -> request.getPath)).mkString(",\n")
(oldState.getState.asScala + ("path" -> request.getPath)).mkString(",\n")

val EMPTY_MAP: util.Map[String, util.List[String]] = Map[String, util.List[String]]().asJava

Expand All @@ -35,7 +35,7 @@ object RequestRouter extends StrictLogging {
case "complete" => Complete(request, oldState)
case "publish" => Publish(request, oldState, config)
case "" => ListServers(oldState)
case _ => Result(pactDispatch(request, oldState), oldState)
case _ => new Result(pactDispatch(request, oldState), oldState)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package au.com.dius.pact.server

import au.com.dius.pact.core.model.{IResponse, OptionalBody, Response}
import au.com.dius.pact.core.model.{OptionalBody, Response}
import ch.qos.logback.classic.Level
import org.slf4j.{Logger, LoggerFactory}

Expand All @@ -9,15 +9,13 @@ import scala.collection.JavaConverters._
object ListServers {

def apply(oldState: ServerState): Result = {
val ports = oldState.keySet.filter(p => p.matches("\\d+")).mkString(", ")
val paths = oldState.keySet.filter(p => !p.matches("\\d+")).map("\"" + _ + "\"").mkString(", ")
val ports = oldState.getState.keySet.asScala.filter(p => p.matches("\\d+")).mkString(", ")
val paths = oldState.getState.keySet.asScala.filter(p => !p.matches("\\d+")).map("\"" + _ + "\"").mkString(", ")
val body = OptionalBody.body(("{\"ports\": [" + ports + "], \"paths\": [" + paths + "]}").getBytes)
Result(new Response(200, Map("Content-Type" -> List("application/json").asJava).asJava, body), oldState)
new Result(new Response(200, Map("Content-Type" -> List("application/json").asJava).asJava, body), oldState)
}
}

case class Result(response: IResponse, newState: ServerState)

object Server extends App {

val parser = new scopt.OptionParser[Config]("pact-jvm-server") {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,23 @@ class CreateSpec extends Specification {
def pact = CreateSpec.getResourceAsStream('/create-pact.json').text

when:
def result = Create.create('test state',
def result = Create.create(
'test state',
JavaConverters.asScalaBuffer(['/data']).toList(),
pact, new scala.collection.immutable.HashMap(),
pact,
new ServerState(),
new Config(4444, 'localhost', false, 20000, 40000, true,
2, '', '', 8444, '', ''))

then:
result.response().status == 201
result.response().body.value != '{"port": 8444}'
result.response.status == 201
result.response.body.value != '{"port": 8444}'

cleanup:
if (result != null) {
def state = result.newState()
def values = state.values()
JavaConverters.asJavaCollection(values).each {
def state = result.newState
def values = state.state.values()
values.each {
it.stop()
}
}
Expand All @@ -42,20 +44,20 @@ class CreateSpec extends Specification {
when:
def result = Create.create('test state',
JavaConverters.asScalaBuffer([]).toList(),
pact, new scala.collection.immutable.HashMap(),
pact,
new ServerState(),
new au.com.dius.pact.server.Config(4444, 'localhost', false, 20000, 40000, true,
2, keystorePath, password, 8444, '', ''))

then:
result.response().status == 201
result.response().body.valueAsString() == '{"port": 8444}'
result.response.status == 201
result.response.body.valueAsString() == '{"port": 8444}'

cleanup:
if (result != null) {
JavaConverters.asJavaCollection(result.newState().values()).each {
result.newState.state.values().each {
it.stop()
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,58 +6,58 @@ import static scala.collection.JavaConverters.mapAsScalaMap
class ListServersSpec extends Specification {
def 'empty state'() {
given:
def state = [:]
def state = new ServerState([:])

when:
def result = ListServers.apply(mapAsScalaMap(state).toMap())
def result = ListServers.apply(state)

then:
result.response().status == 200
result.response().body.valueAsString() == '{"ports": [], "paths": []}'
result.response.status == 200
result.response.body.valueAsString() == '{"ports": [], "paths": []}'
}

def 'with single Mock server'() {
given:
def state = [
def state = new ServerState([
'1234': Mock(StatefulMockProvider)
]
])

when:
def result = ListServers.apply(mapAsScalaMap(state).toMap())
def result = ListServers.apply(state)

then:
result.response().status == 200
result.response().body.valueAsString() == '{"ports": [1234], "paths": []}'
result.response.status == 200
result.response.body.valueAsString() == '{"ports": [1234], "paths": []}'
}

def 'with single Mock server with a path'() {
given:
def state = [
def state = new ServerState([
'/path': Mock(StatefulMockProvider)
]
])

when:
def result = ListServers.apply(mapAsScalaMap(state).toMap())
def result = ListServers.apply(state)

then:
result.response().status == 200
result.response().body.valueAsString() == '{"ports": [], "paths": ["/path"]}'
result.response.status == 200
result.response.body.valueAsString() == '{"ports": [], "paths": ["/path"]}'
}

def 'with multiple Mock servers'() {
given:
def state = [
def state = new ServerState([
'1234': Mock(StatefulMockProvider),
'/path': Mock(StatefulMockProvider),
'8765': Mock(StatefulMockProvider),
'/other-path': Mock(StatefulMockProvider)
]
])

when:
def result = ListServers.apply(mapAsScalaMap(state).toMap())
def result = ListServers.apply(state)

then:
result.response().status == 200
result.response().body.valueAsString() == '{"ports": [1234, 8765], "paths": ["/path", "/other-path"]}'
result.response.status == 200
result.response.body.valueAsString() == '{"ports": [8765, 1234], "paths": ["/other-path", "/path"]}'
}
}

0 comments on commit 36cf032

Please sign in to comment.