1 /* Copyright (c) 2022 Google LLC
2 * SPDX-License-Identifier: Apache-2.0
3 */
4
5 #include <array>
6 #include <iostream>
7 #include <regex>
8 #include <string>
9 #include <zephyr/ztest.h>
10
11 ZTEST_SUITE(fail, nullptr, nullptr, nullptr, nullptr, nullptr);
12
ZTEST(fail,test_framework)13 ZTEST(fail, test_framework)
14 {
15 auto found_error_string = false;
16 char buffer[sizeof(CONFIG_TEST_ERROR_STRING)] = {0};
17 std::string result;
18
19 /* Start running the target binary. This binary is expected to fail. */
20 auto pipe = popen(FAIL_TARGET_BINARY, "r");
21
22 zassert_not_null(pipe, "Failed to execute '" FAIL_TARGET_BINARY "'");
23
24 /* Wait for the binary to finish running and grab the output */
25 while (!feof(pipe)) {
26 if (fgets(buffer, ARRAY_SIZE(buffer), pipe) != nullptr) {
27 if (found_error_string) {
28 /* Already found the error string, no need to do any more string
29 * manipulation.
30 */
31 continue;
32 }
33
34 /* Append the buffer to the result string */
35 result += buffer;
36
37 /* Check if result contains the right error string */
38 found_error_string |=
39 (result.find(CONFIG_TEST_ERROR_STRING) != std::string::npos);
40
41 /* If the result string is longer than the expected string,
42 * we can prune it
43 */
44 auto prune_length = static_cast<int>(result.length()) -
45 static_cast<int>(sizeof(CONFIG_TEST_ERROR_STRING));
46 if (prune_length > 0) {
47 result.erase(0, prune_length);
48 }
49 }
50 }
51 auto rc = WEXITSTATUS(pclose(pipe));
52
53 zassert_equal(1, rc, "Test binary expected to fail with return code 1, but got %d", rc);
54 zassert_true(found_error_string, "Test binary did not produce the expected error string \""
55 CONFIG_TEST_ERROR_STRING "\"");
56 }
57