atexit_ut.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <library/cpp/testing/unittest/registar.h>
  2. #include "atexit.h"
  3. #include <util/generic/singleton.h>
  4. #include <errno.h>
  5. #ifdef _win_
  6. // not implemented
  7. #else
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. #endif //_win_
  11. #include <stdio.h>
  12. #ifdef _win_
  13. // not implemented
  14. #else
  15. struct TAtExitParams {
  16. TAtExitParams(int fd_, const char* str_)
  17. : fd(fd_)
  18. , str(str_)
  19. {
  20. }
  21. int fd;
  22. const char* str;
  23. };
  24. void MyAtExitFunc(void* ptr) {
  25. THolder<TAtExitParams> params{static_cast<TAtExitParams*>(ptr)};
  26. if (write(params->fd, params->str, strlen(params->str)) < 0) {
  27. abort();
  28. }
  29. }
  30. #endif
  31. class TAtExitTest: public TTestBase {
  32. UNIT_TEST_SUITE(TAtExitTest);
  33. UNIT_TEST(TestAtExit)
  34. UNIT_TEST_SUITE_END();
  35. void TestAtExit() {
  36. #ifdef _win_
  37. // not implemented
  38. #else
  39. int ret;
  40. int pipefd[2];
  41. ret = pipe(pipefd);
  42. UNIT_ASSERT(ret == 0);
  43. pid_t pid = fork();
  44. if (pid < 0) {
  45. UNIT_ASSERT(0);
  46. }
  47. if (pid > 0) {
  48. char data[1024];
  49. int last = 0;
  50. close(pipefd[1]);
  51. while (read(pipefd[0], data + last++, 1) > 0 && last < 1024) {
  52. }
  53. data[--last] = 0;
  54. UNIT_ASSERT(strcmp(data, "High prio\nMiddle prio\nLow-middle prio\nLow prio\nVery low prio\n") == 0);
  55. } else {
  56. close(pipefd[0]);
  57. AtExit(MyAtExitFunc, new TAtExitParams(pipefd[1], "Low prio\n"), 3);
  58. AtExit(MyAtExitFunc, new TAtExitParams(pipefd[1], "Middle prio\n"), 5);
  59. AtExit(MyAtExitFunc, new TAtExitParams(pipefd[1], "High prio\n"), 7);
  60. AtExit(MyAtExitFunc, new TAtExitParams(pipefd[1], "Very low prio\n"), 1);
  61. AtExit(MyAtExitFunc, new TAtExitParams(pipefd[1], "Low-middle prio\n"), 4);
  62. exit(0);
  63. }
  64. #endif //_win_
  65. }
  66. };
  67. UNIT_TEST_SUITE_REGISTRATION(TAtExitTest);
  68. Y_UNIT_TEST_SUITE(TestAtExit) {
  69. Y_UNIT_TEST(CreateUponDestruction) {
  70. struct T1 {
  71. };
  72. struct T2 {
  73. ~T2() {
  74. Singleton<T1>();
  75. }
  76. };
  77. Singleton<T2>();
  78. }
  79. } // Y_UNIT_TEST_SUITE(TestAtExit)