package eu.friedcutlet.yokan.services.extensions.recipe import kotlinx.coroutines.CancellationException import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertIs class DeclarativeRecipeRuntimeTest { private val policy = RecipeExecutionPolicy(mapOf("primary" to "https://example.test")) private val inputs = mapOf("pageIndex" to RecipeEntrypointInput.PageIndex(0)) private val bundle = assertIs(StrictRecipeBundleDecoder.decode(validBundle().encodeToByteArray())).bundle @Test fun entrypointProjectsJsonFromTheGrantedOrigin() = runTest { var requested: RecipeBrokerRequest? = null val broker = broker { requested = it; RecipeBrokerResult.Document("""{"data":[{"id":"a","title":"A"}]}""".encodeToByteArray()) } val completed = assertIs(DeclarativeRecipeRuntime(broker).executeEntrypoint(bundle, "popular", inputs, policy)) assertEquals(listOf(RecipeEntrypointResult.Item("a", "A", null)), assertIs(completed.result).items) assertEquals("https://example.test/items", requested?.url) } @Test fun brokerExceptionsBecomeBrokerFailureButCancellationPropagates() = runTest { val failing = DeclarativeRecipeRuntime(broker { throw IllegalStateException("boom") }) assertEquals(RecipeExecutionErrorCode.BrokerFailure, assertIs(failing.executeEntrypoint(bundle, "popular", inputs, policy)).error.code) val cancelling = DeclarativeRecipeRuntime(broker { throw CancellationException("cancel") }) assertFailsWith { cancelling.executeEntrypoint(bundle, "popular", inputs, policy) } } @Test fun malformedJsonResponseIsRejected() = runTest { val runtime = DeclarativeRecipeRuntime(broker { RecipeBrokerResult.Document("{".encodeToByteArray()) }) assertEquals(RecipeExecutionErrorCode.InvalidJsonDocument, assertIs(runtime.executeEntrypoint(bundle, "popular", inputs, policy)).error.code) } private fun broker(respond: (RecipeBrokerRequest) -> RecipeBrokerResult) = object : RecipeCapabilityBroker { override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = respond(request) } }