utccsvdocument.pp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. unit utcCSVDocument;
  2. {$mode objfpc}{$H+}
  3. interface
  4. uses
  5. Classes, SysUtils, punit, csvdocument;
  6. procedure RegisterTests;
  7. implementation
  8. const
  9. TestFileName = 'test.csv';
  10. ColCount = 3;
  11. RowCount = 4;
  12. type
  13. TRow = array[0..ColCount-1] of String;
  14. TCells = array[0..RowCount-1] of TRow;
  15. const
  16. Cells : TCells = (
  17. ('a','b','c'),
  18. ('1','"one"','1.1'),
  19. ('2','"two"','2.2'),
  20. ('3','"three"','3.3')
  21. );
  22. var
  23. FDoc: TCSVDocument;
  24. procedure RemoveTestFile;
  25. begin
  26. if FileExists(TestFileName) then
  27. DeleteFile(TestFileName);
  28. end;
  29. function StripQuotes(S: String): String;
  30. var
  31. L: integer;
  32. begin
  33. Result := S;
  34. L := Length(Result);
  35. if (L > 1) and (Result[1] = '"') and (Result[L] = '"') then
  36. Result := Copy(Result, 2, L - 2);
  37. end;
  38. procedure CreateTestFile;
  39. var
  40. L: TStringList;
  41. R, C: Integer;
  42. S: String;
  43. begin
  44. L := TStringList.Create;
  45. try
  46. for R := 0 to RowCount - 1 do
  47. begin
  48. S := '';
  49. for C := 0 to ColCount - 1 do
  50. begin
  51. if S <> '' then
  52. S := S + ',';
  53. S := S + Cells[R, C];
  54. end;
  55. L.Add(S);
  56. end;
  57. L.SaveToFile(TestFileName);
  58. finally
  59. L.Free;
  60. end;
  61. end;
  62. procedure TestTheFile;
  63. var
  64. R, C: Integer;
  65. begin
  66. AssertEquals('Row count', RowCount, FDoc.RowCount);
  67. for R := 0 to RowCount - 1 do
  68. for C := 0 to ColCount - 1 do
  69. begin
  70. AssertEquals('Col[' + IntToStr(R) + '] count', ColCount, FDoc.ColCount[R]);
  71. AssertEquals(Format('Cell[%d,%d]', [C, R]), StripQuotes(Cells[R, C]), FDoc.Cells[C, R]);
  72. end;
  73. end;
  74. function Setup: TTestString;
  75. begin
  76. Result := '';
  77. FDoc := TCSVDocument.Create;
  78. end;
  79. function TearDown: TTestString;
  80. begin
  81. Result := '';
  82. RemoveTestFile;
  83. FreeAndNil(FDoc);
  84. end;
  85. function TCSVDocument_TestEmpty: TTestString;
  86. begin
  87. Result := '';
  88. AssertNotNull('Have document', FDoc);
  89. end;
  90. function TCSVDocument_TestRead: TTestString;
  91. begin
  92. Result := '';
  93. CreateTestFile;
  94. FDoc.LoadFromFile(TestFileName);
  95. TestTheFile;
  96. end;
  97. procedure RegisterTests;
  98. begin
  99. AddSuite('TCSVDocumentTests', @Setup, @TearDown);
  100. AddTest('TestEmpty', @TCSVDocument_TestEmpty, 'TCSVDocumentTests');
  101. AddTest('TestRead', @TCSVDocument_TestRead, 'TCSVDocumentTests');
  102. end;
  103. end.