1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 // REQUIRES: has-unix-headers
10 // UNSUPPORTED: c++03
11 // XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx{{10.9|10.10|10.11|10.12|10.13|10.14|10.15|11.0|12.0}}
12 // ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_ENABLE_ASSERTIONS=1
13
14 #include <cassert>
15 #include <cstdio>
16 #include <string>
17
18 #include "check_assertion.h"
19
20 template <class Func>
TestDeathTest(const char * stmt,Func && func,DeathTest::ResultKind ExpectResult,AssertionInfoMatcher Matcher=AnyMatcher)21 inline bool TestDeathTest(const char* stmt, Func&& func, DeathTest::ResultKind ExpectResult, AssertionInfoMatcher Matcher = AnyMatcher) {
22 DeathTest DT(Matcher);
23 DeathTest::ResultKind RK = DT.Run(func);
24 auto OnFailure = [&](std::string msg) {
25 std::fprintf(stderr, "EXPECT_DEATH( %s ) failed! (%s)\n\n", stmt, msg.c_str());
26 if (!DT.getChildStdErr().empty()) {
27 std::fprintf(stderr, "---------- standard err ----------\n%s\n", DT.getChildStdErr().c_str());
28 }
29 if (!DT.getChildStdOut().empty()) {
30 std::fprintf(stderr, "---------- standard out ----------\n%s\n", DT.getChildStdOut().c_str());
31 }
32 return false;
33 };
34 if (RK != ExpectResult)
35 return OnFailure(std::string("expected result did not occur: expected ") + DeathTest::ResultKindToString(ExpectResult) + " got: " + DeathTest::ResultKindToString(RK));
36 return true;
37 }
38 #define TEST_DEATH_TEST(RK, ...) assert((TestDeathTest(#__VA_ARGS__, [&]() { __VA_ARGS__; }, RK, AnyMatcher )))
39
40 #define TEST_DEATH_TEST_MATCHES(RK, Matcher, ...) assert((TestDeathTest(#__VA_ARGS__, [&]() { __VA_ARGS__; }, RK, Matcher)))
41
my_libcpp_assert()42 void my_libcpp_assert() {
43 _LIBCPP_ASSERT(false, "other");
44 }
45
test_no_match_found()46 void test_no_match_found() {
47 AssertionInfoMatcher ExpectMatch("my message");
48 TEST_DEATH_TEST_MATCHES(DeathTest::RK_MatchFailure, ExpectMatch, my_libcpp_assert());
49 }
50
test_did_not_die()51 void test_did_not_die() {
52 TEST_DEATH_TEST(DeathTest::RK_DidNotDie, ((void)0));
53 }
54
test_unknown()55 void test_unknown() {
56 TEST_DEATH_TEST(DeathTest::RK_Unknown, std::exit(13));
57 }
58
main(int,char **)59 int main(int, char**) {
60 test_no_match_found();
61 test_did_not_die();
62 test_unknown();
63 return 0;
64 }
65