0

I am trying to unit test my Workers class functions inside my workers.py module while testing file_download() which basically manipulates the message and makes another its own message and publish it to a google pubsub topic.

fileDownloaderWorkerPubSub.publish(
                message=byte_message,
                attributes={"key_1": value1, "key_2": value2},
            )

the pubsub instance used to publish the message is being initialized in main.py

    workers.fileDownloaderWorkerPubSub = create_pubsub(
        project_id, topic_id, logger
    )

This is my unit test code for testing the file_download() in my Workers class inside workers.py

    @patch("src.vapubsub.pubsub_v1.PublisherClient")
    def test_file_downloader_worker(self, mock_publisher_client):
        mock_publish = Mock()
        mock_publisher_client.return_value.publish = mock_publish

        self.worker.file_downloader_worker(self.message)
        mock_publish.assert_called_once()

Here i have patched the publisher client which basically is responsible for publishing messages in pubsub topic

The error i am getting here is mentioned below, how to resolve this?

ERROR:root:error in file downloader worker: name 'fileDownloaderWorkerPubSub' is not defined

Failure
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\unittest\mock.py", line 1369, in patched
    return func(*newargs, **newkeywargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\shivam.kumar27\slb\agora-va-event-service\tests\test_workers.py", line 199, in test_file_downloader_worker
    mock_publish.assert_called_once()
  File "C:\Program Files\Python311\Lib\unittest\mock.py", line 912, in assert_called_once
    raise AssertionError(msg)
AssertionError: Expected 'publish' to have been called once. Called 0 times.

Any leades would be appreciated.

Shivam Kumar
  • 85
  • 1
  • 9
  • The error doesn't seem related to mocking, hard to tell from the limited code in the question. Can you share a traceback from the error? Seems like ti could come from `fileDownloaderWorkerPubSub.publish` – Anentropic Aug 24 '23 at 13:57
  • Hey edited the question with error traceback, hope this might help @Anentropic – Shivam Kumar Aug 25 '23 at 04:57
  • it looks like there is an error in the worker(?) _"name 'fileDownloaderWorkerPubSub' is not defined"_ that is perhaps caught and logged, since you see it but the method call still returns, allowing the test to reach the assertion on the following line. There is clearly something wrong in the file where you have the code `fileDownloaderWorkerPubSub.publish(...)` – Anentropic Aug 25 '23 at 10:27

0 Answers0