ut_util.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma once
  2. #include <library/cpp/binsaver/bin_saver.h>
  3. #include <library/cpp/binsaver/mem_io.h>
  4. #include <library/cpp/binsaver/util_stream_io.h>
  5. #include <library/cpp/testing/unittest/registar.h>
  6. #include <util/generic/vector.h>
  7. #include <util/stream/buffer.h>
  8. #include <functional>
  9. /* comparerChecksInside == true means comparer uses UNIT_ASSERT... inside itself
  10. * comparerChecksInside == false means comparer returns if its arguments are equal
  11. */
  12. template <class T, class TComparer = std::equal_to<T>, bool comparerChecksInside = false>
  13. void UnitTestCheckWithComparer(const T& lhs, const T& rhs, const TComparer& comparer) {
  14. if constexpr (comparerChecksInside) {
  15. comparer(lhs, rhs);
  16. } else {
  17. UNIT_ASSERT(comparer(lhs, rhs));
  18. }
  19. }
  20. /* comparerChecksInside == true means comparer uses UNIT_ASSERT... inside itself
  21. * comparerChecksInside == false means comparer returns true if its arguments are equal
  22. */
  23. template <typename T, typename TComparer = std::equal_to<T>, bool comparerChecksInside = false>
  24. void TestBinSaverSerializationToBuffer(const T& original, const TComparer& comparer = TComparer()) {
  25. TBufferOutput out;
  26. {
  27. TYaStreamOutput yaOut(out);
  28. IBinSaver f(yaOut, false, false);
  29. f.Add(0, const_cast<T*>(&original));
  30. }
  31. TBufferInput in(out.Buffer());
  32. T restored;
  33. {
  34. TYaStreamInput yaIn(in);
  35. IBinSaver f(yaIn, true, false);
  36. f.Add(0, &restored);
  37. }
  38. UnitTestCheckWithComparer<T, TComparer, comparerChecksInside>(original, restored, comparer);
  39. }
  40. template <typename T, typename TComparer = std::equal_to<T>, bool comparerChecksInside = false>
  41. void TestBinSaverSerializationToVector(const T& original, const TComparer& comparer = TComparer()) {
  42. TVector<char> out;
  43. SerializeToMem(&out, *const_cast<T*>(&original));
  44. T restored;
  45. SerializeFromMem(&out, restored);
  46. UnitTestCheckWithComparer<T, TComparer, comparerChecksInside>(original, restored, comparer);
  47. TVector<TVector<char>> out2D;
  48. SerializeToMem(&out2D, *const_cast<T*>(&original));
  49. T restored2D;
  50. SerializeFromMem(&out2D, restored2D);
  51. UnitTestCheckWithComparer<T, TComparer, comparerChecksInside>(original, restored2D, comparer);
  52. }
  53. template <typename T, typename TComparer = std::equal_to<T>, bool comparerChecksInside = false>
  54. void TestBinSaverSerialization(const T& original, const TComparer& comparer = TComparer()) {
  55. TestBinSaverSerializationToBuffer<T, TComparer, comparerChecksInside>(original, comparer);
  56. TestBinSaverSerializationToVector<T, TComparer, comparerChecksInside>(original, comparer);
  57. }