brotli_ut.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "brotli.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/random/fast.h>
  4. Y_UNIT_TEST_SUITE(TBrotliTestSuite) {
  5. TString Compress(TString data) {
  6. TString compressed;
  7. TStringOutput output(compressed);
  8. TBrotliCompress compressStream(&output, 11);
  9. compressStream.Write(data.data(), data.size());
  10. compressStream.Finish();
  11. output.Finish();
  12. return compressed;
  13. }
  14. TString Decompress(TString data) {
  15. TStringInput input(data);
  16. TBrotliDecompress decompressStream(&input);
  17. return decompressStream.ReadAll();
  18. }
  19. void TestCase(const TString& s) {
  20. UNIT_ASSERT_VALUES_EQUAL(s, Decompress(Compress(s)));
  21. }
  22. TString GenerateRandomString(size_t size) {
  23. TReallyFastRng32 rng(42);
  24. TString result;
  25. result.reserve(size + sizeof(ui64));
  26. while (result.size() < size) {
  27. ui64 value = rng.GenRand64();
  28. result += TStringBuf(reinterpret_cast<const char*>(&value), sizeof(value));
  29. }
  30. result.resize(size);
  31. return result;
  32. }
  33. Y_UNIT_TEST(TestHelloWorld) {
  34. TestCase("hello world");
  35. }
  36. Y_UNIT_TEST(TestFlush) {
  37. TStringStream ss;
  38. TBrotliCompress compressStream(&ss);
  39. TBrotliDecompress decompressStream(&ss);
  40. for (size_t i = 0; i < 3; ++i) {
  41. TString s = GenerateRandomString(1 << 15);
  42. compressStream.Write(s.data(), s.size());
  43. compressStream.Flush();
  44. TString r(s.size(), '*');
  45. decompressStream.Load((char*)r.data(), r.size());
  46. UNIT_ASSERT_VALUES_EQUAL(s, r);
  47. }
  48. }
  49. Y_UNIT_TEST(TestSeveralStreams) {
  50. auto s1 = GenerateRandomString(1 << 15);
  51. auto s2 = GenerateRandomString(1 << 15);
  52. auto c1 = Compress(s1);
  53. auto c2 = Compress(s2);
  54. UNIT_ASSERT_VALUES_EQUAL(s1 + s2, Decompress(c1 + c2));
  55. }
  56. Y_UNIT_TEST(TestIncompleteStream) {
  57. TString manyAs(64 * 1024, 'a');
  58. auto compressed = Compress(manyAs);
  59. TString truncated(compressed.data(), compressed.size() - 1);
  60. UNIT_CHECK_GENERATED_EXCEPTION(Decompress(truncated), std::exception);
  61. }
  62. Y_UNIT_TEST(Test64KB) {
  63. auto manyAs = TString(64 * 1024, 'a');
  64. TString str("Hello from the Matrix!@#% How are you?}{\n\t\a");
  65. TestCase(manyAs + str + manyAs);
  66. }
  67. Y_UNIT_TEST(Test1MB) {
  68. TestCase(GenerateRandomString(1 * 1024 * 1024));
  69. }
  70. Y_UNIT_TEST(TestEmpty) {
  71. TestCase("");
  72. }
  73. }