#๐Ÿ”’ Mocking pytest test with @patch unittest.mock decorator

11 messages ยท Page 1 of 1 (latest)

hollow void
#

I use patch to mock send_request(). My problem is that send_request() function is not mocked. The original function is being called.
This is output that proves that. Notice that send request is printed. Also the type is function, not mock.

Send_click
send_request mock: <function send_request at 0x7f9c2146de40>
send request
#logic.py
def send_request(manager, action_method, url, data=None, params=None, headers=None):
    print("send request")
#test_ui.py
from ..ui import UserInterface

@patch("ui.send_request")
def test_send_request(mock_send_request, qtbot):
    ui = UserInterface()
    ui.get_request_data = Mock()
    data = QByteArray(data_str_create.encode("utf-8"))
    action_method, url, data = ACTIONS_METHODS.POST, QUrl("http://example.com/api"), data
    ui.get_request_data.return_value = action_method, url, data
    ui.send_click()
    mock_send_request.assert_called_once()

Because send_request() isn't mocked there is an AssertionError in the last line of test. I want my test to pass.
Below I show how send_request() is being used.

#ui.py
from logic import handle_response, send_request


class UserInterface(QWidget):
  #other methods
  def get_request_data(self):
    action_method = self.combo_box.currentText()
    json_dict = json.loads(
        self.body.toPlainText().encode("utf-8").decode("unicode_escape")
    )
    json_data = json.dumps(json_dict).encode("utf-8")
    data = QByteArray(json_data)
    url = QUrl(self.url.text())
    return action_method, url, data
 
  def send_click(self):
      print("Send_click")
      print(f"send_request mock: {send_request}") 
      send_request(self.rest_manager, *self.get_request_data())
        
        
tawny fiberBOT
#

@hollow void

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hollow void
hollow void
#

I have

sys.path.append("/home/jan/Projekty/QT/")  # TODO fix imports

in my conftest.py

Does it matter?

ebon violet
#

You should use pyproject.toml to add things to the python import path

hollow void
#

yep

#

switched to using pytest.ini

#

but problem is still there

tawny fiberBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.