Cristian
Cristian

Reputation: 7165

Python Mock Not Getting Attributes

The functionality I am trying to test is as follows. I am trying to mock the client in this function, which comes from my auth module. I am trying to make the client's get function return a Mock object, which contains a property text which refers to our mock_response (seen further down).

def get_person_by_email(email):
    client = auth.client()
    # print(client) = <Mock name='mock_client()' id='4324810640'>
    response = client.get(url="http://..." + email)
    # print(response) = <Mock name='mock_client().get()' id='4575780304'>
    # print(response.text) = <Mock name='mock_client().get().text' id='4348534608'>
    return jsonify(loads(utils.strip_security_string(response.text)))

The function which is throwing TypeError: 'Mock' object has no attribute '__getitem__' is:

def strip_security_string(json_string):
    return "\n".join(json_string.split("\n")[1:])

Which simply removes the first line from the response.

And finally, the code which is trying to test the above functionality:

def test_get_person_by_email():
    with app.test_client() as client:
        with app.app_context():
            mock_response = """security-string
                {"key":"value"}"""
            mock_client = Mock(name='mock_client')
            mock_client.get.return_value = Mock(text=mock_response)
            with patch.object(auth, 'client', mock_client):
                response = client.get("http://.../email/[email protected]")

Upvotes: 1

Views: 5202

Answers (2)

Michele d&#39;Amico
Michele d&#39;Amico

Reputation: 23741

I'm not an mock expert but you could try to change mock_client().get.return_value with mock_client.get.return_value. That's because the code use auth.client() instead of auth.client

If you don't want to access to the mock_client() in the Mock creation stage you can do

mock_client_obj = Mock(name='mock_client_obj')
mock_client_obj.get.return_value = Mock(text=mock_response)
mock_client = Mock(name='mock_client',return_value=mock_client_obj)

Or a more simple

mock_client = Mock(name='mock_client')
mock_client.return_value.get.return_value.text = mock_response

Upvotes: 3

chepner
chepner

Reputation: 531938

On closer look, mock_response is not set to a valid JSON value. Perhaps you mean something like

mock_reponse= """[ "security-string", { "key": "value" } ]"""

See http://json.org for the grammar that describes correct values.

Upvotes: 0

Related Questions