/
AbstractHttpServiceIntegrationTest.scala
1333 lines (1173 loc) · 50.9 KB
/
AbstractHttpServiceIntegrationTest.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.http
import java.security.DigestInputStream
import java.time.Instant
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.stream.Materializer
import akka.stream.scaladsl.{Source, StreamConverters}
import akka.util.ByteString
import com.daml.api.util.TimestampConversion
import com.daml.bazeltools.BazelRunfiles.requiredResource
import com.daml.lf.data.Ref
import com.daml.grpc.adapter.{AkkaExecutionSequencerPool, ExecutionSequencerFactory}
import HttpServiceTestFixture.{jsonCodecs, UseTls}
import com.daml.http.domain.ContractId
import com.daml.http.domain.TemplateId.OptionalPkg
import com.daml.http.json.SprayJson.{decode, decode1, objectField}
import com.daml.http.json._
import com.daml.http.util.ClientUtil.{boxedRecord, uniqueId}
import com.daml.http.util.FutureUtil.toFuture
import com.daml.http.util.{FutureUtil, TestUtil}
import com.daml.jwt.JwtSigner
import com.daml.jwt.domain.{DecodedJwt, Jwt}
import com.daml.ledger.api.refinements.{ApiTypes => lar}
import com.daml.ledger.api.v1.{value => v}
import com.daml.ledger.client.LedgerClient
import com.daml.ledger.service.MetadataReader
import com.daml.platform.participant.util.LfEngineToApi
import com.typesafe.scalalogging.StrictLogging
import org.scalatest._
import scalaz.std.list._
import scalaz.std.scalaFuture._
import scalaz.syntax.bitraverse._
import scalaz.syntax.show._
import scalaz.syntax.tag._
import scalaz.syntax.traverse._
import scalaz.{-\/, \/, \/-}
import spray.json._
import scala.collection.breakOut
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Success, Try}
object AbstractHttpServiceIntegrationTestFuns {
private val dar1 = requiredResource("docs/quickstart-model.dar")
private val dar2 = requiredResource("ledger-service/http-json/Account.dar")
private[http] val dar3 = requiredResource("ledger/test-common/Test-stable.dar")
def sha256(source: Source[ByteString, Any])(implicit mat: Materializer): Try[String] = Try {
import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter
val md = MessageDigest.getInstance("SHA-256")
val is = source.runWith(StreamConverters.asInputStream())
val dis = new DigestInputStream(is, md)
// drain the input stream and calculate the hash
while (-1 != dis.read()) ()
dis.on(false)
DatatypeConverter.printHexBinary(md.digest()).toLowerCase
}
}
@SuppressWarnings(Array("org.wartremover.warts.Any", "org.wartremover.warts.NonUnitStatements"))
trait AbstractHttpServiceIntegrationTestFuns extends StrictLogging {
this: AsyncFreeSpec with Matchers with Inside with StrictLogging =>
import AbstractHttpServiceIntegrationTestFuns._
import json.JsonProtocol._
def jdbcConfig: Option[JdbcConfig]
def staticContentConfig: Option[StaticContentConfig]
def useTls: UseTls
protected def testId: String = this.getClass.getSimpleName
protected val metdata2: MetadataReader.LfMetadata =
MetadataReader.readFromDar(dar2).valueOr(e => fail(s"Cannot read dar2 metadata: $e"))
protected val jwt: Jwt = {
val decodedJwt = DecodedJwt(
"""{"alg": "HS256", "typ": "JWT"}""",
s"""{"https://daml.com/ledger-api": {"ledgerId": "${testId: String}", "applicationId": "test", "actAs": ["Alice"]}}"""
)
JwtSigner.HMAC256
.sign(decodedJwt, "secret")
.fold(e => fail(s"cannot sign a JWT: ${e.shows}"), identity)
}
protected val jwtAdminNoParty: Jwt = {
val decodedJwt = DecodedJwt(
"""{"alg": "HS256", "typ": "JWT"}""",
s"""{"https://daml.com/ledger-api": {"ledgerId": "${testId: String}", "applicationId": "test", "admin": true}}"""
)
JwtSigner.HMAC256
.sign(decodedJwt, "secret")
.fold(e => fail(s"cannot sign a JWT: ${e.shows}"), identity)
}
implicit val `AHS asys`: ActorSystem = ActorSystem(testId)
implicit val `AHS mat`: Materializer = Materializer(`AHS asys`)
implicit val `AHS aesf`: ExecutionSequencerFactory =
new AkkaExecutionSequencerPool(testId)(`AHS asys`)
import shapeless.tag
import tag.@@ // used for subtyping to make `AHS ec` beat executionContext
implicit val `AHS ec`: ExecutionContext @@ this.type = tag[this.type](`AHS asys`.dispatcher)
protected def withHttpServiceAndClient[A]
: ((Uri, DomainJsonEncoder, DomainJsonDecoder, LedgerClient) => Future[A]) => Future[A] =
HttpServiceTestFixture
.withHttpService[A](
testId,
List(dar1, dar2),
jdbcConfig,
staticContentConfig,
useTls = useTls)
protected def withHttpService[A](
f: (Uri, DomainJsonEncoder, DomainJsonDecoder) => Future[A]): Future[A] =
withHttpServiceAndClient((a, b, c, _) => f(a, b, c))
protected def withLedger[A]: (LedgerClient => Future[A]) => Future[A] =
HttpServiceTestFixture.withLedger[A](List(dar1, dar2), testId)
protected def accountCreateCommand(
owner: domain.Party,
number: String,
time: v.Value.Sum.Timestamp = TimestampConversion.instantToMicros(Instant.now))
: domain.CreateCommand[v.Record] = {
val templateId = domain.TemplateId(None, "Account", "Account")
val timeValue = v.Value(time)
val enabledVariantValue =
v.Value(v.Value.Sum.Variant(v.Variant(None, "Enabled", Some(timeValue))))
val arg = v.Record(
fields = List(
v.RecordField("owner", Some(v.Value(v.Value.Sum.Party(owner.unwrap)))),
v.RecordField("number", Some(v.Value(v.Value.Sum.Text(number)))),
v.RecordField("status", Some(enabledVariantValue))
))
domain.CreateCommand(templateId, arg, None)
}
protected val headersWithAuth = authorizationHeader(jwt)
protected def authorizationHeader(token: Jwt): List[Authorization] =
List(Authorization(OAuth2BearerToken(token.value)))
protected def postJsonStringRequest(
uri: Uri,
jsonString: String
): Future[(StatusCode, JsValue)] =
TestUtil.postJsonStringRequest(uri, jsonString, headersWithAuth)
protected def postJsonRequest(
uri: Uri,
json: JsValue,
headers: List[HttpHeader] = headersWithAuth): Future[(StatusCode, JsValue)] =
TestUtil.postJsonStringRequest(uri, json.prettyPrint, headers)
protected def getRequest(
uri: Uri,
headers: List[HttpHeader] = headersWithAuth): Future[(StatusCode, JsValue)] = {
Http()
.singleRequest(
HttpRequest(method = HttpMethods.GET, uri = uri, headers = headers)
)
.flatMap { resp =>
val bodyF: Future[String] = getResponseDataBytes(resp, debug = true)
bodyF.map(body => (resp.status, body.parseJson))
}
}
protected def getResponseDataBytes(resp: HttpResponse, debug: Boolean = false): Future[String] = {
val fb = resp.entity.dataBytes.runFold(ByteString.empty)((b, a) => b ++ a).map(_.utf8String)
if (debug) fb.foreach(x => logger.info(s"---- response data: $x"))
fb
}
protected def postCreateCommand(
cmd: domain.CreateCommand[v.Record],
encoder: DomainJsonEncoder,
uri: Uri): Future[(StatusCode, JsValue)] = {
import encoder.implicits._
for {
json <- toFuture(SprayJson.encode1(cmd)): Future[JsValue]
result <- postJsonRequest(uri.withPath(Uri.Path("/v1/create")), json)
} yield result
}
protected def postArchiveCommand(
templateId: domain.TemplateId.OptionalPkg,
contractId: domain.ContractId,
encoder: DomainJsonEncoder,
uri: Uri): Future[(StatusCode, JsValue)] = {
val ref = domain.EnrichedContractId(Some(templateId), contractId)
val cmd = archiveCommand(ref)
for {
json <- toFuture(encoder.encodeExerciseCommand(cmd)): Future[JsValue]
result <- postJsonRequest(uri.withPath(Uri.Path("/v1/exercise")), json)
} yield result
}
protected def lookupContractAndAssert(contractLocator: domain.ContractLocator[JsValue])(
contractId: ContractId,
create: domain.CreateCommand[v.Record],
encoder: DomainJsonEncoder,
decoder: DomainJsonDecoder,
uri: Uri): Future[Assertion] =
postContractsLookup(contractLocator, uri).flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
assertStatus(output, StatusCodes.OK)
val result = getResult(output)
contractId shouldBe getContractId(result)
assertActiveContract(result)(create, encoder, decoder)
}
protected def removeRecordId(a: v.Value): v.Value = a match {
case v.Value(v.Value.Sum.Record(r)) if r.recordId.isDefined =>
v.Value(v.Value.Sum.Record(removeRecordId(r)))
case _ =>
a
}
protected def removeRecordId(a: v.Record): v.Record = a.copy(recordId = None)
protected def iouCreateCommand(
amount: String = "999.9900000000",
currency: String = "USD"): domain.CreateCommand[v.Record] = {
val templateId: OptionalPkg = domain.TemplateId(None, "Iou", "Iou")
val arg = v.Record(
fields = List(
v.RecordField("issuer", Some(v.Value(v.Value.Sum.Party("Alice")))),
v.RecordField("owner", Some(v.Value(v.Value.Sum.Party("Alice")))),
v.RecordField("currency", Some(v.Value(v.Value.Sum.Text(currency)))),
v.RecordField("amount", Some(v.Value(v.Value.Sum.Numeric(amount)))),
v.RecordField("observers", Some(v.Value(v.Value.Sum.List(v.List()))))
))
domain.CreateCommand(templateId, arg, None)
}
protected def iouExerciseTransferCommand(
contractId: lar.ContractId): domain.ExerciseCommand[v.Value, domain.EnrichedContractId] = {
val templateId = domain.TemplateId(None, "Iou", "Iou")
val reference = domain.EnrichedContractId(Some(templateId), contractId)
val arg =
v.Record(fields = List(v.RecordField("newOwner", Some(v.Value(v.Value.Sum.Party("Bob"))))))
val choice = lar.Choice("Iou_Transfer")
domain.ExerciseCommand(reference, choice, boxedRecord(arg), None)
}
protected def iouCreateAndExerciseTransferCommand(
amount: String = "999.9900000000",
currency: String = "USD"): domain.CreateAndExerciseCommand[v.Record, v.Value] = {
val templateId: OptionalPkg = domain.TemplateId(None, "Iou", "Iou")
val payload = v.Record(
fields = List(
v.RecordField("issuer", Some(v.Value(v.Value.Sum.Party("Alice")))),
v.RecordField("owner", Some(v.Value(v.Value.Sum.Party("Alice")))),
v.RecordField("currency", Some(v.Value(v.Value.Sum.Text(currency)))),
v.RecordField("amount", Some(v.Value(v.Value.Sum.Numeric(amount)))),
v.RecordField("observers", Some(v.Value(v.Value.Sum.List(v.List()))))
))
val arg =
v.Record(fields = List(v.RecordField("newOwner", Some(v.Value(v.Value.Sum.Party("Bob"))))))
val choice = lar.Choice("Iou_Transfer")
domain.CreateAndExerciseCommand(
templateId = templateId,
payload = payload,
choice = choice,
argument = boxedRecord(arg),
meta = None)
}
protected def archiveCommand[Ref](reference: Ref): domain.ExerciseCommand[v.Value, Ref] = {
val arg: v.Record = v.Record()
val choice = lar.Choice("Archive")
domain.ExerciseCommand(reference, choice, boxedRecord(arg), None)
}
protected def assertStatus(jsObj: JsValue, expectedStatus: StatusCode): Assertion = {
inside(jsObj) {
case JsObject(fields) =>
inside(fields.get("status")) {
case Some(JsNumber(status)) => status shouldBe BigDecimal(expectedStatus.intValue)
}
}
}
protected def expectedOneErrorMessage(output: JsValue): String =
inside(output) {
case JsObject(fields) =>
inside(fields.get("errors")) {
case Some(JsArray(Vector(JsString(errorMsg)))) => errorMsg
}
}
protected def postContractsLookup(
cmd: domain.ContractLocator[JsValue],
uri: Uri): Future[(StatusCode, JsValue)] =
for {
json <- toFuture(SprayJson.encode(cmd)): Future[JsValue]
result <- postJsonRequest(uri.withPath(Uri.Path("/v1/fetch")), json)
} yield result
protected def activeContractList(output: JsValue): List[domain.ActiveContract[JsValue]] = {
val result = getResult(output)
SprayJson
.decode[List[domain.ActiveContract[JsValue]]](result)
.valueOr(e => fail(e.shows))
}
protected def activeContract(output: JsValue): domain.ActiveContract[JsValue] = {
val result = getResult(output)
SprayJson
.decode[domain.ActiveContract[JsValue]](result)
.valueOr(e => fail(e.shows))
}
protected def getResult(output: JsValue): JsValue = getChild(output, "result")
protected def getWarnings(output: JsValue): JsValue = getChild(output, "warnings")
protected def getChild(output: JsValue, field: String): JsValue = {
def errorMsg = s"Expected JsObject with '$field' field, got: $output"
output
.asJsObject(errorMsg)
.fields
.getOrElse(field, fail(errorMsg))
}
protected def getContractId(result: JsValue): domain.ContractId =
inside(result.asJsObject.fields.get("contractId")) {
case Some(JsString(contractId)) => domain.ContractId(contractId)
}
protected def asContractId(a: JsValue): domain.ContractId = inside(a) {
case JsString(x) => domain.ContractId(x)
}
protected def encodeExercise(encoder: DomainJsonEncoder)(
exercise: domain.ExerciseCommand[v.Value, domain.ContractLocator[v.Value]]): JsValue =
encoder.encodeExerciseCommand(exercise).getOrElse(fail(s"Cannot encode: $exercise"))
protected def decodeExercise(decoder: DomainJsonDecoder)(
jsVal: JsValue): domain.ExerciseCommand[v.Value, domain.EnrichedContractId] = {
import scalaz.syntax.bifunctor._
val cmd = decoder.decodeExerciseCommand(jsVal).getOrElse(fail(s"Cannot decode $jsVal"))
cmd.bimap(
lfToApi,
enrichedContractIdOnly
)
}
protected def enrichedContractIdOnly(x: domain.ContractLocator[_]): domain.EnrichedContractId =
x match {
case a: domain.EnrichedContractId => a
case _: domain.EnrichedContractKey[_] =>
fail(s"Expected domain.EnrichedContractId, got: $x")
}
protected def lfToApi(lfVal: domain.LfValue): v.Value =
LfEngineToApi.lfValueToApiValue(verbose = true, lfVal).fold(e => fail(e), identity)
protected def assertActiveContract(
decoder: DomainJsonDecoder,
actual: domain.ActiveContract[JsValue],
create: domain.CreateCommand[v.Record],
exercise: domain.ExerciseCommand[v.Value, _]): Assertion = {
val expectedContractFields: Seq[v.RecordField] = create.payload.fields
val expectedNewOwner: v.Value = exercise.argument.sum.record
.flatMap(_.fields.headOption)
.flatMap(_.value)
.getOrElse(fail("Cannot extract expected newOwner"))
val active: domain.ActiveContract[v.Value] =
decoder.decodeUnderlyingValues(actual).valueOr(e => fail(e.shows))
inside(active.payload.sum.record.map(_.fields)) {
case Some(
Seq(
v.RecordField("iou", Some(contractRecord)),
v.RecordField("newOwner", Some(newOwner)))) =>
val contractFields: Seq[v.RecordField] =
contractRecord.sum.record.map(_.fields).getOrElse(Seq.empty)
(contractFields: Seq[v.RecordField]) shouldBe (expectedContractFields: Seq[v.RecordField])
(newOwner: v.Value) shouldBe (expectedNewOwner: v.Value)
}
}
protected def assertActiveContract(jsVal: JsValue)(
command: domain.CreateCommand[v.Record],
encoder: DomainJsonEncoder,
decoder: DomainJsonDecoder): Assertion = {
import encoder.implicits._
val expected: domain.CreateCommand[JsValue] =
command.traverse(SprayJson.encode[v.Record]).getOrElse(fail)
inside(SprayJson.decode[domain.ActiveContract[JsValue]](jsVal)) {
case \/-(activeContract) =>
(activeContract.payload: JsValue) shouldBe (expected.payload: JsValue)
}
}
protected def assertTemplateId(
actual: domain.TemplateId.RequiredPkg,
expected: domain.TemplateId.OptionalPkg): Assertion = {
expected.packageId.foreach(x => actual.packageId shouldBe x)
actual.moduleName shouldBe expected.moduleName
actual.entityName shouldBe expected.entityName
}
protected def getAllPackageIds(uri: Uri): Future[domain.OkResponse[List[String]]] =
getRequest(uri = uri.withPath(Uri.Path("/v1/packages"))).map {
case (status, output) =>
status shouldBe StatusCodes.OK
inside(decode1[domain.OkResponse, List[String]](output)) {
case \/-(x) => x
}
}
}
@SuppressWarnings(Array("org.wartremover.warts.Any", "org.wartremover.warts.NonUnitStatements"))
abstract class AbstractHttpServiceIntegrationTest
extends AsyncFreeSpec
with Matchers
with Inside
with StrictLogging
with AbstractHttpServiceIntegrationTestFuns {
import json.JsonProtocol._
override final def useTls = UseTls.NoTls
"query GET empty results" in withHttpService { (uri: Uri, _, _) =>
getRequest(uri = uri.withPath(Uri.Path("/v1/query")))
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
assertStatus(output, StatusCodes.OK)
inside(output) {
case JsObject(fields) =>
inside(fields.get("result")) {
case Some(JsArray(vector)) => vector should have size 0L
}
}
}: Future[Assertion]
}
protected val searchDataSet: List[domain.CreateCommand[v.Record]] = List(
iouCreateCommand(amount = "111.11", currency = "EUR"),
iouCreateCommand(amount = "222.22", currency = "EUR"),
iouCreateCommand(amount = "333.33", currency = "GBP"),
iouCreateCommand(amount = "444.44", currency = "BTC"),
)
"query GET" in withHttpService { (uri: Uri, encoder, _) =>
searchDataSet.traverse(c => postCreateCommand(c, encoder, uri)).flatMap { rs =>
rs.map(_._1) shouldBe List.fill(searchDataSet.size)(StatusCodes.OK)
getRequest(uri = uri.withPath(Uri.Path("/v1/query")))
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
assertStatus(output, StatusCodes.OK)
inside(output) {
case JsObject(fields) =>
inside(fields.get("result")) {
case Some(JsArray(vector)) =>
vector should have size searchDataSet.size.toLong
}
}
}: Future[Assertion]
}
}
"query POST with empty query" in withHttpService { (uri, encoder, _) =>
searchExpectOk(
searchDataSet,
jsObject("""{"templateIds": ["Iou:Iou"]}"""),
uri,
encoder
).map { acl: List[domain.ActiveContract[JsValue]] =>
acl.size shouldBe searchDataSet.size
}
}
"query with query, one field" in withHttpService { (uri, encoder, _) =>
searchExpectOk(
searchDataSet,
jsObject("""{"templateIds": ["Iou:Iou"], "query": {"currency": "EUR"}}"""),
uri,
encoder
).map { acl: List[domain.ActiveContract[JsValue]] =>
acl.size shouldBe 2
acl.map(a => objectField(a.payload, "currency")) shouldBe List.fill(2)(Some(JsString("EUR")))
}
}
"query returns unknown Template IDs as warnings" in withHttpService { (uri, encoder, _) =>
val query =
jsObject(
"""{"templateIds": ["Iou:Iou", "UnknownModule:UnknownEntity"], "query": {"currency": "EUR"}}""")
search(List(), query, uri, encoder).map { response =>
inside(response) {
case domain.OkResponse(acl, warnings, StatusCodes.OK) =>
acl.size shouldBe 0
warnings shouldBe Some(
domain.UnknownTemplateIds(
List(domain.TemplateId(None, "UnknownModule", "UnknownEntity"))))
}
}
}
"query returns unknown Template IDs as warnings and error" in withHttpService {
(uri, encoder, _) =>
search(
searchDataSet,
jsObject("""{"templateIds": ["AAA:BBB", "XXX:YYY"]}"""),
uri,
encoder
).map { response =>
inside(response) {
case domain.ErrorResponse(errors, warnings, StatusCodes.BadRequest) =>
errors shouldBe List(ErrorMessages.cannotResolveAnyTemplateId)
inside(warnings) {
case Some(domain.UnknownTemplateIds(unknownTemplateIds)) =>
unknownTemplateIds.toSet shouldBe Set(
domain.TemplateId(None, "AAA", "BBB"),
domain.TemplateId(None, "XXX", "YYY"))
}
}
}
}
"query with query, can use number or string for numeric field" in withHttpService {
(uri, encoder, _) =>
import scalaz.std.scalaFuture._
searchDataSet.traverse(c => postCreateCommand(c, encoder, uri)).flatMap {
rs: List[(StatusCode, JsValue)] =>
rs.map(_._1) shouldBe List.fill(searchDataSet.size)(StatusCodes.OK)
def queryAmountAs(s: String) =
jsObject(s"""{"templateIds": ["Iou:Iou"], "query": {"amount": $s}}""")
val queryAmountAsString = queryAmountAs("\"111.11\"")
val queryAmountAsNumber = queryAmountAs("111.11")
List(
postJsonRequest(uri.withPath(Uri.Path("/v1/query")), queryAmountAsString),
postJsonRequest(uri.withPath(Uri.Path("/v1/query")), queryAmountAsNumber),
).sequence.flatMap { rs: List[(StatusCode, JsValue)] =>
rs.map(_._1) shouldBe List.fill(2)(StatusCodes.OK)
inside(rs.map(_._2)) {
case List(jsVal1, jsVal2) =>
jsVal1 shouldBe jsVal2
val acl1: List[domain.ActiveContract[JsValue]] = activeContractList(jsVal1)
val acl2: List[domain.ActiveContract[JsValue]] = activeContractList(jsVal2)
acl1 shouldBe acl2
inside(acl1) {
case List(ac) =>
objectField(ac.payload, "amount") shouldBe Some(JsString("111.11"))
}
}
}
}: Future[Assertion]
}
"query with query, two fields" in withHttpService { (uri, encoder, _) =>
searchExpectOk(
searchDataSet,
jsObject(
"""{"templateIds": ["Iou:Iou"], "query": {"currency": "EUR", "amount": "111.11"}}"""),
uri,
encoder).map { acl: List[domain.ActiveContract[JsValue]] =>
acl.size shouldBe 1
acl.map(a => objectField(a.payload, "currency")) shouldBe List(Some(JsString("EUR")))
acl.map(a => objectField(a.payload, "amount")) shouldBe List(Some(JsString("111.11")))
}
}
"query with query, no results" in withHttpService { (uri, encoder, _) =>
searchExpectOk(
searchDataSet,
jsObject(
"""{"templateIds": ["Iou:Iou"], "query": {"currency": "RUB", "amount": "666.66"}}"""),
uri,
encoder
).map { acl: List[domain.ActiveContract[JsValue]] =>
acl.size shouldBe 0
}
}
"query with invalid JSON query should return error" in withHttpService { (uri, _, _) =>
postJsonStringRequest(uri.withPath(Uri.Path("/v1/query")), "{NOT A VALID JSON OBJECT")
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.BadRequest
assertStatus(output, StatusCodes.BadRequest)
}: Future[Assertion]
}
protected def jsObject(s: String): JsObject = {
val r: JsonError \/ JsObject = for {
jsVal <- SprayJson.parse(s).leftMap(e => JsonError(e.shows))
jsObj <- SprayJson.mustBeJsObject(jsVal)
} yield jsObj
r.valueOr(e => fail(e.shows))
}
protected def searchExpectOk(
commands: List[domain.CreateCommand[v.Record]],
query: JsObject,
uri: Uri,
encoder: DomainJsonEncoder): Future[List[domain.ActiveContract[JsValue]]] = {
search(commands, query, uri, encoder).map {
case ok: domain.OkResponse[_] =>
ok.status shouldBe StatusCodes.OK
ok.warnings shouldBe 'empty
ok.result
case err: domain.ErrorResponse =>
fail(s"Expected OK response, got: $err")
}
}
protected def search(
commands: List[domain.CreateCommand[v.Record]],
query: JsObject,
uri: Uri,
encoder: DomainJsonEncoder): Future[
domain.SyncResponse[List[domain.ActiveContract[JsValue]]]
] = {
commands.traverse(c => postCreateCommand(c, encoder, uri)).flatMap { rs =>
rs.map(_._1) shouldBe List.fill(commands.size)(StatusCodes.OK)
postJsonRequest(uri.withPath(Uri.Path("/v1/query")), query).flatMap {
case (_, output) =>
FutureUtil.toFuture(
decode1[domain.SyncResponse, List[domain.ActiveContract[JsValue]]](output))
}
}
}
"create IOU" in withHttpService { (uri, encoder, decoder) =>
val command: domain.CreateCommand[v.Record] = iouCreateCommand()
postCreateCommand(command, encoder, uri).flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
assertStatus(output, StatusCodes.OK)
val activeContract = getResult(output)
assertActiveContract(activeContract)(command, encoder, decoder)
}: Future[Assertion]
}
"create IOU should fail if authorization header is missing" in withHttpService {
(uri, encoder, _) =>
import encoder.implicits._
val command: domain.CreateCommand[v.Record] = iouCreateCommand()
val input: JsValue = SprayJson.encode1(command).valueOr(e => fail(e.shows))
postJsonRequest(uri.withPath(Uri.Path("/v1/create")), input, List()).flatMap {
case (status, output) =>
status shouldBe StatusCodes.Unauthorized
assertStatus(output, StatusCodes.Unauthorized)
expectedOneErrorMessage(output) should include(
"missing Authorization header with OAuth 2.0 Bearer Token")
}: Future[Assertion]
}
"create IOU with unsupported templateId should return proper error" in withHttpService {
(uri, encoder, _) =>
import encoder.implicits._
val command: domain.CreateCommand[v.Record] =
iouCreateCommand().copy(templateId = domain.TemplateId(None, "Iou", "Dummy"))
val input: JsValue = SprayJson.encode1(command).valueOr(e => fail(e.shows))
postJsonRequest(uri.withPath(Uri.Path("/v1/create")), input).flatMap {
case (status, output) =>
status shouldBe StatusCodes.BadRequest
assertStatus(output, StatusCodes.BadRequest)
val unknownTemplateId: domain.TemplateId.OptionalPkg =
domain.TemplateId(None, command.templateId.moduleName, command.templateId.entityName)
expectedOneErrorMessage(output) should include(
s"Cannot resolve template ID, given: ${unknownTemplateId: domain.TemplateId.OptionalPkg}")
}: Future[Assertion]
}
"exercise IOU_Transfer" in withHttpService { (uri, encoder, decoder) =>
val create: domain.CreateCommand[v.Record] = iouCreateCommand()
postCreateCommand(create, encoder, uri)
.flatMap {
case (createStatus, createOutput) =>
createStatus shouldBe StatusCodes.OK
assertStatus(createOutput, StatusCodes.OK)
val contractId = getContractId(getResult(createOutput))
val exercise: domain.ExerciseCommand[v.Value, domain.EnrichedContractId] =
iouExerciseTransferCommand(contractId)
val exerciseJson: JsValue = encodeExercise(encoder)(exercise)
postJsonRequest(uri.withPath(Uri.Path("/v1/exercise")), exerciseJson)
.flatMap {
case (exerciseStatus, exerciseOutput) =>
exerciseStatus shouldBe StatusCodes.OK
assertStatus(exerciseOutput, StatusCodes.OK)
assertExerciseResponseNewActiveContract(
getResult(exerciseOutput),
create,
exercise,
encoder,
decoder,
uri)
}
}: Future[Assertion]
}
"create-and-exercise IOU_Transfer" in withHttpService { (uri, encoder, _) =>
import encoder.implicits._
val cmd: domain.CreateAndExerciseCommand[v.Record, v.Value] =
iouCreateAndExerciseTransferCommand()
val json: JsValue = SprayJson.encode2(cmd).valueOr(e => fail(e.shows))
postJsonRequest(uri.withPath(Uri.Path("/v1/create-and-exercise")), json)
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
inside(
decode1[domain.OkResponse, domain.ExerciseResponse[JsValue]](output)
) {
case \/-(response) =>
response.status shouldBe StatusCodes.OK
response.warnings shouldBe 'empty
inside(response.result.events) {
case List(
domain.Contract(\/-(created0)),
domain.Contract(-\/(archived0)),
domain.Contract(\/-(created1))) =>
assertTemplateId(created0.templateId, cmd.templateId)
assertTemplateId(archived0.templateId, cmd.templateId)
archived0.contractId shouldBe created0.contractId
assertTemplateId(
created1.templateId,
domain.TemplateId(None, "Iou", "IouTransfer"))
asContractId(response.result.exerciseResult) shouldBe created1.contractId
}
}
}: Future[Assertion]
}
private def assertExerciseResponseNewActiveContract(
exerciseResponse: JsValue,
createCmd: domain.CreateCommand[v.Record],
exerciseCmd: domain.ExerciseCommand[v.Value, domain.EnrichedContractId],
encoder: DomainJsonEncoder,
decoder: DomainJsonDecoder,
uri: Uri
): Future[Assertion] = {
inside(SprayJson.decode[domain.ExerciseResponse[JsValue]](exerciseResponse)) {
case \/-(domain.ExerciseResponse(JsString(exerciseResult), List(contract1, contract2))) => {
// checking contracts
inside(contract1) {
case domain.Contract(-\/(archivedContract)) =>
(archivedContract.contractId.unwrap: String) shouldBe (exerciseCmd.reference.contractId.unwrap: String)
}
inside(contract2) {
case domain.Contract(\/-(activeContract)) =>
assertActiveContract(decoder, activeContract, createCmd, exerciseCmd)
}
// checking exerciseResult
exerciseResult.length should be > (0)
val newContractLocator = domain.EnrichedContractId(
Some(domain.TemplateId(None, "Iou", "IouTransfer")),
domain.ContractId(exerciseResult)
)
postContractsLookup(newContractLocator, uri).flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
assertStatus(output, StatusCodes.OK)
getContractId(getResult(output)) shouldBe newContractLocator.contractId
}: Future[Assertion]
}
}
}
"exercise IOU_Transfer with unknown contractId should return proper error" in withHttpService {
(uri, encoder, _) =>
val contractId = lar.ContractId("#NonExistentContractId")
val exerciseJson: JsValue = encodeExercise(encoder)(iouExerciseTransferCommand(contractId))
postJsonRequest(uri.withPath(Uri.Path("/v1/exercise")), exerciseJson)
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.InternalServerError
assertStatus(output, StatusCodes.InternalServerError)
expectedOneErrorMessage(output) should include(
"couldn't find contract AbsoluteContractId(#NonExistentContractId)")
}: Future[Assertion]
}
"exercise Archive" in withHttpService { (uri, encoder, decoder) =>
val create: domain.CreateCommand[v.Record] = iouCreateCommand()
postCreateCommand(create, encoder, uri)
.flatMap {
case (createStatus, createOutput) =>
createStatus shouldBe StatusCodes.OK
assertStatus(createOutput, StatusCodes.OK)
val contractId = getContractId(getResult(createOutput))
val templateId = domain.TemplateId(None, "Iou", "Iou")
val reference = domain.EnrichedContractId(Some(templateId), contractId)
val exercise = archiveCommand(reference)
val exerciseJson: JsValue = encodeExercise(encoder)(exercise)
postJsonRequest(uri.withPath(Uri.Path("/v1/exercise")), exerciseJson)
.flatMap {
case (exerciseStatus, exerciseOutput) =>
exerciseStatus shouldBe StatusCodes.OK
assertStatus(exerciseOutput, StatusCodes.OK)
val exercisedResponse: JsObject = getResult(exerciseOutput).asJsObject
assertExerciseResponseArchivedContract(decoder, exercisedResponse, exercise)
}
}: Future[Assertion]
}
private def assertExerciseResponseArchivedContract(
decoder: DomainJsonDecoder,
exerciseResponse: JsValue,
exercise: domain.ExerciseCommand[v.Value, domain.EnrichedContractId]
): Assertion = {
inside(exerciseResponse) {
case result @ JsObject(_) =>
inside(SprayJson.decode[domain.ExerciseResponse[JsValue]](result)) {
case \/-(domain.ExerciseResponse(exerciseResult, List(contract1))) =>
exerciseResult shouldBe JsObject()
inside(contract1) {
case domain.Contract(-\/(archivedContract)) =>
(archivedContract.contractId.unwrap: String) shouldBe (exercise.reference.contractId.unwrap: String)
}
}
}
}
"should be able to serialize and deserialize domain commands" in withLedger { client =>
jsonCodecs(client).map {
case (encoder, decoder) =>
testCreateCommandEncodingDecoding(encoder, decoder)
testExerciseCommandEncodingDecoding(encoder, decoder)
}: Future[Assertion]
}
private def testCreateCommandEncodingDecoding(
encoder: DomainJsonEncoder,
decoder: DomainJsonDecoder): Assertion = {
import encoder.implicits._
import json.JsonProtocol._
import util.ErrorOps._
val command0: domain.CreateCommand[v.Record] = iouCreateCommand()
val x = for {
jsVal <- SprayJson.encode1(command0).liftErr(JsonError)
command1 <- decoder.decodeCreateCommand(jsVal)
} yield command1.map(removeRecordId) should ===(command0)
x.fold(e => fail(e.shows), identity)
}
private def testExerciseCommandEncodingDecoding(
encoder: DomainJsonEncoder,
decoder: DomainJsonDecoder): Assertion = {
val command0 = iouExerciseTransferCommand(lar.ContractId("#a-contract-ID"))
val jsVal: JsValue = encodeExercise(encoder)(command0)
val command1 = decodeExercise(decoder)(jsVal)
command1.bimap(removeRecordId, identity) should ===(command0)
}
"request non-existent endpoint should return 404 with errors" in withHttpService {
(uri: Uri, _, _) =>
val badUri = uri.withPath(Uri.Path("/contracts/does-not-exist"))
getRequest(uri = badUri)
.flatMap {
case (status, output) =>
status shouldBe StatusCodes.NotFound
assertStatus(output, StatusCodes.NotFound)
expectedOneErrorMessage(output) shouldBe s"${HttpMethods.GET: HttpMethod}, uri: ${badUri: Uri}"
}: Future[Assertion]
}
"parties endpoint should return all known parties" in withHttpServiceAndClient {
(uri, _, _, client) =>
import scalaz.std.vector._
val partyIds = Vector("Alice", "Bob", "Charlie", "Dave")
val partyManagement = client.partyManagementClient
partyIds
.traverse { p =>
partyManagement.allocateParty(Some(p), Some(s"$p & Co. LLC"))
}
.flatMap { allocatedParties =>
getRequest(uri = uri.withPath(Uri.Path("/v1/parties"))).flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
inside(
decode1[domain.OkResponse, List[domain.PartyDetails]](output)
) {
case \/-(response) =>
response.status shouldBe StatusCodes.OK
response.warnings shouldBe 'empty
val actualIds: Set[domain.Party] = response.result.map(_.identifier)(breakOut)
actualIds shouldBe domain.Party.subst(partyIds.toSet)
response.result.toSet shouldBe
allocatedParties.toSet.map(domain.PartyDetails.fromLedgerApi)
}
}
}: Future[Assertion]
}
"parties endpoint should return only requested parties, unknown parties returned as warnings" in withHttpServiceAndClient {
(uri, _, _, client) =>
import scalaz.std.vector._
val charlie = domain.Party("Charlie")
val knownParties = domain.Party.subst(Vector("Alice", "Bob", "Dave")) :+ charlie
val erin = domain.Party("Erin")
val requestedPartyIds: Vector[domain.Party] = knownParties.filterNot(_ == charlie) :+ erin
val partyManagement = client.partyManagementClient
knownParties
.traverse { p =>
partyManagement.allocateParty(Some(p.unwrap), Some(s"${p.unwrap} & Co. LLC"))
}
.flatMap { allocatedParties =>
postJsonRequest(
uri = uri.withPath(Uri.Path("/v1/parties")),
JsArray(requestedPartyIds.map(x => JsString(x.unwrap)))
).flatMap {
case (status, output) =>
status shouldBe StatusCodes.OK
inside(
decode1[domain.OkResponse, List[domain.PartyDetails]](output)
) {
case \/-(response) =>
response.status shouldBe StatusCodes.OK
response.warnings shouldBe Some(domain.UnknownParties(List(erin)))
val actualIds: Set[domain.Party] = response.result.map(_.identifier)(breakOut)
actualIds shouldBe requestedPartyIds.toSet - erin // Erin is not known
val expected: Set[domain.PartyDetails] = allocatedParties.toSet
.map(domain.PartyDetails.fromLedgerApi)
.filterNot(_.identifier == charlie)
response.result.toSet shouldBe expected
}
}
}: Future[Assertion]
}
"parties endpoint should error if empty array passed as input" in withHttpServiceAndClient {
(uri, _, _, _) =>
postJsonRequest(
uri = uri.withPath(Uri.Path("/v1/parties")),
JsArray(Vector.empty)
).flatMap {
case (status, output) =>
status shouldBe StatusCodes.BadRequest
assertStatus(output, StatusCodes.BadRequest)
val errorMsg = expectedOneErrorMessage(output)
errorMsg should include("Cannot read JSON: <[]>")
errorMsg should include("must be a JSON array with at least 1 element")
}: Future[Assertion]
}
"parties endpoint returns empty result with warnings and OK status if nothing found" in withHttpServiceAndClient {
(uri, _, _, _) =>
val requestedPartyIds: Vector[domain.Party] =
domain.Party.subst(Vector("Alice", "Bob", "Dave"))