2 * Copyright 2016 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>
24 #include <glog/logging.h>
25 #include <gtest/gtest.h>
27 namespace folly { namespace test {
29 #define EXPECT_SYSTEM_ERROR(statement, err, msg) \
32 ADD_FAILURE() << "Didn't throw"; \
33 } catch (const std::system_error& e) { \
34 std::system_error expected(err, std::system_category(), msg); \
35 EXPECT_STREQ(expected.what(), e.what()); \
37 ADD_FAILURE() << "Threw a different type"; \
41 TEST(ExceptionTest, Simple) {
42 // Make sure errno isn't used when we don't want it to, set it to something
43 // else than what we set when we call Explicit functions
45 EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello");},
48 EXPECT_SYSTEM_ERROR({throwSystemErrorExplicit(EIO, "hello", " world");},
51 EXPECT_SYSTEM_ERROR({throwSystemError("hello", " world");},
52 ERANGE, "hello world");
54 EXPECT_NO_THROW({checkPosixError(0, "hello", " world");});
56 EXPECT_SYSTEM_ERROR({checkPosixError(EIO, "hello", " world");},
59 EXPECT_NO_THROW({checkKernelError(0, "hello", " world");});
60 EXPECT_NO_THROW({checkKernelError(EIO, "hello", " world");});
62 EXPECT_SYSTEM_ERROR({checkKernelError(-EIO, "hello", " world");},
65 EXPECT_NO_THROW({checkUnixError(0, "hello", " world");});
66 EXPECT_NO_THROW({checkUnixError(1, "hello", " world");});
68 EXPECT_SYSTEM_ERROR({checkUnixError(-1, "hello", " world");},
69 ERANGE, "hello world");
71 EXPECT_NO_THROW({checkUnixErrorExplicit(0, EIO, "hello", " world");});
72 EXPECT_NO_THROW({checkUnixErrorExplicit(1, EIO, "hello", " world");});
74 EXPECT_SYSTEM_ERROR({checkUnixErrorExplicit(-1, EIO, "hello", " world");},
77 TemporaryDirectory tmpdir;
78 auto exnpath = tmpdir.path() / "ExceptionTest";
79 auto fp = fopen(exnpath.string().c_str(), "w+b");
80 ASSERT_TRUE(fp != nullptr);
81 SCOPE_EXIT { fclose(fp); };
83 EXPECT_NO_THROW({ checkFopenError(fp, "hello", " world"); });
85 EXPECT_SYSTEM_ERROR({checkFopenError(nullptr, "hello", " world");},
86 ERANGE, "hello world");
88 EXPECT_NO_THROW({ checkFopenErrorExplicit(fp, EIO, "hello", " world"); });
90 EXPECT_SYSTEM_ERROR({checkFopenErrorExplicit(nullptr, EIO,