<commit_before>import calendar
import datetime
from mock import patch

__all__ = ['FreezeTime']


real_datetime = datetime.datetime


# From six
def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta("NewBase", bases, {})


# Adapted from freezegun. This metaclass will make sure that calls to
# isinstance(real_datetime, FakeDateTime) are True.
class FakeDateTimeMeta(type):
    @classmethod
    def __instancecheck__(self, obj):
        return isinstance(obj, real_datetime)


class FakeDateTime(with_metaclass(FakeDateTimeMeta, real_datetime)):
    """
    A datetime replacement that lets you set utcnow() using set_utcnow().

    The clock starts ticking after calling set_utcnow().
    """

    @classmethod
    def utcnow(cls, *args, **kwargs):
        if not hasattr(cls, 'dt'):
            raise NotImplementedError(
                'use {}.set_utcnow(datetime) first'.format(cls.__name__)
            )
        return cls._utcnow()

    @classmethod
    def set_utcnow(cls, dt):
        cls.dt = dt

    @classmethod
    def _utcnow(cls):
        if not hasattr(cls, '_start'):
            cls._start = real_datetime.utcnow()
        return (real_datetime.utcnow() - cls._start) + cls.dt

    @classmethod
    def now(cls, *args, **kwargs):
        raise NotImplementedError(
            'mocked {}.now() is not implemented yet'.format(cls.__name__)
        )


class FakeFixedDateTime(FakeDateTime):
    @classmethod
    def _utcnow(cls):
        return cls.dt


def fake_time():
    now = datetime.datetime.utcnow()
    ts = calendar.timegm(now.timetuple())
    ts += now.microsecond / 1e6
    return ts


class FreezeTime(object):
    """
    A context manager that freezes the datetime to the given datetime object.

    If tick=True is passed, the clock will start ticking, otherwise the clock
    will remain at the given datetime.
    """
    def __init__(self, dt, tick=False):
        self.dt = dt
        self.tick = tick

    def __enter__(self):
        if self.tick:
            datetime_cls = FakeDateTime
        else:
            datetime_cls = FakeFixedDateTime

        self.p1 = patch('datetime.datetime', datetime_cls)
        self.p2 = patch('time.time', fake_time)

        self.p1.__enter__()
        self.p2.__enter__()

        datetime_cls.set_utcnow(self.dt)

    def __exit__(self, *args):
        self.p2.__exit__(*args)
        self.p1.__exit__(*args)
<commit_msg>better wording<commit_after>import calendar
import datetime
from mock import patch

__all__ = ['FreezeTime']


real_datetime = datetime.datetime


# From six
def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta("NewBase", bases, {})


# Adapted from freezegun. This metaclass will make sure that calls to
# isinstance(real_datetime, FakeDateTime) are True.
class FakeDateTimeMeta(type):
    @classmethod
    def __instancecheck__(self, obj):
        return isinstance(obj, real_datetime)


class FakeDateTime(with_metaclass(FakeDateTimeMeta, real_datetime)):
    """
    A datetime replacement that lets you set utcnow() using set_utcnow().

    The clock starts ticking after calling set_utcnow().
    """

    @classmethod
    def utcnow(cls, *args, **kwargs):
        if not hasattr(cls, 'dt'):
            raise NotImplementedError(
                'use {}.set_utcnow(datetime) first'.format(cls.__name__)
            )
        return cls._utcnow()

    @classmethod
    def set_utcnow(cls, dt):
        cls.dt = dt

    @classmethod
    def _utcnow(cls):
        if not hasattr(cls, '_start'):
            cls._start = real_datetime.utcnow()
        return (real_datetime.utcnow() - cls._start) + cls.dt

    @classmethod
    def now(cls, *args, **kwargs):
        raise NotImplementedError(
            '{}.now() is not implemented yet'.format(cls.__name__)
        )


class FakeFixedDateTime(FakeDateTime):
    @classmethod
    def _utcnow(cls):
        return cls.dt


def fake_time():
    now = datetime.datetime.utcnow()
    ts = calendar.timegm(now.timetuple())
    ts += now.microsecond / 1e6
    return ts


class FreezeTime(object):
    """
    A context manager that freezes the datetime to the given datetime object.

    If tick=True is passed, the clock will start ticking, otherwise the clock
    will remain at the given datetime.
    """
    def __init__(self, dt, tick=False):
        self.dt = dt
        self.tick = tick

    def __enter__(self):
        if self.tick:
            datetime_cls = FakeDateTime
        else:
            datetime_cls = FakeFixedDateTime

        self.p1 = patch('datetime.datetime', datetime_cls)
        self.p2 = patch('time.time', fake_time)

        self.p1.__enter__()
        self.p2.__enter__()

        datetime_cls.set_utcnow(self.dt)

    def __exit__(self, *args):
        self.p2.__exit__(*args)
        self.p1.__exit__(*args)

{'fraction_non_alphanumeric': 0.10433715220949263, 'fraction_numerical': 0.0032733224222585926, 'mean_word_length': 2.6676669167291824, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4516192', 'n_tokens_mistral': 1523, 'n_tokens_neox': 1485, 'n_words': 400}