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

from hypothesis import given


# Tests that a class's getters work
def do_template_test_getters(class_name, members):
    test = class_name(**members)
    for name, expected in members.items():
        value = getattr(test, name)
        if value != expected:
            raise AssertionError("%s doesn't match: %s != %s" % (name, value, expected))


# Tests that a class's equality method works
def do_template_test_equals(value1, value2, members):
    none_value = None
    assert (value1 == none_value) is False
    equals = True
    for name in members:
        member1 = getattr(value1, name)
        member2 = getattr(value2, name)
        equals = equals and (member1 == member2)
    assert (value1 == value2) == equals


# Creates a Hypothesis test that tests class getters and equals
def template_test_structure(class_name, draw, **kwargs):
    @given(**kwargs)
    def do_getters(**args):
        do_template_test_getters(class_name, args)

    @given(draw, draw)
    def do_equals(value1, value2):
        do_template_test_equals(value1, value2, kwargs.keys())

    def do_all():
        do_getters()
        do_equals()

    return lambda func: do_all