1

My code is as below:

class myClass:
    def __init__(self):
        self.client = myClient()

    def myMethod(self):
        query = Query()
        response = self.client.post(data=query)

So now I'd like to introduce code change from data=query to data=query.__dict__, so how to design pytest and Mock() to test self.client.post has been called with passing in data=query.__dict__ rather than data=query?

LookIntoEast
  • 8,048
  • 18
  • 64
  • 92

1 Answers1

0

So, given this code in mymodule.py:

class myClient:
    def post(self, data):
        ...


class Query:
    pass


class myClass:
    def __init__(self):
        self.client = myClient()

    def myMethod(self):
        query = Query()
        response = self.client.post(data=query)

You can set your test like this in test_mymodule.py (same directory):

import pytest
from mymodule import myClass, Query


@pytest.fixture
def post(mocker):
    return mocker.patch("temp.myClient.post")


def test_myMethod_with_class(post):
    myclass = myClass()
    myclass.myMethod()
    assert isinstance(post.call_args[1]["data"], Query)

In which case pytest reports 1 test passed.

Now, if you replace "query" with "query.__dict__" in the above code, pytest will report 1 failed, so you have to change it like this:

def test_myMethod_with_dict(post):
    myclass = myClass()
    myclass.myMethod()
    assert isinstance(post.call_args[1]["data"], dict)

And once again pytest reports 1 test passed.

Laurent
  • 12,287
  • 7
  • 21
  • 37