xref: /aosp_15_r20/external/stg/file_descriptor_test.cc (revision 9e3b08ae94a55201065475453d799e8b1378bea6)
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2022 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License.  You may obtain a copy of the License at
9 //
10 //     https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Matthias Maennich
19 
20 #include "file_descriptor.h"
21 
22 #include <fcntl.h>
23 #include <unistd.h>
24 
25 #include <utility>
26 
27 #include <catch2/catch.hpp>
28 
29 namespace Test {
30 
31 TEST_CASE("default construction") {
32   const stg::FileDescriptor fd;
33   CHECK_THROWS(fd.Value());
34 }
35 
36 TEST_CASE("successful open") {
37   const stg::FileDescriptor fd("/dev/null", O_RDONLY);
38   CHECK(fd.Value());
39 }
40 
41 TEST_CASE("failed open") {
42   CHECK_THROWS(stg::FileDescriptor("/dev/unicorn_null", O_RDONLY));
43 }
44 
45 TEST_CASE("double close") {
__anon9e0281750102() 46   CHECK_THROWS([]() {
47     const stg::FileDescriptor fd("/dev/null", O_RDONLY);
48     close(fd.Value());
49     CHECK_NOTHROW(fd.Value());  // value is still ok
50   }());                         // throws on destruction
51 }
52 
53 TEST_CASE("ownership transfer on move") {
54   stg::FileDescriptor fd("/dev/null", O_RDONLY);
55   CHECK_NOTHROW(fd.Value());  // value is still ok
56 
57   const auto fd_val = fd.Value();
58 
59   auto fd2(std::move(fd));
60   CHECK_THROWS(fd.Value());
61   CHECK(fd_val == fd2.Value());
62 
63   const auto fd3(std::move(fd2));
64   CHECK_THROWS(fd2.Value());
65   CHECK(fd_val == fd3.Value());
66 }
67 
68 }  // namespace Test
69