import sys
import logging
import unittest

from testfixtures import LogCapture
from twisted.python.failure import Failure

from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter,
                              LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
from scrapy.extensions import telnet


class FailureToExcInfoTest(unittest.TestCase):

    def test_failure(self):
        try:
            0 / 0
        except ZeroDivisionError:
            exc_info = sys.exc_info()
            failure = Failure()

        self.assertTupleEqual(exc_info, failure_to_exc_info(failure))

    def test_non_failure(self):
        self.assertIsNone(failure_to_exc_info('test'))


class TopLevelFormatterTest(unittest.TestCase):

    def setUp(self):
        self.handler = LogCapture()
        self.handler.addFilter(TopLevelFormatter(['test']))

    def test_top_level_logger(self):
        logger = logging.getLogger('test')
        with self.handler as log:
            logger.warning('test log msg')
        log.check(('test', 'WARNING', 'test log msg'))

    def test_children_logger(self):
        logger = logging.getLogger('test.test1')
        with self.handler as log:
            logger.warning('test log msg')
        log.check(('test', 'WARNING', 'test log msg'))

    def test_overlapping_name_logger(self):
        logger = logging.getLogger('test2')
        with self.handler as log:
            logger.warning('test log msg')
        log.check(('test2', 'WARNING', 'test log msg'))

    def test_different_name_logger(self):
        logger = logging.getLogger('different')
        with self.handler as log:
            logger.warning('test log msg')
        log.check(('different', 'WARNING', 'test log msg'))


class LogCounterHandlerTest(unittest.TestCase):

    def setUp(self):
        settings = {'LOG_LEVEL': 'WARNING'}
        if not telnet.TWISTED_CONCH_AVAILABLE:
            # disable it to avoid the extra warning
            settings['TELNETCONSOLE_ENABLED'] = False
        self.logger = logging.getLogger('test')
        self.logger.setLevel(logging.NOTSET)
        self.logger.propagate = False
        self.crawler = get_crawler(settings_dict=settings)
        self.handler = LogCounterHandler(self.crawler)
        self.logger.addHandler(self.handler)

    def tearDown(self):
        self.logger.propagate = True
        self.logger.removeHandler(self.handler)

    def test_init(self):
        self.assertIsNone(self.crawler.stats.get_value('log_count/DEBUG'))
        self.assertIsNone(self.crawler.stats.get_value('log_count/INFO'))
        self.assertIsNone(self.crawler.stats.get_value('log_count/WARNING'))
        self.assertIsNone(self.crawler.stats.get_value('log_count/ERROR'))
        self.assertIsNone(self.crawler.stats.get_value('log_count/CRITICAL'))

    def test_accepted_level(self):
        self.logger.error('test log msg')
        self.assertEqual(self.crawler.stats.get_value('log_count/ERROR'), 1)

    def test_filtered_out_level(self):
        self.logger.debug('test log msg')
        self.assertIsNone(self.crawler.stats.get_value('log_count/INFO'))


class StreamLoggerTest(unittest.TestCase):

    def setUp(self):
        self.stdout = sys.stdout
        logger = logging.getLogger('test')
        logger.setLevel(logging.WARNING)
        sys.stdout = StreamLogger(logger, logging.ERROR)

    def tearDown(self):
        sys.stdout = self.stdout

    def test_redirect(self):
        with LogCapture() as log:
            print('test log msg')
        log.check(('test', 'ERROR', 'test log msg'))

[((802, 814), 'testfixtures.LogCapture', 'LogCapture', ([], {}), '()\n', (812, 814), False, 'from testfixtures import LogCapture\n'), ((930, 955), 'logging.getLogger', 'logging.getLogger', (['"""test"""'], {}), "('test')\n", (947, 955), False, 'import logging\n'), ((1142, 1173), 'logging.getLogger', 'logging.getLogger', (['"""test.test1"""'], {}), "('test.test1')\n", (1159, 1173), False, 'import logging\n'), ((1368, 1394), 'logging.getLogger', 'logging.getLogger', (['"""test2"""'], {}), "('test2')\n", (1385, 1394), False, 'import logging\n'), ((1588, 1618), 'logging.getLogger', 'logging.getLogger', (['"""different"""'], {}), "('different')\n", (1605, 1618), False, 'import logging\n'), ((2047, 2072), 'logging.getLogger', 'logging.getLogger', (['"""test"""'], {}), "('test')\n", (2064, 2072), False, 'import logging\n'), ((2179, 2214), 'scrapy.utils.test.get_crawler', 'get_crawler', ([], {'settings_dict': 'settings'}), '(settings_dict=settings)\n', (2190, 2214), False, 'from scrapy.utils.test import get_crawler\n'), ((2238, 2269), 'scrapy.utils.log.LogCounterHandler', 'LogCounterHandler', (['self.crawler'], {}), '(self.crawler)\n', (2255, 2269), False, 'from scrapy.utils.log import failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger\n'), ((3258, 3283), 'logging.getLogger', 'logging.getLogger', (['"""test"""'], {}), "('test')\n", (3275, 3283), False, 'import logging\n'), ((3346, 3381), 'scrapy.utils.log.StreamLogger', 'StreamLogger', (['logger', 'logging.ERROR'], {}), '(logger, logging.ERROR)\n', (3358, 3381), False, 'from scrapy.utils.log import failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger\n'), ((589, 617), 'scrapy.utils.log.failure_to_exc_info', 'failure_to_exc_info', (['failure'], {}), '(failure)\n', (608, 617), False, 'from scrapy.utils.log import failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger\n'), ((678, 705), 'scrapy.utils.log.failure_to_exc_info', 'failure_to_exc_info', (['"""test"""'], {}), "('test')\n", (697, 705), False, 'from scrapy.utils.log import failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger\n'), ((846, 873), 'scrapy.utils.log.TopLevelFormatter', 'TopLevelFormatter', (["['test']"], {}), "(['test'])\n", (863, 873), False, 'from scrapy.utils.log import failure_to_exc_info, TopLevelFormatter, LogCounterHandler, StreamLogger\n'), ((3483, 3495), 'testfixtures.LogCapture', 'LogCapture', ([], {}), '()\n', (3493, 3495), False, 'from testfixtures import LogCapture\n'), ((501, 515), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (513, 515), False, 'import sys\n'), ((538, 547), 'twisted.python.failure.Failure', 'Failure', ([], {}), '()\n', (545, 547), False, 'from twisted.python.failure import Failure\n')]