"""This module holds the test cases for the ``media`` app"""

import pickle
from mock import patch

from mtp.apps.common.tests.test_cases import WithMediaOnDisk
from ..models import PdfMedia
from ..tasks import generate_images_from_pdf_media

from .test_cases import MediaTestCase


class GenerateImagesFromPdfMediaTestTaskCase(MediaTestCase, WithMediaOnDisk):
    """Test case for the task ``generate_images_from_pdf_media``"""

    def test_generate_images_from_pdf_media(self):
        """Test the ``generate_images_from_pdf_media`` task"""

        # We just need to test if the task call the ``generate_images`` method.
        with patch.object(PdfMedia, 'generate_images') as patched:
            generate_images_from_pdf_media(pdf_media_pk=self.pdf_media.pk)

        # The model method was called once, with default args
        patched.assert_called_once_with(async=False)

    def test_generate_images_from_pdf_media_result_is_picklable(self):
        """Test the ``generate_images_from_pdf_media`` task result"""

        result = generate_images_from_pdf_media.delay(pdf_media_pk=self.pdf_media.pk)

        # The task result is picklable
        pickle.dumps(result, protocol=2)

    def test_generate_images_from_pdf_media_arg_is_picklable(self):
        """Test the ``generate_images_from_pdf_media`` task arg"""

        with patch.object(generate_images_from_pdf_media, 'delay') as patched:
            generate_images_from_pdf_media.delay(pdf_media_pk=self.pdf_media.pk)

        # It will raise if args/kwargs are not picklable
        # We use protocol 2 as in celery
        # (cf http://docs.celeryproject.org/projects/kombu/en/latest/userguide/serialization.html)
        for args_list in patched.call_args_list:
            pickle.dumps(args_list[0], protocol=2)  # args
            pickle.dumps(args_list[1], protocol=2)  # kwargs
