Cleanup Python project

This commit is contained in:
Timo Furrer
2019-08-24 22:53:43 +02:00
parent 260f0d54eb
commit a4432eef31
37 changed files with 812 additions and 646 deletions
+12
View File
@@ -0,0 +1,12 @@
[run]
branch = True
source =
maya
[paths]
source =
src
.tox/*/site-packages
[report]
show_missing = True
+46
View File
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at tuxtimo@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+45
View File
@@ -0,0 +1,45 @@
# Contributing
Thank you for helping maya to get a better piece of software.
## Support
If you have any questions regarding the usage of maya please use the Question Issue Template or ask on [StackOverflow](https://stackoverflow.com).
## Reporting Issues / Proposing Features
Before you submit an Issue or proposing a Feature check the existing Issues in order to avoid duplicates. <br>
Please make sure you provide enough information to work on your submitted Issue or proposed Feature:
* Which version of maya are you using?
* Which version of python are you using?
* On which platform are you running maya?
Make sure to use the GitHub Template when reporting an issue.
## Pull Requests
We are very happy to receive Pull Requests considering:
* Style Guide. Follow the rules of [PEP8](http://legacy.python.org/dev/peps/pep-0008/), but you may ignore *too-long-lines* and similar warnings. There is a *pylintrc* file for more information.
* Tests. If our change affects python code inside the source code directory, please make sure your code is covered by an automated test case.
### Testing
To test the maya source code against all supported python versions you should use *tox*:
```bash
cd ~/work/maya
pip install tox
tox
```
However, if you want to test your code on certain circumstances you can create a *virtualenv*:
```
cd ~/work/maya
virtualenv env
source env/bin/activate
pip install -e '.[dev]'
commands = coverage run --parallel -m pytest -s --failed-first
```
+42
View File
@@ -0,0 +1,42 @@
---
name: Bug Report
about: Create a bug report to help us improve maya
title: ''
labels: ''
assignees: ''
---
**Important notices**
Before you add a new report, we ask you kindly to acknowledge the following:
[-] I have read the contributing guide lines at https://github.com/timofurrer/maya/blob/master/.github/CONTRIBUTING.md
[-] I have read and respect the code of conduct at https://github.com/timofurrer/maya/blob/master/.github/CODE_OF_CONDUCT.md
[-] I have searched the existing issues and I'm convinced that mine is new.
**Describe the bug**
A clear and concise description of what the bug is.
**Environment and Version**
* OS (incl. terminal and shell used): ...
* Python Version: ...
* maya Version: ...
* Your timezone: ...
**To Reproduce**
A clear and concise description of steps to reproduce the behavior
you are experiencing.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Relevant log files**
If applicable, information from log files supporting your claim.
**Additional context**
Add any other context about the problem here.
+29
View File
@@ -0,0 +1,29 @@
---
name: Feature Request
about: Suggest an idea for a new feature or enhancement for maya
title: ''
labels: ''
assignees: ''
---
**Important notices**
Before you add a new request, we ask you kindly to acknowledge the following:
[-] I have read the contributing guide lines at https://github.com/timofurrer/maya/blob/master/.github/CONTRIBUTING.md
[-] I have read and respect the code of conduct at https://github.com/timofurrer/maya/blob/master/.github/CODE_OF_CONDUCT.md
[-] I have searched the existing issues and I'm convinced that mine is new.
**Is your Feature Request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the Feature Request here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Ask a Question
about: Ask a Question about maya (Usage, Development, ...)
title: ''
labels: ''
assignees: ''
---
**Important notices**
Before you add a new report, we ask you kindly to acknowledge the following:
[-] I have read the contributing guide lines at https://github.com/timofurrer/maya/blob/master/.github/CONTRIBUTING.md
[-] I have read and respect the code of conduct at https://github.com/timofurrer/maya/blob/master/.github/CODE_OF_CONDUCT.md
[-] I have searched the existing issues and I'm convinced that mine is new.
**Ask your Question**
Ask your question here! If the question is related to a particular environment or behavior please make sure to add some context.
+82
View File
@@ -0,0 +1,82 @@
name: Continuous Integration and Deployment
on: [push]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
max-parallel: 4
matrix:
python-version: [2.7, 3.5, 3.6, 3.7]
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Setup build and test environment
run: |
python -m pip install --upgrade pip setuptools wheel
- name: Build Python Package
run: |
python -m pip install ".[tests]"
- name: Lint with flake8
run: |
pip install flake8
flake8 --show-source src/ tests/
- name: Check Manifest
run: |
pip install check-manifest
check-manifest
- name: Test with pytest
run: |
coverage run --parallel -m pytest
- name: Report code coverage
run: |
coverage combine
coverage report
coverage xml
docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: Setup docs environment
run: |
python -m pip install ".[docs]"
- name: Build documentation with sphinx
run: |
sphinx-build -W -b html -d doctrees docs/source docs/_build/html
publish:
needs: [build, docs]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python 3.7
if: startsWith(github.event.ref, 'refs/tags')
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: Build Package
if: startsWith(github.event.ref, 'refs/tags')
run: |
python -m pip install --upgrade pip setuptools wheel
python setup.py sdist bdist_wheel --universal
- name: Publish Package on PyPI
if: startsWith(github.event.ref, 'refs/tags')
uses: pypa/gh-action-pypi-publish@master
with:
user: __token__
password: ${{ secrets.pypi_token }}
+18
View File
@@ -0,0 +1,18 @@
name: "Close Stale Issues and Pull Requests"
on:
schedule:
- cron: "0 * * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
days-before-stale: 60
days-before-close: 7
stale-issue-label: stale
stale-pr-label: state
stale-issue-message: 'This Issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days'
stale-pr-message: 'This Pull Request is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days'
+32
View File
@@ -0,0 +1,32 @@
repos:
- repo: https://github.com/ambv/black
rev: 19.3b0
hooks:
- id: black
language_version: python3.7
# override until resolved: https://github.com/ambv/black/issues/402
files: \.pyi?$
types: []
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.7
hooks:
- id: flake8
language_version: python3.7
#- repo: https://github.com/asottile/seed-isort-config
#rev: v1.9.1
#hooks:
#- id: seed-isort-config
#- repo: https://github.com/pre-commit/mirrors-isort
#rev: v4.3.20
#hooks:
#- id: isort
#language_version: python3.7
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.3
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
-18
View File
@@ -1,18 +0,0 @@
language: python
python:
- "2.7"
- "3.6"
- "3.7-dev"
matrix:
allow_failures:
- python: "3.7-dev"
# command to install dependencies
install:
- pip install pipenv
- pipenv install '-e .' --skip-lock --ignore-pipfile
- pipenv install --dev --skip-lock
# command to run tests
script: pipenv run pytest tests/
-28
View File
@@ -1,28 +0,0 @@
Contributions to the maya project
=================================
Creator & Maintainer
--------------------
- Kenneth Reitz <me@kennethreitz.org> `@kennethreitz <https://github.com/kennethreitz>`_
Contributors
------------
In chronological order:
- Adam Nelson <adam@varud.com> (`@adamn <https://github.com/adamn>`_)
- Timo Furrer <tuxtimo@gmail.com> (`@timofurrer <https://github.com/timofurrer>`_)
- Moinuddin Quadri <moin18@gmail.com> (`@moin18 <https://github.com/moin18>`_)
- Grigouze <grigouze@yahoo.fr> (`@grigouze <https://github.com/grigouze>`_)
- Tzu-ping Chung <uranusjr@gmail.com> (`@uranusjr <https://github.com/uranusjr>`_)
- aaronjeline (`@aaronjeline <https://github.com/aaronjeline>`_)
- jerry2yu (`@jerry2yu <https://github.com/jerry2yu>`_)
- Joshua Li <joshua.r.li.98@gmail.com> (`@JoshuaRLi <https://github.com/JoshuaRLi>`_)
- Sébastien Eustace <sebastien@eustace.io> (`@sdispater <https://github.com/sdispater>`_)
- Evan Mattiza <emattiza@gmail.com> (`@emattiza <https://github.com/emattiza>`_)
- Dima Spivak <dima@spivak.ch> (`@dimaspivak <https://github.com/dimaspivak>`_)
- Tom Barron <tusculum@gmail.com> (`@dtbarron <https://github.com/tbarron>`_)
- Alex Ward <alxwrd@gmail.com> (`@alxwrd <https://github.com/alxwrd>`_)
- Frank Tobia <frank.tobia@gmail.com> (`@ftobia <https://github.com/ftobia>`_)
+30
View File
@@ -0,0 +1,30 @@
# Additional package data
# Metadata
include LICENSE *.md *.rst *.toml *.yml *.yaml
graft .github
# Jupyter Notebooks
include *.ipynb
# Stubs
recursive-include src *.pyi
# Tests
include tox.ini .coveragerc conftest.py
recursive-include tests *.py
# Documentation
include docs/Makefile docs/docutils.conf
recursive-include docs *.bat
recursive-include docs *.png
recursive-include docs *.svg
recursive-include docs *.py
recursive-include docs *.rst
recursive-include docs *.ico
prune docs/_build
# Just to keep check-manifest happy; on releases those files are gone.
# Last rule wins!
exclude changelog.d/*.rst
include changelog.d/towncrier_template.rst
-6
View File
@@ -1,6 +0,0 @@
.PHONY: tests docs
tests:
pytest tests/
docs:
cd docs && make html
-9
View File
@@ -1,9 +0,0 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
freezegun = "*"
pytest = "*"
sphinx = "*"
+2 -5
View File
@@ -4,11 +4,8 @@ Maya: Datetimes for Humans™
.. image:: https://img.shields.io/pypi/v/maya.svg
:target: https://pypi.python.org/pypi/maya
.. image:: https://travis-ci.org/timofurrer/maya.svg?branch=master
:target: https://travis-ci.org/timofurrer/maya
.. image:: https://img.shields.io/badge/SayThanks-!-1EAEDB.svg
:target: https://saythanks.io/to/kennethreitz
.. image:: https://github.com/timofurrer/maya/workflows/Continuous%20Integration%20and%20Deployment/badge.svg
:target: https://github.com/timofurrer/maya/actions
Datetimes are very frustrating to work with in Python, especially when dealing
+1 -1
View File
@@ -1,2 +1,2 @@
requirements:
- maya==0.6.0
- maya==0.6.0
View File
View File
+32 -33
View File
@@ -19,11 +19,12 @@
#
import os
import sys
# sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('_themes'))
import maya
# sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath(".."))
sys.path.insert(0, os.path.abspath("_themes"))
import maya # noqa
# -- General configuration ------------------------------------------------
@@ -34,27 +35,29 @@ import maya
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode']
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = 'maya'
copyright = '2017, Kenneth Reitz'
author = 'Kenneth Reitz'
project = "maya"
copyright = "2017, Kenneth Reitz"
author = "Kenneth Reitz"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -78,7 +81,7 @@ language = None
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
@@ -89,7 +92,7 @@ todo_include_todos = True
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
@@ -100,13 +103,13 @@ html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# html_static_path = ["_static"]
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'mayadoc'
htmlhelp_basename = "mayadoc"
# -- Options for LaTeX output ---------------------------------------------
@@ -115,15 +118,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
@@ -133,8 +133,7 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'maya.tex', 'maya Documentation',
'Kenneth Reitz', 'manual'),
(master_doc, "maya.tex", "maya Documentation", "Kenneth Reitz", "manual")
]
@@ -142,10 +141,7 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'maya', 'maya Documentation',
[author], 1)
]
man_pages = [(master_doc, "maya", "maya Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
@@ -154,10 +150,13 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'maya', 'maya Documentation',
author, 'maya', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"maya",
"maya Documentation",
author,
"maya",
"One line description of project.",
"Miscellaneous",
)
]
-1
View File
@@ -80,4 +80,3 @@ Table of Contents
user/install
user/quickstart
View File
+2 -3
View File
@@ -1,6 +1,7 @@
.. _install:
Installation
=============
============
Pip Install Maya
----------------
@@ -26,5 +27,3 @@ Once you have a copy of the source, you can embed it in your own Python
package, or install it into your site-packages easily::
$ python setup.py install
View File
+1 -9
View File
@@ -1,4 +1,5 @@
.. _quickstart:
Quickstart
==========
@@ -7,12 +8,6 @@ Quickstart
Ready for a simple datetime tool? This doc provides some tools to use in your
busy workflow.
First, make sure that Maya is:
- :ref:`Installed <install>`
- :ref:`Up to date <update>`
Parse a Date
------------
Parsing a date from a string with Maya is 🍰!
@@ -33,6 +28,3 @@ Use as follows::
>>> recent_win = maya.parse('2016-11-02T20:00PM')
>>> old_win = maya.when('October 14, 1908')
>>> grandpas_date = maya.when('108 years ago')
-27
View File
@@ -1,27 +0,0 @@
.. _update:
Community Updates
=================
If you'd like to stay up to date on the community and development of Maya,
there are several options:
GitHub
------
The best way to track the development of Maya is through
`the GitHub repo <https://github.com/kennethreitz/Maya>`_.
Twitter
-------
The author, Kenneth Reitz, often tweets about new features and releases of Maya.
Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.
Release and Version History
===========================
.. include:: ../../HISTORY.rst
-2
View File
@@ -1,2 +0,0 @@
from .core import *
from .__version__ import __version__
-1
View File
@@ -1 +0,0 @@
__version__ = '0.6.0a1'
+16
View File
@@ -1,2 +1,18 @@
[bdist_wheel]
universal = 1
[metadata]
# ensure LICENSE is included in wheel metadata
license_file = LICENSE
[flake8]
max-line-length = 100
ignore = E203
[tool:pytest]
testpaths = tests/
[isort]
known_first_party=maya
known_third_party=humanize,pytz,dateparser,tzlocal,pendulum,snaptime
multi_line_output=3
Executable → Regular
+80 -94
View File
@@ -1,106 +1,92 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
import codecs
from shutil import rmtree
import os
import re
from setuptools import find_packages, setup, Command
from setuptools import find_packages, setup
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
if sys.argv[-1] == "publish":
os.system("python setup.py sdist bdist_wheel upload")
sys.exit()
required = [
'humanize',
'pytz',
'dateparser>=0.7.0',
'tzlocal',
'pendulum>=2.0.2',
'snaptime'
#: Holds a list of packages to install with the binary distribution
PACKAGES = find_packages(where="src")
META_FILE = os.path.abspath("src/maya/__init__.py")
KEYWORDS = ["datetime", "timezone", "scrape", "web"]
CLASSIFIERS = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development :: Libraries :: Python Modules",
]
packages = [
'maya',
#: Holds the runtime requirements for the end user
INSTALL_REQUIRES = [
"humanize",
"pytz",
"dateparser>=0.7.0",
"tzlocal",
"pendulum>=2.0.2",
"snaptime",
]
#: Holds runtime requirements and development requirements
EXTRAS_REQUIRES = {
# extras for contributors
"docs": ["sphinx"],
"tests": ["freezegun", "coverage", "pytest", "pytest-mock"],
}
EXTRAS_REQUIRES["dev"] = (
EXTRAS_REQUIRES["tests"] + EXTRAS_REQUIRES["docs"] + ["pre-commit"]
)
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPi via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
#: Holds the contents of the README file
with codecs.open("README.rst", encoding="utf-8") as readme:
__README_CONTENTS__ = readme.read()
# About dict to store version and package info
about = dict()
with codecs.open(os.path.join(here, 'maya', '__version__.py'), 'r', encoding='utf-8') as f:
exec(f.read(), about)
def read(metafile):
"""
Return the contents of the given meta data file assuming UTF-8 encoding.
"""
with codecs.open(str(metafile), encoding="utf-8") as f:
return f.read()
def get_meta(meta, metafile):
"""
Extract __*meta*__ from the given metafile.
"""
contents = read(metafile)
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), contents, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))
setup(
name='maya',
version=about['__version__'],
description='Datetimes for Humans.',
long_description=long_description,
author='Kenneth Reitz',
author_email='me@kennethreitz.org',
url='https://github.com/kennethreitz/maya',
packages=packages,
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries :: Python Modules'
),
cmdclass={
'upload': UploadCommand,
},
name="maya",
version=get_meta("version", META_FILE),
license=get_meta("license", META_FILE),
description=get_meta("description", META_FILE),
long_description=__README_CONTENTS__,
author=get_meta("author", META_FILE),
author_email=get_meta("author_email", META_FILE),
maintainer=get_meta("author", META_FILE),
maintainer_email=get_meta("author_email", META_FILE),
platforms=["Linux", "Windows", "MAC OS X"],
url=get_meta("url", META_FILE),
download_url=get_meta("download_url", META_FILE),
bugtrack_url=get_meta("bugtrack_url", META_FILE),
packages=PACKAGES,
package_dir={"": "src"},
include_package_data=True,
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRES,
keywords=KEYWORDS,
classifiers=CLASSIFIERS,
)
+10
View File
@@ -0,0 +1,10 @@
__description__ = "Datetimes for Humans™"
__license__ = "MIT"
__version__ = "0.6.0a1"
__author__ = "Timo Furrer"
__author_email__ = "tuxtimo@gmail.com"
__url__ = "http://github.com/timofurrer/maya"
__download_url__ = "https://github.com/timofurrer/maya"
__bugtrack_url__ = "https://github.com/timofurrer/maya/issues"
from .core import * # noqa
+4 -3
View File
@@ -14,14 +14,15 @@ import sys
# Syntax sugar.
_ver = sys.version_info
# : Python 2.x?
is_py2 = (_ver[0] == 2)
is_py2 = _ver[0] == 2
# : Python 3.x?
is_py3 = (_ver[0] == 3)
is_py3 = _ver[0] == 3
# ---------
# Specifics
# ---------
if is_py2:
cmp = cmp
cmp = cmp # noqa
elif is_py3:
def cmp(a, b):
+67 -103
View File
@@ -26,12 +26,11 @@ def validate_class_type_arguments(operator):
"""
def inner(function):
def wrapper(self, *args, **kwargs):
for arg in args + tuple(kwargs.values()):
if not isinstance(arg, self.__class__):
raise TypeError(
'unorderable types: {}() {} {}()'.format(
"unorderable types: {}() {} {}()".format(
type(self).__name__, operator, type(arg).__name__
)
)
@@ -54,20 +53,15 @@ def validate_arguments_type_of_function(param_type=None):
"""
def inner(function):
def wrapper(self, *args, **kwargs):
type_ = param_type or type(self)
for arg in args + tuple(kwargs.values()):
if not isinstance(arg, type_):
raise TypeError(
(
'Invalid Type: {}.{}() accepts only the '
"Invalid Type: {}.{}() accepts only the "
'arguments of type "<{}>"'
).format(
type(self).__name__,
function.__name__,
type_.__name__,
)
).format(type(self).__name__, function.__name__, type_.__name__)
)
return function(self, *args, **kwargs)
@@ -79,6 +73,7 @@ def validate_arguments_type_of_function(param_type=None):
class MayaDT(object):
"""The Maya Datetime object."""
__EPOCH_START = (1970, 1, 1)
def __init__(self, epoch):
@@ -86,7 +81,7 @@ class MayaDT(object):
self._epoch = epoch
def __repr__(self):
return '<MayaDT epoch={}>'.format(self._epoch)
return "<MayaDT epoch={}>".format(self._epoch)
def __str__(self):
return self.rfc2822()
@@ -95,27 +90,27 @@ class MayaDT(object):
"""Return's the datetime's format"""
return format(self.datetime(), *args, **kwargs)
@validate_class_type_arguments('==')
@validate_class_type_arguments("==")
def __eq__(self, maya_dt):
return int(self._epoch) == int(maya_dt._epoch)
@validate_class_type_arguments('!=')
@validate_class_type_arguments("!=")
def __ne__(self, maya_dt):
return int(self._epoch) != int(maya_dt._epoch)
@validate_class_type_arguments('<')
@validate_class_type_arguments("<")
def __lt__(self, maya_dt):
return int(self._epoch) < int(maya_dt._epoch)
@validate_class_type_arguments('<=')
@validate_class_type_arguments("<=")
def __le__(self, maya_dt):
return int(self._epoch) <= int(maya_dt._epoch)
@validate_class_type_arguments('>')
@validate_class_type_arguments(">")
def __gt__(self, maya_dt):
return int(self._epoch) > int(maya_dt._epoch)
@validate_class_type_arguments('>=')
@validate_class_type_arguments(">=")
def __ge__(self, maya_dt):
return int(self._epoch) >= int(maya_dt._epoch)
@@ -123,9 +118,7 @@ class MayaDT(object):
return hash(int(self.epoch))
def __add__(self, duration):
return self.add(
seconds=_seconds_or_timedelta(duration).total_seconds()
)
return self.add(seconds=_seconds_or_timedelta(duration).total_seconds())
def __radd__(self, duration):
return self + duration
@@ -141,19 +134,15 @@ class MayaDT(object):
def add(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).add(**kwargs)
)
return self.from_datetime(pendulum.instance(self.datetime()).add(**kwargs))
def subtract(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).subtract(**kwargs)
)
return self.from_datetime(pendulum.instance(self.datetime()).subtract(**kwargs))
def subtract_date(self, **kwargs):
"""Returns a timedelta object with the duration between the dates"""
return timedelta(seconds=self.epoch - kwargs['dt'].epoch)
return timedelta(seconds=self.epoch - kwargs["dt"].epoch)
def snap(self, instruction):
"""
@@ -169,7 +158,7 @@ class MayaDT(object):
@property
def timezone(self):
"""Returns the UTC tzinfo name. It's always UTC. Always."""
return 'UTC'
return "UTC"
@property
def _tz(self):
@@ -196,7 +185,7 @@ class MayaDT(object):
# Assume UTC if no datetime is provided.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC'))
epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone("UTC"))
return (dt - epoch_start).total_seconds()
# Importers
@@ -270,7 +259,7 @@ class MayaDT(object):
"""Returns an ISO 8601 representation of the MayaDT."""
# Get a timezone-naive datetime.
dt = self.datetime(naive=True)
return '{}Z'.format(dt.isoformat())
return "{}Z".format(dt.isoformat())
def rfc2822(self):
"""Returns an RFC 2822 representation of the MayaDT."""
@@ -347,7 +336,8 @@ class MayaDT(object):
pass
delta = humanize.time.abs_timedelta(
timedelta(seconds=(self.epoch - now().epoch)))
timedelta(seconds=(self.epoch - now().epoch))
)
format_string = "DD MMM"
if delta.days >= 365:
@@ -402,7 +392,7 @@ def to_utc_offset_aware(dt):
def to_iso8601(dt):
return to_utc_offset_naive(dt).isoformat() + 'Z'
return to_utc_offset_naive(dt).isoformat() + "Z"
def end_of_day_midnight(dt):
@@ -410,10 +400,7 @@ def end_of_day_midnight(dt):
return dt
else:
return (
dt.replace(hour=0, minute=0, second=0, microsecond=0) +
timedelta(days=1)
)
return dt.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
@comparable
@@ -435,9 +422,7 @@ class MayaInterval(object):
)
assert not all((start, end, duration is not None))
except AssertionError:
raise ValueError(
'Exactly 2 of start, end, and duration must be specified'
)
raise ValueError("Exactly 2 of start, end, and duration must be specified")
# Convert duration to timedelta if seconds were provided.
if duration:
@@ -447,25 +432,23 @@ class MayaInterval(object):
if not end:
end = start + duration
if start > end:
raise ValueError('MayaInterval cannot end before it starts')
raise ValueError("MayaInterval cannot end before it starts")
self.start = start
self.end = end
def __repr__(self):
return '<MayaInterval start={0!r} end={1!r}>'.format(
self.start, self.end
)
return "<MayaInterval start={0!r} end={1!r}>".format(self.start, self.end)
def iso8601(self):
"""Returns an ISO 8601 representation of the MayaInterval."""
return '{0}/{1}'.format(self.start.iso8601(), self.end.iso8601())
return "{0}/{1}".format(self.start.iso8601(), self.end.iso8601())
@classmethod
def parse_iso8601_duration(cls, duration, start=None, end=None):
match = re.match(
r'(?:P(?P<weeks>\d+)W)|(?:P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D))?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?)',
duration
r"(?:P(?P<weeks>\d+)W)|(?:P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D))?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?)", # noqa
duration,
)
time_components = {}
@@ -487,7 +470,7 @@ class MayaInterval(object):
@classmethod
def from_iso8601(cls, s):
# # Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
start, end = s.split('/')
start, end = s.split("/")
try:
start = parse(start)
except pendulum.parsing.exceptions.ParserError:
@@ -496,7 +479,7 @@ class MayaInterval(object):
try:
end = parse(end)
except (pendulum.parsing.exceptions.ParserError, TypeError) as e:
except (pendulum.parsing.exceptions.ParserError, TypeError):
end = cls.parse_iso8601_duration(end, start=start)
return cls(start=start, end=end)
@@ -514,9 +497,7 @@ class MayaInterval(object):
@validate_arguments_type_of_function()
def __eq__(self, maya_interval):
return (
self.start == maya_interval.start and self.end == maya_interval.end
)
return self.start == maya_interval.start and self.end == maya_interval.end
def __hash__(self):
return hash((self.start, self.end))
@@ -527,10 +508,7 @@ class MayaInterval(object):
@validate_arguments_type_of_function()
def __cmp__(self, maya_interval):
return (
cmp(self.start, maya_interval.start)
or cmp(self.end, maya_interval.end)
)
return cmp(self.start, maya_interval.start) or cmp(self.end, maya_interval.end)
@property
def duration(self):
@@ -585,7 +563,7 @@ class MayaInterval(object):
# Convert seconds to timedelta, if appropriate.
duration = _seconds_or_timedelta(duration)
if duration <= timedelta(seconds=0):
raise ValueError('cannot call split with a non-positive timedelta')
raise ValueError("cannot call split with a non-positive timedelta")
start = self.start
while start < self.end:
@@ -597,22 +575,18 @@ class MayaInterval(object):
start += duration
def quantize(self, duration, snap_out=False, timezone='UTC'):
def quantize(self, duration, snap_out=False, timezone="UTC"):
"""Returns a quanitzed interval."""
# Convert seconds to timedelta, if appropriate.
duration = _seconds_or_timedelta(duration)
timezone = pytz.timezone(timezone)
if duration <= timedelta(seconds=0):
raise ValueError('cannot quantize by non-positive timedelta')
raise ValueError("cannot quantize by non-positive timedelta")
epoch = timezone.localize(Datetime(1970, 1, 1))
seconds = int(duration.total_seconds())
start_seconds = int(
(self.start.datetime(naive=False) - epoch).total_seconds()
)
end_seconds = int(
(self.end.datetime(naive=False) - epoch).total_seconds()
)
start_seconds = int((self.start.datetime(naive=False) - epoch).total_seconds())
end_seconds = int((self.end.datetime(naive=False) - epoch).total_seconds())
if start_seconds % seconds and not snap_out:
start_seconds += seconds
if end_seconds % seconds and snap_out:
@@ -632,15 +606,13 @@ class MayaInterval(object):
start = max(self.start, maya_interval.start)
end = min(self.end, maya_interval.end)
either_instant = self.is_instant or maya_interval.is_instant
instant_overlap = (self.start == maya_interval.start or start <= end)
instant_overlap = self.start == maya_interval.start or start <= end
if (either_instant and instant_overlap) or (start < end):
return MayaInterval(start, end)
@validate_arguments_type_of_function()
def contains(self, maya_interval):
return (
self.start <= maya_interval.start and self.end >= maya_interval.end
)
return self.start <= maya_interval.start and self.end >= maya_interval.end
def __contains__(self, maya_dt):
if isinstance(maya_dt, MayaDT):
@@ -653,14 +625,13 @@ class MayaInterval(object):
@validate_arguments_type_of_function()
def is_adjacent(self, maya_interval):
return (
self.start == maya_interval.end or self.end == maya_interval.start
)
return self.start == maya_interval.end or self.end == maya_interval.start
@property
def icalendar(self):
ical_dt_format = '%Y%m%dT%H%M%SZ'
return """
ical_dt_format = "%Y%m%dT%H%M%SZ"
return (
"""
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
@@ -669,26 +640,21 @@ class MayaInterval(object):
END:VEVENT
END:VCALENDAR
""".format(
self.start.datetime().strftime(ical_dt_format),
self.end.datetime().strftime(ical_dt_format),
).replace(
' ', ''
).strip(
'\r\n'
).replace(
'\n', '\r\n'
self.start.datetime().strftime(ical_dt_format),
self.end.datetime().strftime(ical_dt_format),
)
.replace(" ", "")
.strip("\r\n")
.replace("\n", "\r\n")
)
@staticmethod
def flatten(interval_list):
return functools.reduce(
lambda reduced,
maya_interval: (
(
reduced[:-1] + maya_interval.combine(reduced[-1])
) if reduced else [
maya_interval
]
lambda reduced, maya_interval: (
(reduced[:-1] + maya_interval.combine(reduced[-1]))
if reduced
else [maya_interval]
),
sorted(interval_list),
[],
@@ -707,7 +673,7 @@ def now():
return MayaDT(epoch=epoch)
def when(string, timezone='UTC', prefer_dates_from='current_period'):
def when(string, timezone="UTC", prefer_dates_from="current_period"):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
@@ -726,20 +692,20 @@ def when(string, timezone='UTC', prefer_dates_from='current_period'):
[1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates
"""
settings = {
'TIMEZONE': timezone,
'RETURN_AS_TIMEZONE_AWARE': True,
'TO_TIMEZONE': 'UTC',
'PREFER_DATES_FROM': prefer_dates_from,
"TIMEZONE": timezone,
"RETURN_AS_TIMEZONE_AWARE": True,
"TO_TIMEZONE": "UTC",
"PREFER_DATES_FROM": prefer_dates_from,
}
dt = dateparser.parse(string, settings=settings)
if dt is None:
raise ValueError('invalid datetime input specified.')
raise ValueError("invalid datetime input specified.")
return MayaDT.from_datetime(dt)
def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False):
def parse(string, timezone="UTC", day_first=False, year_first=True, strict=False):
""""Returns a MayaDT instance for the machine-produced moment specified.
Powered by pendulum.
@@ -758,10 +724,10 @@ def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False
if pendulum's own parsing fails
"""
options = {}
options['tz'] = timezone
options['day_first'] = day_first
options['year_first'] = year_first
options['strict'] = strict
options["tz"] = timezone
options["day_first"] = day_first
options["year_first"] = year_first
options["strict"] = strict
dt = pendulum.parse(str(string), **options)
return MayaDT.from_datetime(dt)
@@ -779,8 +745,8 @@ def _seconds_or_timedelta(duration):
dt_timedelta = duration
else:
raise TypeError(
'Expects argument as `datetime.timedelta` object '
'or seconds in `int` format'
"Expects argument as `datetime.timedelta` object "
"or seconds in `int` format"
)
return dt_timedelta
@@ -806,6 +772,4 @@ def intervals(start, end, interval):
while current_timestamp.epoch < end.epoch:
yield current_timestamp
current_timestamp = current_timestamp.add(
seconds=interval.total_seconds()
)
current_timestamp = current_timestamp.add(seconds=interval.total_seconds())
+17 -16
View File
@@ -2,22 +2,23 @@ from freezegun import freeze_time
import pytest
@pytest.fixture(params=[
("2018-03-25T00:00:00", 2),
("2018-03-25T01:00:00", 2),
("2018-03-25T02:00:00", 2),
("2018-03-25T02:30:00", 2),
("2018-03-25T03:00:00", 2),
("2018-03-25T04:00:00", 2),
("2018-10-28T00:00:00", 2),
("2018-10-28T01:00:00", 2),
("2018-10-28T02:00:00", 2),
("2018-10-28T02:30:00", 2),
("2018-10-28T03:00:00", 2),
("2018-10-28T04:00:00", 2),
], ids=lambda x: x[0] + "_off_" + str(x[1]))
@pytest.fixture(
params=[
("2018-03-25T00:00:00", 2),
("2018-03-25T01:00:00", 2),
("2018-03-25T02:00:00", 2),
("2018-03-25T02:30:00", 2),
("2018-03-25T03:00:00", 2),
("2018-03-25T04:00:00", 2),
("2018-10-28T00:00:00", 2),
("2018-10-28T01:00:00", 2),
("2018-10-28T02:00:00", 2),
("2018-10-28T02:30:00", 2),
("2018-10-28T03:00:00", 2),
("2018-10-28T04:00:00", 2),
],
ids=lambda x: x[0] + "_off_" + str(x[1]),
)
def frozen_now(request):
now_string, tz_offset = request.param
with freeze_time(now_string, tz_offset=tz_offset):
+85 -109
View File
@@ -10,10 +10,9 @@ import maya
from maya.core import _seconds_or_timedelta # import private function
@pytest.mark.parametrize("string,expected", [
('February 21, 1994',
'Mon, 21 Feb 1994 00:00:00 GMT'),
])
@pytest.mark.parametrize(
"string,expected", [("February 21, 1994", "Mon, 21 Feb 1994 00:00:00 GMT")]
)
def test_rfc2822(string, expected):
r = maya.parse(string).rfc2822()
d = maya.MayaDT.from_rfc2822(r)
@@ -21,10 +20,9 @@ def test_rfc2822(string, expected):
assert r == d.rfc2822()
@pytest.mark.parametrize("string,expected", [
('February 21, 1994',
'1994-02-21T00:00:00Z'),
])
@pytest.mark.parametrize(
"string,expected", [("February 21, 1994", "1994-02-21T00:00:00Z")]
)
def test_iso8601(string, expected):
r = maya.parse(string).iso8601()
d = maya.MayaDT.from_iso8601(r)
@@ -32,28 +30,18 @@ def test_iso8601(string, expected):
assert r == d.iso8601()
@pytest.mark.parametrize("string,expected", [
('20161001T1430.4+05:30',
'2016-10-01T09:00:00.400000Z'),
('2016T14',
'2016-01-01T14:00:00Z'),
('2016-10T14',
'2016-10-01T14:00:00Z'),
('2012W05',
'2012-01-30T00:00:00Z'),
('2012W055',
'2012-02-03T00:00:00Z'),
('2012007',
'2012-01-07T00:00:00Z'),
('2016-W07T09',
'2016-02-15T09:00:00Z'),
])
@pytest.mark.parametrize(
"string,expected",
[
("20161001T1430.4+05:30", "2016-10-01T09:00:00.400000Z"),
("2016T14", "2016-01-01T14:00:00Z"),
("2016-10T14", "2016-10-01T14:00:00Z"),
("2012W05", "2012-01-30T00:00:00Z"),
("2012W055", "2012-02-03T00:00:00Z"),
("2012007", "2012-01-07T00:00:00Z"),
("2016-W07T09", "2016-02-15T09:00:00Z"),
],
)
def test_parse_iso8601(string, expected):
d = maya.MayaDT.from_iso8601(string)
assert expected == d.iso8601()
@@ -69,9 +57,7 @@ def test_struct():
assert m.datetime() == dt
ts = time.localtime(now)
m = maya.MayaDT.from_struct(ts)
dt = Datetime.fromtimestamp(
time.mktime(ts) - maya.core.utc_offset(ts), pytz.UTC
)
dt = Datetime.fromtimestamp(time.mktime(ts) - maya.core.utc_offset(ts), pytz.UTC)
assert m._epoch is not None
assert m.datetime() == dt
@@ -80,29 +66,29 @@ def test_issue_104():
e = 1507756331
t = Datetime.utcfromtimestamp(e)
t = maya.MayaDT.from_datetime(t)
assert str(t) == 'Wed, 11 Oct 2017 21:12:11 GMT'
assert str(t) == "Wed, 11 Oct 2017 21:12:11 GMT"
t = time.gmtime(e)
t = maya.MayaDT.from_struct(t)
assert str(t) == 'Wed, 11 Oct 2017 21:12:11 GMT'
assert str(t) == "Wed, 11 Oct 2017 21:12:11 GMT"
def test_human_when():
r1 = maya.when('yesterday')
r2 = maya.when('today')
r1 = maya.when("yesterday")
r2 = maya.when("today")
assert (r2.day - r1.day) in (1, -30, -29, -28, -27)
def test_machine_parse():
r1 = maya.parse('August 14, 2015')
r1 = maya.parse("August 14, 2015")
assert r1.day == 14
r2 = maya.parse('August 15, 2015')
r2 = maya.parse("August 15, 2015")
assert r2.day == 15
@pytest.mark.usefixtures("frozen_now")
def test_dt_tz_translation():
d1 = maya.now().datetime()
d2 = maya.now().datetime(to_timezone='EST')
d2 = maya.now().datetime(to_timezone="EST")
assert (d1.hour - d2.hour) % 24 == 5
@@ -110,14 +96,14 @@ def test_dt_tz_translation():
def test_dt_tz_naive():
d1 = maya.now().datetime(naive=True)
assert d1.tzinfo is None
d2 = maya.now().datetime(to_timezone='EST', naive=True)
d2 = maya.now().datetime(to_timezone="EST", naive=True)
assert d2.tzinfo is None
assert (d1.hour - d2.hour) % 24 == 5
def test_random_date():
# Test properties for maya.when()
d1 = maya.when('11-17-11 08:09:10')
d1 = maya.when("11-17-11 08:09:10")
assert d1.year == 2011
assert d1.month == 11
assert d1.day == 17
@@ -128,7 +114,7 @@ def test_random_date():
assert d1.second == 10
assert d1.microsecond == 0
# Test properties for maya.parse()
d2 = maya.parse('February 29, 1992 13:12:34')
d2 = maya.parse("February 29, 1992 13:12:34")
assert d2.year == 1992
assert d2.month == 2
assert d2.day == 29
@@ -141,60 +127,58 @@ def test_random_date():
def test_print_date(capsys):
d = maya.when('11-17-11')
d = maya.when("11-17-11")
print(d)
out, err = capsys.readouterr()
assert out == 'Thu, 17 Nov 2011 00:00:00 GMT\n'
assert repr(d) == '<MayaDT epoch=1321488000.0>'
assert out == "Thu, 17 Nov 2011 00:00:00 GMT\n"
assert repr(d) == "<MayaDT epoch=1321488000.0>"
def test_invalid_date():
with pytest.raises(ValueError):
maya.when('another day')
maya.when("another day")
def test_slang_date():
d = maya.when('tomorrow')
assert d.slang_date() == 'tomorrow'
d = maya.when("tomorrow")
assert d.slang_date() == "tomorrow"
def test_slang_date_locale():
d = maya.when('tomorrow')
assert d.slang_date(locale='fr') == 'demain'
d = maya.when("tomorrow")
assert d.slang_date(locale="fr") == "demain"
def test_slang_time():
d = maya.when('1 hour ago')
assert d.slang_time() == '1 hour ago'
d = maya.when("1 hour ago")
assert d.slang_time() == "1 hour ago"
def test_slang_time_locale():
d = maya.when('1 hour ago')
assert d.slang_time(locale='de') == 'vor 1 Stunde'
d = maya.when("1 hour ago")
assert d.slang_time(locale="de") == "vor 1 Stunde"
@pytest.mark.parametrize("string,kwds,expected", [
('February 21, 1994', {},
'1994-02-21 00:00:00+00:00'),
('01/05/2016', {},
'2016-01-05 00:00:00+00:00'),
('01/05/2016', dict(day_first=True),
'2016-05-01 00:00:00+00:00'),
('2016/05/01', dict(year_first=True, day_first=False),
'2016-05-01 00:00:00+00:00'),
('2016/01/05', dict(year_first=True, day_first=True),
'2016-05-01 00:00:00+00:00'),
('01/05/2016', dict(timezone='UTC'),
'2016-01-05 00:00:00+00:00'),
('01/05/2016', dict(timezone='US/Central'),
'2016-01-05 06:00:00+00:00'),
])
@pytest.mark.parametrize(
"string,kwds,expected",
[
("February 21, 1994", {}, "1994-02-21 00:00:00+00:00"),
("01/05/2016", {}, "2016-01-05 00:00:00+00:00"),
("01/05/2016", dict(day_first=True), "2016-05-01 00:00:00+00:00"),
(
"2016/05/01",
dict(year_first=True, day_first=False),
"2016-05-01 00:00:00+00:00",
),
(
"2016/01/05",
dict(year_first=True, day_first=True),
"2016-05-01 00:00:00+00:00",
),
("01/05/2016", dict(timezone="UTC"), "2016-01-05 00:00:00+00:00"),
("01/05/2016", dict(timezone="US/Central"), "2016-01-05 06:00:00+00:00"),
],
)
def test_parse(string, kwds, expected):
d = maya.parse(string, **kwds)
assert format(d) == expected
@@ -204,9 +188,7 @@ def test_parse(string, kwds, expected):
def test_when_past():
two_days_away = maya.now().add(days=2)
past_date = maya.when(
two_days_away.slang_date(),
prefer_dates_from='past')
past_date = maya.when(two_days_away.slang_date(), prefer_dates_from="past")
assert past_date < maya.now()
@@ -215,9 +197,7 @@ def test_when_past():
def test_when_future():
two_days_away = maya.now().add(days=2)
future_date = maya.when(
two_days_away.slang_date(),
prefer_dates_from='future')
future_date = maya.when(two_days_away.slang_date(), prefer_dates_from="future")
assert future_date > maya.now()
@@ -227,8 +207,8 @@ def test_when_past_day_name():
two_days_away = maya.now().add(days=2)
past_date = maya.when(
calendar.day_name[two_days_away.weekday],
prefer_dates_from='past')
calendar.day_name[two_days_away.weekday], prefer_dates_from="past"
)
assert past_date < maya.now()
@@ -238,36 +218,36 @@ def test_when_future_day_name():
two_days_away = maya.now().add(days=2)
future_date = maya.when(
calendar.day_name[two_days_away.weekday],
prefer_dates_from='future')
calendar.day_name[two_days_away.weekday], prefer_dates_from="future"
)
assert future_date > maya.now()
def test_datetime_to_timezone():
dt = maya.when('2016-01-01').datetime(to_timezone='US/Eastern')
assert dt.tzinfo.zone == 'US/Eastern'
dt = maya.when("2016-01-01").datetime(to_timezone="US/Eastern")
assert dt.tzinfo.zone == "US/Eastern"
def test_rfc3339_epoch():
mdt = maya.when('2016-01-01')
mdt = maya.when("2016-01-01")
out = mdt.rfc3339()
mdt2 = maya.MayaDT.from_rfc3339(out)
assert mdt.epoch == mdt2.epoch
def test_rfc3339_format():
rfc3339 = maya.MayaDT.rfc3339(maya.when('2016-01-01T12:03:03Z'))
rfc3339 = maya.MayaDT.rfc3339(maya.when("2016-01-01T12:03:03Z"))
# it's important that the string has got a "max 1-digit millis" fragment
# as per https://tools.ietf.org/html/rfc3339#section-5.6
assert rfc3339 == '2016-01-01T12:03:03.0Z'
assert rfc3339 == "2016-01-01T12:03:03.0Z"
@pytest.mark.usefixtures("frozen_now")
def test_comparison_operations():
now = maya.now()
now_copy = copy.deepcopy(now)
tomorrow = maya.when('tomorrow')
tomorrow = maya.when("tomorrow")
assert (now == now_copy) is True
assert (now == tomorrow) is False
assert (now != now_copy) is False
@@ -302,7 +282,7 @@ def test_seconds_or_timedelta():
assert _seconds_or_timedelta(timedelta(0, 1234)) == timedelta(0, 1234)
# test for invalid value
with pytest.raises(TypeError):
_seconds_or_timedelta('invalid interval')
_seconds_or_timedelta("invalid interval")
@pytest.mark.usefixtures("frozen_now")
@@ -342,49 +322,45 @@ def test_mayaDT_sub():
def test_core_local_timezone(monkeypatch):
@property
def mock_local_tz(self):
class StaticTzInfo(object):
zone = 'local'
zone = "local"
def __repr__(self):
return "<StaticTzInfo 'local'>"
return StaticTzInfo()
monkeypatch.setattr(maya.MayaDT, '_local_tz', mock_local_tz)
monkeypatch.setattr(maya.MayaDT, "_local_tz", mock_local_tz)
mdt = maya.MayaDT(0)
assert mdt.local_timezone == 'UTC'
assert mdt.local_timezone == "UTC"
def test_getting_datetime_for_local_timezone(monkeypatch):
@property
def mock_local_tz(self):
class StaticTzInfo(object):
zone = 'Europe/Zurich'
zone = "Europe/Zurich"
def __repr__(self):
return "<StaticTzInfo 'Europe/Zurich'>"
return StaticTzInfo()
monkeypatch.setattr(maya.MayaDT, '_local_tz', mock_local_tz)
monkeypatch.setattr(maya.MayaDT, "_local_tz", mock_local_tz)
d = maya.parse('1994-02-21T12:00:00+05:30')
d = maya.parse("1994-02-21T12:00:00+05:30")
dt = pytz.timezone('Europe/Zurich').localize(
Datetime(1994, 2, 21, 7, 30))
dt = pytz.timezone("Europe/Zurich").localize(Datetime(1994, 2, 21, 7, 30))
assert d.local_datetime() == dt
@pytest.mark.parametrize("when_str,snap_str,expected_when", [
('Mon, 21 Feb 1994 21:21:42 GMT', '@d',
'Mon, 21 Feb 1994 00:00:00 GMT'),
])
@pytest.mark.parametrize(
"when_str,snap_str,expected_when",
[("Mon, 21 Feb 1994 21:21:42 GMT", "@d", "Mon, 21 Feb 1994 00:00:00 GMT")],
)
def test_snaptime(when_str, snap_str, expected_when):
# given
dt = maya.when(when_str)
+100 -168
View File
@@ -7,9 +7,9 @@ import pytz
import maya
from maya.compat import cmp
Los_Angeles = pytz.timezone('America/Los_Angeles')
New_York = pytz.timezone('America/New_York')
Melbourne = pytz.timezone('Australia/Melbourne')
Los_Angeles = pytz.timezone("America/Los_Angeles")
New_York = pytz.timezone("America/New_York")
Melbourne = pytz.timezone("Australia/Melbourne")
def test_interval_requires_2_of_start_end_duration():
@@ -59,7 +59,7 @@ def test_interval_init_end_duration():
@pytest.mark.parametrize(
'start_doy1,end_doy1,start_doy2,end_doy2,intersection_doys',
"start_doy1,end_doy1,start_doy2,end_doy2,intersection_doys",
(
(0, 2, 1, 3, (1, 2)),
(0, 2, 3, 4, None),
@@ -74,40 +74,35 @@ def test_interval_init_end_duration():
(1, 3, 2, 2, (2, 2)),
),
ids=(
'overlapping',
'non-overlapping',
'adjacent',
'equal',
'instant overlapping start only',
'instant equal',
'instant disjoint',
'instant overlapping',
'instant overlapping start only (left)',
'instant disjoint (left)',
'instant overlapping (left)',
"overlapping",
"non-overlapping",
"adjacent",
"equal",
"instant overlapping start only",
"instant equal",
"instant disjoint",
"instant overlapping",
"instant overlapping start only (left)",
"instant disjoint (left)",
"instant overlapping (left)",
),
)
def test_interval_intersection(
start_doy1, end_doy1, start_doy2, end_doy2, intersection_doys
):
base = maya.MayaDT.from_datetime(datetime(2016, 1, 1))
interval1 = maya.MayaInterval(
base.add(days=start_doy1), base.add(days=end_doy1)
)
interval2 = maya.MayaInterval(
base.add(days=start_doy2), base.add(days=end_doy2)
)
interval1 = maya.MayaInterval(base.add(days=start_doy1), base.add(days=end_doy1))
interval2 = maya.MayaInterval(base.add(days=start_doy2), base.add(days=end_doy2))
if intersection_doys:
start_doy_intersection, end_doy_intersection = intersection_doys
assert interval1 & interval2 == maya.MayaInterval(
base.add(days=start_doy_intersection),
base.add(days=end_doy_intersection),
base.add(days=start_doy_intersection), base.add(days=end_doy_intersection)
)
else:
assert (interval1 & interval2) is None
# check invalid argument
with pytest.raises(TypeError):
interval1 & 'invalid type'
interval1 & "invalid type"
def test_interval_intersects():
@@ -119,7 +114,7 @@ def test_interval_intersects():
)
# check invalid argument
with pytest.raises(TypeError):
interval.intersects('invalid type')
interval.intersects("invalid type")
def test_and_operator():
@@ -127,13 +122,13 @@ def test_and_operator():
interval1 = maya.MayaInterval(base, base.add(days=2))
interval2 = maya.MayaInterval(base.add(days=1), base.add(days=3))
assert (
interval1 & interval2 ==
interval2 & interval1 ==
interval1.intersection(interval2)
interval1 & interval2
== interval2 & interval1 # noqa
== interval1.intersection(interval2) # noqa
)
# check invalid argument
with pytest.raises(TypeError):
interval1.intersection('invalid type')
interval1.intersection("invalid type")
def test_interval_eq_operator():
@@ -144,9 +139,9 @@ def test_interval_eq_operator():
assert interval != maya.MayaInterval(start=start, end=end.add(days=1))
# check invalid argument
with pytest.raises(TypeError):
interval == 'invalid type'
interval == "invalid type"
with pytest.raises(TypeError):
interval != 'invalid type'
interval != "invalid type"
def test_interval_timedelta():
@@ -164,7 +159,7 @@ def test_interval_duration():
@pytest.mark.parametrize(
'start_doy1,end_doy1,start_doy2,end_doy2,expected',
"start_doy1,end_doy1,start_doy2,end_doy2,expected",
(
(0, 2, 1, 3, False),
(0, 2, 3, 4, False),
@@ -172,27 +167,21 @@ def test_interval_duration():
(0, 1, 0, 1, True),
(0, 3, 1, 2, True),
),
ids=('overlapping', 'non-overlapping', 'adjacent', 'equal', 'subset'),
ids=("overlapping", "non-overlapping", "adjacent", "equal", "subset"),
)
def test_interval_contains(
start_doy1, end_doy1, start_doy2, end_doy2, expected
):
def test_interval_contains(start_doy1, end_doy1, start_doy2, end_doy2, expected):
base = maya.MayaDT.from_datetime(datetime(2016, 1, 1))
interval1 = maya.MayaInterval(
base.add(days=start_doy1), base.add(days=end_doy1)
)
interval2 = maya.MayaInterval(
base.add(days=start_doy2), base.add(days=end_doy2)
)
interval1 = maya.MayaInterval(base.add(days=start_doy1), base.add(days=end_doy1))
interval2 = maya.MayaInterval(base.add(days=start_doy2), base.add(days=end_doy2))
assert interval1.contains(interval2) is expected
assert (interval2 in interval1) is expected
# check invalid argument
with pytest.raises(TypeError):
interval1.contains('invalid type')
interval1.contains("invalid type")
@pytest.mark.parametrize(
'start_doy,end_doy,dt_doy,expected',
"start_doy,end_doy,dt_doy,expected",
(
(2, 4, 1, False),
(2, 4, 2, True),
@@ -200,7 +189,7 @@ def test_interval_contains(
(2, 4, 4, False),
(2, 4, 5, False),
),
ids=('before-start', 'on-start', 'during', 'on-end', 'after-end'),
ids=("before-start", "on-start", "during", "on-end", "after-end"),
)
def test_interval_in_operator_maya_dt(start_doy, end_doy, dt_doy, expected):
base = maya.MayaDT.from_datetime(datetime(2016, 1, 1))
@@ -211,7 +200,7 @@ def test_interval_in_operator_maya_dt(start_doy, end_doy, dt_doy, expected):
assert (dt in interval) is expected
# check invalid argument
with pytest.raises(TypeError):
'invalid type' in interval
"invalid type" in interval
def test_interval_hash():
@@ -219,9 +208,7 @@ def test_interval_hash():
end = start.add(hours=1)
interval = maya.MayaInterval(start=start, end=end)
assert hash(interval) == hash(maya.MayaInterval(start=start, end=end))
assert hash(interval) != hash(
maya.MayaInterval(start=start, end=end.add(days=1))
)
assert hash(interval) != hash(maya.MayaInterval(start=start, end=end.add(days=1)))
def test_interval_iter():
@@ -231,47 +218,34 @@ def test_interval_iter():
@pytest.mark.parametrize(
'start1,end1,start2,end2,expected',
"start1,end1,start2,end2,expected",
[(1, 2, 1, 2, 0), (1, 3, 2, 4, -1), (2, 4, 1, 3, 1), (1, 2, 1, 3, -1)],
ids=(
'equal',
'less-than',
'greater-than',
'use-end-time-if-start-time-identical',
),
ids=("equal", "less-than", "greater-than", "use-end-time-if-start-time-identical"),
)
def test_interval_cmp(start1, end1, start2, end2, expected):
base = maya.now()
interval1 = maya.MayaInterval(
start=base.add(days=start1), end=base.add(days=end1)
)
interval2 = maya.MayaInterval(
start=base.add(days=start2), end=base.add(days=end2)
)
interval1 = maya.MayaInterval(start=base.add(days=start1), end=base.add(days=end1))
interval2 = maya.MayaInterval(start=base.add(days=start2), end=base.add(days=end2))
assert cmp(interval1, interval2) == expected
# check invalid argument
with pytest.raises(TypeError):
cmp(interval1, 'invalid type')
cmp(interval1, "invalid type")
@pytest.mark.parametrize(
'start1,end1,start2,end2,expected',
"start1,end1,start2,end2,expected",
[
(1, 2, 2, 3, [(1, 3)]),
(1, 3, 2, 4, [(1, 4)]),
(1, 2, 3, 4, [(1, 2), (3, 4)]),
(1, 5, 2, 3, [(1, 5)]),
],
ids=('adjacent', 'overlapping', 'non-overlapping', 'contains'),
ids=("adjacent", "overlapping", "non-overlapping", "contains"),
)
def test_interval_combine(start1, end1, start2, end2, expected):
base = maya.now()
interval1 = maya.MayaInterval(
start=base.add(days=start1), end=base.add(days=end1)
)
interval2 = maya.MayaInterval(
start=base.add(days=start2), end=base.add(days=end2)
)
interval1 = maya.MayaInterval(start=base.add(days=start1), end=base.add(days=end1))
interval2 = maya.MayaInterval(start=base.add(days=start2), end=base.add(days=end2))
expected_intervals = [
maya.MayaInterval(start=base.add(days=start), end=base.add(days=end))
for start, end in expected
@@ -280,11 +254,11 @@ def test_interval_combine(start1, end1, start2, end2, expected):
assert interval2.combine(interval1) == expected_intervals
# check invalid argument
with pytest.raises(TypeError):
interval2.combine('invalid type')
interval2.combine("invalid type")
@pytest.mark.parametrize(
'start1,end1,start2,end2,expected',
"start1,end1,start2,end2,expected",
[
(1, 2, 3, 4, [(1, 2)]),
(1, 2, 2, 4, [(1, 2)]),
@@ -296,24 +270,20 @@ def test_interval_combine(start1, end1, start2, end2, expected):
(1, 4, 3, 4, [(1, 3)]),
],
ids=(
'non-overlapping',
'adjacent',
'contains',
'splits',
'overlaps-left',
'overlaps-right',
'overlaps-left-identical-start',
'overlaps-right-identical-end',
"non-overlapping",
"adjacent",
"contains",
"splits",
"overlaps-left",
"overlaps-right",
"overlaps-left-identical-start",
"overlaps-right-identical-end",
),
)
def test_interval_subtract(start1, end1, start2, end2, expected):
base = maya.now()
interval1 = maya.MayaInterval(
start=base.add(days=start1), end=base.add(days=end1)
)
interval2 = maya.MayaInterval(
start=base.add(days=start2), end=base.add(days=end2)
)
interval1 = maya.MayaInterval(start=base.add(days=start1), end=base.add(days=end1))
interval2 = maya.MayaInterval(start=base.add(days=start2), end=base.add(days=end2))
expected_intervals = [
maya.MayaInterval(start=base.add(days=start), end=base.add(days=end))
for start, end in expected
@@ -321,35 +291,26 @@ def test_interval_subtract(start1, end1, start2, end2, expected):
assert interval1.subtract(interval2) == expected_intervals
# check invalid argument
with pytest.raises(TypeError):
interval1.subtract('invalid type')
interval1.subtract("invalid type")
@pytest.mark.parametrize(
'start1,end1,start2,end2,expected',
[
(1, 2, 2, 3, True),
(2, 3, 1, 2, True),
(1, 3, 2, 3, False),
(2, 3, 4, 5, False),
],
ids=('adjacent-right', 'adjacent-left', 'overlapping', 'non-overlapping'),
"start1,end1,start2,end2,expected",
[(1, 2, 2, 3, True), (2, 3, 1, 2, True), (1, 3, 2, 3, False), (2, 3, 4, 5, False)],
ids=("adjacent-right", "adjacent-left", "overlapping", "non-overlapping"),
)
def test_interval_is_adjacent(start1, end1, start2, end2, expected):
base = maya.now()
interval1 = maya.MayaInterval(
start=base.add(days=start1), end=base.add(days=end1)
)
interval2 = maya.MayaInterval(
start=base.add(days=start2), end=base.add(days=end2)
)
interval1 = maya.MayaInterval(start=base.add(days=start1), end=base.add(days=end1))
interval2 = maya.MayaInterval(start=base.add(days=start2), end=base.add(days=end2))
assert interval1.is_adjacent(interval2) == expected
# check invalid argument
with pytest.raises(TypeError):
interval1.is_adjacent('invalid type')
interval1.is_adjacent("invalid type")
@pytest.mark.parametrize(
'start,end,delta,include_remainder,expected',
"start,end,delta,include_remainder,expected",
[
(0, 10, 5, False, [(0, 5), (5, 10)]),
(0, 10, 5, True, [(0, 5), (5, 10)]),
@@ -359,19 +320,17 @@ def test_interval_is_adjacent(start1, end1, start2, end2, expected):
(0, 2, 5, True, [(0, 2)]),
],
ids=(
'even-split',
'even-split-include-partial',
'uneven-split-do-not-include-partial',
'uneven-split-include-partial',
'delta-larger-than-timepsan-do-not-include-partial',
'delta-larger-than-timepsan-include-partial',
"even-split",
"even-split-include-partial",
"uneven-split-do-not-include-partial",
"uneven-split-include-partial",
"delta-larger-than-timepsan-do-not-include-partial",
"delta-larger-than-timepsan-include-partial",
),
)
def test_interval_split(start, end, delta, include_remainder, expected):
base = maya.now()
interval = maya.MayaInterval(
start=base.add(days=start), end=base.add(days=end)
)
interval = maya.MayaInterval(start=base.add(days=start), end=base.add(days=end))
delta = timedelta(days=delta)
expected_intervals = [
maya.MayaInterval(start=base.add(days=s), end=base.add(days=e))
@@ -393,30 +352,30 @@ def test_interval_split_non_positive_delta():
@pytest.mark.parametrize(
'start,end,minutes,timezone,snap_out,expected_start,expected_end',
"start,end,minutes,timezone,snap_out,expected_start,expected_end",
[
((5, 12), (8, 48), 30, None, False, (5, 30), (8, 30)),
((5, 12), (8, 48), 30, None, True, (5, 0), (9, 0)),
((5, 15), (9, 0), 15, None, False, (5, 15), (9, 0)),
((5, 15), (9, 0), 15, None, True, (5, 15), (9, 0)),
((6, 50), (9, 15), 60, 'America/New_York', False, (7, 0), (9, 0)),
((6, 50), (9, 15), 60, 'America/New_York', True, (6, 0), (10, 0)),
((6, 50), (9, 15), 60, "America/New_York", False, (7, 0), (9, 0)),
((6, 50), (9, 15), 60, "America/New_York", True, (6, 0), (10, 0)),
((6, 20), (6, 50), 60, None, False, (6, 0), (6, 0)),
((6, 20), (6, 50), 60, None, True, (6, 0), (7, 0)),
((6, 20), (6, 50), 60, 'America/Chicago', False, (6, 0), (6, 0)),
((6, 20), (6, 50), 60, 'America/Chicago', True, (6, 0), (7, 0)),
((6, 20), (6, 50), 60, "America/Chicago", False, (6, 0), (6, 0)),
((6, 20), (6, 50), 60, "America/Chicago", True, (6, 0), (7, 0)),
],
ids=(
'normal',
'normal-snap_out',
'already-quantized',
'already-quantized-snap_out',
'with-timezone',
'with-timezone-snap_out',
'too-small',
'too-small-snap_out',
'too-small-with-timezone',
'too-small-with-timezone-snap_out',
"normal",
"normal-snap_out",
"already-quantized",
"already-quantized-snap_out",
"with-timezone",
"with-timezone-snap_out",
"too-small",
"too-small-snap_out",
"too-small-with-timezone",
"too-small-with-timezone-snap_out",
),
)
def test_quantize(
@@ -427,7 +386,7 @@ def test_quantize(
start=base.add(hours=start[0], minutes=start[1]),
end=base.add(hours=end[0], minutes=end[1]),
)
kwargs = {'timezone': timezone} if timezone is not None else {}
kwargs = {"timezone": timezone} if timezone is not None else {}
quantized_interval = interval.quantize(
timedelta(minutes=minutes), snap_out=snap_out, **kwargs
)
@@ -464,11 +423,9 @@ def test_interval_flatten_non_overlapping():
def test_interval_flatten_adjacent():
step = 2
max_hour = 20
base = maya.when('jan/1/2011')
base = maya.when("jan/1/2011")
intervals = [
maya.MayaInterval(
start=base.add(hours=hour), duration=timedelta(hours=step)
)
maya.MayaInterval(start=base.add(hours=hour), duration=timedelta(hours=step))
for hour in range(0, max_hour, step)
]
random.shuffle(intervals)
@@ -483,16 +440,13 @@ def test_interval_flatten_intersecting():
base = maya.now()
intervals = [
maya.MayaInterval(
start=base.add(hours=hour),
duration=timedelta(hours=step, minutes=30),
start=base.add(hours=hour), duration=timedelta(hours=step, minutes=30)
)
for hour in range(0, max_hour, step)
]
random.shuffle(intervals)
assert maya.MayaInterval.flatten(intervals) == [
maya.MayaInterval(
start=base, duration=timedelta(hours=max_hour, minutes=30)
)
maya.MayaInterval(start=base, duration=timedelta(hours=max_hour, minutes=30))
]
@@ -536,9 +490,9 @@ def test_interval_from_datetime():
def test_interval_iso8601():
start = maya.when('11-17-11 08:09:10')
start = maya.when("11-17-11 08:09:10")
interval = maya.MayaInterval(start=start, duration=1)
assert interval.iso8601() == '2011-11-17T08:09:10Z/2011-11-17T08:09:11Z'
assert interval.iso8601() == "2011-11-17T08:09:10Z/2011-11-17T08:09:11Z"
def test_interval_from_iso8601():
@@ -553,18 +507,14 @@ def test_interval_from_iso8601():
def test_interval_from_iso8601_duration():
interval = maya.MayaInterval.from_iso8601(
"2018-03-18T14:27:18Z/P13DT13H48M9S"
)
interval = maya.MayaInterval.from_iso8601("2018-03-18T14:27:18Z/P13DT13H48M9S")
s = maya.when("2018-03-18T14:27:18Z")
e = maya.when("2018-04-01T04:15:27Z")
assert interval.start == s
assert interval.end == e
interval = maya.MayaInterval.from_iso8601(
"2018-03-05T14:27:18Z/P2W"
)
interval = maya.MayaInterval.from_iso8601("2018-03-05T14:27:18Z/P2W")
s = maya.when("2018-03-05T14:27:18Z")
e = maya.when("2018-03-19T14:27:18Z")
@@ -576,26 +526,11 @@ def test_interval_from_iso8601_duration():
"start_string,end_string,interval,expected_count",
[
("2019-01-03 11:40:00Z", "2019-01-03 11:40:20Z", 2, 10),
(
"2019-01-03 11:40:00Z",
"2019-01-03 11:40:30Z",
timedelta(seconds=2),
15,
),
("2019-01-03 11:40:00Z", "2019-01-03 11:40:30Z", timedelta(seconds=2), 15),
("2019-01-03 11:40:00Z", "2019-01-03 11:45:00Z", 2 * 60, 3),
(
"2019-01-03 11:40:00Z",
"2019-01-03 11:51:00Z",
timedelta(minutes=1),
11,
),
("2019-01-03 11:40:00Z", "2019-01-03 11:51:00Z", timedelta(minutes=1), 11),
("2019-01-03 11:40:00Z", "2019-01-03 21:40:00Z", 3 * 60 * 60, 4),
(
"2019-01-03 11:40:00Z",
"2019-01-03 13:41:00Z",
timedelta(hours=1),
3,
),
("2019-01-03 11:40:00Z", "2019-01-03 13:41:00Z", timedelta(hours=1), 3),
("2019-01-03 11:40:00Z", "2019-01-09 11:40:00Z", 3 * 60 * 60 * 24, 2),
("2019-01-03 11:40:00Z", "2019-01-05 12:00:00Z", timedelta(days=2), 2),
],
@@ -623,7 +558,4 @@ def test_issue_168_regression():
# Since the bug causes the generator to never end, first sanity
# check that two results are not the same.
assert next(gen) != next(gen)
assert (
len(list(maya.intervals(start=start, end=end, interval=60 * 60 * 24)))
== 7
)
assert len(list(maya.intervals(start=start, end=end, interval=60 * 60 * 24))) == 7
+39 -10
View File
@@ -1,14 +1,43 @@
[tox]
envlist = py27, py34, py35, py36
envlist = lint,manifest,py27,py35,py36,py37,docs,coverage-report
[testenv]
deps = pipenv
commands=
pipenv install --dev --skip-lock
pytest tests/ {posargs}
# Prevent random setuptools/pip breakages like
# https://github.com/pypa/setuptools/issues/1042 from breaking our builds.
setenv =
VIRTUALENV_NO_DOWNLOAD=1
extras = {env:TOX_AP_TEST_EXTRAS:tests}
commands = coverage run --parallel -m pytest {posargs}
[testenv:py27]
basepython = python2.7
deps =
{[testenv]deps}
funcsigs
[testenv:coverage-report]
basepython = python3.7
skip_install = true
deps = coverage
commands =
coverage combine
coverage report
[testenv:lint]
basepython = python3.7
skip_install = true
deps = pre-commit
passenv = HOMEPATH # needed on Windows
commands = pre-commit run --all-files
[testenv:docs]
basepython = python3.7
extras = docs
commands =
sphinx-build -W -b html -d {envtmpdir}/doctrees docs/source docs/_build/html
;sphinx-build -W -b doctest -d {envtmpdir}/doctrees docs/source docs/_build/html
[testenv:manifest]
basepython = python3.7
deps = check-manifest
skip_install = true
commands = check-manifest