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

问题描述 投票:0回答:0

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

#include <assert.h>

但我不明白如何在终端中模仿用户输入。我尝试使用包含文本的文件并将

stdin
更改为该输入文件并将
stdout
也重定向到输出文件但它没有用。

我还尝试使用

system()
功能将输入插入终端,但效果不佳。

shell程序运行示例

我的 C shell 程序的简单版本

#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;
}

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

https://onlinegdb.com/StEq1lNEI

这是我的测试程序

#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;
}

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

c shell unit-testing stdin assert
© www.soinside.com 2019 - 2024. All rights reserved.