1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * (C) Copyright 2021
4 * Francis Laniel, Amarula Solutions, francis.laniel@amarulasolutions.com
5 */
6
7 #include <command.h>
8 #include <env.h>
9 #include <env_attr.h>
10 #include <test/hush.h>
11 #include <test/ut.h>
12 #include <asm/global_data.h>
13
14 DECLARE_GLOBAL_DATA_PTR;
15
hush_test_for(struct unit_test_state * uts)16 static int hush_test_for(struct unit_test_state *uts)
17 {
18 ut_assertok(run_command("for loop_i in foo bar quux quux; do echo $loop_i; done", 0));
19 ut_assert_nextline("foo");
20 ut_assert_nextline("bar");
21 ut_assert_nextline("quux");
22 ut_assert_nextline("quux");
23 ut_assert_console_end();
24
25 if (gd->flags & GD_FLG_HUSH_MODERN_PARSER) {
26 /* Reset local variable. */
27 ut_assertok(run_command("loop_i=", 0));
28 } else if (gd->flags & GD_FLG_HUSH_OLD_PARSER) {
29 puts("Beware: this test set local variable loop_i and it cannot be unset!\n");
30 }
31
32 return 0;
33 }
34 HUSH_TEST(hush_test_for, UTF_CONSOLE);
35
hush_test_while(struct unit_test_state * uts)36 static int hush_test_while(struct unit_test_state *uts)
37 {
38 if (gd->flags & GD_FLG_HUSH_MODERN_PARSER) {
39 /*
40 * Hush 2021 always returns 0 from while loop...
41 * You can see code snippet near this line to have a better
42 * understanding:
43 * debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
44 */
45 ut_assertok(run_command("while test -z \"$loop_foo\"; do echo bar; loop_foo=quux; done", 0));
46 } else if (gd->flags & GD_FLG_HUSH_OLD_PARSER) {
47 /*
48 * Exit status is that of test, so 1 since test is false to quit
49 * the loop.
50 */
51 ut_asserteq(1, run_command("while test -z \"$loop_foo\"; do echo bar; loop_foo=quux; done", 0));
52 }
53 ut_assert_nextline("bar");
54 ut_assert_console_end();
55
56 if (gd->flags & GD_FLG_HUSH_MODERN_PARSER) {
57 /* Reset local variable. */
58 ut_assertok(run_command("loop_foo=", 0));
59 } else if (gd->flags & GD_FLG_HUSH_OLD_PARSER) {
60 puts("Beware: this test set local variable loop_foo and it cannot be unset!\n");
61 }
62
63 return 0;
64 }
65 HUSH_TEST(hush_test_while, UTF_CONSOLE);
66
hush_test_until(struct unit_test_state * uts)67 static int hush_test_until(struct unit_test_state *uts)
68 {
69 env_set("loop_bar", "bar");
70
71 /*
72 * WARNING We have to use environment variable because it is not possible
73 * resetting local variable.
74 */
75 ut_assertok(run_command("until test -z \"$loop_bar\"; do echo quux; setenv loop_bar; done", 0));
76 ut_assert_nextline("quux");
77 ut_assert_console_end();
78
79 /*
80 * Loop normally resets foo environment variable, but we reset it here in
81 * case the test failed.
82 */
83 env_set("loop_bar", NULL);
84 return 0;
85 }
86 HUSH_TEST(hush_test_until, UTF_CONSOLE);
87