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

from hypothesis import assume, given
from hypothesis.strategies import composite

from src.ast_types import Bool
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_bool, draw_token_random


# Draws tokens to not make a valid boolean
@composite
def draw_token_not_bool(draw):
    token = draw(draw_token_random())
    assume(token.value not in ["True", "False"])
    return token


# Tests parse_bool works correctly
# We expect the following behaviour:
# - The resulting boolean is True if the first token is True
# - The resulting boolean is False if the first token is False
# template_test_valid provides general parsing properties
@given(draw_token_bool())
def test_parse_bool_valid(token):
    value = token.value == "True"
    expected = Bool(value)
    template_test_valid(Parser().parse_bool, [token], expected)


# Tests parsing of invalid booleans
# We expect the following behaviour:
# - Error if the token is not True or False
# - Have ParseError.NOT_BOOL as the exception code
# - Have ParseTask.PARSE_BOOL as the context's parse task
@given(draw_token_not_bool())
def test_parse_bool_invalid_incorrect(token):
    parent_context = static_parse_context()
    context = ParseContext(ParseTask.PARSE_BOOL, token, parent_context)
    error = ParseErrorException(ParseError.NOT_BOOL, token, None, context)
    parser = Parser().parse_bool
    template_test_invalid(parser, parent_context, [token], error)


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