[Tutor] Unit testing infinite loops

eryksun eryksun at gmail.com
Fri Jan 31 13:57:55 CET 2014


On Fri, Jan 31, 2014 at 6:31 AM, James Chapman <james at uplinkzero.com> wrote:
> try:
>     while self.attribute:
>         time.sleep(1)
> except KeyboardInterrupt:
>     ...
>
> My unit test could then set the attribute. However I'd still have the
> problem of how I get from the unit test line that fires up the method to the
> next line to change the attribute.

You could add a method that toggles the attribute, and use a
threading.Timer to run it after a set interval.

> if it's testable as is, how would I test it?

CPython 2.3+ can interrupt the main thread from another thread using
the built-in function `_thread.interrupt_main`:

http://docs.python.org/3/library/_thread#_thread.interrupt_main

    >>> import _thread
    >>> _thread.interrupt_main()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyboardInterrupt

It's also implemented in PyPy, but not in Jython.


More information about the Tutor mailing list