5

Using coverage to look what has to be tested, and coverage shows that next to this has to be tested: send_alert.apply_async()

I know it is celery task, but is there any way to test the line of code?

rest of code to understand logic for test:

class SomeView(GenericAPIView)
    def post(self, request, *args, **kwargs):
        #some code
        if not value:
           send_alert.apply_async()
           # response
        # not if Response

Test written due to first answer

    @patch('event.views.send_alert')
    def test_send_alert(self, mock_send):
        data = {some data for post}
        response = self.client.post('/api/{0}/mettings/'.format(self.user), data)
        print(response.json())
        self.assertTrue(mock_send.called)

Also i check in view that after task print('Tasks Passed') and i see message that tasks passed, but test failed with error AssertionError: False is not true

Beliaf
  • 577
  • 2
  • 8
  • 25

1 Answers1

6

I'm assuming you are using Django, as this is tagged that way.

Decorate your test with:

@override_settings(CELERY_EAGER=True)
def test_foo(self):
    # Make your post

Or if you just want to test that it is called.

from mock import patch

@patch('your_module.your_file.send_alert.apply_async')
def test_foo(self, mock_send):
    # make your post with "value" set to True
    self.assertTrue(mock_send.called)
Cole Howard
  • 343
  • 1
  • 8
  • it works, but how to integrate this for example in post test view, for example if value not `True` this task is called. and test if it was called – Beliaf Apr 23 '18 at 14:12
  • cause this task is applying in view in post method when some value(what was received) wasn't true. – Beliaf Apr 23 '18 at 14:18
  • Updated the answer. The second version with mock should work for your use case. – Cole Howard Apr 23 '18 at 15:22
  • Edit question with test code and error that task isn't called, but have to be called cause after task i see `print`. – Beliaf Apr 23 '18 at 18:47
  • Are you patching in the right place? `send_alert` is in `component.message.tasks.send_alert`. But your patch should point to `..send_alert`. You need to patch the name space it is imported into. – Cole Howard Apr 23 '18 at 19:24
  • change to `events.views.send_alert` in this file `class SomeView` where that tasks is called, Updated code , same eeror – Beliaf Apr 23 '18 at 19:34
  • My bad. You need to patch the async method of the task: ` @patch('event.views.send_alert.apply_async') – Cole Howard Apr 23 '18 at 19:42