"""Helper functions to help access hard-to-reach parts of the code for full
coverage.
"""
import re

records = {}
"""dict: keys are int `recid`; values are the `dict` of model properties. This
is just an in-memory cache for testing purposes.
"""
rxvar = re.compile(r"<(?P<kind>\w+):(?P<varname>\w[\w_\d]*)>")

def urlsub(url, subdict):
    """Substitutes path variables in the specified `url` with their values
    given in the substitution dictionary.

    Args:
        url (str): URL to substitute values in.
        subdict (dict): key-value pairs to substitute in for path variables.
    """
    result = url
    for match in rxvar.finditer(url):
        rstr = "<{kind}:{varname}>".format(**match.groupdict())
        varname = match.group("varname")
        result = result.replace(rstr, str(subdict[varname]))

    return result

#For some reason, the assertions generated by this method pass on the pytest
#side, but the coverage tool says this line isn't getting hit. Skip it...
def exception(**kwargs): # pragma: no cover
    """Creates an unhandled exception.

    Raises:
        ZeroDivisionError: all the time.
    """
    return 1/0.

def save(recid, _data=None, **kwargs):
    """Saves a record from the REST API to file.
    """
    global records
    records[recid] = _data

def query(recid, withname=False, **kwargs):
    """Queries the stored records.

    Args:
        recid (str): record identifier to get.
        withname (bool): argument just to make sure things are wired; doesn't
            do anything.
    """
    rec = records.get(recid, {})
    return {
      "page": 1,
      "pages": 1,
      "per_page": 10,
      "total": 1,
      "items": [rec]
     }
