mercredi 7 août 2019

How to unit test terminal in raw mode on unix

Intro :

Hello,

I'm an engineering student and my exercise is to code a simple shell. I am not allowed to use any librairy. My terminal is in raw mode and I tryind to do e2e shell test, but I can't send and retrieve information with my program.

System :

I'm using mac os mojave and zsh

Github repository :

https://github.com/adrienpsl/stack-unit_testing_shell

Sample project :

// # main.c

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


char *join(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1);

    if (result) // thanks @pmg
    {
        strcpy(result, s1);
        strcat(result, s2);
    }
    return result;
}

/*
 * Activates the row mode and saving
 * the old configuration in t
*/
void ms_activate_raw_mode(struct termios *t)
{
    struct termios termios;

    tcgetattr(STDIN_FILENO, &termios);
    tcgetattr(STDIN_FILENO, t);
    termios.c_lflag &= ~(ICANON | ECHO);
    termios.c_cc[VMIN] = 1;
    termios.c_cc[VTIME] = 0;
    tcsetattr(STDIN_FILENO, TCSANOW, &termios);
}

int main()
{
    struct termios termios;

    char *line;
    static char buff[3] = { 0 };

    ms_activate_raw_mode(&termios);
    line = strdup("");
    while (strcmp(line, "exit\n"))
    {
        line = strdup("");
        bzero(buff, 2);
        while (strcmp(buff, "\n"))
        {
            bzero(buff, 2);
            read(STDIN_FILENO, buff, 2);
            write(1, buff, 1);
            line = join(line, buff);
        }
        printf("the line is : %s", line);
    }
    tcsetattr(STDIN_FILENO, TCSANOW, &termios);

return 0;
}

Sample test :

# test.sh

gcc main.c -o minishell

# It doesn't work, the shell never gives back the hand.
result=$(./minishell <<EFO
  ls
  exit
EFO
)
echo "$result"

# same for that one
result=$(./minishell <<< printf "ls\nexit")
echo "$result"

Expected results

I need to catch the result of multiple commands send to my minishell and see if it's the same as zsh

Aucun commentaire:

Enregistrer un commentaire