assertions.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "assertions.h"
  2. #include <util/string/builder.h>
  3. #include <util/string/split.h>
  4. #include <util/system/type_name.h>
  5. namespace NGTest::NInternal {
  6. namespace {
  7. void FormatActual(const std::exception& err, const TBackTrace* bt, TStringBuilder& out) {
  8. out << "an exception of type " << TypeName(err) << " "
  9. << "with message " << TString(err.what()).Quote() << ".";
  10. if (bt) {
  11. out << "\n Trace: ";
  12. for (auto& line: StringSplitter(bt->PrintToString()).Split('\n')) {
  13. out << " " << line.Token() << "\n";
  14. }
  15. }
  16. }
  17. void FormatActual(TStringBuilder& out) {
  18. out << " Actual: it throws ";
  19. auto exceptionPtr = std::current_exception();
  20. if (exceptionPtr) {
  21. try {
  22. std::rethrow_exception(exceptionPtr);
  23. } catch (const yexception& err) {
  24. FormatActual(err, err.BackTrace(), out);
  25. return;
  26. } catch (const std::exception& err) {
  27. FormatActual(err, nullptr, out);
  28. return;
  29. } catch (...) {
  30. out << "an unknown exception.";
  31. return;
  32. }
  33. }
  34. out << "nothing.";
  35. }
  36. void FormatExpected(const char* statement, const char* type, const TString& contains, TStringBuilder& out) {
  37. out << "Expected: ";
  38. if (TStringBuf(statement).size() > 80) {
  39. out << "statement";
  40. } else {
  41. out << statement;
  42. }
  43. out << " throws an exception of type " << type;
  44. if (!contains.empty()) {
  45. out << " with message containing " << contains.Quote();
  46. }
  47. out << ".";
  48. }
  49. }
  50. TString FormatErrorWrongException(const char* statement, const char* type) {
  51. return FormatErrorWrongException(statement, type, "");
  52. }
  53. TString FormatErrorWrongException(const char* statement, const char* type, TString contains) {
  54. TStringBuilder out;
  55. FormatExpected(statement, type, contains, out);
  56. out << "\n";
  57. FormatActual(out);
  58. return out;
  59. }
  60. TString FormatErrorUnexpectedException(const char* statement) {
  61. TStringBuilder out;
  62. out << "Expected: ";
  63. if (TStringBuf(statement).size() > 80) {
  64. out << "statement";
  65. } else {
  66. out << statement;
  67. }
  68. out << " doesn't throw an exception.\n ";
  69. FormatActual(out);
  70. return out;
  71. }
  72. bool ExceptionMessageContains(const std::exception& err, TString contains) {
  73. return TStringBuf(err.what()).Contains(contains);
  74. }
  75. }