Repository: MaineKuehn/usim

Issue:
Allow delays of 0
As discussed on #27, it would be sensible for the user interface to allow delays of 0. This seems prudent when calculating delays and for usability.

The event loop currently special-cases ``None`` to mean "now" and so disallows other ways of expressing this. Ideally, we handle this in the user interface implementations - these are already doing much more.

There are currently two user-facing cases:
* ``time + 0``
* ``scope.do(after=0)``

Discussion:

Patch:
diff --git a/usim/_primitives/context.py b/usim/_primitives/context.py
index f27581b..7d86ea6 100644
--- a/usim/_primitives/context.py
+++ b/usim/_primitives/context.py
@@ -148,11 +148,16 @@ class Scope:
         which must exit without ``await``\ ing or ``yield``\ ing anything.
         """
         assert after is None or at is None,\
-            "schedule date must be either absolute or relative"
+            "start date must be either absolute or relative"
+        # resolve "now" to what the event loop expects
+        if after == 0:
+            after = None
+        elif at == __LOOP_STATE__.LOOP.time:
+            at = None
         assert after is None or after > 0,\
-            "schedule date must not be in the past"
+            "start date must not be in the past"
         assert at is None or at > __LOOP_STATE__.LOOP.time,\
-            "schedule date must not be in the past"
+            "start date must not be in the past"
         child_task = Task(payload, self, delay=after, at=at)
         __LOOP_STATE__.LOOP.schedule(
             child_task.__runner__,
diff --git a/usim/_primitives/timing.py b/usim/_primitives/timing.py
index ea750a2..d4a9d5d 100644
--- a/usim/_primitives/timing.py
+++ b/usim/_primitives/timing.py
@@ -12,7 +12,7 @@ time can represent more than 285 million years of time accurately.
        it is still not possible to reach :py:class:`Eternity`.
        This may change in the future.
 """
-from typing import Coroutine, Generator, Any, AsyncIterable
+from typing import Coroutine, Generator, Any, AsyncIterable, Union
 
 from .._core.loop import __LOOP_STATE__, __HIBERNATE__, Interrupt as CoreInterrupt
 from .notification import postpone, Notification
@@ -258,13 +258,20 @@ class Delay(Notification):
         delay = time + 20
         await delay      # delay for 20
         await delay      # delay for 20 again
-        print(time.now)  # gives 40
+        print(time.now)  # prints 40
 
-    The expression ``time + duration`` is equivalent to ``Delay(duration)``.
+    Because :py:class:`~.Delay` represents a time duration it is not a
+    :py:class:`~.Condition` that becomes true at some point in time.
+    If a Condition is required, use ``time == time.now + duration`` instead.
+
+    The expression ``time + duration`` is equivalent to ``Delay(duration)``
+    if ``duration`` is positive. If ``duration`` is ``0``, ``time + duration``
+    is equivalent to an :py:class:`~.Instant`.
     """
     __slots__ = ('duration',)
 
     def __init__(self, duration: float):
+        assert duration > 0, "delay must point at the future"
         super().__init__()
         self.duration = duration
 
@@ -278,6 +285,42 @@ class Delay(Notification):
     def __str__(self):
         return 'usim.time + {}'.format(self.duration)
 
+    # NOTE: Python objects *always* have __bool__, which defaults
+    # to True. We could debug-protect against misuse of bool(time + 3)
+    # but that would lead to observably different behaviour.
+    # If we always raise an error, that is inconsistent with other objects.
+
+    if __debug__:
+        def __and__(self, other):
+            raise TypeError((
+                "Operator & not supported for delays\n\n"
+                "Delays (time + delay) are measured from the ongoing current time,\n"
+                "They do not provide a Condition, but a Notification. Operators of\n"
+                "Condition are not supported.\n"
+                "\n"
+                "If a Condition is required, use 'time == time.now + delay' instead"
+            ))
+
+        def __or__(self, other):
+            raise TypeError((
+                "Operator | not supported for delays\n\n"
+                "Delays (time + delay) are measured from the ongoing current time,\n"
+                "They do not provide a Condition, but a Notification. Operators of\n"
+                "Condition are not supported.\n"
+                "\n"
+                "If a Condition is required, use 'time == time.now + delay' instead"
+            ))
+
+        def __invert__(self):
+            raise TypeError((
+                "Operator ~ not supported for delays\n\n"
+                "Delays (time + delay) are measured from the ongoing current time,\n"
+                "They do not provide a Condition, but a Notification. Operators of\n"
+                "Condition are not supported.\n"
+                "\n"
+                "If a Condition is required, use 'time == time.now + delay' instead"
+            ))
+
 
 class Time:
     r"""
@@ -344,7 +387,10 @@ class Time:
         """The current simulation time"""
         return __LOOP_STATE__.LOOP.time
 
-    def __add__(self, other: float) -> Delay:
+    def __add__(self, other: float) -> Union[Delay, Instant]:
+        assert other >= 0, "delay must point at the future"
+        if other == 0:
+            return Instant()
         return Delay(other)
 
     def __ge__(self, other: float) -> After:


Test patch:
diff --git a/usim_pytest/test_types/test_scope.py b/usim_pytest/test_types/test_scope.py
index aefbdd8..e003659 100644
--- a/usim_pytest/test_types/test_scope.py
+++ b/usim_pytest/test_types/test_scope.py
@@ -2,7 +2,7 @@ import pytest
 
 from usim import Scope, time, instant, Concurrent
 
-from ..utility import via_usim
+from ..utility import via_usim, assertion_mode
 
 
 async def async_raise(exc: BaseException, after=0):
@@ -12,6 +12,10 @@ async def async_raise(exc: BaseException, after=0):
     raise exc
 
 
+async def async_pass():
+    pass
+
+
 class TestExceptions:
     @via_usim
     async def test_fail_scope(self):
@@ -131,3 +135,43 @@ class TestExceptions:
                     scope.do(async_raise(TypeError(), 0))
                     scope.do(async_raise(KeyError(), 0))
                     raise exc_type
+
+
+class TestScoping:
+    @via_usim
+    async def test_do_after(self):
+        async with Scope() as scope:
+            apass = scope.do(async_pass(), after=10)
+            assert time.now == 0
+            await apass
+            assert time.now == 10
+            # zero delay is well-defined
+            apass = scope.do(async_pass(), after=0)
+            assert time.now == 10
+            await apass
+            assert time.now == 10
+
+    @via_usim
+    async def test_do_at(self):
+        async with Scope() as scope:
+            apass = scope.do(async_pass(), at=10)
+            assert time.now == 0
+            await apass
+            assert time.now == 10
+            # zero delay is well-defined
+            apass = scope.do(async_pass(), at=10)
+            assert time.now == 10
+            await apass
+            assert time.now == 10
+
+    @assertion_mode
+    @via_usim
+    async def test_do_misuse(self):
+        fail_pass = async_pass()
+        with pytest.raises(AssertionError):
+            async with Scope() as scope:
+                scope.do(fail_pass, at=-1)
+        with pytest.raises(AssertionError):
+            async with Scope() as scope:
+                scope.do(fail_pass, after=-1)
+        fail_pass.close()
diff --git a/usim_pytest/test_types/test_time.py b/usim_pytest/test_types/test_time.py
index 009d84c..27487d6 100644
--- a/usim_pytest/test_types/test_time.py
+++ b/usim_pytest/test_types/test_time.py
@@ -4,7 +4,7 @@ import pytest
 
 from usim import time, until, eternity, instant, each
 
-from ..utility import via_usim
+from ..utility import via_usim, assertion_mode
 
 
 class TestTime:
@@ -19,6 +19,18 @@ class TestTime:
             await time
         with pytest.raises(TypeError):
             await (time <= 100)
+        with pytest.raises(TypeError):
+            ~(time + 3)
+        with pytest.raises(TypeError):
+            (time + 3) & (time == 3)
+        with pytest.raises(TypeError):
+            (time + 3) | (time == 3)
+
+    @assertion_mode
+    @via_usim
+    async def test_debug_misuse(self):
+        with pytest.raises(AssertionError):
+            await (time + -1)
 
     @via_usim
     async def test_delay(self):
@@ -27,6 +39,9 @@ class TestTime:
             assert start + (delay * seq) == time.now
             await (time + delay)
         assert start + (delay * 5) == time.now
+        # allow for 0 delay
+        await (time + 0)
+        assert start + (delay * 5) == time.now
 
     @via_usim
     async def test_moment(self):