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

from hypothesis import given
from hypothesis.strategies import composite

from src.ast_types import Reference
from src.parse import ParseContext, ParseError, ParseErrorException, ParseTask, Parser
from tests.parse.templates import template_test_valid, template_test_invalid
from tests.parse.test_error import static_parse_context
from tests.test_token import draw_token_known, draw_token_unknown


# Draws tokens to make a reference
@composite
def draw_token_reference_valid(draw):
    token = draw(draw_token_unknown())
    return ([token], Reference(token.value))


# Tests parse_reference works correctly
# We expect the following behaviour:
# - The resulting reference has the token's value
# template_test_valid provides general parsing properties
@given(draw_token_reference_valid())
def test_parse_reference_valid(valid_data):
    (tokens, expected) = valid_data
    template_test_valid(Parser().parse_reference, tokens, expected)


# Tests parsing a reference with a reserved name errors
# We expect the following behaviour:
# - Error if a keyword or literal is encountered
# - Have ParseError.RESERVED_NAME as the exception code
# - Have ParseTask.PARSE_REFERENCE as the context's parse task
@given(draw_token_known())
def test_parse_reference_invalid_name(token):
    parent_context = static_parse_context()
    context = ParseContext(ParseTask.PARSE_REFERENCE, token, parent_context)
    error = ParseErrorException(ParseError.RESERVED_NAME, token, None, context)
    template_test_invalid(Parser().parse_reference, parent_context, [token], error)


# Tests parsing of empty references
# We expect the following behaviour:
# - Error if there isn't a token
# - Have ParseError.NO_TOKEN as the exception code
# - Have ParseTask.PARSE_REFERENCE as the context's parse task
def test_parse_reference_invalid_empty():
    parent_context = static_parse_context()
    context = ParseContext(ParseTask.PARSE_REFERENCE, None, parent_context)
    error = ParseErrorException(ParseError.NO_TOKEN, None, None, context)
    template_test_invalid(Parser().parse_reference, parent_context, [], error)