utcstrutils.pp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. unit utcstrutils;
  2. {$mode ObjFPC}{$H+}
  3. interface
  4. uses
  5. sysutils, strutils, fpcunit, testregistry;
  6. Type
  7. { TTestStrUtils }
  8. TTestStrUtils = class(TTestCase)
  9. Published
  10. Procedure TestNaturalCompareText;
  11. end;
  12. implementation
  13. { TTestStrUtils }
  14. type
  15. CaseRec = record
  16. a, b: string;
  17. expect: int8;
  18. end;
  19. const
  20. Cases: array[0 .. 4] of CaseRec = (
  21. (a: '100000000000000000000'; b: '100000000000000000001'; expect: -1),
  22. (a: ' 10 hi'; b: '010 hi'; expect: 0),
  23. (a: 'score: 10'; b: 'score:010'; expect: 0),
  24. (a: '9'; b: ' '; expect: -1),
  25. (a: 'A'; b: ''; expect: +1)
  26. );
  27. procedure TTestStrUtils.TestNaturalCompareText;
  28. var
  29. somethingFailed: boolean = false;
  30. function RandomString: string;
  31. const
  32. TextChars = 'abAB ';
  33. NumberChars = '012';
  34. var
  35. iComp, iSym: SizeInt;
  36. begin
  37. result := '';
  38. for iComp := 0 to random(5) do
  39. case random(2) of
  40. 0:
  41. for iSym := 0 to random(3) do
  42. result += TextChars[1 + random(length(TextChars))];
  43. else
  44. for iSym := 0 to random(3) do
  45. result += NumberChars[1 + random(length(NumberChars))];
  46. end;
  47. end;
  48. const
  49. NFuzzStrings = 200;
  50. var
  51. cs: CaseRec;
  52. got, ab: integer;
  53. desc : string;
  54. fuzz: array of string;
  55. i, iA, iB, iC: SizeInt;
  56. comparisons: array[0 .. NFuzzStrings - 1, 0 .. NFuzzStrings - 1] of int8;
  57. begin
  58. for cs in Cases do
  59. begin
  60. got := NaturalCompareText(cs.a, cs.b);
  61. Desc:=Format('a = ''%s'', b = ''%s'' ',[cs.a, cs.b]);
  62. AssertEquals(Desc,cs.expect,got);
  63. end;
  64. SetLength(fuzz, NFuzzStrings);
  65. fuzz[0] := '';
  66. fuzz[1] := ' ';
  67. for i := 2 to High(fuzz) do
  68. fuzz[i] := RandomString;
  69. for iA := 0 to High(fuzz) do
  70. for iB := iA to High(fuzz) do
  71. begin
  72. comparisons[iA, iB] := NaturalCompareText(fuzz[iA], fuzz[iB]);
  73. comparisons[iB, iA] := NaturalCompareText(fuzz[iB], fuzz[iA]);
  74. Desc:=Format('Antisymmetry: a= ''%s'', b= ''%s'' ',[fuzz[iA],fuzz[iB]]);
  75. AssertEquals('Expect '+Desc, -comparisons[iB, iA], comparisons[iA, iB]);
  76. end;
  77. for iA := 0 to High(fuzz) do
  78. for iB := iA to High(fuzz) do
  79. begin
  80. ab := comparisons[iA, iB];
  81. for iC := 0 to High(fuzz) do
  82. begin
  83. Desc:=Format('Transitivity: a= ''%s'', b= ''%s'' , c= ''%s'' ',[fuzz[iA], fuzz[iB], fuzz[iC]]);
  84. AssertFalse(Desc,(comparisons[iB, iC] = ab) and (comparisons[iA, iC] <> ab));
  85. end;
  86. end;
  87. end;
  88. initialization
  89. RegisterTest(TTestStrUtils);
  90. end.