backtrace_ut.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "backtrace.h"
  2. #include <util/generic/array_ref.h>
  3. #include <library/cpp/testing/unittest/registar.h>
  4. #include <util/stream/output.h>
  5. using PFunc = int (*)(void**, size_t);
  6. int Dbg1(void** buf, size_t len) {
  7. volatile int ret = (int)BackTrace(buf, len);
  8. return ret;
  9. }
  10. int Dbg2(void** buf, size_t len) {
  11. volatile int ret = (int)BackTrace(buf, len);
  12. return ret;
  13. }
  14. void FormatBackTraceReplacement(IOutputStream* out, void* const*, size_t) {
  15. *out << "WorksLikeACharm" << Endl;
  16. }
  17. void SomeMethod() {
  18. TStringStream out;
  19. FormatBackTrace(&out);
  20. #if defined(_musl_)
  21. // musl dladdr broken for us now
  22. return;
  23. #endif
  24. UNIT_ASSERT(out.Empty() || out.Str().find("SomeMethod") != TString::npos);
  25. }
  26. class TBackTraceTest: public TTestBase {
  27. UNIT_TEST_SUITE(TBackTraceTest);
  28. UNIT_TEST(TestBackTrace)
  29. UNIT_TEST(TestBackTraceView)
  30. UNIT_TEST(TestPrintBackTrace)
  31. UNIT_TEST(TestSetFormatBackTraceFn)
  32. UNIT_TEST_SUITE_END();
  33. void TestPrintBackTrace() {
  34. SomeMethod();
  35. }
  36. void TestSetFormatBackTraceFn() {
  37. TFormatBackTraceFn prevFn = SetFormatBackTraceFn(FormatBackTraceReplacement);
  38. TStringStream out;
  39. FormatBackTrace(&out);
  40. SetFormatBackTraceFn(prevFn);
  41. UNIT_ASSERT(out.Str().Contains("WorksLikeACharm"));
  42. TestPrintBackTrace();
  43. }
  44. void TestBackTrace() {
  45. // PrintBackTrace();
  46. void* buf1[100];
  47. size_t ret1;
  48. void* buf2[100];
  49. size_t ret2;
  50. volatile PFunc func = &Dbg1;
  51. ret1 = (*func)(buf1, 100);
  52. func = &Dbg2;
  53. ret2 = (*func)(buf2, 100);
  54. UNIT_ASSERT_EQUAL(ret1, ret2);
  55. }
  56. void TestBackTraceView() {
  57. try {
  58. throw TWithBackTrace<yexception>();
  59. } catch (const yexception& e) {
  60. const TBackTrace bt = *e.BackTrace();
  61. const TBackTraceView btView = bt;
  62. UNIT_ASSERT_VALUES_EQUAL(btView.size(), bt.size());
  63. }
  64. }
  65. };
  66. UNIT_TEST_SUITE_REGISTRATION(TBackTraceTest);