2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/Exception.h>
19 #include <folly/experimental/TestUtil.h>
20 #include <folly/portability/GTest.h>
25 namespace folly { namespace test {
27 #define EXPECT_SYSTEM_ERROR(statement, err, msg) \
30 ADD_FAILURE() << "Didn't throw"; \
31 } catch (const std::system_error& e) { \
32 std::system_error expected(err, std::system_category(), msg); \
33 EXPECT_STREQ(expected.what(), e.what()); \
35 ADD_FAILURE() << "Threw a different type"; \
39 TEST(ExceptionTest, Simple) {
40 // Make sure errno isn't used when we don't want it to, set it to something
41 // else than what we set when we call Explicit functions
43 EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello");},
46 EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello", " world");},
49 EXPECT_SYSTEM_ERROR({throwSystemError("hello", " world");},
50 ERANGE, "hello world");
52 EXPECT_NO_THROW({checkPosixError(0, "hello", " world");});
54 EXPECT_SYSTEM_ERROR({checkPosixError(EIO, "hello", " world");},
57 EXPECT_NO_THROW({checkKernelError(0, "hello", " world");});
58 EXPECT_NO_THROW({checkKernelError(EIO, "hello", " world");});
60 EXPECT_SYSTEM_ERROR({checkKernelError(-EIO, "hello", " world");},
63 EXPECT_NO_THROW({checkUnixError(0, "hello", " world");});
64 EXPECT_NO_THROW({checkUnixError(1, "hello", " world");});
66 EXPECT_SYSTEM_ERROR({checkUnixError(-1, "hello", " world");},
67 ERANGE, "hello world");
69 EXPECT_NO_THROW({checkUnixErrorExplicit(0, EIO, "hello", " world");});
70 EXPECT_NO_THROW({checkUnixErrorExplicit(1, EIO, "hello", " world");});
72 EXPECT_SYSTEM_ERROR({checkUnixErrorExplicit(-1, EIO, "hello", " world");},
75 TemporaryDirectory tmpdir;
76 auto exnpath = tmpdir.path() / "ExceptionTest";
77 auto fp = fopen(exnpath.string().c_str(), "w+b");
78 ASSERT_TRUE(fp != nullptr);
79 SCOPE_EXIT { fclose(fp); };
81 EXPECT_NO_THROW({ checkFopenError(fp, "hello", " world"); });
83 EXPECT_SYSTEM_ERROR({checkFopenError(nullptr, "hello", " world");},
84 ERANGE, "hello world");
86 EXPECT_NO_THROW({ checkFopenErrorExplicit(fp, EIO, "hello", " world"); });
88 EXPECT_SYSTEM_ERROR({checkFopenErrorExplicit(nullptr, EIO,