-
-
Save daviddenton/731b588eaa682e92258bda1049dbfeb4 to your computer and use it in GitHub Desktop.
Test http4k with a report transaction event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.natpryce.hamkrest.assertion.assertThat | |
import com.natpryce.hamkrest.equalTo | |
import org.http4k.core.Filter | |
import org.http4k.core.HttpHandler | |
import org.http4k.core.Method | |
import org.http4k.core.Method.GET | |
import org.http4k.core.Request | |
import org.http4k.core.Response | |
import org.http4k.core.Status | |
import org.http4k.core.Status.Companion.OK | |
import org.http4k.core.then | |
import org.http4k.events.AutoMarshallingEvents | |
import org.http4k.events.Event | |
import org.http4k.events.EventFilters.AddTimestamp | |
import org.http4k.events.Events | |
import org.http4k.events.MetadataEvent | |
import org.http4k.events.then | |
import org.http4k.filter.ResponseFilters.ReportHttpTransaction | |
import org.http4k.format.Jackson | |
import org.http4k.testing.RecordingEvents | |
import org.junit.jupiter.api.Test | |
import java.time.Clock | |
import java.time.Instant.EPOCH | |
import java.time.ZoneId | |
data class IncomingHttpRequest(val method: Method, val path: String, val status: Status, val duration: Long) : Event | |
fun ReportHttpTransactionFilter(rawEvents: Events, clock: Clock): Filter { | |
val events = AddTimestamp(clock).then(rawEvents) | |
return ReportHttpTransaction(clock = clock) { httpTransaction -> | |
events( | |
IncomingHttpRequest( | |
httpTransaction.request.method, | |
httpTransaction.request.uri.path, | |
httpTransaction.response.status, | |
httpTransaction.duration.toMillis() | |
) | |
) | |
} | |
} | |
class ReportHttpTransactionFilterTest { | |
@Test | |
fun `logs events`() { | |
val events = RecordingEvents() | |
val clock = Clock.fixed(EPOCH, ZoneId.of("UTC")) | |
val app = ReportHttpTransactionFilter(events, clock).then { req: Request -> Response(OK) } | |
app(Request(GET, "/foo")) | |
assertThat(events.toList(), equalTo(listOf( | |
MetadataEvent(IncomingHttpRequest(GET, "/foo", OK, 0), mapOf("timestamp" to clock.instant()))))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment