1 (*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  *)
19 
20 unit TestClient;
21 
22 {$I ../src/Thrift.Defines.inc}
23 
24 {.$DEFINE StressTest}   // activate to stress-test the server with frequent connects/disconnects
25 {.$DEFINE PerfTest}     // activate the performance test
26 {$DEFINE Exceptions}    // activate the exceptions test (or disable while debugging)
27 
28 {$if CompilerVersion >= 28}
29 {$DEFINE SupportsAsync}
30 {$ifend}
31 
32 {$WARN SYMBOL_PLATFORM OFF}  // Win32Check
33 
34 interface
35 
36 uses
37   Windows, SysUtils, Classes, Math, ComObj, ActiveX,
38   {$IFDEF SupportsAsync} System.Threading, {$ENDIF}
39   DateUtils,
40   Generics.Collections,
41   TestConstants,
42   ConsoleHelper,
43   PerfTests,
44   Thrift,
45   Thrift.Protocol.Compact,
46   Thrift.Protocol.JSON,
47   Thrift.Protocol,
48   Thrift.Transport.Pipes,
49   Thrift.Transport.WinHTTP,
50   Thrift.Transport.MsxmlHTTP,
51   Thrift.Transport,
52   Thrift.Stream,
53   Thrift.Test,
54   Thrift.WinHTTP,
55   Thrift.Utils,
56 
57   Thrift.Configuration,
58   Thrift.Collections;
59 
60 type
61   TThreadConsole = class
62   private
63     FThread : TThread;
64   public
65     procedure Write( const S : string);
66     procedure WriteLine( const S : string);
67     constructor Create( AThread: TThread);
68   end;
69 
70   TTestSetup = record
71     protType  : TKnownProtocol;
72     endpoint  : TEndpointTransport;
73     layered   : TLayeredTransports;
74     useSSL    : Boolean; // include where appropriate (TLayeredTransport?)
75     host      : string;
76     port      : Integer;
77     sPipeName : string;
78     hAnonRead, hAnonWrite : THandle;
79   end;
80 
81   TClientThread = class( TThread )
82   private type
83     TTestGroup = (
84       test_Unknown,
85       test_BaseTypes,
86       test_Structs,
87       test_Containers,
88       test_Exceptions
89       // new values here
90     );
91     TTestGroups = set of TTestGroup;
92 
93     TTestSize = (
94       Empty,           // Edge case: the zero-length empty binary
95       Normal,          // Fairly small array of usual size (256 bytes)
96       ByteArrayTest,   // THRIFT-4454 Large writes/reads may cause range check errors in debug mode
97       PipeWriteLimit,  // THRIFT-4372 Pipe write operations across a network are limited to 65,535 bytes per write.
98       FifteenMB        // quite a bit of data, but still below the default max frame size
99     );
100 
101   private
102     FSetup : TTestSetup;
103     FTransport : ITransport;
104     FProtocol : IProtocol;
105     FNumIteration : Integer;
106     FConsole : TThreadConsole;
107 
108     // test reporting, will be refactored out into separate class later
109     FTestGroup : string;
110     FCurrentTest : TTestGroup;
111     FSuccesses : Integer;
112     FErrors : TStringList;
113     FFailed : TTestGroups;
114     FExecuted : TTestGroups;
115     procedure StartTestGroup( const aGroup : string; const aTest : TTestGroup);
116     procedure Expect( aTestResult : Boolean; const aTestInfo : string);
117     procedure ReportResults;
CalculateExitCodenull118     function  CalculateExitCode : Byte;
119 
120     procedure ClientTest;
121     {$IFDEF SupportsAsync}
122     procedure ClientAsyncTest;
123     {$ENDIF}
124 
125     procedure InitializeProtocolTransportStack;
126     procedure ShutdownProtocolTransportStack;
InitializeHttpTransportnull127     function  InitializeHttpTransport( const aTimeoutSetting : Integer; const aConfig : IThriftConfiguration = nil) : IHTTPClient;
128 
129     procedure JSONProtocolReadWriteTest;
PrepareBinaryDatanull130     function  PrepareBinaryData( aRandomDist : Boolean; aSize : TTestSize) : TBytes;
131     {$IFDEF StressTest}
132     procedure StressTest(const client : TThriftTest.Iface);
133     {$ENDIF}
134     {$IFDEF Win64}
135     procedure UseInterlockedExchangeAdd64;
136     {$ENDIF}
137   protected
138     procedure Execute; override;
139   public
140     constructor Create( const aSetup : TTestSetup; const aNumIteration: Integer);
141     destructor Destroy; override;
142   end;
143 
144   TTestClient = class
145   private
146     class var
147       FNumIteration : Integer;
148       FNumThread : Integer;
149 
150     class procedure PrintCmdLineHelp;
151     class procedure InvalidArgs;
152   public
Executenull153     class function Execute( const arguments: array of string) : Byte;
154   end;
155 
156 
157 implementation
158 
159 const
160    EXITCODE_SUCCESS           = $00;  // no errors bits set
161    //
162    EXITCODE_FAILBIT_BASETYPES  = $01;
163    EXITCODE_FAILBIT_STRUCTS    = $02;
164    EXITCODE_FAILBIT_CONTAINERS = $04;
165    EXITCODE_FAILBIT_EXCEPTIONS = $08;
166 
167    MAP_FAILURES_TO_EXITCODE_BITS : array[TClientThread.TTestGroup] of Byte = (
168      EXITCODE_SUCCESS,  // no bits here
169      EXITCODE_FAILBIT_BASETYPES,
170      EXITCODE_FAILBIT_STRUCTS,
171      EXITCODE_FAILBIT_CONTAINERS,
172      EXITCODE_FAILBIT_EXCEPTIONS
173    );
174 
175 
176 
BoolToStringnull177 function BoolToString( b : Boolean) : string;
178 // overrides global BoolToString()
179 begin
180   if b
181   then result := 'true'
182   else result := 'false';
183 end;
184 
185 // not available in all versions, so make sure we have this one imported
IsDebuggerPresentnull186 function IsDebuggerPresent: BOOL; stdcall; external KERNEL32 name 'IsDebuggerPresent';
187 
188 { TTestClient }
189 
190 class procedure TTestClient.PrintCmdLineHelp;
191 const HELPTEXT = ' [options]'#10
192                + #10
193                + 'Allowed options:'#10
194                + '  -h | --help                   Produces this help message'#10
195                + '  --host=arg (localhost)        Host to connect'#10
196                + '  --port=arg (9090)             Port number to connect'#10
197                + '  --pipe=arg                    Windows Named Pipe (e.g. MyThriftPipe)'#10
198                + '  --anon-pipes hRead hWrite     Windows Anonymous Pipes pair (handles)'#10
199                + '  --transport=arg (sockets)     Transport: buffered, framed, http, winhttp'#10
200                + '  --protocol=arg (binary)       Protocol: binary, compact, json'#10
201                + '  --ssl                         Encrypted Transport using SSL'#10
202                + '  -n=num | --testloops=num (1)  Number of Tests'#10
203                + '  -t=num | --threads=num (1)    Number of Test threads'#10
204                + '  --performance                 Run the built-in performance test (no other arguments)'#10
205                ;
206 begin
207   Writeln( ChangeFileExt(ExtractFileName(ParamStr(0)),'') + HELPTEXT);
208 end;
209 
210 class procedure TTestClient.InvalidArgs;
211 begin
212   Console.WriteLine( 'Invalid args.');
213   Console.WriteLine( ChangeFileExt(ExtractFileName(ParamStr(0)),'') + ' -h for more information');
214   Abort;
215 end;
216 
TTestClient.Executenull217 class function TTestClient.Execute(const arguments: array of string) : Byte;
218 
IsSwitchnull219   function IsSwitch( const aArgument, aSwitch : string; out sValue : string) : Boolean;
220   begin
221     sValue := '';
222     result := (Copy( aArgument, 1, Length(aSwitch)) = aSwitch);
223     if result then begin
224       if (Copy( aArgument, 1, Length(aSwitch)+1) = (aSwitch+'='))
225       then sValue := Copy( aArgument, Length(aSwitch)+2, MAXINT);
226     end;
227   end;
228 
229 var
230   iArg : Integer;
231   threadExitCode : Byte;
232   sArg, sValue : string;
233   threads : array of TThread;
234   dtStart : TDateTime;
235   test : Integer;
236   thread : TThread;
237   setup : TTestSetup;
238 begin
239   // init record
240   with setup do begin
241     protType   := prot_Binary;
242     endpoint   := trns_Sockets;
243     layered    := [];
244     useSSL     := FALSE;
245     host       := 'localhost';
246     port       := 9090;
247     sPipeName  := '';
248     hAnonRead  := INVALID_HANDLE_VALUE;
249     hAnonWrite := INVALID_HANDLE_VALUE;
250   end;
251 
252   try
253     iArg := 0;
254     while iArg < Length(arguments) do begin
255       sArg := arguments[iArg];
256       Inc(iArg);
257 
258       if IsSwitch( sArg, '-h', sValue)
259       or IsSwitch( sArg, '--help', sValue)
260       then begin
261         // -h [ --help ]               produce help message
262         PrintCmdLineHelp;
263         result := $FF;   // all tests failed
264         Exit;
265       end
266       else if IsSwitch( sArg, '--host', sValue) then begin
267         // --host arg (=localhost)     Host to connect
268         setup.host := sValue;
269       end
270       else if IsSwitch( sArg, '--port', sValue) then begin
271         // --port arg (=9090)          Port number to connect
272         setup.port := StrToIntDef(sValue,0);
273         if setup.port <= 0 then InvalidArgs;
274       end
275       else if IsSwitch( sArg, '--domain-socket', sValue) then begin
276         // --domain-socket arg         Domain Socket (e.g. /tmp/ThriftTest.thrift), instead of host and port
277         raise Exception.Create('domain-socket not supported');
278       end
279         // --pipe arg                 Windows Named Pipe (e.g. MyThriftPipe)
280       else if IsSwitch( sArg, '--pipe', sValue) then begin
281         // --pipe arg                 Windows Named Pipe (e.g. MyThriftPipe)
282         setup.endpoint := trns_NamedPipes;
283         setup.sPipeName := sValue;
284         Console.WriteLine('Using named pipe ('+setup.sPipeName+')');
285       end
286       else if IsSwitch( sArg, '--anon-pipes', sValue) then begin
287         // --anon-pipes hRead hWrite   Windows Anonymous Pipes pair (handles)
288         setup.endpoint := trns_AnonPipes;
289         setup.hAnonRead := THandle( StrToIntDef( arguments[iArg], Integer(INVALID_HANDLE_VALUE)));
290         Inc(iArg);
291         setup.hAnonWrite := THandle( StrToIntDef( arguments[iArg], Integer(INVALID_HANDLE_VALUE)));
292         Inc(iArg);
293         Console.WriteLine('Using anonymous pipes ('+IntToStr(Integer(setup.hAnonRead))+' and '+IntToStr(Integer(setup.hAnonWrite))+')');
294       end
295       else if IsSwitch( sArg, '--transport', sValue) then begin
296         // --transport arg (=sockets)  Transport: buffered, framed, http, winhttp, evhttp
297         if      sValue = 'buffered' then Include( setup.layered, trns_Buffered)
298         else if sValue = 'framed'   then Include( setup.layered, trns_Framed)
299         else if sValue = 'http'     then setup.endpoint := trns_MsXmlHttp
300         else if sValue = 'winhttp'  then setup.endpoint := trns_WinHttp
301         else if sValue = 'evhttp'   then setup.endpoint := trns_EvHttp  // recognized, but not supported
302         else InvalidArgs;
303       end
304       else if IsSwitch( sArg, '--protocol', sValue) then begin
305         // --protocol arg (=binary)    Protocol: binary, compact, json
306         if      sValue = 'binary'   then setup.protType := prot_Binary
307         else if sValue = 'compact'  then setup.protType := prot_Compact
308         else if sValue = 'json'     then setup.protType := prot_JSON
309         else InvalidArgs;
310       end
311       else if IsSwitch( sArg, '--ssl', sValue) then begin
312         // --ssl                       Encrypted Transport using SSL
313         setup.useSSL := TRUE;
314 
315       end
316       else if IsSwitch( sArg, '-n', sValue) or IsSwitch( sArg, '--testloops', sValue) then begin
317         // -n [ --testloops ] arg (=1) Number of Tests
318         FNumIteration := StrToIntDef( sValue, 0);
319         if FNumIteration <= 0
320         then InvalidArgs;
321 
322       end
323       else if IsSwitch( sArg, '-t', sValue) or IsSwitch( sArg, '--threads', sValue) then begin
324         // -t [ --threads ] arg (=1)   Number of Test threads
325         FNumThread := StrToIntDef( sValue, 0);
326         if FNumThread <= 0
327         then InvalidArgs;
328       end
329       else if IsSwitch( sArg, '--performance', sValue) then begin
330         result := TPerformanceTests.Execute;
331         Exit;
332       end
333       else begin
334         InvalidArgs;
335       end;
336     end;
337 
338 
339     // In the anonymous pipes mode the client is launched by the test server
340     // -> behave nicely and allow for attaching a debugger to this process
341     if (setup.endpoint = trns_AnonPipes) and not IsDebuggerPresent
342     then MessageBox( 0, 'Attach Debugger and/or click OK to continue.',
343                         'Thrift TestClient (Delphi)',
344                         MB_OK or MB_ICONEXCLAMATION);
345 
346     SetLength( threads, FNumThread);
347     dtStart := Now;
348 
349     // layered transports are not really meant to be stacked upon each other
350     if (trns_Framed in setup.layered) then begin
351       Console.WriteLine('Using framed transport');
352     end
353     else if (trns_Buffered in setup.layered) then begin
354       Console.WriteLine('Using buffered transport');
355     end;
356 
357     Console.WriteLine(THRIFT_PROTOCOLS[setup.protType]+' protocol');
358 
359     for test := 0 to FNumThread - 1 do begin
360       thread := TClientThread.Create( setup, FNumIteration);
361       threads[test] := thread;
362       thread.Start;
363     end;
364 
365     result := 0;
366     for test := 0 to FNumThread - 1 do begin
367       threadExitCode := threads[test].WaitFor;
368       result := result or threadExitCode;
369       threads[test].Free;
370       threads[test] := nil;
371     end;
372 
373     Console.Write('Total time: ' + IntToStr( MilliSecondsBetween(Now, dtStart)));
374 
375   except
376     on E: EAbort do raise;
377     on E: Exception do begin
378       Console.WriteLine( E.Message + #10 + E.StackTrace);
379       raise;
380     end;
381   end;
382 
383   Console.WriteLine('');
384   Console.WriteLine('done!');
385 end;
386 
387 { TClientThread }
388 
389 procedure TClientThread.ClientTest;
390 var
391   client : TThriftTest.Iface;
392   s : string;
393   i8 : ShortInt;
394   i32 : Integer;
395   i64 : Int64;
396   binOut,binIn : TBytes;
397   dub : Double;
398   o : IXtruct;
399   o2 : IXtruct2;
400   i : IXtruct;
401   i2 : IXtruct2;
402   mapout : IThriftDictionary<Integer,Integer>;
403   mapin : IThriftDictionary<Integer,Integer>;
404   strmapout : IThriftDictionary<string,string>;
405   strmapin : IThriftDictionary<string,string>;
406   j : Integer;
407   first : Boolean;
408   key : Integer;
409   strkey : string;
410   listout : IThriftList<Integer>;
411   listin : IThriftList<Integer>;
412   setout : IHashSet<Integer>;
413   setin : IHashSet<Integer>;
414   ret : TNumberz;
415   uid : Int64;
416   mm : IThriftDictionary<Integer, IThriftDictionary<Integer, Integer>>;
417   pos : IThriftDictionary<Integer, Integer>;
418   neg : IThriftDictionary<Integer, Integer>;
419   m2 : IThriftDictionary<Integer, Integer>;
420   k2 : Integer;
421   insane : IInsanity;
422   truck : IXtruct;
423   whoa : IThriftDictionary<Int64, IThriftDictionary<TNumberz, IInsanity>>;
424   key64 : Int64;
425   val : IThriftDictionary<TNumberz, IInsanity>;
426   k2_2 : TNumberz;
427   k3 : TNumberz;
428   v2 : IInsanity;
429   userMap : IThriftDictionary<TNumberz, Int64>;
430   xtructs : IThriftList<IXtruct>;
431   x : IXtruct;
432   arg0 : ShortInt;
433   arg1 : Integer;
434   arg2 : Int64;
435   arg3 : IThriftDictionary<SmallInt, string>;
436   arg4 : TNumberz;
437   arg5 : Int64;
438   {$IFDEF PerfTest}
439   StartTick : Cardinal;
440   k : Integer;
441   {$ENDIF}
442   hello, goodbye : IXtruct;
443   crazy : IInsanity;
444   looney : IInsanity;
445   first_map : IThriftDictionary<TNumberz, IInsanity>;
446   second_map : IThriftDictionary<TNumberz, IInsanity>;
447   pair : TPair<TNumberz, TUserId>;
448   testsize : TTestSize;
449 begin
450   client := TThriftTest.TClient.Create( FProtocol);
451   FTransport.Open;
452 
453   {$IFDEF StressTest}
454   StressTest( client);
455   {$ENDIF StressTest}
456 
457   {$IFDEF Exceptions}
458   // in-depth exception test
459   // (1) do we get an exception at all?
460   // (2) do we get the right exception?
461   // (3) does the exception contain the expected data?
462   StartTestGroup( 'testException', test_Exceptions);
callnull463   // case 1: exception type declared in IDL at the function call
464   try
465     client.testException('Xception');
466     Expect( FALSE, 'testException(''Xception''): must trow an exception');
467   except
468     on e:TXception do begin
469       Expect( e.ErrorCode = 1001,       'error code');
470       Expect( e.Message_  = 'Xception', 'error message');
471       Console.WriteLine( ' = ' + IntToStr(e.ErrorCode) + ', ' + e.Message_ );
472     end;
473     on e:TTransportException do Expect( FALSE, 'Unexpected : "'+e.ToString+'"');
474     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
475   end;
476 
callnull477   // case 2: exception type NOT declared in IDL at the function call
478   // this will close the connection
479   try
480     client.testException('TException');
481     Expect( FALSE, 'testException(''TException''): must trow an exception');
482   except
483     on e:TTransportException do begin
484       Console.WriteLine( e.ClassName+' = '+e.Message); // this is what we get
485     end;
486     on e:TApplicationException do begin
487       Console.WriteLine( e.ClassName+' = '+e.Message); // this is what we get
488     end;
489     on e:TException do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
490     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
491   end;
492 
493 
494   if FTransport.IsOpen then FTransport.Close;
495   FTransport.Open;   // re-open connection, server has already closed
496 
497 
498   // case 3: no exception
499   try
500     client.testException('something');
501     Expect( TRUE, 'testException(''something''): must not trow an exception');
502   except
503     on e:TTransportException do Expect( FALSE, 'Unexpected : "'+e.ToString+'"');
504     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
505   end;
506   {$ENDIF Exceptions}
507 
508 
509   // simple things
510   StartTestGroup( 'simple Thrift calls', test_BaseTypes);
511   client.testVoid();
512   Expect( TRUE, 'testVoid()');  // success := no exception
513 
514   s := BoolToString( client.testBool(TRUE));
515   Expect( s = BoolToString(TRUE),  'testBool(TRUE) = '+s);
516   s := BoolToString( client.testBool(FALSE));
517   Expect( s = BoolToString(FALSE),  'testBool(FALSE) = '+s);
518 
519   s := client.testString('Test');
520   Expect( s = 'Test', 'testString(''Test'') = "'+s+'"');
521 
522   s := client.testString('');  // empty string
523   Expect( s = '', 'testString('''') = "'+s+'"');
524 
525   s := client.testString(HUGE_TEST_STRING);
526   Expect( length(s) = length(HUGE_TEST_STRING),
527           'testString( length(HUGE_TEST_STRING) = '+IntToStr(Length(HUGE_TEST_STRING))+') '
528          +'=> length(result) = '+IntToStr(Length(s)));
529 
530   i8 := client.testByte(1);
531   Expect( i8 = 1, 'testByte(1) = ' + IntToStr( i8 ));
532 
533   i32 := client.testI32(-1);
534   Expect( i32 = -1, 'testI32(-1) = ' + IntToStr(i32));
535 
536   Console.WriteLine('testI64(-34359738368)');
537   i64 := client.testI64(-34359738368);
538   Expect( i64 = -34359738368, 'testI64(-34359738368) = ' + IntToStr( i64));
539 
540   // random binary small
541   for testsize := Low(TTestSize) to High(TTestSize) do begin
542     binOut := PrepareBinaryData( TRUE, testsize);
543     Console.WriteLine('testBinary('+IntToStr(Length(binOut))+' bytes)');
544     try
545       binIn := client.testBinary(binOut);
546       Expect( Length(binOut) = Length(binIn), 'testBinary('+IntToStr(Length(binOut))+' bytes): '+IntToStr(Length(binIn))+' bytes received');
547       i32 := Min( Length(binOut), Length(binIn));
548       Expect( CompareMem( binOut, binIn, i32), 'testBinary('+IntToStr(Length(binOut))+' bytes): validating received data');
549     except
550       on e:TApplicationException do Console.WriteLine('testBinary(): '+e.Message);
551       on e:Exception do Expect( FALSE, 'testBinary(): Unexpected exception "'+e.ClassName+'": '+e.Message);
552     end;
553   end;
554 
555   Console.WriteLine('testDouble(5.325098235)');
556   dub := client.testDouble(5.325098235);
557   Expect( abs(dub-5.325098235) < 1e-14, 'testDouble(5.325098235) = ' + FloatToStr( dub));
558 
559   // structs
560   StartTestGroup( 'testStruct', test_Structs);
561   Console.WriteLine('testStruct({''Zero'', 1, -3, -5})');
562   o := TXtructImpl.Create;
563   o.String_thing := 'Zero';
564   o.Byte_thing := 1;
565   o.I32_thing := -3;
566   o.I64_thing := -5;
567   i := client.testStruct(o);
568   Expect( i.String_thing = 'Zero', 'i.String_thing = "'+i.String_thing+'"');
569   Expect( i.Byte_thing = 1, 'i.Byte_thing = '+IntToStr(i.Byte_thing));
570   Expect( i.I32_thing = -3, 'i.I32_thing = '+IntToStr(i.I32_thing));
571   Expect( i.I64_thing = -5, 'i.I64_thing = '+IntToStr(i.I64_thing));
572   Expect( i.__isset_String_thing, 'i.__isset_String_thing = '+BoolToString(i.__isset_String_thing));
573   Expect( i.__isset_Byte_thing, 'i.__isset_Byte_thing = '+BoolToString(i.__isset_Byte_thing));
574   Expect( i.__isset_I32_thing, 'i.__isset_I32_thing = '+BoolToString(i.__isset_I32_thing));
575   Expect( i.__isset_I64_thing, 'i.__isset_I64_thing = '+BoolToString(i.__isset_I64_thing));
576 
577   // nested structs
578   StartTestGroup( 'testNest', test_Structs);
579   Console.WriteLine('testNest({1, {''Zero'', 1, -3, -5}, 5})');
580   o2 := TXtruct2Impl.Create;
581   o2.Byte_thing := 1;
582   o2.Struct_thing := o;
583   o2.I32_thing := 5;
584   i2 := client.testNest(o2);
585   i := i2.Struct_thing;
586   Expect( i.String_thing = 'Zero', 'i.String_thing = "'+i.String_thing+'"');
587   Expect( i.Byte_thing = 1,  'i.Byte_thing = '+IntToStr(i.Byte_thing));
588   Expect( i.I32_thing = -3,  'i.I32_thing = '+IntToStr(i.I32_thing));
589   Expect( i.I64_thing = -5,  'i.I64_thing = '+IntToStr(i.I64_thing));
590   Expect( i2.Byte_thing = 1, 'i2.Byte_thing = '+IntToStr(i2.Byte_thing));
591   Expect( i2.I32_thing = 5,  'i2.I32_thing = '+IntToStr(i2.I32_thing));
592   Expect( i.__isset_String_thing, 'i.__isset_String_thing = '+BoolToString(i.__isset_String_thing));
593   Expect( i.__isset_Byte_thing,  'i.__isset_Byte_thing = '+BoolToString(i.__isset_Byte_thing));
594   Expect( i.__isset_I32_thing,  'i.__isset_I32_thing = '+BoolToString(i.__isset_I32_thing));
595   Expect( i.__isset_I64_thing,  'i.__isset_I64_thing = '+BoolToString(i.__isset_I64_thing));
596   Expect( i2.__isset_Byte_thing, 'i2.__isset_Byte_thing');
597   Expect( i2.__isset_I32_thing,  'i2.__isset_I32_thing');
598 
599   // map<type1,type2>: A map of strictly unique keys to values.
600   // Translates to an STL map, Java HashMap, PHP associative array, Python/Ruby dictionary, etc.
601   StartTestGroup( 'testMap', test_Containers);
602   mapout := TThriftDictionaryImpl<Integer,Integer>.Create;
603   for j := 0 to 4 do
604   begin
605     mapout.AddOrSetValue( j, j - 10);
606   end;
607   Console.Write('testMap({');
608   first := True;
609   for key in mapout.Keys do
610   begin
611     if first
612     then first := False
613     else Console.Write( ', ' );
614     Console.Write( IntToStr( key) + ' => ' + IntToStr( mapout[key]));
615   end;
616   Console.WriteLine('})');
617 
618   mapin := client.testMap( mapout );
619   Expect( mapin.Count = mapout.Count, 'testMap: mapin.Count = mapout.Count');
620   for j := 0 to 4 do
621   begin
622     Expect( mapout.ContainsKey(j), 'testMap: mapout.ContainsKey('+IntToStr(j)+') = '+BoolToString(mapout.ContainsKey(j)));
623   end;
624   for key in mapin.Keys do
625   begin
626     Expect( mapin[key] = mapout[key], 'testMap: '+IntToStr(key) + ' => ' + IntToStr( mapin[key]));
627     Expect( mapin[key] = key - 10, 'testMap: mapin['+IntToStr(key)+'] = '+IntToStr( mapin[key]));
628   end;
629 
630 
631   // map<type1,type2>: A map of strictly unique keys to values.
632   // Translates to an STL map, Java HashMap, PHP associative array, Python/Ruby dictionary, etc.
633   StartTestGroup( 'testStringMap', test_Containers);
634   strmapout := TThriftDictionaryImpl<string,string>.Create;
635   for j := 0 to 4 do
636   begin
637     strmapout.AddOrSetValue( IntToStr(j), IntToStr(j - 10));
638   end;
639   Console.Write('testStringMap({');
640   first := True;
641   for strkey in strmapout.Keys do
642   begin
643     if first
644     then first := False
645     else Console.Write( ', ' );
646     Console.Write( strkey + ' => ' + strmapout[strkey]);
647   end;
648   Console.WriteLine('})');
649 
650   strmapin := client.testStringMap( strmapout );
651   Expect( strmapin.Count = strmapout.Count, 'testStringMap: strmapin.Count = strmapout.Count');
652   for j := 0 to 4 do
653   begin
654     Expect( strmapout.ContainsKey(IntToStr(j)),
655             'testStringMap: strmapout.ContainsKey('+IntToStr(j)+') = '
656             + BoolToString(strmapout.ContainsKey(IntToStr(j))));
657   end;
658   for strkey in strmapin.Keys do
659   begin
660     Expect( strmapin[strkey] = strmapout[strkey], 'testStringMap: '+strkey + ' => ' + strmapin[strkey]);
661     Expect( strmapin[strkey] = IntToStr( StrToInt(strkey) - 10), 'testStringMap: strmapin['+strkey+'] = '+strmapin[strkey]);
662   end;
663 
664 
665   // set<type>: An unordered set of unique elements.
666   // Translates to an STL set, Java HashSet, set in Python, etc.
667   // Note: PHP does not support sets, so it is treated similar to a List
668   StartTestGroup( 'testSet', test_Containers);
669   setout := THashSetImpl<Integer>.Create;
670   for j := -2 to 2 do
671   begin
672     setout.Add( j );
673   end;
674   Console.Write('testSet({');
675   first := True;
676   for j in setout do
677   begin
678     if first
679     then first := False
680     else Console.Write(', ');
681     Console.Write(IntToStr( j));
682   end;
683   Console.WriteLine('})');
684 
685   setin := client.testSet(setout);
686   Expect( setin.Count = setout.Count, 'testSet: setin.Count = setout.Count');
687   Expect( setin.Count = 5, 'testSet: setin.Count = '+IntToStr(setin.Count));
688   for j := -2 to 2 do // unordered, we can't rely on the order => test for known elements only
689   begin
690     Expect( setin.Contains(j), 'testSet: setin.Contains('+IntToStr(j)+') => '+BoolToString(setin.Contains(j)));
691   end;
692 
693   // list<type>: An ordered list of elements.
694   // Translates to an STL vector, Java ArrayList, native arrays in scripting languages, etc.
695   StartTestGroup( 'testList', test_Containers);
696   listout := TThriftListImpl<Integer>.Create;
697   listout.Add( +1);
698   listout.Add( -2);
699   listout.Add( +3);
700   listout.Add( -4);
701   listout.Add( 0);
702   Console.Write('testList({');
703   first := True;
704   for j in listout do
705     begin
706     if first
707     then first := False
708     else Console.Write(', ');
709     Console.Write(IntToStr( j));
710   end;
711   Console.WriteLine('})');
712 
713   listin := client.testList(listout);
714   Expect( listin.Count = listout.Count, 'testList: listin.Count = listout.Count');
715   Expect( listin.Count = 5, 'testList: listin.Count = '+IntToStr(listin.Count));
716   Expect( listin[0] = +1, 'listin[0] = '+IntToStr( listin[0]));
717   Expect( listin[1] = -2, 'listin[1] = '+IntToStr( listin[1]));
718   Expect( listin[2] = +3, 'listin[2] = '+IntToStr( listin[2]));
719   Expect( listin[3] = -4, 'listin[3] = '+IntToStr( listin[3]));
720   Expect( listin[4] = 0,  'listin[4] = '+IntToStr( listin[4]));
721 
722   // enums
723   ret := client.testEnum(TNumberz.ONE);
724   Expect( ret = TNumberz.ONE, 'testEnum(ONE) = '+IntToStr(Ord(ret)));
725 
726   ret := client.testEnum(TNumberz.TWO);
727   Expect( ret = TNumberz.TWO, 'testEnum(TWO) = '+IntToStr(Ord(ret)));
728 
729   ret := client.testEnum(TNumberz.THREE);
730   Expect( ret = TNumberz.THREE, 'testEnum(THREE) = '+IntToStr(Ord(ret)));
731 
732   ret := client.testEnum(TNumberz.FIVE);
733   Expect( ret = TNumberz.FIVE, 'testEnum(FIVE) = '+IntToStr(Ord(ret)));
734 
735   ret := client.testEnum(TNumberz.EIGHT);
736   Expect( ret = TNumberz.EIGHT, 'testEnum(EIGHT) = '+IntToStr(Ord(ret)));
737 
738 
739   // typedef
740   uid := client.testTypedef(309858235082523);
741   Expect( uid = 309858235082523, 'testTypedef(309858235082523) = '+IntToStr(uid));
742 
743 
744   // maps of maps
745   StartTestGroup( 'testMapMap(1)', test_Containers);
746   mm := client.testMapMap(1);
747   Console.Write(' = {');
748   for key in mm.Keys do
749   begin
750     Console.Write( IntToStr( key) + ' => {');
751     m2 := mm[key];
752     for  k2 in m2.Keys do
753     begin
754       Console.Write( IntToStr( k2) + ' => ' + IntToStr( m2[k2]) + ', ');
755     end;
756     Console.Write('}, ');
757   end;
758   Console.WriteLine('}');
759 
760   // verify result data
761   Expect( mm.Count = 2, 'mm.Count = '+IntToStr(mm.Count));
762   pos := mm[4];
763   neg := mm[-4];
764   for j := 1 to 4 do
765   begin
766     Expect( pos[j]  = j,  'pos[j]  = '+IntToStr(pos[j]));
767     Expect( neg[-j] = -j, 'neg[-j] = '+IntToStr(neg[-j]));
768   end;
769 
770 
771 
772   // insanity
773   StartTestGroup( 'testInsanity', test_Structs);
774   insane := TInsanityImpl.Create;
775   insane.UserMap := TThriftDictionaryImpl<TNumberz, Int64>.Create;
776   insane.UserMap.AddOrSetValue( TNumberz.FIVE, 5000);
777   truck := TXtructImpl.Create;
778   truck.String_thing := 'Truck';
779   truck.Byte_thing := -8;  // byte is signed
780   truck.I32_thing := 32;
781   truck.I64_thing := 64;
782   insane.Xtructs := TThriftListImpl<IXtruct>.Create;
783   insane.Xtructs.Add( truck );
784   whoa := client.testInsanity( insane );
785   Console.Write(' = {');
786   for key64 in whoa.Keys do
787   begin
788     val := whoa[key64];
789     Console.Write( IntToStr( key64) + ' => {');
790     for k2_2 in val.Keys do
791     begin
792       v2 := val[k2_2];
793       Console.Write( IntToStr( Integer( k2_2)) + ' => {');
794       userMap := v2.UserMap;
795       Console.Write('{');
796       if userMap <> nil then
797       begin
798         for k3 in userMap.Keys do
799         begin
800           Console.Write( IntToStr( Integer( k3)) + ' => ' + IntToStr( userMap[k3]) + ', ');
801         end;
802       end else
803       begin
804         Console.Write('null');
805       end;
806       Console.Write('}, ');
807       xtructs := v2.Xtructs;
808       Console.Write('{');
809 
810       if xtructs <> nil then
811       begin
812         for x in xtructs do
813         begin
814           Console.Write('{"' + x.String_thing + '", ' +
815             IntToStr( x.Byte_thing) + ', ' +
816             IntToStr( x.I32_thing) + ', ' +
817             IntToStr( x.I32_thing) + '}, ');
818         end;
819       end else
820       begin
821         Console.Write('null');
822       end;
823       Console.Write('}');
824       Console.Write('}, ');
825     end;
826     Console.Write('}, ');
827   end;
828   Console.WriteLine('}');
829 
830   (**
831    * So you think you've got this all worked, out eh?
832    *
833    * Creates a the returned map with these values and prints it out:
834    *   { 1 => { 2 => argument,
835    *            3 => argument,
836    *          },
837    *     2 => { 6 => <empty Insanity struct>, },
838    *   }
839    * @return map<UserId, map<Numberz,Insanity>> - a map with the above values
840    *)
841 
842   // verify result data
843   Expect( whoa.Count = 2, 'whoa.Count = '+IntToStr(whoa.Count));
844   //
845   first_map  := whoa[1];
846   second_map := whoa[2];
847   Expect( first_map.Count = 2, 'first_map.Count = '+IntToStr(first_map.Count));
848   Expect( second_map.Count = 1, 'second_map.Count = '+IntToStr(second_map.Count));
849   //
850   looney := second_map[TNumberz.SIX];
851   Expect( Assigned(looney), 'Assigned(looney) = '+BoolToString(Assigned(looney)));
852   Expect( not looney.__isset_UserMap, 'looney.__isset_UserMap = '+BoolToString(looney.__isset_UserMap));
853   Expect( not looney.__isset_Xtructs, 'looney.__isset_Xtructs = '+BoolToString(looney.__isset_Xtructs));
854   //
855   for ret in [TNumberz.TWO, TNumberz.THREE] do begin
856     crazy := first_map[ret];
857     Console.WriteLine('first_map['+intToStr(Ord(ret))+']');
858 
859     Expect( crazy.__isset_UserMap, 'crazy.__isset_UserMap = '+BoolToString(crazy.__isset_UserMap));
860     Expect( crazy.__isset_Xtructs, 'crazy.__isset_Xtructs = '+BoolToString(crazy.__isset_Xtructs));
861 
862     Expect( crazy.UserMap.Count = insane.UserMap.Count, 'crazy.UserMap.Count = '+IntToStr(crazy.UserMap.Count));
863     for pair in insane.UserMap do begin
864       Expect( crazy.UserMap[pair.Key] = pair.Value, 'crazy.UserMap['+IntToStr(Ord(pair.key))+'] = '+IntToStr(crazy.UserMap[pair.Key]));
865     end;
866 
867     Expect( crazy.Xtructs.Count = insane.Xtructs.Count, 'crazy.Xtructs.Count = '+IntToStr(crazy.Xtructs.Count));
868     for arg0 := 0 to insane.Xtructs.Count-1 do begin
869       hello   := insane.Xtructs[arg0];
870       goodbye := crazy.Xtructs[arg0];
871       Expect( goodbye.String_thing = hello.String_thing, 'goodbye.String_thing = '+goodbye.String_thing);
872       Expect( goodbye.Byte_thing = hello.Byte_thing, 'goodbye.Byte_thing = '+IntToStr(goodbye.Byte_thing));
873       Expect( goodbye.I32_thing = hello.I32_thing, 'goodbye.I32_thing = '+IntToStr(goodbye.I32_thing));
874       Expect( goodbye.I64_thing = hello.I64_thing, 'goodbye.I64_thing = '+IntToStr(goodbye.I64_thing));
875     end;
876   end;
877 
878 
879   // multi args
880   StartTestGroup( 'testMulti', test_BaseTypes);
881   arg0 := 1;
882   arg1 := 2;
883   arg2 := High(Int64);
884   arg3 := TThriftDictionaryImpl<SmallInt, string>.Create;
885   arg3.AddOrSetValue( 1, 'one');
886   arg4 := TNumberz.FIVE;
887   arg5 := 5000000;
888   Console.WriteLine('Test Multi(' + IntToStr( arg0) + ',' +
889     IntToStr( arg1) + ',' + IntToStr( arg2) + ',' +
890     arg3.ToString + ',' + IntToStr( Integer( arg4)) + ',' +
891       IntToStr( arg5) + ')');
892 
893   i := client.testMulti( arg0, arg1, arg2, arg3, arg4, arg5);
894   Expect( i.String_thing = 'Hello2', 'testMulti: i.String_thing = "'+i.String_thing+'"');
895   Expect( i.Byte_thing = arg0, 'testMulti: i.Byte_thing = '+IntToStr(i.Byte_thing));
896   Expect( i.I32_thing = arg1, 'testMulti: i.I32_thing = '+IntToStr(i.I32_thing));
897   Expect( i.I64_thing = arg2, 'testMulti: i.I64_thing = '+IntToStr(i.I64_thing));
898   Expect( i.__isset_String_thing, 'testMulti: i.__isset_String_thing = '+BoolToString(i.__isset_String_thing));
899   Expect( i.__isset_Byte_thing, 'testMulti: i.__isset_Byte_thing = '+BoolToString(i.__isset_Byte_thing));
900   Expect( i.__isset_I32_thing, 'testMulti: i.__isset_I32_thing = '+BoolToString(i.__isset_I32_thing));
901   Expect( i.__isset_I64_thing, 'testMulti: i.__isset_I64_thing = '+BoolToString(i.__isset_I64_thing));
902 
903   // multi exception
904   StartTestGroup( 'testMultiException(1)', test_Exceptions);
905   try
906     i := client.testMultiException( 'need more pizza', 'run out of beer');
907     Expect( i.String_thing = 'run out of beer', 'i.String_thing = "' +i.String_thing+ '"');
908     Expect( i.__isset_String_thing, 'i.__isset_String_thing = '+BoolToString(i.__isset_String_thing));
909     { this is not necessarily true, these fields are default-serialized
910     Expect( not i.__isset_Byte_thing, 'i.__isset_Byte_thing = '+BoolToString(i.__isset_Byte_thing));
911     Expect( not i.__isset_I32_thing, 'i.__isset_I32_thing = '+BoolToString(i.__isset_I32_thing));
912     Expect( not i.__isset_I64_thing, 'i.__isset_I64_thing = '+BoolToString(i.__isset_I64_thing));
913     }
914   except
915     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
916   end;
917 
918   StartTestGroup( 'testMultiException(Xception)', test_Exceptions);
919   try
920     i := client.testMultiException( 'Xception', 'second test');
921     Expect( FALSE, 'testMultiException(''Xception''): must trow an exception');
922   except
923     on x:TXception do begin
924       Expect( x.__isset_ErrorCode, 'x.__isset_ErrorCode = '+BoolToString(x.__isset_ErrorCode));
925       Expect( x.__isset_Message_,  'x.__isset_Message_ = '+BoolToString(x.__isset_Message_));
926       Expect( x.ErrorCode = 1001, 'x.ErrorCode = '+IntToStr(x.ErrorCode));
927       Expect( x.Message_ = 'This is an Xception', 'x.Message = "'+x.Message_+'"');
928     end;
929     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
930   end;
931 
932   StartTestGroup( 'testMultiException(Xception2)', test_Exceptions);
933   try
934     i := client.testMultiException( 'Xception2', 'third test');
935     Expect( FALSE, 'testMultiException(''Xception2''): must trow an exception');
936   except
937     on x:TXception2 do begin
938       Expect( x.__isset_ErrorCode, 'x.__isset_ErrorCode = '+BoolToString(x.__isset_ErrorCode));
939       Expect( x.__isset_Struct_thing,  'x.__isset_Struct_thing = '+BoolToString(x.__isset_Struct_thing));
940       Expect( x.ErrorCode = 2002, 'x.ErrorCode = '+IntToStr(x.ErrorCode));
941       Expect( x.Struct_thing.String_thing = 'This is an Xception2', 'x.Struct_thing.String_thing = "'+x.Struct_thing.String_thing+'"');
942       Expect( x.Struct_thing.__isset_String_thing, 'x.Struct_thing.__isset_String_thing = '+BoolToString(x.Struct_thing.__isset_String_thing));
943       { this is not necessarily true, these fields are default-serialized
944       Expect( not x.Struct_thing.__isset_Byte_thing, 'x.Struct_thing.__isset_Byte_thing = '+BoolToString(x.Struct_thing.__isset_Byte_thing));
945       Expect( not x.Struct_thing.__isset_I32_thing, 'x.Struct_thing.__isset_I32_thing = '+BoolToString(x.Struct_thing.__isset_I32_thing));
946       Expect( not x.Struct_thing.__isset_I64_thing, 'x.Struct_thing.__isset_I64_thing = '+BoolToString(x.Struct_thing.__isset_I64_thing));
947       }
948     end;
949     on e:Exception do Expect( FALSE, 'Unexpected exception "'+e.ClassName+'": '+e.Message);
950   end;
951 
952 
953   // oneway functions
954   StartTestGroup( 'Test Oneway(1)', test_Unknown);
955   client.testOneway(1);
956   Expect( TRUE, 'Test Oneway(1)');  // success := no exception
957 
958   // call time
959   {$IFDEF PerfTest}
960   StartTestGroup( 'Test Calltime()');
961   StartTick := GetTickCount;
962   for k := 0 to 1000 - 1 do
963   begin
964     client.testVoid();
965   end;
966   Console.WriteLine(' = ' + FloatToStr( (GetTickCount - StartTick) / 1000 ) + ' ms a testVoid() call' );
967   {$ENDIF PerfTest}
968 
969   // no more tests here
970   StartTestGroup( '', test_Unknown);
971 end;
972 
973 
974 {$IFDEF SupportsAsync}
975 procedure TClientThread.ClientAsyncTest;
976 var
977   client : TThriftTest.IAsync;
978   s : string;
979   i8 : ShortInt;
980 begin
981   StartTestGroup( 'Async Tests', test_Unknown);
982   client := TThriftTest.TClient.Create( FProtocol);
983   FTransport.Open;
984 
985   // oneway void functions
986   client.testOnewayAsync(1).Wait;
987   Expect( TRUE, 'Test Oneway(1)');  // success := no exception
988 
989   // normal functions
990   s := client.testStringAsync(HUGE_TEST_STRING).Value;
991   Expect( length(s) = length(HUGE_TEST_STRING),
992           'testString( length(HUGE_TEST_STRING) = '+IntToStr(Length(HUGE_TEST_STRING))+') '
993          +'=> length(result) = '+IntToStr(Length(s)));
994 
995   i8 := client.testByte(1).Value;
996   Expect( i8 = 1, 'testByte(1) = ' + IntToStr( i8 ));
997 end;
998 {$ENDIF}
999 
1000 
1001 {$IFDEF StressTest}
1002 procedure TClientThread.StressTest(const client : TThriftTest.Iface);
1003 begin
1004   while TRUE do begin
1005     try
1006       if not FTransport.IsOpen then FTransport.Open;   // re-open connection, server has already closed
1007       try
1008         client.testString('Test');
1009         Write('.');
1010       finally
1011         if FTransport.IsOpen then FTransport.Close;
1012       end;
1013     except
1014       on e:Exception do Writeln(#10+e.message);
1015     end;
1016   end;
1017 end;
1018 {$ENDIF}
1019 
1020 
TClientThread.PrepareBinaryDatanull1021 function TClientThread.PrepareBinaryData( aRandomDist : Boolean; aSize : TTestSize) : TBytes;
1022 var i : Integer;
1023 begin
1024   case aSize of
1025     Empty          : SetLength( result, 0);
1026     Normal         : SetLength( result, $100);
1027     ByteArrayTest  : SetLength( result, SizeOf(TByteArray) + 128);
1028     PipeWriteLimit : SetLength( result, 65535 + 128);
1029     FifteenMB      : SetLength( result, 15 * 1024 * 1024);
1030   else
1031     raise EArgumentException.Create('aSize');
1032   end;
1033 
1034   ASSERT( Low(result) = 0);
1035   if Length(result) = 0 then Exit;
1036 
1037   // linear distribution, unless random is requested
1038   if not aRandomDist then begin
1039     for i := Low(result) to High(result) do begin
1040       result[i] := i mod $100;
1041     end;
1042     Exit;
1043   end;
1044 
1045   // random distribution of all 256 values
1046   FillChar( result[0], Length(result) * SizeOf(result[0]), $0);
1047   for i := Low(result) to High(result) do begin
1048     result[i] := Byte( Random($100));
1049   end;
1050 end;
1051 
1052 
1053 {$IFDEF Win64}
1054 procedure TClientThread.UseInterlockedExchangeAdd64;
1055 var a,b : Int64;
1056 begin
1057   a := 1;
1058   b := 2;
1059   Thrift.Utils.InterlockedExchangeAdd64( a,b);
1060   Expect( a = 3, 'InterlockedExchangeAdd64');
1061 end;
1062 {$ENDIF}
1063 
1064 
1065 procedure TClientThread.JSONProtocolReadWriteTest;
1066 // Tests only then read/write procedures of the JSON protocol
1067 // All tests succeed, if we can read what we wrote before
1068 // Note that passing this test does not imply, that our JSON is really compatible to what
1069 // other clients or servers expect as the real JSON. This is beyond the scope of this test.
1070 var prot   : IProtocol;
1071     stm    : TStringStream;
1072     list   : TThriftList;
1073     config : IThriftConfiguration;
1074     binary, binRead, emptyBinary : TBytes;
1075     i,iErr : Integer;
1076 const
1077   TEST_SHORT   = ShortInt( $FE);
1078   TEST_SMALL   = SmallInt( $FEDC);
1079   TEST_LONG    = LongInt( $FEDCBA98);
1080   TEST_I64     = Int64( $FEDCBA9876543210);
1081   TEST_DOUBLE  = -1.234e-56;
1082   DELTA_DOUBLE = TEST_DOUBLE * 1e-14;
1083   TEST_STRING  = 'abc-'#$00E4#$00f6#$00fc; // german umlauts (en-us: "funny chars")
1084   // Test THRIFT-2336 and THRIFT-3404 with U+1D11E (G Clef symbol) and 'Русское Название';
1085   G_CLEF_AND_CYRILLIC_TEXT = #$1d11e' '#$0420#$0443#$0441#$0441#$043a#$043e#$0435' '#$041d#$0430#$0437#$0432#$0430#$043d#$0438#$0435;
1086   G_CLEF_AND_CYRILLIC_JSON = '"\ud834\udd1e \u0420\u0443\u0441\u0441\u043a\u043e\u0435 \u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435"';
1087   // test both possible solidus encodings
1088   SOLIDUS_JSON_DATA = '"one/two\/three"';
1089   SOLIDUS_EXCPECTED = 'one/two/three';
1090 begin
1091   stm  := TStringStream.Create;
1092   try
1093     StartTestGroup( 'JsonProtocolTest', test_Unknown);
1094 
1095     config := TThriftConfigurationImpl.Create;
1096 
1097     // prepare binary data
1098     binary := PrepareBinaryData( FALSE, Normal);
1099     SetLength( emptyBinary, 0); // empty binary data block
1100 
1101     // output setup
1102     prot := TJSONProtocolImpl.Create(
1103               TStreamTransportImpl.Create(
1104                 nil, TThriftStreamAdapterDelphi.Create( stm, FALSE), config));
1105 
1106     // write
1107     Init( list, TType.String_, 9);
1108     prot.WriteListBegin( list);
1109     prot.WriteBool( TRUE);
1110     prot.WriteBool( FALSE);
1111     prot.WriteByte( TEST_SHORT);
1112     prot.WriteI16( TEST_SMALL);
1113     prot.WriteI32( TEST_LONG);
1114     prot.WriteI64( TEST_I64);
1115     prot.WriteDouble( TEST_DOUBLE);
1116     prot.WriteString( TEST_STRING);
1117     prot.WriteBinary( binary);
1118     prot.WriteString( '');  // empty string
1119     prot.WriteBinary( emptyBinary); // empty binary data block
1120     prot.WriteListEnd;
1121 
1122     // input setup
1123     Expect( stm.Position = stm.Size, 'Stream position/length after write');
1124     stm.Position := 0;
1125     prot := TJSONProtocolImpl.Create(
1126               TStreamTransportImpl.Create(
1127                 TThriftStreamAdapterDelphi.Create( stm, FALSE), nil, config));
1128 
1129     // read and compare
1130     list := prot.ReadListBegin;
1131     Expect( list.ElementType = TType.String_, 'list element type');
1132     Expect( list.Count = 9, 'list element count');
1133     Expect( prot.ReadBool, 'WriteBool/ReadBool: TRUE');
1134     Expect( not prot.ReadBool, 'WriteBool/ReadBool: FALSE');
1135     Expect( prot.ReadByte   = TEST_SHORT,  'WriteByte/ReadByte');
1136     Expect( prot.ReadI16    = TEST_SMALL,  'WriteI16/ReadI16');
1137     Expect( prot.ReadI32    = TEST_LONG,   'WriteI32/ReadI32');
1138     Expect( prot.ReadI64    = TEST_I64,    'WriteI64/ReadI64');
1139     Expect( abs(prot.ReadDouble-TEST_DOUBLE) < abs(DELTA_DOUBLE), 'WriteDouble/ReadDouble');
1140     Expect( prot.ReadString = TEST_STRING, 'WriteString/ReadString');
1141     binRead := prot.ReadBinary;
1142     Expect( Length(prot.ReadString) = 0, 'WriteString/ReadString (empty string)');
1143     Expect( Length(prot.ReadBinary) = 0, 'empty WriteBinary/ReadBinary (empty data block)');
1144     prot.ReadListEnd;
1145 
1146     // test binary data
1147     Expect( Length(binary) = Length(binRead), 'Binary data length check');
1148     iErr := -1;
1149     for i := Low(binary) to High(binary) do begin
1150       if binary[i] <> binRead[i] then begin
1151         iErr := i;
1152         Break;
1153       end;
1154     end;
1155     if iErr < 0
1156     then Expect( TRUE,  'Binary data check ('+IntToStr(Length(binary))+' Bytes)')
1157     else Expect( FALSE, 'Binary data check at offset '+IntToStr(iErr));
1158 
1159     Expect( stm.Position = stm.Size, 'Stream position after read');
1160 
1161 
1162     // Solidus can be encoded in two ways. Make sure we can read both
1163     stm.Position := 0;
1164     stm.Size     := 0;
1165     stm.WriteString(SOLIDUS_JSON_DATA);
1166     stm.Position := 0;
1167     prot := TJSONProtocolImpl.Create(
1168               TStreamTransportImpl.Create(
1169                 TThriftStreamAdapterDelphi.Create( stm, FALSE), nil, config));
1170     Expect( prot.ReadString = SOLIDUS_EXCPECTED, 'Solidus encoding');
1171 
1172 
1173     // Widechars should work too. Do they?
1174     // After writing, we ensure that we are able to read it back
1175     // We can't assume hex-encoding, since (nearly) any Unicode char is valid JSON
1176     stm.Position := 0;
1177     stm.Size     := 0;
1178     prot := TJSONProtocolImpl.Create(
1179               TStreamTransportImpl.Create(
1180                 nil, TThriftStreamAdapterDelphi.Create( stm, FALSE), config));
1181     prot.WriteString( G_CLEF_AND_CYRILLIC_TEXT);
1182     stm.Position := 0;
1183     prot := TJSONProtocolImpl.Create(
1184               TStreamTransportImpl.Create(
1185                 TThriftStreamAdapterDelphi.Create( stm, FALSE), nil, config));
1186     Expect( prot.ReadString = G_CLEF_AND_CYRILLIC_TEXT, 'Writing JSON with chars > 8 bit');
1187 
1188     // Widechars should work with hex-encoding too. Do they?
1189     stm.Position := 0;
1190     stm.Size     := 0;
1191     stm.WriteString( G_CLEF_AND_CYRILLIC_JSON);
1192     stm.Position := 0;
1193     prot := TJSONProtocolImpl.Create(
1194               TStreamTransportImpl.Create(
1195                 TThriftStreamAdapterDelphi.Create( stm, FALSE), nil, config));
1196     Expect( prot.ReadString = G_CLEF_AND_CYRILLIC_TEXT, 'Reading JSON with chars > 8 bit');
1197 
1198 
1199   finally
1200     stm.Free;
1201     prot := nil;  //-> Release
1202     StartTestGroup( '', test_Unknown);  // no more tests here
1203   end;
1204 end;
1205 
1206 
1207 procedure TClientThread.StartTestGroup( const aGroup : string; const aTest : TTestGroup);
1208 begin
1209   FTestGroup := aGroup;
1210   FCurrentTest := aTest;
1211 
1212   Include( FExecuted, aTest);
1213 
1214   if FTestGroup <> '' then begin
1215     Console.WriteLine('');
1216     Console.WriteLine( aGroup+' tests');
1217     Console.WriteLine( StringOfChar('-',60));
1218   end;
1219 end;
1220 
1221 
1222 procedure TClientThread.Expect( aTestResult : Boolean; const aTestInfo : string);
1223 begin
1224   if aTestResult  then begin
1225     Inc(FSuccesses);
1226     Console.WriteLine( aTestInfo+': passed');
1227   end
1228   else begin
1229     FErrors.Add( FTestGroup+': '+aTestInfo);
1230     Include( FFailed, FCurrentTest);
1231     Console.WriteLine( aTestInfo+': *** FAILED ***');
1232 
1233     // We have a failed test!
1234     // -> issue DebugBreak ONLY if a debugger is attached,
1235     // -> unhandled DebugBreaks would cause Windows to terminate the app otherwise
1236     if IsDebuggerPresent
1237     then {$IFDEF CPUX64} DebugBreak {$ELSE} asm int 3 end {$ENDIF};
1238   end;
1239 end;
1240 
1241 
1242 procedure TClientThread.ReportResults;
1243 var nTotal : Integer;
1244     sLine : string;
1245 begin
1246   // prevent us from stupid DIV/0 errors
1247   nTotal := FSuccesses + FErrors.Count;
1248   if nTotal = 0 then begin
1249     Console.WriteLine('No results logged');
1250     Exit;
1251   end;
1252 
1253   Console.WriteLine('');
1254   Console.WriteLine( StringOfChar('=',60));
1255   Console.WriteLine( IntToStr(nTotal)+' tests performed');
1256   Console.WriteLine( IntToStr(FSuccesses)+' tests succeeded ('+IntToStr(round(100*FSuccesses/nTotal))+'%)');
1257   Console.WriteLine( IntToStr(FErrors.Count)+' tests failed ('+IntToStr(round(100*FErrors.Count/nTotal))+'%)');
1258   Console.WriteLine( StringOfChar('=',60));
1259   if FErrors.Count > 0 then begin
1260     Console.WriteLine('FAILED TESTS:');
1261     for sLine in FErrors do Console.WriteLine('- '+sLine);
1262     Console.WriteLine( StringOfChar('=',60));
1263     InterlockedIncrement( ExitCode);  // return <> 0 on errors
1264   end;
1265   Console.WriteLine('');
1266 end;
1267 
1268 
CalculateExitCodenull1269 function TClientThread.CalculateExitCode : Byte;
1270 var test : TTestGroup;
1271 begin
1272   result := EXITCODE_SUCCESS;
1273   for test := Low(TTestGroup) to High(TTestGroup) do begin
1274     if (test in FFailed) or not (test in FExecuted)
1275     then result := result or MAP_FAILURES_TO_EXITCODE_BITS[test];
1276   end;
1277 end;
1278 
1279 
1280 constructor TClientThread.Create( const aSetup : TTestSetup; const aNumIteration: Integer);
1281 begin
1282   FSetup := aSetup;
1283   FNumIteration := ANumIteration;
1284 
1285   FConsole := TThreadConsole.Create( Self );
1286   FCurrentTest := test_Unknown;
1287 
1288   // error list: keep correct order, allow for duplicates
1289   FErrors := TStringList.Create;
1290   FErrors.Sorted := FALSE;
1291   FErrors.Duplicates := dupAccept;
1292 
1293   inherited Create( TRUE);
1294 end;
1295 
1296 destructor TClientThread.Destroy;
1297 begin
1298   FreeAndNil( FConsole);
1299   FreeAndNil( FErrors);
1300   inherited;
1301 end;
1302 
1303 procedure TClientThread.Execute;
1304 var
1305   i : Integer;
1306 begin
1307   // perform all tests
1308   try
1309     {$IFDEF Win64}
1310     UseInterlockedExchangeAdd64;
1311     {$ENDIF}
1312     JSONProtocolReadWriteTest;
1313 
1314     // must be run in the context of the thread
1315     InitializeProtocolTransportStack;
1316     try
1317       for i := 0 to FNumIteration - 1 do begin
1318         ClientTest;
1319         {$IFDEF SupportsAsync}
1320         ClientAsyncTest;
1321         {$ENDIF}
1322       end;
1323 
1324       // report the outcome
1325       ReportResults;
1326       SetReturnValue( CalculateExitCode);
1327 
1328     finally
1329       ShutdownProtocolTransportStack;
1330     end;
1331 
1332   except
1333     on e:Exception do Expect( FALSE, 'unexpected exception: "'+e.message+'"');
1334   end;
1335 end;
1336 
1337 
InitializeHttpTransportnull1338 function TClientThread.InitializeHttpTransport( const aTimeoutSetting : Integer; const aConfig : IThriftConfiguration) : IHTTPClient;
1339 var sUrl    : string;
1340     comps   : URL_COMPONENTS;
1341     dwChars : DWORD;
1342 begin
1343   ASSERT( FSetup.endpoint in [trns_MsxmlHttp, trns_WinHttp]);
1344 
1345   if FSetup.useSSL
1346   then sUrl := 'https://'
1347   else sUrl := 'http://';
1348 
1349   sUrl := sUrl + FSetup.host;
1350 
1351   // add the port number if necessary and at the right place
1352   FillChar( comps, SizeOf(comps), 0);
1353   comps.dwStructSize := SizeOf(comps);
1354   comps.dwSchemeLength    := MAXINT;
1355   comps.dwHostNameLength  := MAXINT;
1356   comps.dwUserNameLength  := MAXINT;
1357   comps.dwPasswordLength  := MAXINT;
1358   comps.dwUrlPathLength   := MAXINT;
1359   comps.dwExtraInfoLength := MAXINT;
1360   Win32Check( WinHttpCrackUrl( PChar(sUrl), Length(sUrl), 0, comps));
1361   case FSetup.port of
1362     80  : if FSetup.useSSL then comps.nPort := FSetup.port;
1363     443 : if not FSetup.useSSL then comps.nPort := FSetup.port;
1364   else
1365     if FSetup.port > 0 then comps.nPort := FSetup.port;
1366   end;
1367   dwChars := Length(sUrl) + 64;
1368   SetLength( sUrl, dwChars);
1369   Win32Check( WinHttpCreateUrl( comps, 0, @sUrl[1], dwChars));
1370   SetLength( sUrl, dwChars);
1371 
1372 
1373   Console.WriteLine('Target URL: '+sUrl);
1374   case FSetup.endpoint of
1375     trns_MsxmlHttp :  result := TMsxmlHTTPClientImpl.Create( sUrl, aConfig);
1376     trns_WinHttp   :  result := TWinHTTPClientImpl.Create(   sUrl, aConfig);
1377   else
1378     raise Exception.Create(ENDPOINT_TRANSPORTS[FSetup.endpoint]+' unhandled case');
1379   end;
1380 
1381   result.DnsResolveTimeout := aTimeoutSetting;
1382   result.ConnectionTimeout := aTimeoutSetting;
1383   result.SendTimeout       := aTimeoutSetting;
1384   result.ReadTimeout       := aTimeoutSetting;
1385 end;
1386 
1387 
1388 procedure TClientThread.InitializeProtocolTransportStack;
1389 var streamtrans : IStreamTransport;
1390     canSSL : Boolean;
1391 const
1392   DEBUG_TIMEOUT   = 30 * 1000;
1393   RELEASE_TIMEOUT = DEFAULT_THRIFT_TIMEOUT;
1394   PIPE_TIMEOUT    = RELEASE_TIMEOUT;
1395   HTTP_TIMEOUTS   = 10 * 1000;
1396 begin
1397   // needed for HTTP clients as they utilize the MSXML COM components
1398   OleCheck( CoInitialize( nil));
1399 
1400   canSSL := FALSE;
1401   case FSetup.endpoint of
1402     trns_Sockets: begin
1403       Console.WriteLine('Using sockets ('+FSetup.host+' port '+IntToStr(FSetup.port)+')');
1404       streamtrans := TSocketImpl.Create( FSetup.host, FSetup.port);
1405       FTransport := streamtrans;
1406     end;
1407 
1408     trns_MsxmlHttp,
1409     trns_WinHttp: begin
1410       Console.WriteLine('Using HTTPClient');
1411       FTransport := InitializeHttpTransport( HTTP_TIMEOUTS);
1412       canSSL := TRUE;
1413     end;
1414 
1415     trns_EvHttp: begin
1416       raise Exception.Create(ENDPOINT_TRANSPORTS[FSetup.endpoint]+' transport not implemented');
1417     end;
1418 
1419     trns_NamedPipes: begin
1420       streamtrans := TNamedPipeTransportClientEndImpl.Create( FSetup.sPipeName, 0, nil, PIPE_TIMEOUT, PIPE_TIMEOUT);
1421       FTransport := streamtrans;
1422     end;
1423 
1424     trns_AnonPipes: begin
1425       streamtrans := TAnonymousPipeTransportImpl.Create( FSetup.hAnonRead, FSetup.hAnonWrite, FALSE, PIPE_TIMEOUT);
1426       FTransport := streamtrans;
1427     end;
1428 
1429   else
1430     raise Exception.Create('Unhandled endpoint transport');
1431   end;
1432   ASSERT( FTransport <> nil);
1433 
1434   // layered transports are not really meant to be stacked upon each other
1435   if (trns_Framed in FSetup.layered) then begin
1436     FTransport := TFramedTransportImpl.Create( FTransport);
1437   end
1438   else if (trns_Buffered in FSetup.layered) and (streamtrans <> nil) then begin
1439     FTransport := TBufferedTransportImpl.Create( streamtrans, 32);  // small buffer to test read()
1440   end;
1441 
1442   if FSetup.useSSL and not canSSL then begin
1443     raise Exception.Create('SSL/TLS not implemented');
1444   end;
1445 
1446   // create protocol instance, default to BinaryProtocol
1447   case FSetup.protType of
1448     prot_Binary  :  FProtocol := TBinaryProtocolImpl.Create( FTransport, BINARY_STRICT_READ, BINARY_STRICT_WRITE);
1449     prot_JSON    :  FProtocol := TJSONProtocolImpl.Create( FTransport);
1450     prot_Compact :  FProtocol := TCompactProtocolImpl.Create( FTransport);
1451   else
1452     raise Exception.Create('Unhandled protocol');
1453   end;
1454 
1455   ASSERT( (FTransport <> nil) and (FProtocol <> nil));
1456 end;
1457 
1458 
1459 procedure TClientThread.ShutdownProtocolTransportStack;
1460 begin
1461   try
1462     FProtocol := nil;
1463 
1464     if FTransport <> nil then begin
1465       FTransport.Close;
1466       FTransport := nil;
1467     end;
1468 
1469   finally
1470     CoUninitialize;
1471   end;
1472 end;
1473 
1474 
1475 { TThreadConsole }
1476 
1477 constructor TThreadConsole.Create(AThread: TThread);
1478 begin
1479   inherited Create;
1480   FThread := AThread;
1481 end;
1482 
1483 procedure TThreadConsole.Write(const S: string);
1484 var
1485   proc : TThreadProcedure;
1486 begin
1487   proc := procedure
1488   begin
1489     Console.Write( S );
1490   end;
1491   TThread.Synchronize( FThread, proc);
1492 end;
1493 
1494 procedure TThreadConsole.WriteLine(const S: string);
1495 var
1496   proc : TThreadProcedure;
1497 begin
1498   proc := procedure
1499   begin
1500     Console.WriteLine( S );
1501   end;
1502   TThread.Synchronize( FThread, proc);
1503 end;
1504 
1505 initialization
1506 begin
1507   TTestClient.FNumIteration := 1;
1508   TTestClient.FNumThread := 1;
1509 end;
1510 
1511 end.
1512