Newer
Older
NewLang / tests / parse / test_file.py
# SPDX-License-Identifier: LGPL-2.1-only
# Copyright 2022 Jookia <contact@jookia.org>

# File syntax consists of the following:
# - One or more directives
#
# Parsing gives the following:
# A list of directives - All directives in the file
#
# The following error contexts are used:
# PARSE_FILE - Used when parsing the file
#
# No parse errors are generated.

from hypothesis import given
from hypothesis.strategies import composite, just, lists

from src.token import TokenStream
from src.parse import (
    ParseContext,
    ParseTask,
    parse_file,
)
from tests.parse.templates import template_test_invalid
from tests.parse.test_error import static_parse_context
from tests.parse.test_directive import (
    static_directive_valid,
    static_directive_invalid,
    static_directive_invalid_error,
)


# A valid file
@composite
def draw_file_valid(draw):
    directives = draw(lists(just(static_directive_valid())))
    all_tokens = []
    all_expected = []
    for (tokens, expected) in directives:
        all_tokens += tokens
        all_expected.append(expected)
    return (all_tokens, all_expected)


#
# Test functions
#

# Tests parsing a valid file
# We expect the following behaviour:
# - All directives are parsed
# - No tokens are left after parsing
@given(draw_file_valid())
def test_parse_file_valid(test_data):
    (tokens, expected) = test_data
    stream = TokenStream(tokens.copy())
    parsed = parse_file(stream, None)
    assert parsed == expected
    assert stream.pop() is None


# Tests parsing a invalid file
# We expect the following behaviour:
# - The error context is PARSE_FILE
# - A wrong directive error is propagated
@given(draw_file_valid())
def test_parse_file_invalid(test_data):
    (tokens, expected) = test_data
    invalid_directive = static_directive_invalid()
    new_tokens = tokens + invalid_directive
    parent_context = static_parse_context()
    context = ParseContext(ParseTask.PARSE_FILE, new_tokens[0], parent_context)
    error = static_directive_invalid_error(context)
    template_test_invalid(parse_file, parent_context, new_tokens, error)