class GetUtcTimestamp(TestCase):
    def test_time_is_not_supplied___timestamp_of_utcnow_is_returned(self):
        _now = datetime.utcnow()

        with freeze_time(_now):
            res = get_utctimestamp()

            self.assertEqual(_now.strftime('%Y-%b-%d %H:%M:%S'), res)

    @given(datetimes(timezones=timezones(), min_value=datetime(1990, 1, 1)))
    def test_time_is_supplied___timestamp_of_supplied_time_is_returned(
            self, dt):
        res = get_utctimestamp(dt)

        self.assertEqual(
            dt.astimezone(pytz.utc).strftime('%Y-%b-%d %H:%M:%S'), res)

    @given(datetimes(timezones=timezones(), min_value=datetime(1990, 1, 1)))
    def test_fmt_is_supplied___timestamp_of_supplied_time_is_returned(
            self, dt):
        fmt = 'foo %Y-%m-%d %H:%M:%S bar'

        res = get_utctimestamp(dt, fmt=fmt)

        self.assertEqual(dt.astimezone(pytz.utc).strftime(fmt), res)
Example #2
0
def item_dict(draw):
    return dict(
        uuid=str(draw(uuids())),
        content=draw(one_of(none(), text(), from_regex(VALID_STRING_REGEX))),
        content_type=draw(text()),
        enc_item_key=draw(
            one_of(none(), text(), from_regex(VALID_STRING_REGEX))),
        deleted=draw(booleans()),
        created_at=draw(datetimes(timezones=timezones())).isoformat(),
        updated_at=draw(datetimes(timezones=timezones())).isoformat(),
        auth_hash=draw(one_of(none(), text())),
    )
def primitives():
    return (
        st.integers() |
        st.floats(allow_nan=False) |
        st.text() |
        st.binary() |
        st.datetimes(timezones=timezones() | st.none()) |
        st.dates() |
        st.times(timezones=timezones() | st.none()) |
        st.timedeltas() |
        st.booleans() |
        st.none()
    )
Example #4
0
def test_overflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(
        datetimes(min_value=dt.datetime.max - dt.timedelta(days=3),
                  timezones=timezones()),
        lambda x: x.tzinfo != pytz.UTC,
    )
def test_can_trigger_error_in_draw_near_max_date():
    assert_can_trigger_event(
        datetimes(
            min_value=dt.datetime.max - dt.timedelta(days=3), timezones=timezones()
        ),
        lambda event: "Failed to draw a datetime" in event,
    )
Example #6
0
class TestDateSerialization(TestCase):
    @given(
        st.one_of(st.datetimes(timezones=st.none() | timezones()), st.none()))
    @example(datetime(16, 1, 1, 0, 0, 16))
    def test_round_trip(self, date):
        serialized = serialize(date)
        parsed = deserialize(serialized)
        self.assertEqual(date, parsed)
def test_overflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(
        datetimes(
            min_value=dt.datetime.max - dt.timedelta(days=3), timezones=timezones()
        ),
        lambda x: x.tzinfo != pytz.UTC,
    )
Example #8
0
def timezones():
    # From Django 4.0, the default is to use zoneinfo instead of pytz.
    assert getattr(django.conf.settings, "USE_TZ", False)
    if getattr(django.conf.settings, "USE_DEPRECATED_PYTZ", True):
        from hypothesis.extra.pytz import timezones
    else:
        from hypothesis.strategies import timezones

    return timezones()
Example #9
0
def pg_tstz() -> strategies.SearchStrategy:
    """Generate values that fit in a PostgreSQL timestamptz.

    Notes:
      We're forbidding old datetimes, because until 1956, many timezones had
      seconds in their "UTC offsets" (see
      <https://en.wikipedia.org/wiki/Time_zone Worldwide_time_zones>), which is
      not representable by PostgreSQL.

    """
    min_value = datetime.datetime(1960, 1, 1, 0, 0, 0)
    return strategies.datetimes(min_value=min_value, timezones=timezones())
def test_can_generate_non_utc():
    times(timezones=timezones()).filter(
        lambda d: assume(d.tzinfo) and d.tzinfo.zone != u'UTC'
    ).validate()
Example #11
0
def _for_form_time(field):
    if getattr(django.conf.settings, "USE_TZ", False):
        return st.times(timezones=timezones())
    return st.times()
Example #12
0
def test_can_generate_non_utc():
    times(timezones=timezones()).filter(
        lambda d: assume(d.tzinfo) and d.tzinfo.zone != "UTC").validate()
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())


def test_can_generate_non_naive_time():
    assert minimal(times(timezones=timezones()), lambda d: d.tzinfo).tzinfo == pytz.UTC


def test_can_generate_non_naive_datetime():
    assert (
        minimal(datetimes(timezones=timezones()), lambda d: d.tzinfo).tzinfo == pytz.UTC
    )


@given(datetimes(timezones=timezones()))
def test_timezone_aware_datetimes_are_timezone_aware(dt):
    assert dt.tzinfo is not None


@given(sampled_from(["min_value", "max_value"]), datetimes(timezones=timezones()))
def test_datetime_bounds_must_be_naive(name, val):
    with pytest.raises(InvalidArgument):
        datetimes(**{name: val}).validate()


def test_underflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(
        datetimes(
            max_value=dt.datetime.min + dt.timedelta(days=3), timezones=timezones()
Example #14
0
def single_type_lists(draw, types=s.integers()):
    """Create lists drawn from only one of the types generated by the argument
    strategy.

    """
    v = draw(types)
    if isinstance(v, list) and len(v) > 0:
        es = s.lists(s.from_type(type(v[0])))
    else:
        es = s.from_type(type(v))
    vl = draw(s.lists(es))
    return vl

toml_vals = s.recursive(
    s.text() | s.integers() | s.floats() | s.booleans() |
    s.datetimes(timezones=s.none() | timezones()) |
    s.dates() | s.times(),
    lambda leaves: (single_type_lists(leaves) |
                    s.dictionaries(s.text(), leaves)))

# Top-level TOML element must be a dict
toml_data = s.dictionaries(s.text(), toml_vals)

@given(toml_data)
def test_circular_encode(data):
    assert patch_floats(qtoml.loads(qtoml.dumps(data))) == patch_floats(data)

@given(s.text())
def test_string_encode(data):
    obj = {'key': data}
    assert qtoml.loads(qtoml.dumps(obj)) == obj
Example #15
0
    type(Ellipsis): st.just(Ellipsis),
    type(NotImplemented): st.just(NotImplemented),
    bytearray: st.binary().map(bytearray),
    memoryview: st.binary().map(memoryview),
    # Pull requests with more types welcome!
}

if PY2:
    _global_type_lookup.update({
        int: st.integers().filter(lambda x: isinstance(x, int)),
        long: st.integers().map(long)  # noqa
    })

try:
    from hypothesis.extra.pytz import timezones
    _global_type_lookup[datetime.tzinfo] = timezones()
except ImportError:  # pragma: no cover
    pass
try:  # pragma: no cover
    import numpy as np
    from hypothesis.extra.numpy import \
        arrays, array_shapes, scalar_dtypes, nested_dtypes
    _global_type_lookup.update({
        np.dtype: nested_dtypes(),
        np.ndarray: arrays(scalar_dtypes(), array_shapes(max_dims=2)),
    })
except ImportError:  # pragma: no cover
    pass

try:
    import typing
Example #16
0
                            precision=st.integers(min_value=1, max_value=38),
                            scale=st.integers(min_value=1, max_value=38))
decimal256_type = st.builds(pa.decimal256,
                            precision=st.integers(min_value=1, max_value=76),
                            scale=st.integers(min_value=1, max_value=76))
numeric_types = st.one_of(integer_types, floating_types, decimal128_type,
                          decimal256_type)

date_types = st.sampled_from([pa.date32(), pa.date64()])
time_types = st.sampled_from(
    [pa.time32('s'),
     pa.time32('ms'),
     pa.time64('us'),
     pa.time64('ns')])
if tzst and zoneinfo:
    timezones = st.one_of(st.none(), tzst.timezones(), st.timezones())
elif tzst:
    timezones = st.one_of(st.none(), tzst.timezones())
elif zoneinfo:
    timezones = st.one_of(st.none(), st.timezones())
else:
    timezones = st.none()
timestamp_types = st.builds(pa.timestamp,
                            unit=st.sampled_from(['s', 'ms', 'us', 'ns']),
                            tz=timezones)
duration_types = st.builds(pa.duration,
                           st.sampled_from(['s', 'ms', 'us', 'ns']))
interval_types = st.just(pa.month_day_nano_interval())
temporal_types = st.one_of(date_types, time_types, timestamp_types,
                           duration_types, interval_types)
Example #17
0
import ddt
import six
from hypothesis import strategies as st
from hypothesis import given
from hypothesis.extra.pytz import timezones
from mock import patch

from edx_ace.message import Message, MessageType
from edx_ace.recipient import Recipient
from edx_ace.utils.date import get_current_time

LOG = logging.getLogger(__name__)

context_values = st.one_of(st.text(), st.booleans(),
                           st.floats(allow_nan=False))
dates = st.datetimes(timezones=st.none() | timezones() | st.none())

msg = st.builds(
    Message,
    app_label=st.text(),
    name=st.text(),
    expiration_time=dates,
    context=st.dictionaries(
        st.text(),
        context_values,
    ),
    recipient=st.builds(
        Recipient,
        username=st.text(),
    ),
    send_uuid=st.one_of(st.uuids(), st.none()),
Example #18
0
def get_tz_strat():
    # type: () -> st.SearchStrategy[Optional[tzinfo]]
    if getattr(django_settings, 'USE_TZ', False):
        return timezones()
    return st.none()
Example #19
0
def get_datetime_strat():
    if getattr(django_settings, 'USE_TZ', False):
        return st.datetimes(timezones=timezones())
    return st.datetimes()
Example #20
0
def test_can_generate_non_utc():
    times(timezones=timezones()).filter(
        lambda d: assume(d.tzinfo) and d.tzinfo.zone != u'UTC').example()
Example #21
0
from __future__ import division, print_function, absolute_import

import datetime as dt

import pytz
import pytest

from hypothesis import given, assume
from hypothesis.errors import InvalidArgument
from tests.common.debug import minimal
from hypothesis.extra.pytz import timezones
from hypothesis.strategies import times, datetimes, sampled_from
from hypothesis.strategytests import strategy_test_suite

TestStandardDescriptorFeatures1 = strategy_test_suite(timezones())
TestStandardDescriptorFeatures_datetimes2 = strategy_test_suite(
    datetimes(timezones=timezones()))


def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())


def test_can_generate_non_naive_time():
    assert minimal(times(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


def test_can_generate_non_naive_datetime():
    assert minimal(datetimes(timezones=timezones()),
def _for_datetime(field):
    if getattr(django.conf.settings, "USE_TZ", False):
        return st.datetimes(timezones=timezones())
    return st.datetimes()
Example #23
0
def get_tz_strat():
    # type: () -> st.SearchStrategy[Optional[tzinfo]]
    if getattr(django_settings, 'USE_TZ', False):
        return timezones()
    return st.none()
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())


def test_can_generate_non_naive_time():
    assert minimal(times(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


def test_can_generate_non_naive_datetime():
    assert minimal(datetimes(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


@given(datetimes(timezones=timezones()))
def test_timezone_aware_datetimes_are_timezone_aware(dt):
    assert dt.tzinfo is not None


@given(sampled_from(['min_value', 'max_value']),
       datetimes(timezones=timezones()))
def test_datetime_bounds_must_be_naive(name, val):
    with pytest.raises(InvalidArgument):
        datetimes(**{name: val}).validate()


def test_underflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(
        datetimes(max_value=dt.datetime.min + dt.timedelta(days=3),
Example #25
0
def test_tzinfo_to_string_errors():
    msg = "Not an instance of datetime.tzinfo"
    with pytest.raises(TypeError):
        pa.lib.tzinfo_to_string("Europe/Budapest")

    if sys.version_info >= (3, 8):
        # before 3.8 it was only possible to create timezone objects with whole
        # number of minutes
        tz = datetime.timezone(datetime.timedelta(hours=1, seconds=30))
        msg = "Offset must represent whole number of minutes"
        with pytest.raises(ValueError, match=msg):
            pa.lib.tzinfo_to_string(tz)


if tzst:
    timezones = tzst.timezones()
else:
    timezones = st.none()


@h.given(timezones)
def test_pytz_timezone_roundtrip(tz):
    if tz is None:
        pytest.skip('requires timezone not None')
    timezone_string = pa.lib.tzinfo_to_string(tz)
    timezone_tzinfo = pa.lib.string_to_tzinfo(timezone_string)
    assert timezone_tzinfo == tz


def test_convert_custom_tzinfo_objects_to_string():
    class CorrectTimezone1(datetime.tzinfo):
Example #26
0
numeric_types = st.one_of(integer_types, floating_types, decimal_type)

date_types = st.sampled_from([
    pa.date32(),
    pa.date64()
])
time_types = st.sampled_from([
    pa.time32('s'),
    pa.time32('ms'),
    pa.time64('us'),
    pa.time64('ns')
])
timestamp_types = st.builds(
    pa.timestamp,
    unit=st.sampled_from(['s', 'ms', 'us', 'ns']),
    tz=tzst.timezones()
)
temporal_types = st.one_of(date_types, time_types, timestamp_types)

primitive_types = st.one_of(
    null_type,
    bool_type,
    binary_type,
    string_type,
    numeric_types,
    temporal_types
)

metadata = st.dictionaries(st.text(), st.text())

Example #27
0
def test_datetimes_stay_within_naive_bounds(data, lo, hi):
    if lo > hi:
        lo, hi = hi, lo
    out = data.draw(datetimes(lo, hi, timezones=timezones()))
    assert lo <= out.replace(tzinfo=None) <= hi
def get_tz_strat():
    if getattr(django_settings, 'USE_TZ', False):
        return timezones()
    return st.none()
Example #29
0
def test_can_generate_non_naive_datetime():
    assert (minimal(datetimes(timezones=timezones()),
                    lambda d: d.tzinfo).tzinfo == pytz.UTC)
Example #30
0
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())


def test_can_generate_non_naive_time():
    assert minimal(times(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


def test_can_generate_non_naive_datetime():
    assert (minimal(datetimes(timezones=timezones()),
                    lambda d: d.tzinfo).tzinfo == pytz.UTC)


@given(datetimes(timezones=timezones()))
def test_timezone_aware_datetimes_are_timezone_aware(dt):
    assert dt.tzinfo is not None


@given(sampled_from(["min_value", "max_value"]),
       datetimes(timezones=timezones()))
def test_datetime_bounds_must_be_naive(name, val):
    with pytest.raises(InvalidArgument):
        datetimes(**{name: val}).validate()


def test_underflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(
        datetimes(max_value=dt.datetime.min + dt.timedelta(days=3),
Example #31
0
def get_datetime_strat():
    if getattr(django_settings, 'USE_TZ', False):
        return st.datetimes(timezones=timezones())
    return st.datetimes()
Example #32
0
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())
Example #33
0
from math import inf, nan

import pandas as pd

import pytest
from hypothesis import given
from hypothesis.extra.pytz import timezones
from hypothesis.strategies import datetimes, floats

from pysoleng.solar_geom import convert_to_solar_time

# Create time zone-aware datetimes for use in testing
aware_datetimes = datetimes(
    min_value=pd.Timestamp.min + pd.DateOffset(2),
    max_value=pd.Timestamp.max - pd.DateOffset(2),
    timezones=timezones(),
)


@pytest.mark.solar_geom
@given(
    aware_datetimes,
    floats(min_value=0, max_value=360, allow_nan=False, allow_infinity=False),
)
def test_convert_to_solar_time(dt, longitude):
    """Functional test to ensure the convert_to_solar_time() method
    runs properly given valid arguments."""
    assert isinstance(
        convert_to_solar_time(
            local_standard_time=dt, longitude_degrees=longitude
        ),
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())
Example #35
0
def test_tzinfo_to_string_errors():
    msg = "Not an instance of datetime.tzinfo"
    with pytest.raises(TypeError):
        pa.lib.tzinfo_to_string("Europe/Budapest")

    if sys.version_info >= (3, 8):
        # before 3.8 it was only possible to create timezone objects with whole
        # number of minutes
        tz = datetime.timezone(datetime.timedelta(hours=1, seconds=30))
        msg = "Offset must represent whole number of minutes"
        with pytest.raises(ValueError, match=msg):
            pa.lib.tzinfo_to_string(tz)


@h.given(tzst.timezones())
def test_pytz_timezone_roundtrip(tz):
    timezone_string = pa.lib.tzinfo_to_string(tz)
    timezone_tzinfo = pa.lib.string_to_tzinfo(timezone_string)
    assert timezone_tzinfo == tz


def test_convert_custom_tzinfo_objects_to_string():
    class CorrectTimezone1(datetime.tzinfo):
        """
        Conversion is using utcoffset()
        """
        def tzname(self, dt):
            return None

        def utcoffset(self, dt):
Example #36
0
def _for_model_time(field):
    # SQLITE supports TZ-aware datetimes, but not TZ-aware times.
    if getattr(django.conf.settings, "USE_TZ", False) and not using_sqlite():
        return st.times(timezones=timezones())
    return st.times()
Example #37
0
floating_types = st.sampled_from([pa.float16(), pa.float32(), pa.float64()])
decimal_type = st.builds(pa.decimal128,
                         precision=st.integers(min_value=0, max_value=38),
                         scale=st.integers(min_value=0, max_value=38))
numeric_types = st.one_of(integer_types, floating_types, decimal_type)

date_types = st.sampled_from([pa.date32(), pa.date64()])
time_types = st.sampled_from(
    [pa.time32('s'),
     pa.time32('ms'),
     pa.time64('us'),
     pa.time64('ns')])
timestamp_types = st.builds(pa.timestamp,
                            unit=st.sampled_from(['s', 'ms', 'us', 'ns']),
                            tz=tzst.timezones())
temporal_types = st.one_of(date_types, time_types, timestamp_types)

primitive_types = st.one_of(null_type, bool_type, binary_type, string_type,
                            numeric_types, temporal_types)

metadata = st.dictionaries(st.text(), st.text())


def fields(type_strategy=primitive_types):
    return st.builds(pa.field,
                     name=custom_text,
                     type=type_strategy,
                     nullable=st.booleans(),
                     metadata=metadata)
def test_utc_is_minimal():
    assert pytz.UTC is minimal(timezones())


def test_can_generate_non_naive_time():
    assert minimal(times(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


def test_can_generate_non_naive_datetime():
    assert minimal(datetimes(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC


@given(datetimes(timezones=timezones()))
def test_timezone_aware_datetimes_are_timezone_aware(dt):
    assert dt.tzinfo is not None


@given(sampled_from(['min_value', 'max_value']),
       datetimes(timezones=timezones()))
def test_datetime_bounds_must_be_naive(name, val):
    with pytest.raises(InvalidArgument):
        datetimes(**{name: val}).validate()


def test_underflow_in_simplify():
    # we shouldn't trigger a pytz bug when we're simplifying
    minimal(datetimes(max_value=dt.datetime.min + dt.timedelta(days=3),
                      timezones=timezones()),
def test_can_generate_non_naive_datetime():
    assert minimal(datetimes(timezones=timezones()),
                   lambda d: d.tzinfo).tzinfo == pytz.UTC
def test_can_trigger_error_in_draw_near_boundary(bound):
    assert_can_trigger_event(
        datetimes(**bound, timezones=timezones()),
        lambda event: "Failed to draw a datetime" in event,
    )
def _for_model_time(field):
    # SQLITE supports TZ-aware datetimes, but not TZ-aware times.
    if getattr(django.conf.settings, "USE_TZ", False) and not using_sqlite():
        return st.times(timezones=timezones())
    return st.times()
Example #42
0
    _global_type_lookup.update(
        {
            range: st.integers(min_value=0).map(range)
            | st.builds(range, st.integers(), st.integers())
            | st.builds(range, st.integers(), st.integers(), st.integers().filter(bool))
        }
    )

_global_type_lookup[type] = st.sampled_from(
    [type(None)] + sorted(_global_type_lookup, key=str)
)

try:
    from hypothesis.extra.pytz import timezones

    _global_type_lookup[datetime.tzinfo] = timezones()
except ImportError:  # pragma: no cover
    pass
try:  # pragma: no cover
    import numpy as np
    from hypothesis.extra.numpy import (
        arrays,
        array_shapes,
        scalar_dtypes,
        nested_dtypes,
    )

    _global_type_lookup.update(
        {
            np.dtype: nested_dtypes(),
            np.ndarray: arrays(scalar_dtypes(), array_shapes(max_dims=2)),
Example #43
0
def get_tz_strat():
    if getattr(django_settings, 'USE_TZ', False):
        return timezones()
    return st.none()