atexit_ut.cpp 1.9 KB

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