forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.soa.core.pas
More file actions
2548 lines (2397 loc) · 87.2 KB
/
test.soa.core.pas
File metadata and controls
2548 lines (2397 loc) · 87.2 KB
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
/// regression tests for RESTful SOA core process
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit test.soa.core;
interface
{$I ..\src\mormot.defines.inc}
uses
sysutils,
contnrs,
classes,
mormot.core.base,
mormot.core.os,
mormot.core.text,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.datetime,
mormot.core.rtti,
mormot.crypt.core,
mormot.core.data,
mormot.core.variants,
mormot.core.json,
mormot.core.log,
mormot.core.perf,
mormot.core.search,
mormot.core.mustache,
mormot.core.test,
mormot.core.threads,
mormot.core.interfaces,
mormot.core.mvc,
mormot.crypt.jwt,
mormot.net.client,
mormot.net.server,
mormot.net.http,
mormot.net.relay,
mormot.net.ws.core,
mormot.net.ws.client,
mormot.net.ws.server,
mormot.db.core,
mormot.db.nosql.bson,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.orm.storage,
mormot.orm.sqlite3,
mormot.orm.client,
mormot.orm.server,
mormot.soa.core,
mormot.soa.client,
mormot.soa.server,
mormot.soa.codegen,
mormot.rest.core,
mormot.rest.client,
mormot.rest.server,
mormot.rest.memserver,
mormot.rest.sqlite3,
mormot.rest.http.client,
mormot.rest.http.server,
mormot.rest.mvc,
mormot.db.raw.sqlite3,
mormot.db.raw.sqlite3.static,
test.core.data,
test.core.base,
test.orm.core;
type
/// a record used by IComplexCalculator.GetCustomer
TCustomerData = packed record
Id: Integer;
AccountNum: RawUtf8;
Name: RawUtf8;
Address: RawUtf8;
end;
/// a record which is an Homogeneous Floating-point Aggregate (HFA)
TCoords = packed record
X, Y: double;
end;
TClientSide = (
csUndefined, csDirect, csServer,
csMainThread, csBackground, csJsonObject, csSessions, csLocked,
csCrc32, csCrc32c, csXxHash, csMd5, csSha1, csSha256, csSha512, csSha3,
csWeak, csBasic, csDbLog, csJsonRpc, csHttp, csHttpLog, csHttpBearer,
csCustomRtti);
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test basic and high-level remote service calls
ICalculator = interface(IInvokable)
['{9A60C8ED-CEB2-4E09-87D4-4A16F496E5FE}']
/// add two signed 32 bit integers
function Add(n1, n2: integer): integer;
/// multiply two signed 64 bit integers
function Multiply(n1, n2: Int64): Int64;
/// substract two floating-point values
function Subtract(n1, n2: double): double;
/// convert a currency value into text
procedure ToText(Value: Currency; var Result: RawUtf8);
/// convert a floating-point value into text
function ToTextFunc(Value: double): string;
/// swap two by-reference floating-point values
// - would validate pointer use instead of XMM1/XMM2 registers on x86-64
// - also that /calculator/swap would be processed by ICalculator._Swap()
procedure _Swap(var n1, n2: double);
/// test unaligned stack access
function StackIntMultiply(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: integer): Int64;
/// test float stack access
function StackFloatMultiply(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: double): Int64;
/// do some work with strings, sets and enumerates parameters,
// testing also var (in/out) parameters and set as a function result
function SpecialCall(Txt: RawUtf8; var Int: integer; var Card: cardinal;
field: TRttiParserComplexTypes; fields: TRttiParserComplexTypes;
var options: TServiceInstanceImplementations): TRttiParserComplexTypes;
/// test integer, strings and wide strings dynamic arrays, together with records
function ComplexCall(const Ints: TIntegerDynArray;
const Strs1: TRawUtf8DynArray; var Str2: TWideStringDynArray;
const Rec1: TVirtualTableModuleProperties; var Rec2: TEntry;
Float1: double; var Float2: double): TEntry;
/// a variant is a TVarRec with mixed types so is a pointer even on the SysV ABI
function VariantCall(const Value: variant): RawUtf8;
{$ifndef HASNOSTATICRTTI} // Delphi 7/2007 raises "TGuid has no type info"
/// test small TGuid record and HFA to be passed on registers on the SysV ABI
function RecordCall(const Uuid: TGuid; const Pos: TCoords): RawJson;
{$endif HASNOSTATICRTTI}
/// validates ArgsInputIsOctetStream raw binary upload
function DirectCall(const Data: RawBlob): integer;
// validates huge RawJson/RawUtf8
function RepeatJsonArray(const item: RawUtf8; count: integer): RawJson;
function RepeatTextArray(const item: RawUtf8; count: integer): RawUtf8;
// validates IDocList/IDocDict parameters - cannot be in result
procedure TestDocList(var list: IDocList; const data: variant; out input: IDocList);
procedure TestDocDict(var dict: IDocDict; const data: variant; out input: IDocDict);
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test remote service calls with objects as parameters (its published
// properties will be serialized as standard Json objects)
// - since it inherits from ICalculator interface, it will also test
// the proper interface inheritance handling (i.e. it will test that
// ICalculator methods are also available)
IComplexCalculator = interface(ICalculator)
['{8D0F3839-056B-4488-A616-986CF8D4DEB7}']
/// customize the server-side execution expectations for this interface
/// purpose of this method is to substract two complex numbers
// - using class instances as parameters
procedure Substract(n1, n2: TComplexNumber; out Result: TComplexNumber);
/// purpose of this method is to check for boolean handling
function IsNull(n: TComplexNumber): boolean;
/// this will test the BLOB kind of remote answer
function TestBlob(n: TComplexNumber; cs: TClientSide): TServiceCustomAnswer;
/// test variant kind of parameters
function TestVariants(const Text: RawUtf8; V1: Variant;
var V2: variant): variant;
/// test (maybe huge) RawJson content
function TestRawJson(len, value: integer; const j: RawJson): RawJson;
/// test in/out collections
procedure Collections(Item: TCollTest; var List: TCollTestsI;
out Copy: TCollTestsI);
/// returns the thread ID running the method on server side
function GetCurrentThreadID: PtrUInt;
/// validate record transmission
function GetCustomer(CustomerId: Integer;
out CustomerData: TCustomerData): Boolean;
//// validate TOrm transmission
procedure FillPeople(var People: TOrmPeople);
/// validate array of TOrm transmission
procedure FillPeoples(n: integer; out People: TOrmPeopleObjArray);
{$ifndef CPUAARCH64} // FPC doesn't follow the AARCH64 ABI -> fixme
{$ifndef HASNOSTATICRTTI}
/// validate simple record transmission
// - older Delphi versions (e.g. 6-7-2009) do not allow records without
// nested reference-counted types
// - CPUAARCH64 has troubles with TConsultNav size and trigger GPF when
// returned as function result -> Echo is an "out" parameter here
function EchoRecord(const Nav: TConsultaNav): TConsultaNav;
{$endif HASNOSTATICRTTI}
{$endif CPUAARCH64}
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test sicClientDriven implementation pattern: data will remain on
// the server until the IComplexNumber instance is out of scope
IComplexNumber = interface(IInvokable)
['{29D753B2-E7EF-41B3-B7C3-827FEB082DC1}']
procedure Assign(aReal, aImaginary: double);
function GetImaginary: double;
function GetReal: double;
procedure SetImaginary(const Value: double);
procedure SetReal(const Value: double);
procedure Add(aReal, aImaginary: double);
property Real: double
read GetReal write SetReal;
property Imaginary: double
read GetImaginary write SetImaginary;
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test sicPerUser implementation pattern
ITestUser = interface(IInvokable)
['{EABB42BF-FD08-444A-BF9C-6B73FA4C4788}']
function GetContextSessionID: integer;
function GetContextSessionUser: integer;
function GetContextSessionGroup: integer;
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test sicPerGroup implementation pattern
ITestGroup = interface(ITestUser)
['{DCBA5A38-62CC-4A52-8639-E709B31DDCE1}']
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test sicPerSession implementation pattern
ITestSession = interface(ITestUser)
['{5237A687-C0B2-46BA-9F39-BEEA7C3AA6A9}']
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test threading implementation pattern
ITestPerThread = interface(IInvokable)
['{202B6C9F-FCCB-488D-A425-5472554FD9B1}']
function GetContextServiceInstanceID: PtrUInt;
function GetThreadIDAtCreation: PtrUInt;
function GetCurrentThreadID: PtrUInt;
function GetCurrentRunningThreadID: PtrUInt;
end;
/// a test value object, used by IUserRepository/ISmsSender interfaces
// - to test stubing/mocking implementation pattern
TUser = record
Name: RawUtf8;
Password: RawUtf8;
MobilePhoneNumber: RawUtf8;
ID: Integer;
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test stubing/mocking implementation pattern
IUserRepository = interface(IInvokable)
['{B21E5B21-28F4-4874-8446-BD0B06DAA07F}']
function GetUserByName(const Name: RawUtf8): TUser;
procedure Save(const User: TUser);
end;
/// a test interface, used by TTestServiceOrientedArchitecture
// - to test stubing/mocking implementation pattern
ISmsSender = interface(IInvokable)
['{8F87CB56-5E2F-437E-B2E6-B3020835DC61}']
function Send(const Text, Number: RawUtf8): boolean;
end;
const
IID_ICalculator: TGuid = '{9A60C8ED-CEB2-4E09-87D4-4A16F496E5FE}';
type
TTestServiceInstances = record
I: ICalculator;
CC: IComplexCalculator;
CN: IComplexNumber;
CU: ITestUser;
CG: ITestGroup;
CS: ITestSession;
CT: ITestPerThread;
ClientSide: TClientSide;
ExpectedSessionID: integer;
ExpectedUserID: integer;
ExpectedGroupID: integer;
end;
TRestClientDBNamed = class(TRestClientDB)
public
Name: RawUtf8;
ClientSide: TClientSide;
end;
/// a test case which will test the interface-based SOA implementation of
// the mORMot framework
TTestServiceOrientedArchitecture = class(TSynTestCase)
protected
fMain: TRestClientDBNamed;
procedure Test(const Inst: TTestServiceInstances; Iterations: Cardinal = 700);
procedure TestHttp(aClient: TRestClientDBNamed; const port: RawUtf8);
procedure ClientTest(aClient: TRestClientDBNamed; aRouting: TRestServerUriContextClass;
aAsJsonObject: boolean; aRunInOtherThread: boolean = false;
aOptions: TInterfaceMethodOptions = []);
class procedure CustomReader(var Context: TJsonParserContext; Data: pointer);
class procedure CustomWriter(W: TJsonWriter; Data: pointer;
Options: TTextWriterWriteObjectOptions);
procedure IntSubtractJson(Ctxt: TOnInterfaceStubExecuteParamsJson);
procedure IntSubtractVariant(Ctxt: TOnInterfaceStubExecuteParamsVariant);
procedure IntSubtractVariantVoid(Ctxt: TOnInterfaceStubExecuteParamsVariant);
public
{ all threaded callbacks for validating all client side modes }
/// test the client-side in RESTful mode with values transmitted as Json objects
procedure ClientSideRESTAsJsonObject(Sender: TObject);
/// test the client-side in RESTful mode with full SQlite3 session statistics
procedure ClientSideRESTSessionsStats(Sender: TObject);
/// test the client-side implementation with threading options
procedure ClientSideRESTThread(Sender: TObject);
/// test the client-side implementation with any hash URI signature
procedure ClientSideRESTSign(Sender: TObject);
/// test the client-side implementation using TRestServerAuthentication*
procedure ClientSideRESTAuth(Sender: TObject);
/// test the client-side in RESTful mode with all calls logged in a table
procedure ClientSideRESTServiceLogToDB(Sender: TObject);
/// test the client-side implementation in Json-RPC mode
procedure ClientSideJsonRPC(Sender: TObject);
/// test REStful mode using HTTP client/server communication
procedure ClientSideOverHTTP(Sender: TObject);
/// test the custom record Json serialization - could NOT be parallelized
procedure ClientSideRESTCustomRecord(Client: TRestClientDBNamed);
/// initialize a new REST server + REST client with SOA implementation
function NewClient(aClientSide: TClientSide): TRestClientDBNamed;
published
/// test the SetWeak/SetWeakZero weak interface functions
procedure WeakInterfaces;
/// test direct call to the class instance
procedure DirectCall;
/// test the server-side implementation
procedure ServerSide;
/// test the security features
procedure Security;
/// multi-threaded tests of the client-side implementation in all mode
procedure ClientSide;
/// test interface stubbing / mocking
procedure MocksAndStubs;
end;
implementation
{ TServiceCalculator }
type
TServiceCalculator = class(TInjectableObject, ICalculator)
public
function Add(n1, n2: integer): integer;
function Subtract(n1, n2: double): double;
procedure _Swap(var n1, n2: double);
function Multiply(n1, n2: Int64): Int64;
procedure ToText(Value: Currency; var Result: RawUtf8);
function ToTextFunc(Value: double): string;
function StackIntMultiply(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: integer): Int64;
function StackFloatMultiply(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: double): Int64;
function SpecialCall(Txt: RawUtf8; var Int: integer; var Card: cardinal;
field: TRttiParserComplexTypes; fields: TRttiParserComplexTypes;
var options: TServiceInstanceImplementations): TRttiParserComplexTypes;
function ComplexCall(const Ints: TIntegerDynArray;
const Strs1: TRawUtf8DynArray; var Str2: TWideStringDynArray;
const Rec1: TVirtualTableModuleProperties; var Rec2: TEntry;
Float1: double; var Float2: double): TEntry;
function DirectCall(const Data: RawBlob): integer; // not used on Delphi 7/2007
function VariantCall(const Value: variant): RawUtf8;
function RecordCall(const Uuid: TGuid; const Pos: TCoords): RawJson;
function RepeatJsonArray(const item: RawUtf8; count: integer): RawJson;
function RepeatTextArray(const item: RawUtf8; count: integer): RawUtf8;
procedure TestDocList(var list: IDocList; const data: variant; out input: IDocList);
procedure TestDocDict(var dict: IDocDict; const data: variant; out input: IDocDict);
function Test(A, B: Integer): RawUtf8;
end;
TServiceComplexCalculator = class(TServiceCalculator, IComplexCalculator)
protected
fExpected: TClientSide;
fMethodThread: PtrUInt;
procedure EnsureInExpectedThread;
public
procedure Substract(n1, n2: TComplexNumber; out Result: TComplexNumber);
function IsNull(n: TComplexNumber): boolean;
function TestBlob(n: TComplexNumber; cs: TClientSide): TServiceCustomAnswer;
function TestVariants(const Text: RawUtf8;
V1: Variant; var V2: variant): variant;
function TestRawJson(len, value: integer; const j: RawJson): RawJson;
procedure Collections(Item: TCollTest; var List: TCollTestsI;
out Copy: TCollTestsI);
destructor Destroy; override;
function GetCurrentThreadID: PtrUInt;
function EchoRecord(const Nav: TConsultaNav): TConsultaNav;
function GetCustomer(CustomerId: Integer;
out CustomerData: TCustomerData): Boolean;
procedure FillPeople(var People: TOrmPeople);
procedure FillPeoples(n: integer; out People: TOrmPeopleObjArray);
end;
TServiceComplexNumber = class(TInterfacedObject, IComplexNumber)
private
fReal: double;
fImaginary: double;
function GetImaginary: double;
function GetReal: double;
procedure SetImaginary(const Value: double);
procedure SetReal(const Value: double);
public
procedure Assign(aReal, aImaginary: double);
procedure Add(aReal, aImaginary: double);
property Real: double
read GetReal write SetReal;
property Imaginary: double
read GetImaginary write SetImaginary;
end;
TServiceUserGroupSession = class(TInterfacedObject, ITestUser, ITestGroup, ITestSession)
public
function GetContextSessionID: integer;
function GetContextSessionUser: integer;
function GetContextSessionGroup: integer;
end;
TServicePerThread = class(TInterfacedPersistent, ITestPerThread)
protected
fThreadIDAtCreation: PtrUInt; // TThreadID = ^TThreadRec under BSD
public
constructor Create; override;
function GetContextServiceInstanceID: PtrUInt;
function GetThreadIDAtCreation: PtrUInt;
function GetCurrentThreadID: PtrUInt;
function GetCurrentRunningThreadID: PtrUInt;
end;
function TServiceCalculator.Add(n1, n2: integer): integer;
begin
result := n1 + n2;
end;
function TServiceCalculator.Multiply(n1, n2: Int64): Int64;
begin
result := n1 * n2;
end;
function TServiceCalculator.StackIntMultiply(
n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: integer): Int64;
begin
result := n1 * n2 * n3 * n4 * n5 * n6 * n7 * n8 * n9 * n10;
end;
function TServiceCalculator.StackFloatMultiply(
n1, n2, n3, n4, n5, n6, n7, n8, n9, n10: double): Int64;
begin
result := round(n1 * n2 * n3 * n4 * n5 * n6 * n7 * n8 * n9 * n10);
end;
function TServiceCalculator.SpecialCall(Txt: RawUtf8; var Int: integer;
var Card: cardinal; field, fields: TRttiParserComplexTypes;
var options: TServiceInstanceImplementations): TRttiParserComplexTypes;
var
dummy: IComplexNumber;
begin
TryResolve(TypeInfo(IComplexNumber), dummy);
inc(Int, length(Txt));
inc(Card);
result := fields + field;
Include(options, sicClientDriven);
Exclude(options, sicSingle);
end;
function TServiceCalculator.Subtract(n1, n2: double): double;
begin
result := n1 - n2;
end;
procedure TServiceCalculator._Swap(var n1, n2: double);
var
tmp: double;
begin
tmp := n2;
n2 := n1;
n1 := tmp;
end;
function TServiceCalculator.Test(A, B: Integer): RawUtf8;
begin
result := Int32ToUtf8(A + B);
end;
procedure TServiceCalculator.ToText(Value: Currency; var Result: RawUtf8);
begin
Result := Curr64ToStr(PInt64(@Value)^);
end;
function TServiceCalculator.ToTextFunc(Value: double): string;
begin
Result := DoubleToString(Value);
end;
function TServiceCalculator.ComplexCall(const Ints: TIntegerDynArray;
const Strs1: TRawUtf8DynArray; var Str2: TWideStringDynArray;
const Rec1: TVirtualTableModuleProperties; var Rec2: TEntry;
Float1: double; var Float2: double): TEntry;
var
i: integer;
begin
Result := Rec2;
Result.Json := StringToUtf8(Rec1.FileExtension);
i := length(Str2);
SetLength(Str2, i + 1);
Str2[i] := UTF8ToWideString(RawUtf8ArrayToCSV(Strs1));
inc(Rec2.ID);
dec(Rec2.Timestamp512);
Rec2.Json := IntegerDynArrayToCSV(pointer(Ints), length(Ints));
Float2 := Float1;
end;
function TServiceCalculator.DirectCall(const Data: RawBlob): integer;
var
i: integer;
begin
Result := length(Data);
for i := 1 to Result do
if Data[i] <> #1 then
Result := 0;
end;
function TServiceCalculator.VariantCall(const Value: variant): RawUtf8;
begin
VariantToUtf8(Value, result);
end;
function TServiceCalculator.RecordCall(const Uuid: TGuid; const Pos: TCoords): RawJson;
begin
result := FormatUtf8('["%",%,%]', [GuidToShort(Uuid), Pos.X, Pos.Y]);
end;
function TServiceCalculator.RepeatJsonArray(
const item: RawUtf8; count: integer): RawJson;
var
buf: TBuffer64K;
begin
with TJsonWriter.CreateOwnedStream(@buf, SizeOf(buf)) do
try
Add('[');
while count > 0 do
begin
Add('"');
AddJsonEscape(pointer(item));
Add('"', ',');
dec(count);
end;
CancelLastComma(']');
SetText(RawUtf8(Result));
finally
Free;
end;
end;
function TServiceCalculator.RepeatTextArray(
const item: RawUtf8; count: integer): RawUtf8;
var
buf: TBuffer64K;
begin
with TJsonWriter.CreateOwnedStream(@buf, SizeOf(buf)) do
try
while count > 0 do
begin
AddJsonEscape(pointer(item));
dec(count);
end;
SetText(Result);
finally
Free;
end;
end;
procedure TServiceCalculator.TestDocList(var list: IDocList;
const data: variant; out input: IDocList);
begin
input := list;
list := DocList([1, 2, 3, data]);
end;
procedure TServiceCalculator.TestDocDict(var dict: IDocDict;
const data: variant; out input: IDocDict);
begin
input := dict;
dict := DocDict(['a', 1, 'b', 2, 'data', data]);
end;
{ TServiceComplexCalculator }
function GetThreadID: PtrUInt; {$ifdef HASINLINE} inline; {$endif}
begin // avoid name conflict with TServiceComplexCalculator.GetCurrentThreadID
Result := PtrUInt(GetCurrentThreadId);
end;
function TServiceComplexCalculator.IsNull(n: TComplexNumber): boolean;
begin
result := (n.Real = 0) and (n.Imaginary = 0);
end;
procedure TServiceComplexCalculator.Substract(n1, n2: TComplexNumber;
out Result: TComplexNumber);
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
{%H-}result.Real := n1.Real - n2.Real;
result.Imaginary := n1.Imaginary - n2.Imaginary;
end;
function TServiceComplexCalculator.EchoRecord(const Nav: TConsultaNav): TConsultaNav;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
result := Nav;
end;
procedure TServiceComplexCalculator.EnsureInExpectedThread;
var
name: PShortString;
thrid: PtrUInt;
begin
name := GetEnumName(TypeInfo(TClientSide), ord(fExpected));
thrid := GetThreadID;
if fMethodThread <> 0 then
if fMethodThread <> thrid then
ESynException.RaiseUtf8('%.EnsureInExpectedThread % in #% <> #%',
[self, name^, thrid, fMethodThread]);
case fExpected of
csDirect,
csServer,
csMainThread:
{$ifdef OSANDROID}
// On Android, processes never run in the mainthread
;
{$else}
if thrid <> PtrUInt(MainThreadID) then
ESynException.RaiseUtf8('% shall be in main thread', [name^]);
{$endif OSANDROID}
csBackground,
csHttp,
csHttpLog,
csHttpBearer:
if thrid = PtrUInt(MainThreadID) then
ESynException.RaiseUtf8('% shall NOT be in main thread', [name^])
else if ServiceRunningContext.RunningThread = nil then
ESynException.RaiseUtf8('% shall have a known RunningThread', [name^]);
// other TClientSide could be in main thread or background thread
end;
end;
function TServiceComplexCalculator.TestBlob(n: TComplexNumber;
cs: TClientSide): TServiceCustomAnswer;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
fExpected := cs;
EnsureInExpectedThread;
Result.Header := TEXT_CONTENT_TYPE_HEADER;
if n.Real = maxInt then
Result.Content := RawUtf8OfChar('-', 600)
else
Result.Content := FormatUtf8('%,%', [n.Real, n.Imaginary]);
end;
function TServiceComplexCalculator.TestVariants(const Text: RawUtf8;
V1: Variant; var V2: variant): variant;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
V2 := V2 + V1;
VariantLoadJson(Result, Text);
end;
const
_TESTRAWJSON = '["toto"]';
function TServiceComplexCalculator.TestRawJson(
len, value: integer; const j: RawJson): RawJson;
var
p: PByteArray;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
if len < 0 then
len := 0;
if j <> _TESTRAWJSON then
begin
result:= '';
exit;
end;
p := FastSetString(RawUtf8(result), len + 2);
p[0] := ord('"');
FillcharFast(p[1], len, value);
p[len + 1] := ord('"');
end;
function TServiceComplexCalculator.GetCurrentThreadID: PtrUInt;
begin
Result := GetThreadID;
fMethodThread := Result;
end;
function TServiceComplexCalculator.GetCustomer(CustomerId: Integer;
out CustomerData: TCustomerData): Boolean;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
CustomerData.Id := CustomerId;
CustomerData.AccountNum := Int32ToUtf8(CustomerId);
Result := True;
end;
procedure TServiceComplexCalculator.FillPeople(var People: TOrmPeople);
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
if People.ID = 0 then
exit; // check transmission of LastName/FirstName as ""
People.LastName := FormatUtf8('Last %', [People.ID]);
People.FirstName := FormatUtf8('First %', [People.ID]);
end;
procedure TServiceComplexCalculator.FillPeoples(
n: integer; out People: TOrmPeopleObjArray);
var
i: PtrInt;
p: TOrmPeople;
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
SetLength(People, n);
for i := 0 to n - 1 do
begin
p := TOrmPeople.Create;
p.IDValue := i;
p.FirstName := UInt32ToUtf8(i);
p.LastName := 'Last';
p.YearOfBirth := 1982 + i;
p.YearOfDeath := 1992 + i;
People[i] := p;
end;
end;
procedure TServiceComplexCalculator.Collections(Item: TCollTest;
var List: TCollTestsI; out Copy: TCollTestsI);
begin
if fMethodThread = 0 then
fMethodThread := GetThreadID;
CopyObject(Item, List.Add);
CopyObject(List, Copy{%H-});
end;
destructor TServiceComplexCalculator.Destroy;
begin
EnsureInExpectedThread;
inherited;
end;
{ TServiceComplexNumber }
procedure TServiceComplexNumber.Add(aReal, aImaginary: double);
begin
fReal := fReal + aReal;
fImaginary := fImaginary + aImaginary;
end;
procedure TServiceComplexNumber.Assign(aReal, aImaginary: double);
begin
fReal := aReal;
fImaginary := aImaginary;
end;
function TServiceComplexNumber.GetImaginary: double;
begin
Result := fImaginary;
end;
function TServiceComplexNumber.GetReal: double;
begin
Result := fReal;
end;
procedure TServiceComplexNumber.SetImaginary(const Value: double);
begin
fImaginary := Value;
end;
procedure TServiceComplexNumber.SetReal(const Value: double);
begin
fReal := Value;
end;
{ TServiceUserGroupSession }
function TServiceUserGroupSession.GetContextSessionGroup: integer;
begin
with ServiceRunningContext^ do
if Request = nil then
Result := 0
else
Result := Request.SessionGroup;
end;
function TServiceUserGroupSession.GetContextSessionID: integer;
begin
with ServiceRunningContext^ do
if Request = nil then
Result := 0
else
Result := Request.Session;
end;
function TServiceUserGroupSession.GetContextSessionUser: integer;
begin
with ServiceRunningContext^ do
if Request = nil then
Result := 0
else
Result := Request.SessionUser;
end;
{ TServicePerThread }
constructor TServicePerThread.Create;
begin
inherited;
fThreadIDAtCreation := GetThreadID;
end;
function TServicePerThread.GetCurrentThreadID: PtrUInt;
begin
result := GetThreadID;
with ServiceRunningContext^ do
if Request <> nil then
if result <> PtrUInt(Request.ServiceInstanceID) then
ESynException.RaiseUtf8('%.GetCurrentThreadID=%<>%',
[self, result, Request.ServiceInstanceID]);
end;
function TServicePerThread.GetThreadIDAtCreation: PtrUInt;
begin
result := fThreadIDAtCreation;
end;
function TServicePerThread.GetContextServiceInstanceID: PtrUInt;
begin
with ServiceRunningContext^ do
if Request = nil then
result := 0
else
begin
result := Request.ServiceInstanceID;
if result <> GetThreadID then
ESynException.RaiseUtf8('%.GetContextServiceInstanceID=%<>%',
[self, result, GetThreadID]);
end;
end;
function TServicePerThread.GetCurrentRunningThreadID: PtrUInt;
var
Thread: TThread;
begin
Thread := ServiceRunningContext.RunningThread;
if Thread = nil then
result := 0
else
begin
result := PtrUInt(Thread.ThreadID);
if result <> GetThreadID then
ESynException.RaiseUtf8('%.GetCurrentRunningThreadID=%<>%',
[self, result, GetThreadID]);
end;
end;
{ TTestServiceOrientedArchitecture }
function TTestServiceOrientedArchitecture.NewClient(
aClientSide: TClientSide): TRestClientDBNamed;
function Ask(client: TRestClientDBNamed; Method, Params, ParamsURI, ParamsObj: RawUtf8;
ExpectedResult: integer): RawUtf8;
var
resp, data, uriencoded, head: RawUtf8;
begin
Params := ' [ ' + Params + ' ]'; // add some ' ' to test real-world values
uriencoded := '?' + UrlEncode(Params);
if client.Server.ServicesRouting = TRestServerRoutingRest then
begin
FastSetString(data, pointer(Params), length(Params)); // =UniqueString
CheckEqual(client.URI(
'root/calculator.' + Method, 'POST', @resp, nil, @data),
ExpectedResult);
if ExpectedResult = HTTP_SUCCESS then
begin
CheckEqual(client.URI(
'root/CALCulator.' + Method + uriencoded, 'POST', @data),
ExpectedResult);
CheckEqual(data, resp, 'alternative URI-encoded-inlined parameters use');
CheckEqual(client.URI(
'root/Calculator.' + Method + '?' + ParamsURI, 'GET', @data),
ExpectedResult);
CheckEqual(data, resp,
'alternative "param1=value1¶m2=value2" URI-encoded scheme');
FastSetString(data, pointer(Params), length(Params)); // =UniqueString
CheckEqual(client.URI(
'root/calculator/' + Method, 'POST', @data, nil, @data),
ExpectedResult);
CheckEqual(data, resp, 'interface/method routing');
FastSetString(data, pointer(Params), length(Params)); // =UniqueString
CheckEqual(client.URI(
'root/CALCulator/' + Method + uriencoded, 'POST', @data),
ExpectedResult);
CheckEqual(data, resp, 'alternative URI-encoded-inlined parameters use');
CheckEqual(client.URI(
'root/Calculator/' + Method + '?' + ParamsURI, 'GET', @data),
ExpectedResult);
CheckEqual(data, resp,
'alternative "param1=value1¶m2=value2" URI-encoded scheme');
FastSetString(data, pointer(ParamsObj), length(ParamsObj)); // =UniqueString
CheckEqual(client.URI(
'root/calculator/' + Method, 'POST', @data, nil, @data),
ExpectedResult);
CheckEqual(data, resp, 'alternative object-encoded-as-body parameters use');
head := 'accept: application/xml';
CheckEqual(client.URI(
'root/Calculator/' + Method + '?' + ParamsURI, 'GET', @data, @head),
ExpectedResult);
Check(data <> resp, 'returned as XML');
CheckEqual(head, XML_CONTENT_TYPE_HEADER);
Check(IdemPChar(pointer(data), '<?XML'), 'returned as XML');
end;
end
else if client.Server.ServicesRouting = TRestServerRoutingJsonRpc then
begin
data := '{"method":"' + Method + '", "params":' + Params + '}';
CheckEqual(client.URI(
'root/calculator', 'POST', @resp, nil, @data), ExpectedResult);
end
else
raise Exception.Create('Invalid call');
result := JsonDecode(resp, 'result', nil, true);
if IdemPChar(Pointer(result), '{"result"') then
result := JsonDecode(result, 'result', nil, false)
else
TrimChars(result, 1, 1); // trim '[' + ']'
if (result <> '') and
(result[1] = '"') then
result := UnQuoteSQLString(result); // '"777"' -> '777'
if (ExpectedResult = HTTP_SUCCESS) and
(client.Server.ServicesRouting = TRestServerRoutingRest) then
begin
resp := XMLUTF8_HEADER + '<result><Result>' + result + '</Result></result>';
CheckEqual(data, resp, 'xml');
end;
end;
var
S: TServiceFactory;
i: integer;
uid: TID;
rout: integer;
resp: RawUtf8;
const
ROUTING: array[0..1] of TRestServerURIContextClass = (
TRestServerRoutingRest, TRestServerRoutingJsonRpc);
const
ExpectedURI: array[0..5] of RawUtf8 = (
'Add', 'Multiply', 'Subtract', 'ToText', 'ToTextFunc', '_Swap');
ExpectedParCount: array[0..5] of Integer = (
4, 4, 4, 3, 3, 3);
ExpectedArgs: array[0..5] of TInterfaceMethodValueTypes = (
[imvSelf, imvInteger],
[imvSelf, imvInt64],
[imvSelf, imvDouble],
[imvSelf, imvCurrency, imvRawUtf8],
[imvSelf, imvDouble, imvString],
[imvSelf, imvDouble]);
ExpectedTypes: array[0..4] of string[10] = (
'Integer', 'Int64', 'Double', 'Currency', 'Double');
ExpectedType: array[0..5] of TInterfaceMethodValueType = (
imvInteger, imvInt64, imvDouble, imvCurrency, imvDouble, imvDouble);
ExpectedResult: array[0..2] of string[10] = (
'Integer', 'Int64', 'Double');
begin
// create model, client and server
result := TRestClientDBNamed.Create(
TOrmModel.Create([TAuthUser, TAuthGroup]),
nil, SQLITE_MEMORY_DATABASE_NAME, TRestServerDB, {useAuth=}true);
result.Name := GetEnumNameTrimed(TypeInfo(TClientSide), ord(aClientSide));
result.ClientSide := aClientSide;
result.Model.Owner := result;
result.Server.Server.CreateMissingTables; // if tests are run with no db
uid := result.Server.Orm.MainFieldID(TAuthGroup, 'User');
Check(uid <> 0, 'server orm');
CheckEqual(result.Orm.MainFieldID(TAuthGroup, 'User'), 0, 'client orm');
Check(result.SetUser('User', 'synopse'), 'default user for Security tests');
Check(result.Server.ServiceRegister(TServiceCalculator,
[TypeInfo(ICalculator)], sicShared) <> nil,
'register TServiceCalculator as the ICalculator implementation on the server');
// verify ICalculator RTTI-generated details
Check(result.Server.Services <> nil);
if CheckFailed(result.Server.Services.Count = 1) then
exit;