may*_*hen 0 c shell stdin unit-testing assert
我正在用 c 编写一个名为:“shell”(我模仿 shell)的程序,我想编写一些测试以确保我遵循所有测试用例,所以我尝试使用#include <assert.h>
但我不明白如何模仿终端中的用户输入。我尝试使用包含文本的文件并更改stdin
为该输入文件并重定向stdout
到输出文件,但它不起作用。
我还尝试使用该函数将输入插入到终端system()
,但效果不佳。
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)
如果您明白为什么它不起作用,请告诉我:)将不胜感激!
但我不明白如何模仿终端中的用户输入。
有几种方法可以做到这一点:
myshell ./myscript
。myshell < ./myscript
. 它是本机 shell(例如)bash
为您的shell 执行输入重定向。source
命令。/dev/pts/*
,/dev/ptmx
请参阅:man 7 pty
expect
。 归档时间: |
|
查看次数: |
93 次 |
最近记录: |