Finishing natural language plugin.

This commit is contained in:
Adsooi 2024-10-17 02:08:24 +02:00
parent 8fab9d8e52
commit ef465b34e7
Signed by: Ad5001
GPG key ID: EF45F9C6AFE20160
10 changed files with 751 additions and 320 deletions

View file

@ -17,14 +17,23 @@
"""
class Assertion(Exception):
def __init__(self, assertion: bool, message: str):
def __init__(self, assertion: bool, message: str, invert: bool):
self.assertion = assertion
self.message = message
self.invert = invert
def _invert_message(self):
for verb in ('is', 'was', 'has', 'have'):
for negative in ("n't", ' not', ' never', ' no'):
self.message = self.message.replace(f"{verb}{negative}", verb.upper())
def __str__(self):
return self.message
def __bool__(self):
if not self.assertion:
if not self.invert and not self.assertion:
raise self
return self.assertion
if self.invert and self.assertion:
self._invert_message()
raise self
return True # Raises otherwise.

View file

@ -15,10 +15,10 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from typing import Self
from typing import Self, Callable, Any
from tests.plugins.natural.interfaces.assertion import Assertion
from tests.plugins.natural.interfaces.utils import repr_
from .assertion import Assertion
from .utils import repr_
class AssertionInterface:
@ -26,15 +26,91 @@ class AssertionInterface:
Most basic assertion interface.
You probably want to use BaseAssertionInterface
"""
def __init__(self, value):
def __init__(self, value, parent: Self = None):
self._value = value
self._parent = parent
if parent is None:
self.__not = False
@property
def was(self) -> Self:
def _not(self) -> bool:
"""
Internal state of whether the expression was negated.
Use "not_" to set it.
:return:
"""
return self.__not if self._parent is None else self._parent._not
@_not.setter
def _not(self, value: bool):
if self._not is True:
raise RuntimeError("Cannot call is_not or was_not twice in the same statement.")
if self._parent is None:
self.__not = True
else:
self._parent._not = True
def instance_of(self, type_: type) -> Assertion:
"""
Checks if the current value is equal to the provided value
"""
value_type_name = type(self._value).__name__
if not isinstance(type_, type):
raise RuntimeError("Provided 'type' provided is not a class.")
return Assertion(
isinstance(self._value, type_),
f"The value ({value_type_name} {repr_(self._value)}) is not a {type_.__name__}.",
self._not
)
def __call__(self, condition: Callable[[Any], bool]) -> Assertion:
"""
Apply condition to value that returns whether or not the value is valid.
"""
return Assertion(
condition(self._value),
f"The value ({repr_(self._value)}) did not match given conditions.",
self._not
)
"""
NOT Properties.
"""
@property
def NOT(self) -> Self:
self._not = True
return self
@property
def be(self) -> Self:
def not_(self) -> Self:
self._not = True
return self
@property
def never(self) -> Self:
self._not = True
return self
"""
Chain self properties to sound natural
"""
@property
def that(self) -> Self:
return self
@property
def is_(self) -> Self:
return self
@property
def does(self) -> Self:
return self
@property
def was(self) -> Self:
return self
@property
@ -57,31 +133,25 @@ class AssertionInterface:
def an(self) -> Self:
return self
def is_a(self, type_) -> Assertion:
"""
Checks if the current value is equal to the provided value
"""
value_type_name = type(self._value).__name__
return Assertion(isinstance(type_, type_), f"The value ({value_type_name} {repr_(self._value)}) is not a {type_.__name__}.")
class EqualAssertionInterface(AssertionInterface):
"""
Interface created for when its value should be checked for equality
"""
def __init__(self, value):
super().__init__(value)
def __init__(self, value, parent: AssertionInterface = None):
super().__init__(value, parent)
def __call__(self, value) -> Assertion:
return Assertion(value == self._value, f"The value ({repr_(self._value)}) is not equal to {repr(value)}.")
def to(self, value) -> Self:
return self(value)
def of(self, value) -> Self:
return self(value)
return Assertion(
value == self._value,
f"The value {repr_(self._value)} is different from {repr(value)}.",
self._not
)
@property
def to(self) -> Self:
return self
class BaseAssertionInterface(AssertionInterface):
@ -91,11 +161,11 @@ class BaseAssertionInterface(AssertionInterface):
"""
Checks if the current value is equal to the provided value
"""
return EqualAssertionInterface(self._value)
return EqualAssertionInterface(self._value, self)
@property
def is_equal(self) -> EqualAssertionInterface:
def equal(self) -> EqualAssertionInterface:
"""
Checks if the current value is equal to the provided value
"""
return self.equals
return self.equals

View file

@ -15,47 +15,69 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from tests.plugins.natural.interfaces.assertion import Assertion
from tests.plugins.natural.interfaces.base import BaseAssertionInterface
from tests.plugins.natural.interfaces.int import IntInterface
from tests.plugins.natural.interfaces.utils import repr_
from .assertion import Assertion
from .base import BaseAssertionInterface
from .int import NumberInterface
from .utils import repr_
class FixedIteratorInterface(BaseAssertionInterface):
@property
def length(self) -> IntInterface:
return IntInterface(len(self._value))
def length(self) -> NumberInterface:
return NumberInterface(len(self._value), self)
def elements(self, *elements) -> Assertion:
tests = [elem for elem in elements if elem in self._value]
tests = [repr_(elem) for elem in elements if elem not in self._value]
return Assertion(
len(tests) == 0,
f"This value ({repr_(self._value)}) does not have elements ({repr_(tests)})"
f"This value ({repr_(self._value)}) does not have elements {', '.join(tests)}.",
self._not
)
def element(self, element) -> Assertion:
return Assertion(
element in self._value,
f"This value ({repr_(self._value)}) does not have element ({repr_(element)})"
f"This value ({repr_(self._value)}) does not have element {repr_(element)}.",
self._not
)
def contains(self, *elements) -> Assertion:
return self.elements(*elements)
"""
Check if the element(s) are contained in the iterator.
"""
if len(elements) == 1:
return self.element(elements[0])
else:
return self.elements(*elements)
def contain(self, *elements):
"""
Check if the element(s) are contained in the iterator.
"""
return self.contains(*elements)
class BoolInterface(BaseAssertionInterface):
@property
def is_true(self):
def true(self):
return Assertion(
self._value == True,
f"The value ({repr_(self._value)}) is not True."
f"The value ({repr_(self._value)}) is not True.",
self._not
)
@property
def is_false(self):
def false(self):
return Assertion(
self._value == False,
f"The value ({repr_(self._value)}) is not False."
f"The value ({repr_(self._value)}) is not False.",
self._not
)
class StringInterface(LengthInterface):
pass
class StringInterface(FixedIteratorInterface):
pass
class ListInterface(FixedIteratorInterface):
pass

View file

@ -15,17 +15,47 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from idlelib.configdialog import is_int
from math import log10, floor, ceil
from typing import Self
from tests.plugins.natural.interfaces.assertion import Assertion
from tests.plugins.natural.interfaces.base import BaseAssertionInterface, EqualAssertionInterface, AssertionInterface
from tests.plugins.natural.interfaces.utils import repr_
from .assertion import Assertion
from .base import AssertionInterface
from .utils import repr_
class IntComparisonAssertionInterface(AssertionInterface):
def __init__(self, value):
super().__init__(value)
self._compare_to = None
class NumberComparisonAssertionInterface(AssertionInterface):
def __init__(self, value, parent: AssertionInterface = None):
super().__init__(value, parent)
self._compare_stack = []
def _generate_compare_to(self) -> int:
"""
The number generated by the comparison stack.
E.g. can parse one.hundred.million.and.thirty.three.thousand.and.twelve.hundred.and.seven
as ['one', 'hundred', 'million', 'thirty', 'three', 'thousand', 'twelve', 'hundred', 'seven']
which results 100,034,207
"""
minus = len(self._compare_stack) > 0 and self._compare_stack[0] == -1
if len(self._compare_stack) < (2 if minus else 1):
raise RuntimeError("No number to compare the value to provided.")
if minus:
self._compare_stack.pop(0)
# Compute the number
add_stack = [self._compare_stack.pop(0)]
for element in self._compare_stack:
last_power = floor(log10(abs(add_stack[-1])))
current_power = floor(log10(abs(element)))
if last_power < current_power: # E.g. one hundred
add_stack[-1] *= element
elif last_power == 1 and current_power == 0: # E.g thirty four
add_stack[-1] += element
elif last_power > current_power: # E.g a hundred and five
add_stack.append(element)
else:
raise RuntimeError(f"Cannot chain two numbers with the same power ({add_stack[-1]} => {element}.")
total = sum(add_stack)
return -total if minus else total
def _compare(self) -> Assertion:
raise RuntimeError(f"No comparison method defined in {type(self).__name__}.")
@ -34,23 +64,26 @@ class IntComparisonAssertionInterface(AssertionInterface):
return bool(self._compare())
def __call__(self, compare_to: int) -> Self:
if self._compare_to is None:
self._compare_to = int(compare_to)
else:
self._compare_to *= int(compare_to)
if type(compare_to) not in (float, int):
raise RuntimeError(f"Cannot compare number ({self._value}) to non number ({repr_(compare_to)}).")
self._compare_stack.append(compare_to)
return self
"""
Chain self properties
"""
@property
def and_(self) -> Self:
return self
@property
def time(self) -> Self:
def AND(self) -> Self:
return self
@property
def times(self) -> Self:
return self
@property
def never(self) -> Self:
return self(0)
"""
Number shorthands
"""
@property
def once(self) -> Self:
@ -64,6 +97,10 @@ class IntComparisonAssertionInterface(AssertionInterface):
def thrice(self) -> Self:
return self(3)
@property
def minus(self) -> Self:
return self(-1)
@property
def zero(self) -> Self:
return self(0)
@ -108,6 +145,42 @@ class IntComparisonAssertionInterface(AssertionInterface):
def ten(self) -> Self:
return self(10)
@property
def eleven(self) -> Self:
return self(11)
@property
def twelve(self) -> Self:
return self(12)
@property
def thirteen(self) -> Self:
return self(13)
@property
def fourteen(self) -> Self:
return self(14)
@property
def fifteen(self) -> Self:
return self(15)
@property
def sixteen(self) -> Self:
return self(16)
@property
def seventeen(self) -> Self:
return self(17)
@property
def eighteen(self) -> Self:
return self(18)
@property
def nineteen(self) -> Self:
return self(19)
@property
def twenty(self) -> Self:
return self(20)
@ -134,11 +207,11 @@ class IntComparisonAssertionInterface(AssertionInterface):
@property
def eighty(self) -> Self:
return self(70)
return self(80)
@property
def ninety(self) -> Self:
return self(70)
return self(90)
@property
def hundred(self) -> Self:
@ -157,73 +230,92 @@ class IntComparisonAssertionInterface(AssertionInterface):
return self(1_000_000_000)
class LessThanComparisonInterface(IntComparisonAssertionInterface):
class LessThanComparisonInterface(NumberComparisonAssertionInterface):
def _compare(self) -> Assertion:
compare = self._generate_compare_to()
return Assertion(
self._value < self._compare_to,
f"The value ({repr_(self._value)}) is not less than to {repr_(self._compare_to)}."
self._value < compare,
f"The value ({repr_(self._value)}) is not less than to {repr_(compare)}.",
self._not
)
class MoreThanComparisonInterface(IntComparisonAssertionInterface):
class MoreThanComparisonInterface(NumberComparisonAssertionInterface):
def _compare(self) -> Assertion:
compare = self._generate_compare_to()
return Assertion(
self._value > self._compare_to,
f"The value ({repr_(self._value)}) is not more than to {repr_(self._compare_to)}."
self._value > compare,
f"The value ({repr_(self._value)}) is not more than to {repr_(compare)}.",
self._not
)
class AtLeastComparisonInterface(IntComparisonAssertionInterface):
class AtLeastComparisonInterface(NumberComparisonAssertionInterface):
def _compare(self) -> Assertion:
compare = self._generate_compare_to()
return Assertion(
self._value >= self._compare_to,
f"The value ({repr_(self._value)}) is not at least to {repr_(self._compare_to)}."
self._value >= compare,
f"The value ({repr_(self._value)}) is not at least to {repr_(compare)}.",
self._not
)
class AtMostComparisonInterface(IntComparisonAssertionInterface):
class AtMostComparisonInterface(NumberComparisonAssertionInterface):
def _compare(self) -> Assertion:
compare = self._generate_compare_to()
return Assertion(
self._value <= self._compare_to,
f"The value ({repr_(self._value)}) is not at least to {repr_(self._compare_to)}."
self._value <= compare,
f"The value ({repr_(self._value)}) is not at least to {repr_(compare)}.",
self._not
)
class EqualComparisonInterface(IntComparisonAssertionInterface):
class EqualComparisonInterface(NumberComparisonAssertionInterface):
def _compare(self) -> Assertion:
compare = self._generate_compare_to()
return Assertion(
self._value == self._compare_to,
f"The value ({repr_(self._value)}) is not equal to {repr_(self._compare_to)}."
self._value == compare,
f"The value ({repr_(self._value)}) is not equal to {repr_(compare)}.",
self._not
)
@property
def to(self) -> Self:
return self
def of(self) -> Self:
return self
class IntInterface(AssertionInterface):
def less_than(self) -> LessThanComparisonInterface:
return LessThanComparisonInterface(self._value)
@property
def more_than(self) -> MoreThanComparisonInterface:
return MoreThanComparisonInterface(self._value)
@property
def at_least(self) -> AtLeastComparisonInterface:
return AtLeastComparisonInterface(self._value)
@property
def at_most(self) -> AtMostComparisonInterface:
return AtMostComparisonInterface(self._value)
class NumberInterface(AssertionInterface):
def __call__(self, value):
return EqualComparisonInterface(self._value, self)(value)
@property
def equals(self) -> EqualComparisonInterface:
return EqualComparisonInterface(self._value)
return EqualComparisonInterface(self._value, self)
@property
def is_equal(self) -> EqualComparisonInterface:
return EqualComparisonInterface(self._value)
def equal(self) -> EqualComparisonInterface:
return EqualComparisonInterface(self._value, self)
@property
def exactly(self) -> EqualComparisonInterface:
return EqualComparisonInterface(self._value)
return EqualComparisonInterface(self._value, self)
@property
def of(self) -> EqualComparisonInterface:
return EqualComparisonInterface(self._value, self)
@property
def less_than(self) -> LessThanComparisonInterface:
return LessThanComparisonInterface(self._value, self)
@property
def more_than(self) -> MoreThanComparisonInterface:
return MoreThanComparisonInterface(self._value, self)
@property
def at_least(self) -> AtLeastComparisonInterface:
return AtLeastComparisonInterface(self._value, self)
@property
def at_most(self) -> AtMostComparisonInterface:
return AtMostComparisonInterface(self._value, self)

View file

@ -0,0 +1,218 @@
"""
* LogarithmPlotter - 2D plotter software to make BODE plots, sequences and distribution functions.
* Copyright (C) 2021-2024 Ad5001
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from typing import Callable, Self
from .base import Assertion, repr_, AssertionInterface
from .int import NumberComparisonAssertionInterface
PRINT_PREFIX = (" " * 24)
class SpyAssertion(Assertion):
def __init__(self, assertion: bool, message: str, calls: list, invert: bool):
super().__init__(assertion, message + "\n", invert)
if len(calls) > 0:
self.message += self.render_calls(calls)
else:
self.message += f"{PRINT_PREFIX}0 registered calls."
def render_calls(self, calls):
lines = [f"{PRINT_PREFIX}{len(calls)} registered call(s):"]
for call in calls:
repr_args = [repr_(arg) for arg in call[0]]
repr_kwargs = [f"{key}={repr_(arg)}" for key, arg in call[1].items()]
lines.append(f" - {', '.join([*repr_args, *repr_kwargs])}")
return ("\n" + PRINT_PREFIX).join(lines)
class Methods:
AT_LEAST_ONCE = "AT_LEAST_ONCE"
EXACTLY = "EXACTLY"
AT_LEAST = "AT_LEAST"
AT_MOST = "AT_MOST"
MORE_THAN = "MORE_THAN"
LESS_THAN = "LESS_THAN"
class CalledInterface(NumberComparisonAssertionInterface):
"""
Internal class generated by Spy.called.
"""
def __init__(self, calls: list[tuple[list, dict]], parent: AssertionInterface):
super().__init__(len(calls), parent)
self.__calls = calls
self.__method = Methods.AT_LEAST_ONCE
def __apply_method(self, calls):
required = None if self._compare_stack == [] else self._generate_compare_to()
calls_count = len(calls)
match self.__method:
case Methods.AT_LEAST_ONCE:
compare = len(calls) >= 1
error = f"Method was not called"
case Methods.EXACTLY:
compare = len(calls) == required
error = f"Method was not called {required} times ({required} != {calls_count})"
case Methods.AT_LEAST:
compare = len(calls) >= required
error = f"Method was not called at least {required} times ({required} >= {calls_count})"
case Methods.AT_MOST:
compare = len(calls) <= required
error = f"Method was not called at most {required} times ({required} <= {calls_count})"
case Methods.MORE_THAN:
compare = len(calls) > required
error = f"Method was not called more than {required} times ({required} > {calls_count})"
case Methods.LESS_THAN:
compare = len(calls) < required
error = f"Method was not called less than {required} times ({required} < {calls_count})"
case _:
raise RuntimeError(f"Unknown method {self.__method}.")
return compare, error
def __bool__(self) -> bool:
"""
Converts to boolean on assertion.
"""
compare, error = self.__apply_method(self.__calls)
return bool(SpyAssertion(compare, error + ".", self.__calls, self._not))
"""
Chaining methods
"""
def __call__(self, compare_to: int) -> Self:
super().__call__(compare_to)
if self.__method == Methods.AT_LEAST_ONCE:
self.__method = Methods.EXACTLY
return self
@property
def at_least(self) -> Self:
if self.__method == Methods.AT_LEAST_ONCE:
self.__method = Methods.AT_LEAST
else:
raise RuntimeError(f"Cannot redefine method from {self.__method} to {Methods.AT_MOST}")
return self
@property
def at_most(self) -> Self:
if self.__method == Methods.AT_LEAST_ONCE:
self.__method = Methods.AT_MOST
else:
raise RuntimeError(f"Cannot redefine method from {self.__method} to {Methods.AT_MOST}")
return self
@property
def more_than(self) -> Self:
if self.__method == Methods.AT_LEAST_ONCE:
self.__method = Methods.MORE_THAN
else:
raise RuntimeError(f"Cannot redefine method from {self.__method} to {Methods.MORE_THAN}")
return self
@property
def less_than(self) -> Self:
if self.__method == Methods.AT_LEAST_ONCE:
self.__method = Methods.LESS_THAN
else:
raise RuntimeError(f"Cannot redefine method from {self.__method} to {Methods.LESS_THAN}")
return self
@property
def time(self) -> Self:
return self
@property
def times(self) -> Self:
return self
"""
Class properties.
"""
def __match_calls_for_condition(self, condition: Callable[[list, dict], bool]) -> tuple[bool, str]:
calls = []
for call in self.__calls:
if condition(call[0], call[1]):
calls.append(call)
compare, error = self.__apply_method(calls)
return compare, error
def with_arguments(self, *args, **kwargs) -> SpyAssertion:
"""
Checks if the Spy has been called the given number of times
with at least the given arguments.
"""
def some_args_matched(a, kw):
args_matched = all((
arg in a
for arg in args
))
kwargs_matched = all((
key in kw and kw[key] == arg
for key, arg in kwargs.items()
))
return args_matched and kwargs_matched
compare, error = self.__match_calls_for_condition(some_args_matched)
repr_args = ', '.join([repr(arg) for arg in args])
repr_kwargs = ', '.join([f"{key}={repr(arg)}" for key, arg in kwargs.items()])
msg = f"{error} with arguments ({repr_args}) and keyword arguments ({repr_kwargs})."
return SpyAssertion(compare, msg, self.__calls, self._not)
def with_arguments_matching(self, test_condition: Callable[[list, dict], bool]) -> SpyAssertion:
"""
Checks if the Spy has been called the given number of times
with arguments matching the given conditions.
"""
compare, error = self.__match_calls_for_condition(test_condition)
msg = f"{error} with arguments matching given conditions."
return SpyAssertion(compare, msg, self.__calls, self._not)
def with_exact_arguments(self, *args, **kwargs) -> SpyAssertion:
"""
Checks if the Spy has been called the given number of times
with all the given arguments.
"""
compare, error = self.__match_calls_for_condition(lambda a, kw: a == args and kw == kwargs)
repr_args = ', '.join([repr(arg) for arg in args])
repr_kwargs = ', '.join([f"{key}={repr(arg)}" for key, arg in kwargs.items()])
msg = f"{error} with exact arguments ({repr_args}) and keyword arguments ({repr_kwargs})."
return SpyAssertion(compare, msg, self.__calls, self._not)
def with_no_argument(self) -> SpyAssertion:
"""
Checks if the Spy has been called the given number of times
with all the given arguments.
"""
compare, error = self.__match_calls_for_condition(lambda a, kw: len(a) == 0 and len(kw) == 0)
return SpyAssertion(compare, f"{error} with no arguments.", self.__calls, self._not)
class SpyAssertionInterface(AssertionInterface):
@property
def called(self) -> CalledInterface:
"""
Returns a boolean-able interface to check conditions for a given number of
time the spy was called.
"""
return CalledInterface(self._value.calls, self)