# Buggy code
def wait_for_successful_query(name, wait_for=300, **kwargs):
    """
    Like query but, repeat and wait until match/match_type or status is fulfilled. State returns result from last
    query state in case of success or if no successful query was made within wait_for timeout.

    request_interval
        Optional interval to delay requests by N seconds to reduce the number of requests sent.
    """
    starttime = time.time()

    while True:
        caught_exception = None
        ret = None
        try:
            ret = query(name, wait_for=wait_for, **kwargs)
            if ret["result"]:
                return ret
        except Exception as exc:
            caught_exception = exc

        if time.time() > starttime + wait_for:
            if not ret and caught_exception:
                # workaround pylint bug https://www.logilab.org/ticket/3207
                raise caught_exception  # pylint: disable=E0702
            return ret
        else:
            # Space requests out by delaying for an interval
            if "request_interval" in kwargs:
                log.debug(
                    "delaying query for {0} seconds.".format(kwargs["request_interval"])
                )
                time.sleep(kwargs["request_interval"])


# Traceback (OSError)
vernoncole@pizero:/projects/learn-salt $ sudo salt-call state.apply test_html
[ERROR   ] Failed to import module sensehat, this is due most likely to a syntax error:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1438, in _load_module
mod = imp.load_module(mod_namespace, fn_, fpath, desc)
File "/usr/lib/python2.7/dist-packages/salt/modules/sensehat.py", line 28, in <module>
_sensehat = SenseHat()
File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 39, in __init__
raise OSError('Cannot detect %s device' % self.SENSE_HAT_FB_NAME)
OSError: Cannot detect RPi-Sense FB device
[ERROR   ] Command '/tmp/file_clearing_daemon.py' failed with return code: None
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1934, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1802, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/http.py", line 153, in wait_for_successful_query
raise caught_exception  # pylint: disable=E0702
error: [Errno 111] Connection refused

local:
----------
ID: check_python3
Function: pkg.installed
Name: python3
Result: True
Comment: All specified packages are already installed
Started: 15:44:27.987937
Duration: 1411.573 ms
Changes:
----------
ID: create_the_file_clearing_daemon
Function: file.managed
Name: /tmp/file_clearing_daemon.py
Result: True
Comment: File /tmp/file_clearing_daemon.py is in the correct state
Started: 15:44:29.477777
Duration: 725.488 ms
Changes:
----------
ID: run_the_file_clearing_daemon
Function: cmd.run
Name: /tmp/file_clearing_daemon.py
Result: True
Comment: Command "/tmp/file_clearing_daemon.py" run
Started: 15:44:30.251466
Duration: 189.711 ms
Changes:
----------
pid:
10665
retcode:
None
stderr:
stdout:
----------
ID: let_the_file_clearing_daemon_get_started
Function: http.wait_for_successful_query
Name: http://127.0.0.1:4545/ping
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1934, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1802, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/states/http.py", line 153, in wait_for_successful_query
raise caught_exception  # pylint: disable=E0702
error: [Errno 111] Connection refused
Started: 15:44:30.463873
Duration: 30040.184 ms
Changes:

Summary for local
------------
Succeeded: 3 (changed=1)
Failed:    1
------------
Total states run:     4
Total run time:  32.367 s
vernoncole@pizero:/projects/learn-salt $ PXE_File_Clearing_Daemon --> Starting server - port:4545
PXE_File_Clearing_Daemon --> running server...

# Fixed code
def wait_for_successful_query(name, wait_for=300, **kwargs):
    """
    Like query but, repeat and wait until match/match_type or status is fulfilled. State returns result from last
    query state in case of success or if no successful query was made within wait_for timeout.

    name
        The name of the query.

    wait_for
        Total time to wait for requests that succeed.

    request_interval
        Optional interval to delay requests by N seconds to reduce the number of requests sent.

    .. note::

        All other arguements are passed to the http.query state.
    """
    starttime = time.time()

    while True:
        caught_exception = None
        ret = None
        try:
            ret = query(name, **kwargs)
            if ret["result"]:
                return ret
        except Exception as exc:
            caught_exception = exc

        if time.time() > starttime + wait_for:
            if not ret and caught_exception:
                # workaround pylint bug https://www.logilab.org/ticket/3207
                raise caught_exception  # pylint: disable=E0702
            return ret
        else:
            # Space requests out by delaying for an interval
            if "request_interval" in kwargs:
                log.debug(
                    "delaying query for {0} seconds.".format(kwargs["request_interval"])
                )
                time.sleep(kwargs["request_interval"])