I have a thorny problem that I can't seem to get to grips with. I am currently writing unit tests for a django custom auth-backend. On our system we actually have two backends: one the built-in django backend and the custom backend that sends out requests to a Java based API that returns user info in the form of XML. Now, I am writing unit tests so I don't want to be sending requests outside the system like that, I'm not trying to test the Java API, so my question is how can I get around this and mock the side-effects in the most robust way.

The function I am testing is something like this, where the url settings value is just the base url for the Java server that authenticates the username and password data and returns the xml, and the service value is just some magic for building the url query, its unimportant for us:

@staticmethod
def get_info_from_api_with_un_pw(username, password, service=12345):
    url = settings.AUTHENTICATE_URL_VIA_PASSWORD
    if AUTH_FIELD == "username":
        params = {"nick": username, "password": password}
    elif AUTH_FIELD == "email":
        params = {"email": username, "password": password}
    params["service"] = service
    encoded_params = urlencode([(k, smart_str(v, "latin1")) for k, v in params.items()])
    try:
        # get the user's data from the api
        xml = urlopen(url + encoded_params).read()
        userinfo = dict((e.tag, smart_unicode(e.text, strings_only=True))
                        for e in ET.fromstring(xml).getchildren())
        if "nil" in userinfo:
            return userinfo
        else:
            return None

So, we get the xml, parse it into a dict and if the key nil is present then we can return the dict and carry on happy and authenticated. Clearly, one solution is just to find a way to somehow override or monkeypatch the logic in the xml variable, I found this answer:

python django unit-testing mocking

Edit
Report