def test_recreate_previews(pngcrush_image_mock):
    addon = addon_factory()
    # Set up the preview so it has files in the right places.
    preview_no_original = Preview.objects.create(addon=addon)
    with root_storage.open(preview_no_original.image_path, 'wb') as dest:
        shutil.copyfileobj(open(get_image_path('preview_landscape.jpg'), 'rb'),
                           dest)
    with root_storage.open(preview_no_original.thumbnail_path, 'wb') as dest:
        shutil.copyfileobj(open(get_image_path('mozilla.png'), 'rb'), dest)
    # And again but this time with an "original" image.
    preview_has_original = Preview.objects.create(addon=addon)
    with root_storage.open(preview_has_original.image_path, 'wb') as dest:
        shutil.copyfileobj(open(get_image_path('preview_landscape.jpg'), 'rb'),
                           dest)
    with root_storage.open(preview_has_original.thumbnail_path, 'wb') as dest:
        shutil.copyfileobj(open(get_image_path('mozilla.png'), 'rb'), dest)
    with root_storage.open(preview_has_original.original_path, 'wb') as dest:
        shutil.copyfileobj(open(get_image_path('teamaddons.jpg'), 'rb'), dest)

    tasks.recreate_previews([addon.id])

    assert preview_no_original.reload().sizes == {
        'image': [533, 400],
        'thumbnail': [533, 400],
        'thumbnail_format': 'jpg',
    }
    # Check no resize for full size, but resize happened for thumbnail
    assert root_storage.size(
        preview_no_original.image_path) == root_storage.size(
            get_image_path('preview_landscape.jpg'))
    assert root_storage.size(
        preview_no_original.thumbnail_path) != root_storage.size(
            get_image_path('mozilla.png'))
    assert root_storage.size(preview_no_original.thumbnail_path) > 0

    assert preview_has_original.reload().sizes == {
        'image': [2400, 1600],
        'thumbnail': [533, 355],
        'original': [3000, 2000],
        'thumbnail_format': 'jpg',
    }
    # Check both full and thumbnail changed, but original didn't.
    assert root_storage.size(
        preview_has_original.image_path) != root_storage.size(
            get_image_path('preview_landscape.jpg'))
    assert root_storage.size(
        preview_has_original.thumbnail_path) != root_storage.size(
            get_image_path('mozilla.png'))
    assert root_storage.size(preview_has_original.thumbnail_path) > 0
    assert root_storage.size(
        preview_has_original.original_path) == root_storage.size(
            get_image_path('teamaddons.jpg'))
Exemple #2
0
    def test_create_persona_preview_image(self, pngcrush_image_mock):
        addon = addon_factory()
        addon.modified = self.days_ago(41)
        # Given an image, a 680x100 and a 32x32 thumbnails need to be generated
        # and processed with pngcrush.
        expected_dst1 = tempfile.NamedTemporaryFile(
            mode='wb', suffix=".png", delete=False, dir=settings.TMP_PATH)
        expected_dst2 = tempfile.NamedTemporaryFile(
            mode='wb', suffix=".png", delete=False, dir=settings.TMP_PATH)
        create_persona_preview_images(
            src=get_image_path('persona-header.jpg'),
            full_dst=[expected_dst1.name, expected_dst2.name],
            set_modified_on=addon.serializable_reference(),
        )
        # pngcrush_image should have been called twice, once for each
        # destination thumbnail.
        assert pngcrush_image_mock.call_count == 2
        assert pngcrush_image_mock.call_args_list[0][0][0] == (
            expected_dst1.name)
        assert pngcrush_image_mock.call_args_list[1][0][0] == (
            expected_dst2.name)

        assert image_size(expected_dst1.name) == (680, 100)
        assert image_size(expected_dst2.name) == (32, 32)

        addon.reload()
        self.assertCloseToNow(addon.modified)
    def test_preview_size(self, pngcrush_image_mock):
        addon = Addon.objects.get(pk=3615)
        name = 'non-animated.gif'
        form = forms.PreviewForm({
            'caption': 'test',
            'upload_hash': name,
            'position': 1
        })
        with storage.open(os.path.join(self.dest, name), 'w') as f:
            shutil.copyfileobj(open(get_image_path(name)), f)
        assert form.is_valid()
        form.save(addon)
        preview = addon.previews.all()[0]
        assert preview.sizes == ({
            u'image': [250, 297],
            u'thumbnail': [168, 200],
            u'original': [250, 297]
        })
        assert os.path.exists(preview.image_path)
        assert os.path.exists(preview.thumbnail_path)
        assert os.path.exists(preview.original_path)

        assert pngcrush_image_mock.call_count == 2
        assert pngcrush_image_mock.call_args_list[0][0][0] == (
            preview.thumbnail_path)
        assert pngcrush_image_mock.call_args_list[1][0][0] == (
            preview.image_path)
    def test_edit_media_uploadedicon(self):
        img = get_image_path("mozilla.png")
        src_image = open(img, "rb")

        data = dict(upload_image=src_image)

        response = self.client.post(self.icon_upload, data)
        response_json = json.loads(response.content)
        addon = self.get_addon()

        # Now, save the form so it gets moved properly.
        data = dict(icon_type="image/png", icon_upload_hash=response_json["upload_hash"])
        data_formset = self.formset_media(**data)

        r = self.client.post(self.media_edit_url, data_formset)
        eq_(r.context["form"].errors, {})
        addon = self.get_addon()

        # Unfortunate hardcoding of URL
        url = addon.get_icon_url(64)
        assert ("addon_icons/3/%s" % addon.id) in url, "Unexpected path: %r" % url

        eq_(data["icon_type"], "image/png")

        # Check that it was actually uploaded
        dirname = os.path.join(user_media_path("addon_icons"), "%s" % (addon.id / 1000))
        dest = os.path.join(dirname, "%s-32.png" % addon.id)

        assert storage.exists(dest)

        eq_(Image.open(storage.open(dest)).size, (32, 12))
Exemple #5
0
    def test_create_persona_preview_image(self, pngcrush_image_mock):
        addon = addon_factory()
        addon.modified = self.days_ago(41)
        # Given an image, a 680x100 and a 32x32 thumbnails need to be generated
        # and processed with pngcrush.
        expected_dst1 = tempfile.NamedTemporaryFile(mode='r+w+b',
                                                    suffix=".png",
                                                    delete=False,
                                                    dir=settings.TMP_PATH)
        expected_dst2 = tempfile.NamedTemporaryFile(mode='r+w+b',
                                                    suffix=".png",
                                                    delete=False,
                                                    dir=settings.TMP_PATH)
        create_persona_preview_images(
            src=get_image_path('persona-header.jpg'),
            full_dst=[expected_dst1.name, expected_dst2.name],
            set_modified_on=addon.serializable_reference(),
        )
        # pngcrush_image should have been called twice, once for each
        # destination thumbnail.
        assert pngcrush_image_mock.call_count == 2
        assert pngcrush_image_mock.call_args_list[0][0][0] == (
            expected_dst1.name)
        assert pngcrush_image_mock.call_args_list[1][0][0] == (
            expected_dst2.name)

        assert image_size(expected_dst1.name) == (680, 100)
        assert image_size(expected_dst2.name) == (32, 32)

        addon.reload()
        self.assertCloseToNow(addon.modified)
Exemple #6
0
    def test_preview_size(self, pngcrush_image_mock):
        addon = Addon.objects.get(pk=3615)
        name = 'teamaddons.jpg'
        form = forms.PreviewForm({
            'caption': 'test',
            'upload_hash': name,
            'position': 1
        })
        with storage.open(os.path.join(self.dest, name), 'wb') as f:
            shutil.copyfileobj(open(get_image_path(name), 'rb'), f)
        assert form.is_valid()
        form.save(addon)
        preview = addon.previews.all()[0]
        assert preview.sizes == ({
            'image': [2400, 1600],
            'thumbnail': [533, 355],
            'original': [3000, 2000],
            'thumbnail_format': 'jpg',
        })
        assert os.path.exists(preview.image_path)
        assert os.path.exists(preview.thumbnail_path)
        assert os.path.exists(preview.original_path)

        assert pngcrush_image_mock.call_count == 1  # the thumbnail isn't a png now
        assert pngcrush_image_mock.call_args_list[0][0][0] == (
            preview.image_path)
Exemple #7
0
    def test_success(self, save_persona_image_mock,
                     create_persona_preview_images_mock, make_checksum_mock):
        make_checksum_mock.return_value = 'hashyourselfbeforeyoucrashyourself'

        self.request.user = UserProfile.objects.get(pk=2519)

        data = self.get_dict()
        header_url = self.get_img_urls()

        # Upload header image.
        img = open(get_image_path('persona-header.jpg'), 'rb')
        r_ajax = self.client.post(header_url, {'upload_image': img})
        content = json.loads(force_text(r_ajax.content))
        data.update(header_hash=content['upload_hash'])

        # Populate and save form.
        self.post()
        assert self.form.is_valid(), self.form.errors
        self.form.save()

        addon = Addon.objects.filter(type=amo.ADDON_PERSONA).order_by('-id')[0]
        persona = addon.persona

        # Test for correct Addon and Persona values.
        assert six.text_type(addon.name) == data['name']
        assert addon.slug == data['slug']
        self.assertSetEqual(set(addon.categories.values_list('id', flat=True)),
                            {self.cat.id})
        self.assertSetEqual(set(addon.tags.values_list('tag_text', flat=True)),
                            set(data['tags'].split(', ')))
        assert persona.persona_id == 0
        assert persona.license == data['license']
        assert persona.accentcolor == data['accentcolor'].lstrip('#')
        assert persona.textcolor == data['textcolor'].lstrip('#')
        assert persona.author == self.request.user.username
        assert persona.display_username == self.request.user.name
        assert not persona.dupe_persona

        v = addon.versions.all()
        assert len(v) == 1
        assert v[0].version == '0'

        # Test for header and preview images.
        dst = os.path.join(user_media_path('addons'), str(addon.id))

        header_src = os.path.join(settings.TMP_PATH, 'persona_header',
                                  u'b4ll1n')

        assert save_persona_image_mock.mock_calls == ([
            mock.call(src=header_src, full_dst=os.path.join(dst, 'header.png'))
        ])

        create_persona_preview_images_mock.assert_called_with(
            src=header_src,
            full_dst=[
                os.path.join(dst, 'preview.png'),
                os.path.join(dst, 'icon.png')
            ],
            set_modified_on=addon.serializable_reference())
Exemple #8
0
 def test_preview_transparency(self):
     addon = Addon.objects.get(pk=3615)
     name = 'transparent-cotton'
     hash = '12345678abcd'
     form = forms.PreviewForm(
         {'caption': 'test', 'upload_hash': hash, 'position': 1}
     )
     with storage.open(os.path.join(self.dest, hash), 'wb') as f:
         shutil.copyfileobj(open(get_image_path(name + '.png'), 'rb'), f)
     assert form.is_valid()
     form.save(addon)
     preview = addon.previews.all()[0]
     assert os.path.exists(preview.thumbnail_path)
     with storage.open(preview.thumbnail_path, 'rb') as thumb_file, open(
         get_image_path(name + '.jpg'), 'rb'
     ) as sample_file:
         assert thumb_file.read() == sample_file.read()
Exemple #9
0
 def test_img_size(self):
     img = get_image_path('mozilla.png')
     for url, img_type in zip(self.get_img_urls(), ('header', 'footer')):
         r_ajax = self.client.post(url, {'upload_image': open(img, 'rb')})
         r_json = json.loads(r_ajax.content)
         w, h = amo.PERSONA_IMAGE_SIZES.get(img_type)[1]
         eq_(r_json['errors'], ['Image must be exactly %s pixels wide '
                                'and %s pixels tall.' % (w, h)])
 def test_filename_not_uuidfied(self, validate_mock):
     validate_mock.return_value = json.dumps(amo.VALIDATOR_SKELETON_RESULTS)
     url = reverse('devhub.upload')
     data = open(get_image_path('animated.png'), 'rb')
     self.client.post(url, {'upload': data})
     upload = FileUpload.objects.get()
     response = self.client.get(
         reverse('devhub.upload_detail', args=(upload.uuid.hex, )))
     assert 'Validation Results for animated.png' in response.content
Exemple #11
0
 def test_preview_modified(self, update_mock):
     addon = Addon.objects.get(pk=3615)
     name = "transparent.png"
     form = forms.PreviewForm({"caption": "test", "upload_hash": name, "position": 1})
     with storage.open(os.path.join(self.dest, name), "w") as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert update_mock.called
Exemple #12
0
 def test_preview_size(self):
     addon = Addon.objects.get(pk=3615)
     name = "non-animated.gif"
     form = forms.PreviewForm({"caption": "test", "upload_hash": name, "position": 1})
     with storage.open(os.path.join(self.dest, name), "w") as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert addon.previews.all()[0].sizes == ({u"image": [250, 297], u"thumbnail": [126, 150]})
Exemple #13
0
 def test_filename_not_uuidfied(self, validate_mock):
     validate_mock.return_value = json.dumps(amo.VALIDATOR_SKELETON_RESULTS)
     url = reverse('devhub.upload')
     data = open(get_image_path('animated.png'), 'rb')
     self.client.post(url, {'upload': data})
     upload = FileUpload.objects.get()
     response = self.client.get(
         reverse('devhub.upload_detail', args=(upload.uuid.hex,)))
     assert 'Validation Results for animated.png' in response.content
Exemple #14
0
    def test_success(self, save_persona_image_mock,
                     create_persona_preview_images_mock, make_checksum_mock):
        make_checksum_mock.return_value = 'hashyourselfbeforeyoucrashyourself'

        self.request.user = UserProfile.objects.get(pk=2519)

        data = self.get_dict()
        header_url = self.get_img_urls()

        # Upload header image.
        img = open(get_image_path('persona-header.jpg'), 'rb')
        r_ajax = self.client.post(header_url, {'upload_image': img})
        data.update(header_hash=json.loads(r_ajax.content)['upload_hash'])

        # Populate and save form.
        self.post()
        assert self.form.is_valid(), self.form.errors
        self.form.save()

        addon = Addon.objects.filter(type=amo.ADDON_PERSONA).order_by('-id')[0]
        persona = addon.persona

        # Test for correct Addon and Persona values.
        assert unicode(addon.name) == data['name']
        assert addon.slug == data['slug']
        self.assertSetEqual(set(addon.categories.values_list('id', flat=True)),
                            {self.cat.id})
        self.assertSetEqual(set(addon.tags.values_list('tag_text', flat=True)),
                            set(data['tags'].split(', ')))
        assert persona.persona_id == 0
        assert persona.license == data['license']
        assert persona.accentcolor == data['accentcolor'].lstrip('#')
        assert persona.textcolor == data['textcolor'].lstrip('#')
        assert persona.author == self.request.user.username
        assert persona.display_username == self.request.user.name
        assert not persona.dupe_persona

        v = addon.versions.all()
        assert len(v) == 1
        assert v[0].version == '0'

        # Test for header and preview images.
        dst = os.path.join(user_media_path('addons'), str(addon.id))

        header_src = os.path.join(settings.TMP_PATH, 'persona_header',
                                  u'b4ll1n')

        assert save_persona_image_mock.mock_calls == (
            [mock.call(src=header_src,
                       full_dst=os.path.join(dst, 'header.png'))])

        create_persona_preview_images_mock.assert_called_with(
            src=header_src,
            full_dst=[os.path.join(dst, 'preview.png'),
                      os.path.join(dst, 'icon.png')],
            set_modified_on=addon.serializable_reference())
Exemple #15
0
 def test_preview_modified(self, update_mock):
     addon = Addon.objects.get(pk=3615)
     name = 'transparent.png'
     form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
                               'position': 1})
     with storage.open(os.path.join(self.dest, name), 'w') as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert update_mock.called
Exemple #16
0
 def test_upload_sideload_addon(self, validate_mock):
     """Sideload addons are validated as "self-hosted" addons."""
     validate_mock.return_value = json.dumps(amo.VALIDATOR_SKELETON_RESULTS)
     self.url = reverse('devhub.upload_sideload')
     data = open(get_image_path('animated.png'), 'rb')
     self.client.post(self.url, {'upload': data})
     # Make sure it was called with listed=False.
     assert not validate_mock.call_args[1]['listed']
     # No automated signing for sideload add-ons.
     assert FileUpload.objects.get().automated_signing is False
Exemple #17
0
 def test_preview_modified(self, update_mock):
     addon = Addon.objects.get(pk=3615)
     name = 'transparent.png'
     form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
                               'position': 1})
     with storage.open(os.path.join(self.dest, name), 'w') as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert update_mock.called
Exemple #18
0
 def test_upload_unlisted_addon(self, validate_mock):
     """Unlisted addons are validated as "self-hosted" addons."""
     validate_mock.return_value = json.dumps(amo.VALIDATOR_SKELETON_RESULTS)
     self.url = reverse('devhub.upload_unlisted')
     data = open(get_image_path('animated.png'), 'rb')
     self.client.post(self.url, {'upload': data})
     # Make sure it was called with listed=False.
     assert not validate_mock.call_args[1]['listed']
     # Automated signing enabled for unlisted add-ons.
     assert FileUpload.objects.get().automated_signing is True
Exemple #19
0
 def test_preview_size(self):
     addon = Addon.objects.get(pk=3615)
     name = 'non-animated.gif'
     form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
                               'position': 1})
     with storage.open(os.path.join(self.dest, name), 'w') as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert addon.previews.all()[0].sizes == (
         {u'image': [250, 297], u'thumbnail': [126, 150]})
Exemple #20
0
 def test_preview_size(self):
     addon = Addon.objects.get(pk=3615)
     name = 'non-animated.gif'
     form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
                               'position': 1})
     with storage.open(os.path.join(self.dest, name), 'w') as f:
         copyfileobj(open(get_image_path(name)), f)
     assert form.is_valid()
     form.save(addon)
     assert addon.previews.all()[0].sizes == (
         {u'image': [250, 297], u'thumbnail': [126, 150]})
Exemple #21
0
    def test_icon_modified(self, update_mock):
        name = 'transparent.png'
        form = forms.AddonFormMedia({'icon_upload_hash': name},
                                    request=self.request,
                                    instance=self.addon)

        dest = os.path.join(self.icon_path, name)
        with storage.open(dest, 'wb') as f:
            shutil.copyfileobj(open(get_image_path(name), 'rb'), f)
        assert form.is_valid()
        form.save(addon=self.addon)
        assert update_mock.called
Exemple #22
0
 def test_save_persona_image(self, pngcrush_image_mock):
     # save_persona_image() simply saves an image as a png to the
     # destination file. The image should be processed with pngcrush.
     expected_dst = tempfile.NamedTemporaryFile(mode='r+w+b',
                                                suffix=".png",
                                                delete=False,
                                                dir=settings.TMP_PATH)
     save_persona_image(get_image_path('persona-header.jpg'),
                        expected_dst.name)
     # pngcrush_image should have been called once.
     assert pngcrush_image_mock.call_count == 1
     assert pngcrush_image_mock.call_args_list[0][0][0] == expected_dst.name
Exemple #23
0
    def setUp(self):
        super(TestFileDownload, self).setUp()

        assert self.client.login(email='*****@*****.**')

        self.file = open(get_image_path('animated.png'), 'rb')
        resp = self.client.post(reverse('devhub.upload'),
                                {'upload': self.file})
        assert resp.status_code == 302

        self.upload = FileUpload.objects.get()
        self.url = reverse('zadmin.download_file', args=[self.upload.uuid.hex])
Exemple #24
0
 def test_save_persona_image_not_an_image(self, pngcrush_image_mock):
     # If the source is not an image, save_persona_image() should just
     # return early without writing the destination or calling pngcrush.
     expected_dst = tempfile.NamedTemporaryFile(mode='r+w+b',
                                                suffix=".png",
                                                delete=False,
                                                dir=settings.TMP_PATH)
     save_persona_image(get_image_path('non-image.png'), expected_dst.name)
     # pngcrush_image should not have been called.
     assert pngcrush_image_mock.call_count == 0
     # the destination file should not have been written to.
     assert os.stat(expected_dst.name).st_size == 0
    def test_icon_modified(self, update_mock):
        name = 'transparent.png'
        form = forms.AddonFormMedia({'icon_upload_hash': name},
                                    request=self.request,
                                    instance=self.addon)

        dest = os.path.join(self.icon_path, name)
        with storage.open(dest, 'w') as f:
            copyfileobj(open(get_image_path(name)), f)
        assert form.is_valid()
        form.save(addon=self.addon)
        assert update_mock.called
Exemple #26
0
 def test_save_persona_image(self, pngcrush_image_mock):
     # save_persona_image() simply saves an image as a png to the
     # destination file. The image should be processed with pngcrush.
     expected_dst = tempfile.NamedTemporaryFile(
         mode='wb', suffix=".png", delete=False, dir=settings.TMP_PATH)
     save_persona_image(
         get_image_path('persona-header.jpg'),
         expected_dst.name
     )
     # pngcrush_image should have been called once.
     assert pngcrush_image_mock.call_count == 1
     assert pngcrush_image_mock.call_args_list[0][0][0] == expected_dst.name
Exemple #27
0
    def setUp(self):
        super(TestFileDownload, self).setUp()

        assert self.client.login(email='*****@*****.**')

        self.file = open(get_image_path('animated.png'), 'rb')
        resp = self.client.post(reverse('devhub.upload'),
                                {'upload': self.file})
        assert resp.status_code == 302

        self.upload = FileUpload.objects.get()
        self.url = reverse('zadmin.download_file', args=[self.upload.uuid.hex])
Exemple #28
0
def test_resize_icon_poorly():
    """If we attempt to set the src/dst, we do nothing."""
    somepic = get_image_path("mozilla.png")
    src = tempfile.NamedTemporaryFile(mode="r+w+b", suffix=".png", delete=False, dir=settings.TMP_PATH)
    shutil.copyfile(somepic, src.name)
    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)

    resize_icon(src.name, src.name, locally=True)

    # assert nothing happenned
    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)
Exemple #29
0
 def test_save_persona_image_not_an_image(self, pngcrush_image_mock):
     # If the source is not an image, save_persona_image() should just
     # return early without writing the destination or calling pngcrush.
     expected_dst = tempfile.NamedTemporaryFile(
         mode='wb', suffix=".png", delete=False, dir=settings.TMP_PATH)
     save_persona_image(
         get_image_path('non-image.png'),
         expected_dst.name
     )
     # pngcrush_image should not have been called.
     assert pngcrush_image_mock.call_count == 0
     # the destination file should not have been written to.
     assert os.stat(expected_dst.name).st_size == 0
def test_resize_photo_poorly():
    """If we attempt to set the src/dst, we do nothing."""
    somepic = get_image_path('mozilla.png')
    src = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                      delete=False, dir=settings.TMP_PATH)
    shutil.copyfile(somepic, src.name)
    src_image = Image.open(src.name)
    eq_(src_image.size, (339, 128))

    resize_photo(src.name, src.name)

    # assert nothing happenned
    src_image = Image.open(src.name)
    eq_(src_image.size, (339, 128))
def test_resize_icon_poorly():
    """If we attempt to set the src/dst, we do nothing."""
    somepic = get_image_path('mozilla.png')
    src = tempfile.NamedTemporaryFile(mode='r+w+b',
                                      suffix=".png",
                                      delete=False,
                                      dir=settings.TMP_PATH)
    shutil.copyfile(somepic, src.name)
    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)

    resize_icon(src.name, src.name, locally=True)

    # assert nothing happened
    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)
def _uploader(resize_size, final_size):
    img = get_image_path('mozilla.png')
    original_size = (339, 128)

    src = tempfile.NamedTemporaryFile(mode='r+b',
                                      suffix='.png',
                                      delete=False,
                                      dir=settings.TMP_PATH)

    if not isinstance(final_size, list):
        final_size = [final_size]
        resize_size = [resize_size]
    uploadto = user_media_path('addon_icons')
    try:
        os.makedirs(uploadto)
    except OSError:
        pass
    for rsize, expected_size in zip(resize_size, final_size):
        # resize_icon moves the original
        shutil.copyfile(img, src.name)
        src_image = Image.open(src.name)
        assert src_image.size == original_size
        dest_name = os.path.join(uploadto, '1234')

        with mock.patch('olympia.amo.utils.pngcrush_image') as pngcrush_mock:
            return_value = tasks.resize_icon(src.name, dest_name, [rsize])
        dest_image = '%s-%s.png' % (dest_name, rsize)
        assert pngcrush_mock.call_count == 1
        assert pngcrush_mock.call_args_list[0][0][0] == dest_image
        assert image_size(dest_image) == expected_size
        # original should have been moved to -original
        orig_image = '%s-original.png' % dest_name
        assert os.path.exists(orig_image)

        # Return value of the task should be a dict with an icon_hash key
        # containing the 8 first chars of the md5 hash of the source file,
        # which is bb362450b00f0461c6bddc6b97b3c30b.
        assert return_value == {'icon_hash': 'bb362450'}

        os.remove(dest_image)
        assert not os.path.exists(dest_image)
        os.remove(orig_image)
        assert not os.path.exists(orig_image)
    shutil.rmtree(uploadto)

    assert not os.path.exists(src.name)
Exemple #33
0
def test_resize_photo():
    somepic = get_image_path('sunbird-small.png')

    src = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                      delete=False, dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                       dir=settings.TMP_PATH)

    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == (64, 64)
    resize_photo(src.name, dest.name)

    # Image is smaller than 200x200 so it should stay the same.
    dest_image = Image.open(dest.name)
    assert dest_image.size == (64, 64)
Exemple #34
0
def test_resize_icon():
    somepic = get_image_path("mozilla.png")

    src = tempfile.NamedTemporaryFile(mode="r+w+b", suffix=".png", delete=False, dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode="r+w+b", suffix=".png", dir=settings.TMP_PATH)

    # resize_icon removes the original
    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)
    resize_icon(src.name, dest.name, locally=True)

    dest_image = Image.open(dest.name)
    assert dest_image.size == (32, 12)

    assert not os.path.exists(src.name)
def _uploader(resize_size, final_size):
    img = get_image_path('mozilla.png')
    original_size = (339, 128)

    src = tempfile.NamedTemporaryFile(
        mode='r+w+b', suffix='.png', delete=False, dir=settings.TMP_PATH)

    if not isinstance(final_size, list):
        final_size = [final_size]
        resize_size = [resize_size]
    uploadto = user_media_path('addon_icons')
    try:
        os.makedirs(uploadto)
    except OSError:
        pass
    for rsize, expected_size in zip(resize_size, final_size):
        # resize_icon moves the original
        shutil.copyfile(img, src.name)
        src_image = Image.open(src.name)
        assert src_image.size == original_size
        dest_name = os.path.join(uploadto, '1234')

        with mock.patch('olympia.amo.utils.pngcrush_image') as pngcrush_mock:
            return_value = tasks.resize_icon(src.name, dest_name, [rsize])
        dest_image = '%s-%s.png' % (dest_name, rsize)
        assert pngcrush_mock.call_count == 1
        assert pngcrush_mock.call_args_list[0][0][0] == dest_image
        assert image_size(dest_image) == expected_size
        # original should have been moved to -original
        orig_image = '%s-original.png' % dest_name
        assert os.path.exists(orig_image)

        # Return value of the task should be a dict with an icon_hash key
        # containing the 8 first chars of the md5 hash of the source file,
        # which is bb362450b00f0461c6bddc6b97b3c30b.
        assert return_value == {'icon_hash': 'bb362450'}

        os.remove(dest_image)
        assert not os.path.exists(dest_image)
        os.remove(orig_image)
        assert not os.path.exists(orig_image)
    shutil.rmtree(uploadto)

    assert not os.path.exists(src.name)
def test_resize_photo():
    somepic = get_image_path('sunbird-small.png')

    src = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                      delete=False, dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                       dir=settings.TMP_PATH)

    # resize_photo removes the original
    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    eq_(src_image.size, (64, 64))
    resize_photo(src.name, dest.name, locally=True)

    # Image is smaller than 200x200 so it should stay the same.
    dest_image = Image.open(dest.name)
    eq_(dest_image.size, (64, 64))

    assert not os.path.exists(src.name)
Exemple #37
0
def test_resize_icon():
    somepic = get_image_path('mozilla.png')

    src = tempfile.NamedTemporaryFile(mode='r+w+b',
                                      suffix=".png",
                                      delete=False,
                                      dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode='r+w+b',
                                       suffix=".png",
                                       dir=settings.TMP_PATH)

    # resize_icon removes the original
    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == (339, 128)
    resize_icon(src.name, dest.name)

    dest_image = Image.open(dest.name)
    assert dest_image.size == (32, 12)
Exemple #38
0
def test_resize_photo():
    somepic = get_image_path('sunbird-small.png')

    src = tempfile.NamedTemporaryFile(mode='r+b',
                                      suffix=".png",
                                      delete=False,
                                      dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode='r+b',
                                       suffix=".png",
                                       dir=settings.TMP_PATH)

    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == (64, 64)
    resize_photo(src.name, dest.name)

    # Image is smaller than 200x200 so it should stay the same.
    dest_image = Image.open(dest.name)
    assert dest_image.size == (64, 64)
    def testIconUpload(self, get_icon_dir):
        # TODO(gkoberger): clarify this please.
        # We no longer use AddonFormMedia to upload icons, so
        # skipping until I can ask andym what the point of this
        # test is.  Additionally, it's called "TestIconRemoval",
        # but it doesn't seem to remove icons.
        return
        get_icon_dir.return_value = self.temp_dir

        for path in self.get_icon_paths():
            assert not os.path.exists(path)

        img = get_image_path('non-animated.png')
        data = {'icon_upload': img, 'icon_type': 'text/png'}
        self.request.FILES = {'icon_upload': open(img)}
        form = forms.AddonFormMedia(data=data, request=self.request,
                                    instance=self.addon)
        assert form.is_valid()
        form.save(self.addon)
        for path in self.get_icon_paths():
            assert os.path.exists(path)
    def preview_add(self, amount=1):
        img = get_image_path("mozilla.png")
        src_image = open(img, "rb")

        data = dict(upload_image=src_image)
        data_formset = self.formset_media(**data)
        url = self.preview_upload
        r = self.client.post(url, data_formset)

        details = json.loads(r.content)
        upload_hash = details["upload_hash"]

        # Create and post with the formset.
        fields = []
        for i in range(amount):
            fields.append(self.formset_new_form(caption="hi", upload_hash=upload_hash, position=i))
        data_formset = self.formset_media(*fields)

        self.media_edit_url

        r = self.client.post(self.media_edit_url, data_formset)
Exemple #41
0
    def testIconUpload(self, get_icon_dir):
        # TODO(gkoberger): clarify this please.
        # We no longer use AddonFormMedia to upload icons, so
        # skipping until I can ask andym what the point of this
        # test is.  Additionally, it's called "TestIconRemoval",
        # but it doesn't seem to remove icons.
        return
        get_icon_dir.return_value = self.temp_dir

        for path in self.get_icon_paths():
            assert not os.path.exists(path)

        img = get_image_path('non-animated.png')
        data = {'icon_upload': img, 'icon_type': 'text/png'}
        self.request.FILES = {'icon_upload': open(img)}
        form = forms.AddonFormMedia(data=data, request=self.request,
                                    instance=self.addon)
        assert form.is_valid()
        form.save(self.addon)
        for path in self.get_icon_paths():
            assert os.path.exists(path)
Exemple #42
0
    def test_preview_size(self, pngcrush_image_mock):
        addon = Addon.objects.get(pk=3615)
        name = 'non-animated.gif'
        form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
                                  'position': 1})
        with storage.open(os.path.join(self.dest, name), 'w') as f:
            shutil.copyfileobj(open(get_image_path(name)), f)
        assert form.is_valid()
        form.save(addon)
        preview = addon.previews.all()[0]
        assert preview.sizes == (
            {u'image': [250, 297], u'thumbnail': [168, 200],
             u'original': [250, 297]})
        assert os.path.exists(preview.image_path)
        assert os.path.exists(preview.thumbnail_path)
        assert os.path.exists(preview.original_path)

        assert pngcrush_image_mock.call_count == 2
        assert pngcrush_image_mock.call_args_list[0][0][0] == (
            preview.thumbnail_path)
        assert pngcrush_image_mock.call_args_list[1][0][0] == (
            preview.image_path)
Exemple #43
0
def _uploader(resize_size, final_size):
    img = get_image_path('mozilla.png')
    original_size = (339, 128)

    src = tempfile.NamedTemporaryFile(mode='r+w+b',
                                      suffix=".png",
                                      delete=False)

    # resize_icon removes the original
    shutil.copyfile(img, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == original_size

    if isinstance(final_size, list):
        uploadto = user_media_path('addon_icons')
        try:
            os.makedirs(uploadto)
        except OSError:
            pass
        for rsize, fsize in zip(resize_size, final_size):
            dest_name = os.path.join(uploadto, '1234')

            tasks.resize_icon(src.name, dest_name, resize_size, locally=True)
            dest_image = Image.open(open('%s-%s.png' % (dest_name, rsize)))
            assert dest_image.size == fsize

            if os.path.exists(dest_image.filename):
                os.remove(dest_image.filename)
            assert not os.path.exists(dest_image.filename)
        shutil.rmtree(uploadto)
    else:
        dest = tempfile.mktemp(suffix='.png')
        tasks.resize_icon(src.name, dest, resize_size, locally=True)
        dest_image = Image.open(dest)
        assert dest_image.size == final_size

    assert not os.path.exists(src.name)
Exemple #44
0
def test_resize_photo():
    somepic = get_image_path('sunbird-small.png')

    src = tempfile.NamedTemporaryFile(mode='r+w+b',
                                      suffix=".png",
                                      delete=False,
                                      dir=settings.TMP_PATH)
    dest = tempfile.NamedTemporaryFile(mode='r+w+b',
                                       suffix=".png",
                                       dir=settings.TMP_PATH)

    # resize_photo removes the original
    shutil.copyfile(somepic, src.name)

    src_image = Image.open(src.name)
    eq_(src_image.size, (64, 64))
    resize_photo(src.name, dest.name, locally=True)

    # Image is smaller than 200x200 so it should stay the same.
    dest_image = Image.open(dest.name)
    eq_(dest_image.size, (64, 64))

    assert not os.path.exists(src.name)
Exemple #45
0
def _uploader(resize_size, final_size):
    img = get_image_path('mozilla.png')
    original_size = (339, 128)

    src = tempfile.NamedTemporaryFile(mode='r+w+b', suffix=".png",
                                      delete=False)

    # resize_icon removes the original
    shutil.copyfile(img, src.name)

    src_image = Image.open(src.name)
    assert src_image.size == original_size

    if isinstance(final_size, list):
        uploadto = user_media_path('addon_icons')
        try:
            os.makedirs(uploadto)
        except OSError:
            pass
        for rsize, fsize in zip(resize_size, final_size):
            dest_name = os.path.join(uploadto, '1234')

            tasks.resize_icon(src.name, dest_name, resize_size, locally=True)
            dest_image = Image.open(open('%s-%s.png' % (dest_name, rsize)))
            assert dest_image.size == fsize

            if os.path.exists(dest_image.filename):
                os.remove(dest_image.filename)
            assert not os.path.exists(dest_image.filename)
        shutil.rmtree(uploadto)
    else:
        dest = tempfile.mktemp(suffix='.png')
        tasks.resize_icon(src.name, dest, resize_size, locally=True)
        dest_image = Image.open(dest)
        assert dest_image.size == final_size

    assert not os.path.exists(src.name)
Exemple #46
0
    def test_success(self, save_persona_image_mock, create_persona_preview_images_mock, make_checksum_mock):
        make_checksum_mock.return_value = "hashyourselfbeforeyoucrashyourself"

        self.request.user = UserProfile.objects.get(pk=2519)

        data = self.get_dict()
        header_url, footer_url = self.get_img_urls()

        # Upload header image.
        img = open(get_image_path("persona-header.jpg"), "rb")
        r_ajax = self.client.post(header_url, {"upload_image": img})
        data.update(header_hash=json.loads(r_ajax.content)["upload_hash"])

        # Upload footer image.
        img = open(get_image_path("persona-footer.jpg"), "rb")
        r_ajax = self.client.post(footer_url, {"upload_image": img})
        data.update(footer_hash=json.loads(r_ajax.content)["upload_hash"])

        # Populate and save form.
        self.post()
        assert self.form.is_valid(), self.form.errors
        self.form.save()

        addon = Addon.objects.filter(type=amo.ADDON_PERSONA).order_by("-id")[0]
        persona = addon.persona

        # Test for correct Addon and Persona values.
        assert unicode(addon.name) == data["name"]
        assert addon.slug == data["slug"]
        self.assertSetEqual(addon.categories.values_list("id", flat=True), [self.cat.id])
        self.assertSetEqual(addon.tags.values_list("tag_text", flat=True), data["tags"].split(", "))
        assert persona.persona_id == 0
        assert persona.license == data["license"]
        assert persona.accentcolor == data["accentcolor"].lstrip("#")
        assert persona.textcolor == data["textcolor"].lstrip("#")
        assert persona.author == self.request.user.username
        assert persona.display_username == self.request.user.name
        assert not persona.dupe_persona

        v = addon.versions.all()
        assert len(v) == 1
        assert v[0].version == "0"

        # Test for header, footer, and preview images.
        dst = os.path.join(user_media_path("addons"), str(addon.id))

        header_src = os.path.join(settings.TMP_PATH, "persona_header", u"b4ll1n")
        footer_src = os.path.join(settings.TMP_PATH, "persona_footer", u"5w4g")

        assert save_persona_image_mock.mock_calls == (
            [
                mock.call(src=header_src, full_dst=os.path.join(dst, "header.png")),
                mock.call(src=footer_src, full_dst=os.path.join(dst, "footer.png")),
            ]
        )

        create_persona_preview_images_mock.assert_called_with(
            src=header_src,
            full_dst=[os.path.join(dst, "preview.png"), os.path.join(dst, "icon.png")],
            set_modified_on=[addon],
        )
Exemple #47
0
    def test_success(self, save_persona_image_mock,
                     create_persona_preview_images_mock, make_checksum_mock):
        if not hasattr(Image.core, 'jpeg_encoder'):
            raise SkipTest
        make_checksum_mock.return_value = 'hashyourselfbeforeyoucrashyourself'

        self.request.user = UserProfile.objects.get(pk=2519)

        data = self.get_dict()
        header_url, footer_url = self.get_img_urls()

        # Upload header image.
        img = open(get_image_path('persona-header.jpg'), 'rb')
        r_ajax = self.client.post(header_url, {'upload_image': img})
        data.update(header_hash=json.loads(r_ajax.content)['upload_hash'])

        # Upload footer image.
        img = open(get_image_path('persona-footer.jpg'), 'rb')
        r_ajax = self.client.post(footer_url, {'upload_image': img})
        data.update(footer_hash=json.loads(r_ajax.content)['upload_hash'])

        # Populate and save form.
        self.post()
        eq_(self.form.is_valid(), True, self.form.errors)
        self.form.save()

        addon = Addon.objects.filter(type=amo.ADDON_PERSONA).order_by('-id')[0]
        persona = addon.persona

        # Test for correct Addon and Persona values.
        eq_(unicode(addon.name), data['name'])
        eq_(addon.slug, data['slug'])
        self.assertSetEqual(addon.categories.values_list('id', flat=True),
                            [self.cat.id])
        self.assertSetEqual(addon.tags.values_list('tag_text', flat=True),
                            data['tags'].split(', '))
        eq_(persona.persona_id, 0)
        eq_(persona.license, data['license'])
        eq_(persona.accentcolor, data['accentcolor'].lstrip('#'))
        eq_(persona.textcolor, data['textcolor'].lstrip('#'))
        eq_(persona.author, self.request.user.username)
        eq_(persona.display_username, self.request.user.name)
        assert not persona.dupe_persona

        v = addon.versions.all()
        eq_(len(v), 1)
        eq_(v[0].version, '0')

        # Test for header, footer, and preview images.
        dst = os.path.join(user_media_path('addons'), str(addon.id))

        header_src = os.path.join(settings.TMP_PATH, 'persona_header',
                                  u'b4ll1n')
        footer_src = os.path.join(settings.TMP_PATH, 'persona_footer', u'5w4g')

        eq_(save_persona_image_mock.mock_calls, [
            mock.call(src=header_src, full_dst=os.path.join(dst,
                                                            'header.png')),
            mock.call(src=footer_src, full_dst=os.path.join(dst, 'footer.png'))
        ])

        create_persona_preview_images_mock.assert_called_with(
            src=header_src,
            full_dst=[
                os.path.join(dst, 'preview.png'),
                os.path.join(dst, 'icon.png')
            ],
            set_modified_on=[addon])
Exemple #48
0
from olympia import amo
from olympia.amo.tests import TestCase
from olympia.amo.tests.test_helpers import get_image_path
from olympia.devhub.models import UserLog
from olympia.lib.video import get_library
from olympia.lib.video import ffmpeg, totem
from olympia.lib.video.tasks import resize_video
from olympia.users.models import UserProfile


pytestmark = pytest.mark.django_db

files = {
    'good': os.path.join(os.path.dirname(__file__),
                         'fixtures/disco-truncated.webm'),
    'bad': get_image_path('mozilla.png'),
}

older_output = """
Input #0, matroska,webm, from 'lib/video/fixtures/disco-truncated.webm':
  Duration: 00:00:10.00, start: 0.000000, bitrate: 298 kb/s
    Stream #0:0(eng): Video: vp8, yuv420p, 640x360, SAR 1:1 DAR 16:9,
    Stream #0:1(eng): Audio: vorbis, 44100 Hz, stereo, s16 (default)
"""

other_output = """
Input #0, matroska, from 'disco-truncated.webm':
  Metadata:
    doctype         : webm
"""
Exemple #49
0
    def test_success(self, save_persona_image_mock,
                     create_persona_preview_images_mock, make_checksum_mock):
        if not hasattr(Image.core, 'jpeg_encoder'):
            raise SkipTest
        make_checksum_mock.return_value = 'hashyourselfbeforeyoucrashyourself'

        self.request.user = UserProfile.objects.get(pk=2519)

        data = self.get_dict()
        header_url, footer_url = self.get_img_urls()

        # Upload header image.
        img = open(get_image_path('persona-header.jpg'), 'rb')
        r_ajax = self.client.post(header_url, {'upload_image': img})
        data.update(header_hash=json.loads(r_ajax.content)['upload_hash'])

        # Upload footer image.
        img = open(get_image_path('persona-footer.jpg'), 'rb')
        r_ajax = self.client.post(footer_url, {'upload_image': img})
        data.update(footer_hash=json.loads(r_ajax.content)['upload_hash'])

        # Populate and save form.
        self.post()
        eq_(self.form.is_valid(), True, self.form.errors)
        self.form.save()

        addon = Addon.objects.filter(type=amo.ADDON_PERSONA).order_by('-id')[0]
        persona = addon.persona

        # Test for correct Addon and Persona values.
        eq_(unicode(addon.name), data['name'])
        eq_(addon.slug, data['slug'])
        self.assertSetEqual(addon.categories.values_list('id', flat=True),
                            [self.cat.id])
        self.assertSetEqual(addon.tags.values_list('tag_text', flat=True),
                            data['tags'].split(', '))
        eq_(persona.persona_id, 0)
        eq_(persona.license, data['license'])
        eq_(persona.accentcolor, data['accentcolor'].lstrip('#'))
        eq_(persona.textcolor, data['textcolor'].lstrip('#'))
        eq_(persona.author, self.request.user.username)
        eq_(persona.display_username, self.request.user.name)
        assert not persona.dupe_persona

        v = addon.versions.all()
        eq_(len(v), 1)
        eq_(v[0].version, '0')

        # Test for header, footer, and preview images.
        dst = os.path.join(user_media_path('addons'), str(addon.id))

        header_src = os.path.join(settings.TMP_PATH, 'persona_header',
                                  u'b4ll1n')
        footer_src = os.path.join(settings.TMP_PATH, 'persona_footer',
                                  u'5w4g')

        eq_(save_persona_image_mock.mock_calls,
            [mock.call(src=header_src,
                       full_dst=os.path.join(dst, 'header.png')),
             mock.call(src=footer_src,
                       full_dst=os.path.join(dst, 'footer.png'))])

        create_persona_preview_images_mock.assert_called_with(
            src=header_src,
            full_dst=[os.path.join(dst, 'preview.png'),
                      os.path.join(dst, 'icon.png')],
            set_modified_on=[addon])
Exemple #50
0
 def fake_xpi(self, filename=None):
     """Any useless file that has a name property (for Django)."""
     if not filename:
         return open(get_image_path('non-animated.gif'), 'rb')
     return storage.open(filename, 'rb')
Exemple #51
0
 def fake_xpi(self, filename=None):
     """Any useless file that has a name property (for Django)."""
     if not filename:
         return open(get_image_path('non-animated.gif'), 'rb')
     return storage.open(filename, 'rb')
    def check_image_animated(self, url, msg):
        filehandle = open(get_image_path("animated.png"), "rb")

        res = self.client.post(url, {"upload_image": filehandle})
        response_json = json.loads(res.content)
        eq_(response_json["errors"][0], msg)