Commit b37b9257 authored by Federico Ceratto's avatar Federico Ceratto

Imported Upstream version 0.1.17

parents
Patches and Suggestions
```````````````````````
- `Dan Miller <https://github.com/dnmiller>`_
- `Matthew Schinckel <https://github.com/schinckel>`_
- `JJ Geewax <https://github.com/jgeewax>`_
- `Roman Imankulov <https://github.com/imankulov>`_
- `Martin Geisler <https://github.com/mgeisler>`_
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2012 Steve Pulec
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
include README.rst LICENSE AUTHORS.rst
Metadata-Version: 1.0
Name: freezegun
Version: 0.1.17
Summary: Let your Python tests travel through time
Home-page: https://github.com/spulec/freezegun
Author: Steve Pulec
Author-email: spulec@gmail
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN
FreezeGun: Let your Python tests travel through time
====================================================
.. image:: https://secure.travis-ci.org/spulec/freezegun.png?branch=master
:target: https://travis-ci.org/spulec/freezegun
.. image:: https://coveralls.io/repos/spulec/freezegun/badge.png?branch=master
:target: https://coveralls.io/r/spulec/freezegun
FreezeGun is a library that allows your python tests to travel through time by mocking the datetime module.
Usage
-----
Once the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), and time.time() will return the time that has been frozen.
Decorator
~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
# Or class based
@freeze_time("2012-01-14")
class Tester(object):
def test_the_class(self):
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
Context Manager
~~~~~~~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
def test():
assert datetime.datetime.now() != datetime.datetime(2012, 01, 14)
with freeze_time("2012-01-14"):
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
assert datetime.datetime.now() != datetime.datetime(2012, 01, 14)
Raw use
~~~~~~~
.. code-block:: python
from freezegun import freeze_time
freezer = freeze_time("2012-01-14 12:00:01")
freezer.start()
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14, 12, 00, 01)
freezer.stop()
Timezones
~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
@freeze_time("2012-01-14 03:21:34", tz_offset=-4)
def test():
assert datetime.datetime.utcnow() == datetime.datetime(2012, 01, 14, 03, 21, 34)
assert datetime.datetime.now() == datetime.datetime(2012, 01, 13, 23, 21, 34)
# datetime.date.today() uses local time
assert datetime.date.today() == datetime.datetime(2012, 01, 13)
Nice inputs
~~~~~~~~~~~
FreezeGun uses dateutil behind the scenes so you can have nice-looking datetimes
.. code-block:: python
@freeze_time("Jan 14th, 2012")
def test_nice_datetime():
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
Installation
------------
To install FreezeGun, simply:
.. code-block:: bash
$ pip install freezegun
Metadata-Version: 1.0
Name: freezegun
Version: 0.1.17
Summary: Let your Python tests travel through time
Home-page: https://github.com/spulec/freezegun
Author: Steve Pulec
Author-email: spulec@gmail
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN
AUTHORS.rst
LICENSE
MANIFEST.in
README.rst
setup.cfg
setup.py
freezegun/__init__.py
freezegun/api.py
freezegun.egg-info/PKG-INFO
freezegun.egg-info/SOURCES.txt
freezegun.egg-info/dependency_links.txt
freezegun.egg-info/requires.txt
freezegun.egg-info/top_level.txt
tests/__init__.py
tests/fake_module.py
tests/test_class_import.py
tests/test_datetimes.py
tests/test_operations.py
\ No newline at end of file
six
python-dateutil>=1.0, <2.0, >=2.1
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
freezegun
~~~~~~~~
:copyright: (c) 2012 by Steve Pulec.
"""
__title__ = 'freezegun'
__version__ = '0.1.16'
__author__ = 'Steve Pulec'
__license__ = 'Apache License 2.0'
__copyright__ = 'Copyright 2012 Steve Pulec'
from .api import freeze_time
__all__ = ["freeze_time"]
import time
import datetime
import functools
import sys
import inspect
import unittest
from dateutil import parser
real_time = time.time
real_date = datetime.date
real_datetime = datetime.datetime
# Stolen from six
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta("NewBase", bases, {})
class FakeTime(object):
def __init__(self, time_to_freeze):
self.time_to_freeze = time_to_freeze
def __call__(self):
shifted_time = self.time_to_freeze - datetime.timedelta(seconds=time.timezone)
return time.mktime(shifted_time.timetuple()) + shifted_time.microsecond / 1000000.0
class FakeDateMeta(type):
@classmethod
def __instancecheck__(self, obj):
return isinstance(obj, real_date)
def datetime_to_fakedatetime(datetime):
return FakeDatetime(datetime.year,
datetime.month,
datetime.day,
datetime.hour,
datetime.minute,
datetime.second,
datetime.microsecond,
datetime.tzinfo)
def date_to_fakedate(date):
return FakeDate(date.year,
date.month,
date.day)
class FakeDate(with_metaclass(FakeDateMeta, real_date)):
date_to_freeze = None
def __new__(cls, *args, **kwargs):
return real_date.__new__(cls, *args, **kwargs)
def __add__(self, other):
result = real_date.__add__(self, other)
if result is NotImplemented:
return result
return date_to_fakedate(result)
def __sub__(self, other):
result = real_date.__sub__(self, other)
if result is NotImplemented:
return result
if isinstance(result, real_date):
return date_to_fakedate(result)
else:
return result
@classmethod
def today(cls):
result = cls.date_to_freeze
return date_to_fakedate(result)
FakeDate.min = date_to_fakedate(real_date.min)
FakeDate.max = date_to_fakedate(real_date.max)
class FakeDatetimeMeta(FakeDateMeta):
@classmethod
def __instancecheck__(self, obj):
return isinstance(obj, real_datetime)
class FakeDatetime(with_metaclass(FakeDatetimeMeta, real_datetime, FakeDate)):
time_to_freeze = None
tz_offset = None
def __new__(cls, *args, **kwargs):
return real_datetime.__new__(cls, *args, **kwargs)
def __add__(self, other):
result = real_datetime.__add__(self, other)
if result is NotImplemented:
return result
return datetime_to_fakedatetime(result)
def __sub__(self, other):
result = real_datetime.__sub__(self, other)
if result is NotImplemented:
return result
if isinstance(result, real_datetime):
return datetime_to_fakedatetime(result)
else:
return result
@classmethod
def now(cls, tz=None):
if tz:
result = tz.fromutc(cls.time_to_freeze.replace(tzinfo=tz)) + datetime.timedelta(hours=cls.tz_offset)
else:
result = cls.time_to_freeze + datetime.timedelta(hours=cls.tz_offset)
return datetime_to_fakedatetime(result)
@classmethod
def utcnow(cls):
result = cls.time_to_freeze
return datetime_to_fakedatetime(result)
FakeDatetime.min = datetime_to_fakedatetime(real_datetime.min)
FakeDatetime.max = datetime_to_fakedatetime(real_datetime.max)
class FreezeMixin(object):
"""
With unittest.TestCase subclasses, we must return the class from our
freeze_time decorator, else test discovery tools may not discover the
test. Instead, we inject this mixin, which starts and stops the freezer
before and after each test.
"""
def setUp(self):
self._freezer.start()
super(FreezeMixin, self).setUp()
def tearDown(self):
super(FreezeMixin, self).tearDown()
self._freezer.stop()
class _freeze_time(object):
def __init__(self, time_to_freeze_str, tz_offset):
time_to_freeze = parser.parse(time_to_freeze_str)
self.time_to_freeze = time_to_freeze
self.tz_offset = tz_offset
def __call__(self, func):
if inspect.isclass(func) and issubclass(func, unittest.TestCase):
# Inject a mixin that does what we want, as otherwise we
# would not be found by the test discovery tool.
func.__bases__ = (FreezeMixin,) + func.__bases__
# And, we need a reference to this object...
func._freezer = self
return func
return self.decorate_callable(func)
def __enter__(self):
self.start()
def __exit__(self, *args):
self.stop()
def start(self):
datetime.datetime = FakeDatetime
datetime.date = FakeDate
fake_time = FakeTime(self.time_to_freeze)
time.time = fake_time
for mod_name, module in list(sys.modules.items()):
if module is None:
continue
if mod_name.startswith(('six.moves.', 'django.utils.six.moves.')):
continue
if hasattr(module, "__name__") and module.__name__ != 'datetime':
if hasattr(module, 'datetime') and module.datetime == real_datetime:
module.datetime = FakeDatetime
if hasattr(module, 'date') and module.date == real_date:
module.date = FakeDate
if hasattr(module, "__name__") and module.__name__ != 'time':
if hasattr(module, 'time') and module.time == real_time:
module.time = fake_time
datetime.datetime.time_to_freeze = self.time_to_freeze
datetime.datetime.tz_offset = self.tz_offset
# Since datetime.datetime has already been mocked, just use that for
# calculating the date
datetime.date.date_to_freeze = datetime.datetime.now().date()
def stop(self):
datetime.datetime = real_datetime
datetime.date = real_date
time.time = real_time
for mod_name, module in list(sys.modules.items()):
if mod_name.startswith(('six.moves.', 'django.utils.six.moves.')):
continue
if mod_name != 'datetime':
if hasattr(module, 'datetime') and module.datetime == FakeDatetime:
module.datetime = real_datetime
if hasattr(module, 'date') and module.date == FakeDate:
module.date = real_date
if mod_name != 'time':
if hasattr(module, 'time') and isinstance(module.time, FakeTime):
module.time = real_time
def decorate_callable(self, func):
def wrapper(*args, **kwargs):
with self:
result = func(*args, **kwargs)
return result
functools.update_wrapper(wrapper, func)
return wrapper
def freeze_time(time_to_freeze, tz_offset=0):
if isinstance(time_to_freeze, datetime.datetime):
time_to_freeze = time_to_freeze.isoformat()
elif isinstance(time_to_freeze, datetime.date):
time_to_freeze = time_to_freeze.isoformat()
# Python3 doesn't have basestring, but it does have str.
try:
string_type = basestring
except NameError:
string_type = str
if not isinstance(time_to_freeze, string_type):
raise TypeError(('freeze_time() expected a string, date instance, or '
'datetime instance, but got type {0}.').format(type(time_to_freeze)))
return _freeze_time(time_to_freeze, tz_offset)
# Setup adapters for sqlite
try:
import sqlite3
except ImportError:
# Some systems have trouble with this
pass
else:
# These are copied from Python sqlite3.dbapi2
def adapt_date(val):
return val.isoformat()
def adapt_datetime(val):
return val.isoformat(" ")
sqlite3.register_adapter(FakeDate, adapt_date)
sqlite3.register_adapter(FakeDatetime, adapt_datetime)
[nosetests]
verbosity = 1
detailed-errors = 1
with-coverage = 1
cover-package = freezegun
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
requires = ['six']
if sys.version_info[0] == 2:
requires += ['python-dateutil>=1.0, <2.0, >=2.1']
else:
# Py3k
requires += ['python-dateutil>=2.0']
setup(
name='freezegun',
version='0.1.17',
description='Let your Python tests travel through time',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/freezegun',
packages=find_packages(exclude=("tests", "tests.*",)),
install_requires=requires,
include_package_data=True,
)
from datetime import datetime
from datetime import date
from time import time
def fake_datetime_function():
return datetime.now()
def fake_date_function():
return date.today()
def fake_time_function():
return time()
import sure
import time
from .fake_module import fake_datetime_function, fake_date_function, fake_time_function
from freezegun import freeze_time
from freezegun.api import FakeDatetime
import datetime
@freeze_time("2012-01-14")
def test_import_datetime_works():
fake_datetime_function().day.should.equal(14)
@freeze_time("2012-01-14")
def test_import_date_works():
fake_date_function().day.should.equal(14)
@freeze_time("2012-01-14")
def test_import_time():
local_time = datetime.datetime(2012, 1, 14)
utc_time = local_time - datetime.timedelta(seconds=time.timezone)
expected_timestamp = time.mktime(utc_time.timetuple())
fake_time_function().should.equal(expected_timestamp)
def test_start_and_stop_works():
freezer = freeze_time("2012-01-14")
result = fake_datetime_function()
result.__class__.should.equal(datetime.datetime)
result.__class__.shouldnt.equal(FakeDatetime)
freezer.start()
fake_datetime_function().day.should.equal(14)
fake_datetime_function().should.be.a(datetime.datetime)
fake_datetime_function().should.be.a(FakeDatetime)
freezer.stop()
result = fake_datetime_function()
result.__class__.should.equal(datetime.datetime)
result.__class__.shouldnt.equal(FakeDatetime)
def test_isinstance_works():
date = datetime.date.today()
now = datetime.datetime.now()
freezer = freeze_time('2011-01-01')
freezer.start()
isinstance(date, datetime.date).should.equal(True)
isinstance(date, datetime.datetime).should.equal(False)
isinstance(now, datetime.datetime).should.equal(True)
isinstance(now, datetime.date).should.equal(True)
freezer.stop()
import pickle
import time
import datetime
import unittest
import locale
from nose.plugins import skip
from freezegun import freeze_time
from freezegun.api import FakeDatetime, FakeDate, real_datetime,