def test_get_prep_value(self):
     res = CloudinaryResource(metadata=self.uploaded)
     value = "image/upload/v{version}/{id}.{format}".format(
         version=self.uploaded["version"],
         id=self.uploaded["public_id"],
         format=self.uploaded["format"])
     self.assertEqual(value, res.get_prep_value())
class TestCloudinaryResource(TestCase):
    mocked_response = http_response_mock('{"breakpoints": [50, 500, 1000]}')
    mocked_breakpoints = [50, 500, 1000]
    expected_transformation = "c_scale,w_auto:breakpoints_50_1000_20_20:json"

    crop_transformation = {'crop': 'crop', 'width': 100}
    crop_transformation_str = 'c_crop,w_100'

    @classmethod
    def setUpClass(cls):
        cloudinary.reset_config()
        cls.uploaded = uploader.upload(TEST_IMAGE,
                                       public_id=TEST_ID,
                                       tags=TEST_TAG)

    @classmethod
    def tearDownClass(cls):
        api.delete_resources_by_tag(TEST_TAG)

    def setUp(self):
        self.res = CloudinaryResource(metadata=self.uploaded)

    def test_empty_class(self):
        """An empty CloudinaryResource"""

        self.shortDescription()
        res = CloudinaryResource()
        self.assertFalse(res, "should be 'False'")
        self.assertEqual(len(res), 0, "should have zero len()")
        self.assertIsNone(res.url, "should have None url")

    def test_validate(self):
        self.assertTrue(self.res.validate())
        self.assertTrue(self.res)
        self.assertGreater(len(self.res), 0)

    def test_get_prep_value(self):
        value = "image/upload/v{version}/{id}.{format}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"])

        self.assertEqual(value, self.res.get_prep_value())

    def test_get_presigned(self):
        value = "image/upload/v{version}/{id}.{format}#{signature}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"],
            signature=self.uploaded["signature"])

        self.assertEqual(value, self.res.get_presigned())

    def test_url(self):
        self.assertEqual(self.res.url, self.uploaded["url"])

    def test_image(self):
        image = self.res.image()
        self.assertIn(' src="{url}'.format(url=self.res.url), image)
        self.assertNotIn('data-src="{url}'.format(url=self.res.url), image)
        image = self.res.image(responsive=True, width="auto", crop="scale")
        self.assertNotIn(
            ' src="{url}'.format(
                url=self.res.build_url(width="auto", crop="scale")), image)
        self.assertIn(
            'data-src="{url}'.format(
                url=self.res.build_url(width="auto", crop="scale")), image)

    @mock.patch('urllib3.request.RequestMethods.request',
                return_value=mocked_response)
    def test_fetch_breakpoints(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource (mocked)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.expected_transformation,
                      get_request_url(mocked_request))

    @mock.patch('urllib3.request.RequestMethods.request',
                return_value=mocked_response)
    def test_fetch_breakpoints_with_transformation(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource with custom transformation (mocked)"""
        srcset = {"transformation": self.crop_transformation}
        actual_breakpoints = self.res._fetch_breakpoints(srcset)

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(
            self.crop_transformation_str + "/" + self.expected_transformation,
            get_request_url(mocked_request))

    def test_fetch_breakpoints_real(self):
        """Should retrieve responsive breakpoints from cloudinary resource (real request)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertIsInstance(actual_breakpoints, list)

        self.assertGreater(len(actual_breakpoints), 0)
예제 #3
0
	def post(self, request):
		form = ConstructorForm(request.POST, request.FILES)
		if form.is_valid():
			im = Image.open("static/img/template-{}.png".format(form.cleaned_data["sex"]))
			is_pattern = form.cleaned_data["is_pattern"]
			print(is_pattern)
			bg = form.cleaned_data["background"]
			if is_pattern:
				imP = Image.open(form.cleaned_data["file"])
				
				width, height = imP.size   # Get dimensions

				left = (width - 1000) / 2
				top = (height - 1000) / 2
				right = (width + 1000) / 2
				bottom = (height + 1000) / 2

				imP = imP.crop((left, top, right, bottom))
			else:
				imP = Image.new("RGBA", size=(1000, 1000), color=(int(bg[1:3], 16), int(bg[3:5], 16), int(bg[5:7], 16), 255))
			
			imP.paste(im, (0, 0), im)
			
			im = imP.copy()

			if not is_pattern and form.cleaned_data["file"]:
				imPR = Image.open(form.cleaned_data["file"])

				ratio = (imPR.size[0] / 250)

				r_imPR = imPR.resize((250, int(imPR.size[1] / ratio)))

				pos = (500 - r_imPR.size[0] // 2, 500 - r_imPR.size[1] // 2)
				im.paste(r_imPR, pos)

			im.save("temp/temp.png")

			resp = cloudinary.uploader.upload('temp/temp.png')
			result = CloudinaryResource(
				public_id=resp['public_id'],
				type=resp['type'],
				resource_type=resp['resource_type'],
				version=resp['version'],
				format=resp['format'],
			)

			str_result = result.get_prep_value()

			if request.FILES:
				resp2 = cloudinary.uploader.upload(File.open(request.FILES["file"], "rb"))
				result2 = CloudinaryResource(
					public_id=resp2['public_id'],
					type=resp2['type'],
					resource_type=resp2['resource_type'],
					version=resp2['version'],
					format=resp2['format'],
				)
				str_result2 = result2.get_prep_value()
			else:
				str_result2 = None


			tshirt = TShirt.objects.create(
				user=request.user,
				name=form.cleaned_data["name"],
				description=form.cleaned_data["description"],
				image=str_result,
				sex=form.cleaned_data["sex"],
				uploaded_image=str_result2,
				background=form.cleaned_data["background"],
				is_pattern=form.cleaned_data["is_pattern"],
			)
			tshirt.topic.set(form.cleaned_data["topic"])
			tshirt.tag.set(form.cleaned_data["tag"])
	


			return redirect('design_view', tshirt_id=tshirt.id)
		else:
			data = {
				"form": form,
			}
			return render(request, "core/constructor.html", context=data)
class TestCloudinaryResource(TestCase):
    mocked_response = http_response_mock('{"breakpoints": [50, 500, 1000]}')
    mocked_breakpoints = [50, 500, 1000]
    expected_transformation = "c_scale,w_auto:breakpoints_50_1000_20_20:json"

    crop_transformation = {'crop': 'crop', 'width': 100}
    crop_transformation_str = 'c_crop,w_100'

    @classmethod
    def setUpClass(cls):
        cloudinary.reset_config()
        cls.uploaded = uploader.upload(TEST_IMAGE, public_id=TEST_ID, tags=TEST_TAG)

    @classmethod
    def tearDownClass(cls):
        cleanup_test_resources_by_tag([(TEST_TAG,)])

    def setUp(self):
        self.res = CloudinaryResource(metadata=self.uploaded)

    def test_empty_class(self):
        """An empty CloudinaryResource"""

        self.shortDescription()
        res = CloudinaryResource()
        self.assertFalse(res, "should be 'False'")
        self.assertEqual(len(res), 0, "should have zero len()")
        self.assertIsNone(res.url, "should have None url")

    def test_validate(self):
        self.assertTrue(self.res.validate())
        self.assertTrue(self.res)
        self.assertGreater(len(self.res), 0)

    def test_get_prep_value(self):
        value = "image/upload/v{version}/{id}.{format}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"])

        self.assertEqual(value, self.res.get_prep_value())

    def test_get_presigned(self):
        value = "image/upload/v{version}/{id}.{format}#{signature}".format(
            version=self.uploaded["version"],
            id=self.uploaded["public_id"],
            format=self.uploaded["format"],
            signature=self.uploaded["signature"])

        self.assertEqual(value, self.res.get_presigned())

    def test_url(self):
        self.assertEqual(self.res.url, self.uploaded["url"])

    def test_image(self):
        image = self.res.image()
        self.assertIn(' src="{url}'.format(url=self.res.url), image)
        self.assertNotIn('data-src="{url}'.format(url=self.res.url), image)
        image = self.res.image(responsive=True, width="auto", crop="scale")
        self.assertNotIn(' src="{url}'.format(url=self.res.build_url(width="auto", crop="scale")), image)
        self.assertIn('data-src="{url}'.format(url=self.res.build_url(width="auto", crop="scale")), image)

    @mock.patch('urllib3.request.RequestMethods.request', return_value=mocked_response)
    def test_fetch_breakpoints(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource (mocked)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.expected_transformation, get_request_url(mocked_request))

    @mock.patch('urllib3.request.RequestMethods.request', return_value=mocked_response)
    def test_fetch_breakpoints_with_transformation(self, mocked_request):
        """Should retrieve responsive breakpoints from cloudinary resource with custom transformation (mocked)"""
        srcset = {"transformation": self.crop_transformation}
        actual_breakpoints = self.res._fetch_breakpoints(srcset)

        self.assertEqual(self.mocked_breakpoints, actual_breakpoints)

        self.assertIn(self.crop_transformation_str + "/" + self.expected_transformation,
                      get_request_url(mocked_request))

    def test_fetch_breakpoints_real(self):
        """Should retrieve responsive breakpoints from cloudinary resource (real request)"""
        actual_breakpoints = self.res._fetch_breakpoints()

        self.assertIsInstance(actual_breakpoints, list)

        self.assertGreater(len(actual_breakpoints), 0)
예제 #5
0
 def test_get_prep_value(self):
     res = CloudinaryResource(metadata=self.uploaded)
     value = "image/upload/v{version}/{id}.{format}".format(version=self.uploaded["version"],
                                                            id=self.uploaded["public_id"],
                                                            format=self.uploaded["format"])
     self.assertEqual(value, res.get_prep_value())