测试从终端获取用户输入的 ac 程序

may*_*hen 0 c shell stdin unit-testing assert

我正在用 c 编写一个名为:“shell”(我模仿 shell)的程序,我想编写一些测试以确保我遵循所有测试用例,所以我尝试使用#include <assert.h>

但我不明白如何模仿终端中的用户输入。我尝试使用包含文本的文件并更改stdin为该输入文件并重定向stdout到输出文件,但它不起作用。

我还尝试使用该函数将输入插入到终端system(),但效果不佳。

shell 程序如何运行的示例

外壳示例

我的 C shell 程序的简单版本

所以shell.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
    char buf[1024];
    while (1)
    {

        fgets(buf, 1024, stdin);

        if (strncmp(buf, "quit", 4) == 0)
        {
            exit(0);
        }

        int fildes[2];
        pipe(fildes);
        if (fork() == 0)
        {
            close(fildes[0]);
            dup2(fildes[1], STDOUT_FILENO);
            execlp("ls", "ls", "-l", NULL);
            perror("exec error");
            exit(1);
        }
        else
        {
            close(fildes[1]);
            read(fildes[0], buf, 1024);
            printf("%s", buf);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以只需将其复制并粘贴到 ac 文件中并编译它或使用这个在线编译器我发现可以更好地看到功能

https://onlinegdb.com/StEq1lNEI

这是我的测试程序所以 test.c

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


int main()
{
    // change the output of ls -l to a file
    freopen("input.txt", "r", stdin);   //redirects standard input
    freopen("output.txt", "w", stdout); //redirects standard output

    // run the program ./shell
    system("./shell");
    // insert to the program the command ls -l
    system("ls -l");

    // read the output from the file output.txt into a buffer of size 1024
    char buf[1024];
    FILE *fp = fopen("output.txt", "r");
    fread(buf, 1024, 1, fp);
    fclose(fp);

    // compare the output of the program with the output of ls -l
    // if they are the same, the test passes

    // now how do i test the output of the program?
    assert(strcmp("shell.c \n shell",
                  buf) == 0);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您明白为什么它不起作用,请告诉我:)将不胜感激!

Cra*_*tey 6

但我不明白如何模仿终端中的用户输入。

有几种方法可以做到这一点:

  1. 使用脚本文件路径参数调用 shell(例如):myshell ./myscript
  2. 调用方式:myshell < ./myscript. 它是本机 shell(例如)bash您的shell 执行输入重定向。
  3. 您可以在您的 shell 中执行该source命令。
  4. 您可以编写一个单独的程序,在伪 tty 下调用 shell(例如)/dev/pts/*/dev/ptmx请参阅:man 7 pty
  5. 您可以使用该命令,而不是创建自己的 PTY 程序expect