/
E2ESpec.scala
316 lines (272 loc) · 11.6 KB
/
E2ESpec.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
* Copyright © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package org.knora.webapi
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import akka.event.LoggingAdapter
import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.model._
import akka.stream.Materializer
import akka.testkit.TestKit
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.LazyLogging
import org.knora.webapi.auth.JWTService
import org.knora.webapi.config.AppConfig
import org.knora.webapi.config.AppConfigForTestContainers
import org.knora.webapi.core.Core
import org.knora.webapi.core.Logging
import org.knora.webapi.exceptions.FileWriteException
import org.knora.webapi.feature.FeatureFactoryConfig
import org.knora.webapi.feature.KnoraSettingsFeatureFactoryConfig
import org.knora.webapi.feature.TestFeatureFactoryConfig
import org.knora.webapi.messages.StringFormatter
import org.knora.webapi.messages.app.appmessages.AppStart
import org.knora.webapi.messages.app.appmessages.SetAllowReloadOverHTTPState
import org.knora.webapi.messages.store.sipimessages.SipiUploadResponse
import org.knora.webapi.messages.store.triplestoremessages.RdfDataObject
import org.knora.webapi.messages.store.triplestoremessages.TriplestoreJsonProtocol
import org.knora.webapi.messages.util.rdf._
import org.knora.webapi.settings._
import org.knora.webapi.store.cacheservice.CacheServiceManager
import org.knora.webapi.store.cacheservice.impl.CacheServiceInMemImpl
import org.knora.webapi.store.iiif.IIIFServiceManager
import org.knora.webapi.store.iiif.impl.IIIFServiceSipiImpl
import org.knora.webapi.testcontainers.SipiTestContainer
import org.knora.webapi.testservices.FileToUpload
import org.knora.webapi.testservices.TestClientService
import org.knora.webapi.util.FileUtil
import org.knora.webapi.util.StartupUtils
import org.scalatest.BeforeAndAfterAll
import org.scalatest.Suite
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import spray.json._
import zio.&
import zio.Runtime
import zio.ZEnvironment
import zio.ZIO
import zio.ZLayer
import zio._
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration
import app.ApplicationActor
object E2ESpec {
val defaultConfig: Config = ConfigFactory.load()
}
/**
* This class can be used in End-to-End testing. It starts the Knora-API server
* and provides access to settings and logging.
*/
class E2ESpec(_system: ActorSystem)
extends TestKit(_system)
with Core
with StartupUtils
with TriplestoreJsonProtocol
with Suite
with AnyWordSpecLike
with Matchers
with ScalaFutures
with BeforeAndAfterAll
with RequestBuilding
with LazyLogging {
/* constructors */
def this(name: String, config: Config) =
this(ActorSystem(name, TestContainerFuseki.PortConfig.withFallback(config.withFallback(E2ESpec.defaultConfig))))
def this(config: Config) =
this(
ActorSystem("E2ETest", TestContainerFuseki.PortConfig.withFallback(config.withFallback(E2ESpec.defaultConfig)))
)
def this(name: String) = this(ActorSystem(name, TestContainerFuseki.PortConfig.withFallback(E2ESpec.defaultConfig)))
def this() = this(ActorSystem("E2ETest", TestContainerFuseki.PortConfig.withFallback(E2ESpec.defaultConfig)))
/* needed by the core trait */
implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system)
implicit val materializer: Materializer = Materializer.matFromSystem(system)
implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher)
// can be overridden in individual spec
lazy val rdfDataObjects = Seq.empty[RdfDataObject]
/* Needs to be initialized before any responders */
StringFormatter.initForTest()
RdfFeatureFactory.init(settings)
val log: LoggingAdapter = akka.event.Logging(system, this.getClass)
// The ZIO runtime used to run functional effects
val runtime = Runtime.unsafeFromLayer(Logging.fromInfo)
// The effect for building a cache service manager and a IIIF service manager.
lazy val managers = for {
csm <- ZIO.service[CacheServiceManager]
iiifsm <- ZIO.service[IIIFServiceManager]
appConfig <- ZIO.service[AppConfig]
} yield (csm, iiifsm, appConfig)
/**
* The effect layers which will be used to run the managers effect.
* Can be overriden in specs that need other implementations.
*/
lazy val effectLayers =
ZLayer.make[CacheServiceManager & IIIFServiceManager & AppConfig](
CacheServiceManager.layer,
CacheServiceInMemImpl.layer,
IIIFServiceManager.layer,
IIIFServiceSipiImpl.layer, // alternative: MockSipiImpl.layer
AppConfigForTestContainers.testcontainers,
JWTService.layer,
// FusekiTestContainer.layer,
SipiTestContainer.layer
)
/**
* Create both managers by unsafe running them.
*/
lazy val (cacheServiceManager, iiifServiceManager, appConfig) =
runtime
.unsafeRun(
managers
.provide(
effectLayers
)
)
// start the Application Actor
lazy val appActor: ActorRef =
system.actorOf(
Props(new ApplicationActor(cacheServiceManager, iiifServiceManager, appConfig)),
name = APPLICATION_MANAGER_ACTOR_NAME
)
protected val baseApiUrl: String = appConfig.knoraApi.internalKnoraApiBaseUrl
protected val defaultFeatureFactoryConfig: FeatureFactoryConfig = new TestFeatureFactoryConfig(
testToggles = Set.empty,
parent = new KnoraSettingsFeatureFactoryConfig(settings)
)
override def beforeAll(): Unit = {
// create temp data dir if not present
createTmpFileDir()
// set allow reload over http
appActor ! SetAllowReloadOverHTTPState(true)
// start the knora service, loading data from the repository
appActor ! AppStart(ignoreRepository = true, requiresIIIFService = true)
// waits until knora is up and running
applicationStateRunning()
// loadTestData
loadTestData(rdfDataObjects)
}
override def afterAll(): Unit =
/* Stop the server when everything else has finished */
TestKit.shutdownActorSystem(system)
protected def loadTestData(rdfDataObjects: Seq[RdfDataObject]): Unit =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.loadTestData(rdfDataObjects)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def singleAwaitingRequest(request: HttpRequest, duration: zio.Duration = 15.seconds): HttpResponse =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.singleAwaitingRequest(request, duration)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def getResponseAsString(request: HttpRequest): String =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.getResponseString(request)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def checkResponseOK(request: HttpRequest): Unit =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.checkResponseOK(request)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def getResponseAsJson(request: HttpRequest): JsObject =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.getResponseJson(request)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def getResponseAsJsonLD(request: HttpRequest): JsonLDDocument =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.getResponseJsonLD(request)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def uploadToSipi(loginToken: String, filesToUpload: Seq[FileToUpload]): SipiUploadResponse =
runtime.unsafeRunTask(
(for {
testClient <- ZIO.service[TestClientService]
result <- testClient.uploadToSipi(loginToken, filesToUpload)
} yield result).provide(TestClientService.layer(appConfig, system))
)
protected def responseToJsonLDDocument(httpResponse: HttpResponse): JsonLDDocument = {
val responseBodyFuture: Future[String] =
httpResponse.entity.toStrict(FiniteDuration(10L, TimeUnit.SECONDS)).map(_.data.decodeString("UTF-8"))
val responseBodyStr = Await.result(responseBodyFuture, FiniteDuration(10L, TimeUnit.SECONDS))
JsonLDUtil.parseJsonLD(responseBodyStr)
}
protected def responseToString(httpResponse: HttpResponse): String = {
val responseBodyFuture: Future[String] =
httpResponse.entity.toStrict(FiniteDuration(10L, TimeUnit.SECONDS)).map(_.data.decodeString("UTF-8"))
Await.result(responseBodyFuture, FiniteDuration(10L, TimeUnit.SECONDS))
}
protected def doGetRequest(urlPath: String): String = {
val request = Get(s"$baseApiUrl$urlPath")
val response: HttpResponse = singleAwaitingRequest(request)
responseToString(response)
}
protected def parseTrig(trigStr: String): RdfModel = {
val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(defaultFeatureFactoryConfig)
rdfFormatUtil.parseToRdfModel(rdfStr = trigStr, rdfFormat = TriG)
}
protected def parseTurtle(turtleStr: String): RdfModel = {
val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(defaultFeatureFactoryConfig)
rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle)
}
protected def parseRdfXml(rdfXmlStr: String): RdfModel = {
val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(defaultFeatureFactoryConfig)
rdfFormatUtil.parseToRdfModel(rdfStr = rdfXmlStr, rdfFormat = RdfXml)
}
/**
* Reads or writes a test data file.
*
* @param responseAsString the API response received from Knora.
* @param file the file in which the expected API response is stored.
* @param writeFile if `true`, writes the response to the file and returns it, otherwise returns the current contents of the file.
* @return the expected response.
*/
protected def readOrWriteTextFile(responseAsString: String, file: Path, writeFile: Boolean = false): String =
if (writeFile) {
val testOutputDir = Paths.get("..", "test_data", "ontologyR2RV2")
val newOutputFile = testOutputDir.resolve(file)
Files.createDirectories(newOutputFile.getParent)
FileUtil.writeTextFile(
newOutputFile,
responseAsString.replaceAll(settings.externalSipiIIIFGetUrl, "IIIF_BASE_URL")
)
responseAsString
} else {
FileUtil.readTextFile(file).replaceAll("IIIF_BASE_URL", settings.externalSipiIIIFGetUrl)
}
private def createTmpFileDir(): Unit = {
// check if tmp datadir exists and create it if not
val tmpFileDir = Path.of(settings.tmpDataDir)
if (!Files.exists(tmpFileDir)) {
try {
Files.createDirectories(tmpFileDir)
} catch {
case e: Throwable =>
throw FileWriteException(s"Tmp data directory ${settings.tmpDataDir} could not be created: ${e.getMessage}")
}
}
}
}