#!/usr/bin/python
# -*- coding: utf-8 -*-

# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki

# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com

from unittest import TestCase, mock

from thumbor.config import Config
from thumbor.context import Context, RequestParameters
from thumbor.optimizers.jpegtran import Optimizer


class JpegtranOptimizerTest(TestCase):
    def setUp(self):
        self.patcher = mock.patch("thumbor.optimizers.jpegtran.Popen")
        self.mock_popen = self.patcher.start()
        self.os_path_exists_patcher = mock.patch(
            "thumbor.optimizers.jpegtran.exists"
        )
        self.mock_os_path_exists = self.os_path_exists_patcher.start()

    def tearDown(self):
        self.patcher.stop()
        self.os_path_exists_patcher.stop()

    @staticmethod
    def get_optimizer(filters=None, progressive=False, scans_file=""):
        conf = Config()
        conf.STATSD_HOST = ""
        conf.JPEGTRAN_PATH = "/somewhere/jpegtran"
        conf.PROGRESSIVE_JPEG = progressive
        conf.JPEGTRAN_SCANS_FILE = scans_file
        req = RequestParameters(filters=filters)
        ctx = Context(config=conf)
        ctx.request = req
        optimizer = Optimizer(ctx)

        return optimizer

    def test_should_run_for_jpeg(self):
        optimizer = self.get_optimizer()
        self.assertTrue(optimizer.should_run(".jpg", ""))
        self.assertTrue(optimizer.should_run(".jpeg", ""))

    def test_should_not_run_for_not_jpeg(self):
        optimizer = self.get_optimizer()

        self.assertFalse(optimizer.should_run(".png", ""))
        self.assertFalse(optimizer.should_run(".webp", ""))
        self.assertFalse(optimizer.should_run(".gif", ""))