tests: unit: add parsing tests

This commit is contained in:
Bruno BELANYI 2020-09-29 20:35:51 +02:00
parent ad57d063d3
commit 41550b1291
4 changed files with 175 additions and 0 deletions

15
tests/unit/common.c Normal file
View file

@ -0,0 +1,15 @@
#include <criterion/redirect.h>
void redirect_streams(void)
{
cr_redirect_stdin();
cr_redirect_stdout();
cr_redirect_stderr();
}
void write_to_stdin(const char *input)
{
FILE *f = cr_get_redirected_stdin();
fputs(input, f);
fclose(f); // Make sure to send EOF when parsing
}

7
tests/unit/common.h Normal file
View file

@ -0,0 +1,7 @@
#ifndef COMMON_H
#define COMMON_H
void redirect_streams(void);
void write_to_stdin(const char *input);
#endif /* !COMMON_H */

116
tests/unit/parse.c Normal file
View file

@ -0,0 +1,116 @@
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include "common.h"
#include "ast/ast.h"
#include "parse/parse-jitters.h"
TestSuite(parser, .init = redirect_streams);
void do_correct(const char *input)
{
write_to_stdin(input);
struct ast_node *ast = NULL;
cr_assert_eq(yyparse(&ast), 0);
cr_assert_not_null(ast);
destroy_ast(ast);
}
void do_incorrect(const char *input)
{
write_to_stdin(input);
struct ast_node *ast = NULL;
cr_expect_neq(yyparse(&ast), 0);
cr_expect_null(ast);
destroy_ast(ast);
}
Test(parser, empty)
{
do_incorrect("");
}
Test(parser, trailing_operator)
{
do_incorrect("1 +");
}
Test(parser, trailing_expression)
{
do_incorrect("1 1");
}
Test(parser, double_operator)
{
do_incorrect("1 * * 1");
}
Test(parser, one)
{
do_correct("1");
}
Test(parser, the_answer)
{
do_correct("42");
}
Test(parser, int_max)
{
do_correct("2147483647");
}
Test(parser, whitespace)
{
do_correct(" 1 ");
}
Test(parser, more_whitespace)
{
do_correct(" 1 + 2 ");
}
Test(parser, one_plus_one)
{
do_correct("1+1");
}
Test(parser, one_minus_one)
{
do_correct("1-1");
}
Test(parser, additions)
{
do_correct("1+1+1+1+1");
}
Test(parser, substractions)
{
do_correct("1-1-1-1-1");
}
Test(parser, multiplication)
{
do_correct("2 * 3");
}
Test(parser, multiplications)
{
do_correct("1 * 2 * 3 * 4");
}
Test(parser, division)
{
do_correct("12 / 3");
}
Test(parser, divisions)
{
do_correct("24 / 4 / 3 / 2");
}