1
0

fd_guard_unittest.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #include <sys/types.h> // open
  18. #include <sys/stat.h> // ^
  19. #include <fcntl.h> // ^
  20. #include <gtest/gtest.h>
  21. #include <errno.h>
  22. #include "butil/fd_guard.h"
  23. namespace {
  24. class FDGuardTest : public ::testing::Test{
  25. protected:
  26. FDGuardTest(){
  27. };
  28. virtual ~FDGuardTest(){};
  29. virtual void SetUp() {
  30. };
  31. virtual void TearDown() {
  32. };
  33. };
  34. TEST_F(FDGuardTest, default_constructor) {
  35. butil::fd_guard guard;
  36. ASSERT_EQ(-1, guard);
  37. }
  38. TEST_F(FDGuardTest, destructor_closes_fd) {
  39. int fd = -1;
  40. {
  41. butil::fd_guard guard(open(".tmp1", O_WRONLY|O_CREAT, 0600));
  42. ASSERT_GT(guard, 0);
  43. fd = guard;
  44. }
  45. char dummy = 0;
  46. ASSERT_EQ(-1L, write(fd, &dummy, 1));
  47. ASSERT_EQ(EBADF, errno);
  48. }
  49. TEST_F(FDGuardTest, reset_closes_previous_fd) {
  50. butil::fd_guard guard(open(".tmp1", O_WRONLY|O_CREAT, 0600));
  51. ASSERT_GT(guard, 0);
  52. const int fd = guard;
  53. const int fd2 = open(".tmp2", O_WRONLY|O_CREAT, 0600);
  54. guard.reset(fd2);
  55. char dummy = 0;
  56. ASSERT_EQ(-1L, write(fd, &dummy, 1));
  57. ASSERT_EQ(EBADF, errno);
  58. guard.reset(-1);
  59. ASSERT_EQ(-1L, write(fd2, &dummy, 1));
  60. ASSERT_EQ(EBADF, errno);
  61. }
  62. TEST_F(FDGuardTest, release) {
  63. butil::fd_guard guard(open(".tmp1", O_WRONLY|O_CREAT, 0600));
  64. ASSERT_GT(guard, 0);
  65. const int fd = guard;
  66. ASSERT_EQ(fd, guard.release());
  67. ASSERT_EQ(-1, guard);
  68. close(fd);
  69. }
  70. }