<commit_before>"""Tests for Unix Timestamp Flask application."""

import unittest
from contextlib import contextmanager
from urllib.parse import urlparse, quote
from datetime import datetime, MINYEAR, MAXYEAR
from calendar import monthrange
from itertools import product
import re
from math import ceil, floor
from xml.etree import ElementTree

from flask import template_rendered
from pytz import utc
from dateutil.parser import parse
from werkzeug.urls import url_encode

import unixtimestamp
from unixtimestamp import parse_accept_language


@contextmanager
def captured_templates(app):
    """Capture all templates being rendered along with the context used."""
    recorded = []

    def record(sender, template, context, **extra):
        # pylint:disable=unused-argument
        recorded.append((template, context))

    template_rendered.connect(record, app)

    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)


def max_timestamp_for_datetime():
    """Calculate the latest timestamp Python will allow in a datetime."""
    max_datetime = datetime(year=MAXYEAR, month=12, day=31,
                            hour=23, minute=59, second=59)
    return int(max_datetime.timestamp())


def min_timestamp_for_datetime():
    """Return the earliest timestamp Python will allow in a datetime."""
    if MINYEAR != 1:
        raise RuntimeError('Cannot calculate min timestamp')

    return -62135596800  # 1st Jan 1; calculation in code causes OverflowError


class TestCase(unittest.TestCase):
    """Base test case."""

    def setUp(self):
        """Set up test case."""
        unixtimestamp.app.testing = True
        self.app = unixtimestamp.app.test_client()


class ShowTimestampTestCase(TestCase):
    """Tests for showing timestamp."""

    def test_timestamp(self):
        """Test getting timestamps."""
        for timestamp in (0, 1, 123456, '-0', -1, -123456):
            with captured_templates(unixtimestamp.app) as templates:
                response = self.app.get('/{}'.format(timestamp))
                self.assertEqual(200, response.status_code)
                self.assertEqual(1, len(templates))
                context = templates[0][1]
                self.assertEqual(int(timestamp), context['timestamp'])
                self.assertEqual(int(timestamp),
                                 context['datetime'].timestamp())

    def test_max_timestamp(self):
        """Test getting maximum timestamp."""
        with captured_templates(unixtimestamp.app) as templates:
            timestamp = max_timestamp_for_datetime()
            response = self.app.get('/{}'.format(timestamp))<commit_msg>Debug enabled in tests as a workaround for https://github.com/kennethreitz/flask-sslify/issues/50<commit_after>"""Tests for Unix Timestamp Flask application."""

import unittest
from contextlib import contextmanager
from urllib.parse import urlparse, quote
from datetime import datetime, MINYEAR, MAXYEAR
from calendar import monthrange
from itertools import product
import re
from math import ceil, floor
from xml.etree import ElementTree

from flask import template_rendered
from pytz import utc
from dateutil.parser import parse
from werkzeug.urls import url_encode

import unixtimestamp
from unixtimestamp import parse_accept_language


@contextmanager
def captured_templates(app):
    """Capture all templates being rendered along with the context used."""
    recorded = []

    def record(sender, template, context, **extra):
        # pylint:disable=unused-argument
        recorded.append((template, context))

    template_rendered.connect(record, app)

    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)


def max_timestamp_for_datetime():
    """Calculate the latest timestamp Python will allow in a datetime."""
    max_datetime = datetime(year=MAXYEAR, month=12, day=31,
                            hour=23, minute=59, second=59)
    return int(max_datetime.timestamp())


def min_timestamp_for_datetime():
    """Return the earliest timestamp Python will allow in a datetime."""
    if MINYEAR != 1:
        raise RuntimeError('Cannot calculate min timestamp')

    return -62135596800  # 1st Jan 1; calculation in code causes OverflowError


class TestCase(unittest.TestCase):
    """Base test case."""

    def setUp(self):
        """Set up test case."""
        unixtimestamp.app.testing = True
        # Debug enabled in tests as a workaround for
        # https://github.com/kennethreitz/flask-sslify/issues/50.
        unixtimestamp.app.debug = True
        self.app = unixtimestamp.app.test_client()


class ShowTimestampTestCase(TestCase):
    """Tests for showing timestamp."""

    def test_timestamp(self):
        """Test getting timestamps."""
        for timestamp in (0, 1, 123456, '-0', -1, -123456):
            with captured_templates(unixtimestamp.app) as templates:
                response = self.app.get('/{}'.format(timestamp))
                self.assertEqual(200, response.status_code)
                self.assertEqual(1, len(templates))
                context = templates[0][1]
                self.assertEqual(int(timestamp), context['timestamp'])
                self.assertEqual(int(timestamp),
                                 context['datetime'].timestamp())

    def test_max_timestamp(self):
        """Test getting maximum timestamp."""
        with captured_templates(unixtimestamp.app) as templates:
            timestamp = max_timestamp_for_datetime()
            response = self.app.get('/{}'.format(timestamp))
{'fraction_non_alphanumeric': 0.09680889207601291, 'fraction_numerical': 0.017210469702402295, 'mean_word_length': 3.1264792899408285, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1229838', 'n_tokens_mistral': 1538, 'n_tokens_neox': 1432, 'n_words': 438}