1import os
2import time
3
4import infra.basetest
5
6
7class TestNgrep(infra.basetest.BRTest):
8    config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
9        """
10        BR2_PACKAGE_BUSYBOX_SHOW_OTHERS=y
11        BR2_PACKAGE_NETCAT=y
12        BR2_PACKAGE_NGREP=y
13        BR2_TARGET_ROOTFS_CPIO=y
14        # BR2_TARGET_ROOTFS_TAR is not set
15        """
16
17    def test_run(self):
18        cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
19        self.emulator.boot(arch="armv5",
20                           kernel="builtin",
21                           options=["-initrd", cpio_file])
22        self.emulator.login()
23
24        port = 12345
25        msg = 'Hello Buildroot'
26
27        # Check the program can execute.
28        self.assertRunOk("ngrep -V")
29
30        # Start a netcat server in background accepting connections
31        cmd = f"nc -l -p {port} >/dev/null </dev/null &"
32        self.assertRunOk(cmd)
33
34        time.sleep(1)
35
36        # Start a netcat client in background, sending one message
37        # every seconds
38        cmd = "( while true ; do "
39        cmd += f"echo '{msg}'; "
40        cmd += "sleep 1 ; "
41        cmd += "done) | "
42        cmd += f"nc 127.0.0.1 {port} &"
43        self.assertRunOk(cmd)
44
45        time.sleep(1)
46
47        # Capture 3 packets with the message.
48        cmd = f"ngrep -n 3 '{msg}'"
49        self.assertRunOk(cmd)
50