1import os
2
3import infra.basetest
4
5
6class TestEd(infra.basetest.BRTest):
7    config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
8        """
9        BR2_PACKAGE_ED=y
10        BR2_TARGET_ROOTFS_CPIO=y
11        # BR2_TARGET_ROOTFS_TAR is not set
12        """
13
14    def run_ed_cmds(self, ed_cmds):
15        cmd = "ed <<EOF\n"
16        cmd += "\n".join(ed_cmds)
17        cmd += "\nEOF"
18        self.assertRunOk(cmd)
19
20    def test_run(self):
21        cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
22        self.emulator.boot(arch="armv5",
23                           kernel="builtin",
24                           options=["-initrd", cpio_file])
25        self.emulator.login()
26
27        # We check the program can run. This also check we have the
28        # actual GNU ed, rather than the Busybox ed, which does not
29        # recognize the --version option.
30        self.assertRunOk("ed --version")
31
32        test_fname = "test.txt"
33        input_text_lines = [
34            "Hello World",
35            "Embedded Linux is Hard."
36        ]
37        output_expected_text = [
38            "Hello Buildroot",
39            "---------------",
40            "Making Embedded Linux Easy."
41        ]
42
43        # We define few "ed" command sequences, creating and editing a
44        # text file. The final output of this sequence is expected to
45        # match the expected text previously defined.
46        create_file = ["a"]
47        create_file += input_text_lines
48        create_file += [
49            ".",
50            f"w {test_fname}",
51            "q"
52        ]
53
54        edit_file = [
55            f"r {test_fname}",
56            "1",
57            "s/World/Buildroot/",
58            "2",
59            "s/is Hard/Easy/",
60            "s/^/Making /",
61            "w",
62            "q"
63        ]
64
65        insert_txt = [
66            f"r {test_fname}",
67            "2",
68            "i",
69            "This is a new line",
70            ".",
71            "w",
72            "q"
73        ]
74
75        change_txt = [
76            f"r {test_fname}",
77            "2",
78            "c",
79            "---------------",
80            ".",
81            "w"
82            "q"
83        ]
84
85        # We execute all "ed" command batches.
86        ed_cmd_batches = [
87            create_file,
88            edit_file,
89            insert_txt,
90            change_txt
91        ]
92        for ed_cmd_batch in ed_cmd_batches:
93            self.run_ed_cmds(ed_cmd_batch)
94
95        # The final test file should contain the expected text.
96        out, ret = self.emulator.run(f"cat {test_fname}")
97        self.assertEqual(ret, 0)
98        self.assertEqual(out, output_expected_text)
99