chunk_ut.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include "chunk.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/stream/file.h>
  4. #include <util/system/tempfile.h>
  5. #include <util/stream/null.h>
  6. #define CDATA "./chunkedio"
  7. Y_UNIT_TEST_SUITE(TestChunkedIO) {
  8. static const char test_data[] = "87s6cfbsudg cuisg s igasidftasiy tfrcua6s";
  9. TString CombString(const TString& s, size_t chunkSize) {
  10. TString result;
  11. for (size_t pos = 0; pos < s.size(); pos += 2 * chunkSize)
  12. result += s.substr(pos, chunkSize);
  13. return result;
  14. }
  15. void WriteTestData(IOutputStream * stream, TString * contents) {
  16. contents->clear();
  17. for (size_t i = 0; i < sizeof(test_data); ++i) {
  18. stream->Write(test_data, i);
  19. contents->append(test_data, i);
  20. }
  21. }
  22. void ReadInSmallChunks(IInputStream * stream, TString * contents) {
  23. char buf[11];
  24. size_t read = 0;
  25. contents->clear();
  26. do {
  27. read = stream->Read(buf, sizeof(buf));
  28. contents->append(buf, read);
  29. } while (read > 0);
  30. }
  31. void ReadCombed(IInputStream * stream, TString * contents, size_t chunkSize) {
  32. Y_ASSERT(chunkSize < 128);
  33. char buf[128];
  34. contents->clear();
  35. while (true) {
  36. size_t read = stream->Load(buf, chunkSize);
  37. contents->append(buf, read);
  38. if (read == 0)
  39. break;
  40. size_t toSkip = chunkSize;
  41. size_t skipped = 0;
  42. do {
  43. skipped = stream->Skip(toSkip);
  44. toSkip -= skipped;
  45. } while (skipped != 0 && toSkip != 0);
  46. }
  47. }
  48. Y_UNIT_TEST(TestChunkedIo) {
  49. TTempFile tmpFile(CDATA);
  50. TString tmp;
  51. {
  52. TUnbufferedFileOutput fo(CDATA);
  53. TChunkedOutput co(&fo);
  54. WriteTestData(&co, &tmp);
  55. }
  56. {
  57. TUnbufferedFileInput fi(CDATA);
  58. TChunkedInput ci(&fi);
  59. TString r;
  60. ReadInSmallChunks(&ci, &r);
  61. UNIT_ASSERT_EQUAL(r, tmp);
  62. }
  63. {
  64. TUnbufferedFileInput fi(CDATA);
  65. TChunkedInput ci(&fi);
  66. TString r;
  67. ReadCombed(&ci, &r, 11);
  68. UNIT_ASSERT_EQUAL(r, CombString(tmp, 11));
  69. }
  70. }
  71. Y_UNIT_TEST(TestBadChunk) {
  72. bool hasError = false;
  73. try {
  74. TString badChunk = "10\r\nqwerty";
  75. TMemoryInput mi(badChunk.data(), badChunk.size());
  76. TChunkedInput ci(&mi);
  77. TransferData(&ci, &Cnull);
  78. } catch (...) {
  79. hasError = true;
  80. }
  81. UNIT_ASSERT(hasError);
  82. }
  83. }