Exemple #1
0
def indices(draw, max_length=5):
    date = draw(
        dates(
            min_value=Timestamp.min.ceil("D").to_pydatetime().date(),
            max_value=Timestamp.max.floor("D").to_pydatetime().date(),
        ).map(Timestamp)
    )
    periods = draw(integers(0, max_length))
    freq = draw(sampled_from(list("BDHTS")))
    dr = date_range(date, periods=periods, freq=freq)
    return pd.DatetimeIndex(list(dr))
def dates(min_year=None, max_year=None):
    """Return a strategy for generating dates.

    .. deprecated:: 3.9.0
        use :py:func:`hypothesis.strategies.dates` instead.

    All generated dates will be between min_year and max_year, inclusive.
    """
    note_deprecation('Use hypothesis.strategies.dates, which supports bounds '
                     'given as date objects for single-day resolution.')
    return st.dates(convert_year_bound(min_year, dt.date.min),
                    convert_year_bound(max_year, dt.date.max))
 def test_generated_excel_should_equal_input(self, data):
     """
     Check the property that the generated excel file should be readable
     by openpyxl and the data read from that file should be the same as the
     input data.
     """
     st_cells = st.one_of(
         st.none(),
         st.integers(),
         st.text(st.characters(blacklist_categories=['Cs', 'Cc']),
                 min_size=1),
         st.dates(),
         st.booleans(),
     )
     expected, actual = self._test_generated_excel_should_equal_input(
         data.draw, st_cells)
     self.assertEqual(expected, actual)
Exemple #4
0
def _generate_dumpable(draw):
    output = draw(
        st.recursive(
            name()
            | st.integers()
            | st.datetimes()
            | st.dates()
            | st.sampled_from(draw(generate_enum()))
            | st.none()
            | st.booleans(),
            lambda children: st.lists(children)
            | st.dictionaries(keys=name(), values=children),
            max_leaves=5,
        )
    )

    return output
Exemple #5
0
class PrettifyTestCase(TestCase):
    def setUp(self):
        self.now = datetime(2016, 10, 15)
        self.parser = Parser(self.now)

    @given(dates(min_value=MIN_DATE))
    def test_prettify_date(self, d):
        s = prettify_date(d.year, d.month, d.day)
        res = self.parser.extract_date(s)
        self.assertEqual(res.year, d.year)
        self.assertEqual(res.month, d.month)
        self.assertEqual(res.day, d.day)

        s = prettify_date(d.year, d.month)
        year, month = self.parser.extract_month(s)
        self.assertEqual(year, d.year)
        self.assertEqual(month, d.month)

    @given(datetimes(min_value=MIN_DATETIME))
    def test_prettify_datetime(self, dt):
        s = prettify_datetime(dt)
        parts = s.rsplit(maxsplit=1)

        res = self.parser.extract_date(parts[0])
        self.assertEqual(res.year, dt.year)
        self.assertEqual(res.month, dt.month)
        self.assertEqual(res.day, dt.day)

        hour, minute = map(int, parts[1].split(':'))
        self.assertEqual(hour, dt.hour)
        self.assertEqual(minute, dt.minute)

    def test_prettify_delta(self):
        self.assertEqual(prettify_delta(timedelta(hours=1)), '1 hour')
        self.assertEqual(prettify_delta(timedelta(hours=2)), '2 hours')

        self.assertEqual(prettify_delta(timedelta(minutes=1)), '1 minute')
        self.assertEqual(prettify_delta(timedelta(minutes=2)), '2 minutes')

        self.assertEqual(prettify_delta(timedelta(seconds=1)), '1 second')
        self.assertEqual(prettify_delta(timedelta(seconds=2)), '2 seconds')

        self.assertEqual(prettify_delta(timedelta(seconds=3600 + 60 + 1)),
                         '1 hour, 1 minute, 1 second')
def options(
    underlying: SearchStrategy[str] = text(min_size=1),
    currency: SearchStrategy[Currency] = from_type(Currency),
    optionType: SearchStrategy[OptionType] = from_type(OptionType),
    expiration: SearchStrategy[date] = dates(min_value=date(1900, 1, 1)),
    strike: SearchStrategy[Decimal] = strikes(),
    multiplier: SearchStrategy[Decimal] = multipliers(),
    exchange: SearchStrategy[Optional[str]] = optionals(exchanges()),
) -> SearchStrategy[Option]:
    return builds(
        Option,
        underlying=underlying,
        currency=currency,
        optionType=optionType,
        expiration=expiration,
        strike=strike,
        multiplier=multiplier,
        exchange=exchange,
    )
Exemple #7
0
class TestIsoParsing:
    @given(test_date=st.dates())
    def test_str_convert(self, test_date):
        assert _utils.iso_str_to_datetime(str(test_date)) == test_date

    @given(random_data=st.tuples(
        st.integers(max_value=9999),
        st.integers(max_value=99),
        st.integers(max_value=99),
    ))
    @example(random_data=(0, 0, 0))
    def test_raw_str_convert(self, random_data):
        assume(all((not x < 0 for x in random_data)))
        assert (_utils.parse_isoformat_date(
            f"{random_data[0]:04}-{random_data[1]:02}-{random_data[2]:02}") ==
                random_data)

    @given(invalid_string=st.text())
    def test_raises(self, invalid_string):
        assume(not re.match(r"\d{4}-\d{4}-\d{4}", invalid_string))
        with pytest.raises(ValueError):
            _utils.parse_isoformat_date(invalid_string)
Exemple #8
0
def rfc3339(name: str) -> st.SearchStrategy[str]:
    """Get a strategy for date or time strings in the given RFC3339 format.

    See https://tools.ietf.org/html/rfc3339#section-5.6
    """
    # Hmm, https://github.com/HypothesisWorks/hypothesis/issues/170
    # would make this a lot easier...
    assert name in RFC3339_FORMATS

    def zfill(width: int) -> Callable[[int], str]:
        return lambda v: str(v).zfill(width)

    simple = {
        "date-fullyear": st.integers(0, 9999).map(zfill(4)),
        "date-month": st.integers(1, 12).map(zfill(2)),
        "date-mday": st.integers(1, 28).map(zfill(2)),  # incomplete but valid
        "time-hour": st.integers(0, 23).map(zfill(2)),
        "time-minute": st.integers(0, 59).map(zfill(2)),
        "time-second":
        st.integers(0, 59).map(zfill(2)),  # ignore negative leap seconds
        "time-secfrac": st.from_regex(r"\.[0-9]+"),
    }
    if name in simple:
        return simple[name]
    if name == "time-numoffset":
        return st.tuples(st.sampled_from(["+", "-"]), rfc3339("time-hour"),
                         rfc3339("time-minute")).map("%s%s:%s".__mod__)
    if name == "time-offset":
        return st.one_of(st.just("Z"), rfc3339("time-numoffset"))
    if name == "partial-time":
        return st.times().map(str)
    if name == "full-date":
        return st.dates().map(str)
    if name == "full-time":
        return st.tuples(rfc3339("partial-time"),
                         rfc3339("time-offset")).map("".join)
    assert name == "date-time"
    return st.tuples(rfc3339("full-date"), rfc3339("full-time")).map("T".join)
Exemple #9
0
class TestCache(unittest.TestCase):
    def setUp(self) -> None:
        cache.client = fakeredis.FakeStrictRedis()
        assert not cache.client.keys("*")

    @given(symbol=st.text(),
           date=st.datetimes(),
           price=st.floats(allow_infinity=False, allow_nan=False))
    def test_add_record(self, symbol: str, date: datetime.date, price: float):
        cache.add_record(symbol, date, price)
        self.assertEqual(cache.get_price(symbol, date), price)

        price += 1
        cache.add_record(symbol, date, price)
        self.assertEqual(cache.get_price(symbol, date), price)

    @given(
        symbol=st.text(min_size=1),
        records=st.lists(st.tuples(
            st.dates(), st.floats(allow_infinity=False, allow_nan=False)),
                         unique=True),
    )
    def test_add_many_records(self, symbol: str,
                              records: Iterable[Tuple[datetime.date, float]]):
        # remove date-duplicates:
        seen: Set[datetime.date] = set()
        tmp_records: List[Tuple[datetime.date, float]] = []
        for tup in records:
            if tup[0] not in seen:
                seen.add(tup[0])
                tmp_records.append(tup)
        records = tmp_records

        cache.client.delete(symbol)
        cache.add_records(symbol, records)

        records.sort(key=lambda x: x[0])
        self.assertEqual(cache.get_prices(symbol), [p for _, p in records])
Exemple #10
0
class TestCompileGeneral(TestCase):
    @given(literals
           | st.dates()
           | st.datetimes()
           | st.decimals(allow_nan=False)
           | st.fractions()
           | st.timedeltas()
           | st.times()
           | st.uuids())
    def test_compile_pickle(self, form):
        self.assertEqual(form, eval(compiler.Compiler().pickle(form)))

    @given(literals)
    def test_compile_literal(self, form):
        self.assertEqual(form, eval(compiler.Compiler().quoted(form)))

    @given(st.characters(whitelist_categories=["Lu", "Ll", "Lt", "Nl",
                                               "Sm"], ))
    def test_un_x_quote(self, char):
        x = munger.x_quote(char)
        self.assertTrue(("x" + x).isidentifier())
        match = re.fullmatch("x(.*?)_", x)
        if match:
            self.assertEqual(char, munger.un_x_quote(match))
    def format_strategies(self, schema):
        """

        :param schema:

        :return:
        """
        min_max_size = dict(min_size=schema.min_length or 0,
                            max_size=schema.max_length)
        return {
            **self._format_strategies,
            "uuid": st.uuids().map(str),
            "uri": st_uris(),
            "uriref": st_uris(),
            "hostname": st_hostnames(),
            "date": st.dates().map(str),
            "date-time": st.datetimes().map(datetime.isoformat),
            "binary": st.binary(**min_max_size),
            "byte": st.binary(**min_max_size).map(base64.encodebytes),
            "int32": self.numbers(st_base=st.integers, schema=schema),
            "int64": self.numbers(st_base=st.integers, schema=schema),
            "float": self.numbers(st_base=st.floats, schema=schema),
            "double": self.numbers(st_base=st.floats, schema=schema),
        }
Exemple #12
0
def field_mappings():
    global __default_field_mappings

    if __default_field_mappings is None:
        # Sized fields are handled in _get_strategy_for_field()
        # URL fields are not yet handled
        __default_field_mappings = {
            dm.SmallIntegerField: st.integers(-32768, 32767),
            dm.IntegerField: st.integers(-2147483648, 2147483647),
            dm.BigIntegerField:
                st.integers(-9223372036854775808, 9223372036854775807),
            dm.PositiveIntegerField: st.integers(0, 2147483647),
            dm.PositiveSmallIntegerField: st.integers(0, 32767),
            dm.BinaryField: st.binary(),
            dm.BooleanField: st.booleans(),
            dm.DateField: st.dates(),
            dm.DateTimeField: st.datetimes(timezones=get_tz_strat()),
            dm.DurationField: st.timedeltas(),
            dm.EmailField: emails(),
            dm.FloatField: st.floats(),
            dm.NullBooleanField: st.one_of(st.none(), st.booleans()),
            dm.TimeField: st.times(timezones=get_tz_strat()),
            dm.UUIDField: st.uuids(),
        }

        # SQLite does not support timezone-aware times, or timedeltas that
        # don't fit in six bytes of microseconds, so we override those
        db = getattr(django_settings, 'DATABASES', {}).get('default', {})
        if db.get('ENGINE', '').endswith('.sqlite3'):  # pragma: no branch
            sqlite_delta = timedelta(microseconds=2 ** 47 - 1)
            __default_field_mappings.update({
                dm.TimeField: st.times(),
                dm.DurationField: st.timedeltas(-sqlite_delta, sqlite_delta),
            })

    return __default_field_mappings
Exemple #13
0
def field_mappings():
    global __default_field_mappings

    if __default_field_mappings is None:
        # Sized fields are handled in _get_strategy_for_field()
        # URL fields are not yet handled
        __default_field_mappings = {
            dm.SmallIntegerField: st.integers(-32768, 32767),
            dm.IntegerField: st.integers(-2147483648, 2147483647),
            dm.BigIntegerField:
                st.integers(-9223372036854775808, 9223372036854775807),
            dm.PositiveIntegerField: st.integers(0, 2147483647),
            dm.PositiveSmallIntegerField: st.integers(0, 32767),
            dm.BinaryField: st.binary(),
            dm.BooleanField: st.booleans(),
            dm.DateField: st.dates(),
            dm.DateTimeField: st.datetimes(timezones=get_tz_strat()),
            dm.DurationField: st.timedeltas(),
            dm.EmailField: emails(),
            dm.FloatField: st.floats(),
            dm.NullBooleanField: st.one_of(st.none(), st.booleans()),
            dm.TimeField: st.times(timezones=get_tz_strat()),
            dm.UUIDField: st.uuids(),
        }

        # SQLite does not support timezone-aware times, or timedeltas that
        # don't fit in six bytes of microseconds, so we override those
        db = getattr(django_settings, 'DATABASES', {}).get('default', {})
        if db.get('ENGINE', '').endswith('.sqlite3'):  # pragma: no branch
            sqlite_delta = timedelta(microseconds=2 ** 47 - 1)
            __default_field_mappings.update({
                dm.TimeField: st.times(),
                dm.DurationField: st.timedeltas(-sqlite_delta, sqlite_delta),
            })

    return __default_field_mappings
Exemple #14
0
class DateRangeTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        with connection.schema_editor(atomic=True) as schema_editor:
            schema_editor.create_model(statusDateRangeTest)

    @given(title=postgres_text,
           published_from=dates(max_value=today),
           published_to=dates(min_value=today))
    def test_get(self, title, published_from, published_to) -> None:
        statusDateRangeTest.objects.create(title=title,
                                           published_from=published_from,
                                           published_to=published_to,
                                           status=ModelStatus.LIVE_STATUS)
        all_items = statusDateRangeTest.objects.all()
        self.assertEqual(len(all_items), 1)

    @given(title=postgres_text,
           published_from=dates(max_value=yesterday),
           published_to=dates(max_value=yesterday))
    def test_date_in_past(self, title, published_from, published_to) -> None:
        statusDateRangeTest.objects.create(title=title,
                                           published_from=published_from,
                                           published_to=published_to,
                                           status=ModelStatus.LIVE_STATUS)
        all_items = statusDateRangeTest.objects.all()
        self.assertEqual(len(all_items), 0)

    @given(title=postgres_text,
           published_from=dates(min_value=tomorrow),
           published_to=dates(min_value=tomorrow))
    def test_date_in_future(self, title, published_from, published_to) -> None:
        statusDateRangeTest.objects.create(title=title,
                                           published_from=published_from,
                                           published_to=published_to,
                                           status=ModelStatus.LIVE_STATUS)
        all_items = statusDateRangeTest.objects.all()
        self.assertEqual(len(all_items), 0)
# This is free software; you can do what the LICENCE file allows you to.
#

from __future__ import (
    division as _py3_division,
    print_function as _py3_print,
    absolute_import as _py3_abs_import,
)
from xoutil.future.datetime import TimeSpan, parse_date

from datetime import date
from hypothesis import strategies, given
from xoeuf.odoo.tests.common import TransactionCase


maybe_dates = strategies.dates(min_value=date(1900, 1, 1)) | strategies.none()


@strategies.composite
def timespans(draw):
    start = draw(maybe_dates)
    end = draw(maybe_dates)
    return TimeSpan(start, end)


class TestTimespan(TransactionCase):
    def setUp(self):
        super(TestTimespan, self).setUp()
        self.Value = self.env["test.timespan.value"]

    def assertDateEqual(self, value1, value2):
def test_can_find_each_month():
    for month in hrange(1, 13):
        find_any(dates(), lambda x: x.month == month)
def test_can_find_after_the_year_2000():
    assert minimal(dates(), lambda x: x.year > 2000).year == 2001

def test_can_find_each_month():
    for month in hrange(1, 13):
        find_any(dates(), lambda x: x.month == month)


def test_min_year_is_respected():
    assert minimal(dates(min_value=dt.date.min.replace(2003))).year == 2003


def test_max_year_is_respected():
    assert minimal(dates(max_value=dt.date.min.replace(1998))).year == 1998


@given(dates())
def test_single_date(val):
    assert find_any(dates(val, val)) is val


def test_can_find_midnight():
    find_any(times(), lambda x: x.hour == x.minute == x.second == 0)


def test_can_find_non_midnight():
    assert minimal(times(), lambda x: x.hour != 0).hour == 1


def test_can_find_on_the_minute():
    find_any(times(), lambda x: x.second == 0)
Exemple #19
0
def two_dates(draw):
    debut = draw(dates())
    fin = draw(
        dates(min_value=debut - timedelta(days=15),
              max_value=debut + timedelta(days=150)))
    return (debut, fin)
Exemple #20
0
    )


@st.composite
def in_interval_cli_args(draw):
    return [
        'in_interval',
        '-s', draw(st.dates()).strftime('%Y-%m-%d'),
        '-e', draw(st.dates()).strftime('%Y-%m-%d')
    ], draw(st.builds(
        lambda e: list(map(lambda d: d.strftime('%Y-%m-%d'), e)),
        st.lists(st.dates(), min_size=1, max_size=100))
    )


@h.given(days=st.integers(min_value=-500, max_value=500), start=st.dates(),
         skip=list_of_dates())
def test_business_days_from_now_general(days, start, skip):
    if days >= 0:
        assert business_days_from_now(days, start, skip) >= start
    else:
        assert business_days_from_now(days, start, skip) <= start
    if not (start.weekday() >= 5 and days == 0):
        assert (business_days_from_now(days, start, skip)).weekday() < 5


def test_business_days_from_now_specific_cases():
    assert business_days_from_now(-5, date(2000, 1, 1)) == date(1999, 12, 27)
    assert business_days_from_now(0, date(2000, 1, 1)) == date(2000, 1, 1)
    assert business_days_from_now(1, date(2017, 1, 1)) == date(2017, 1, 2)
    assert business_days_from_now(1, date(2017, 1, 3)) == date(2017, 1, 4)
Exemple #21
0
from hypothesis import given
from hypothesis.strategies import text, one_of, none, integers, lists
from hypothesis.strategies import dates
from pytest import raises

from kanban.domain.model.workitem import register_new_work_item


@given(name=text(min_size=1), due_date=one_of(dates(), none()), content=text())
def test_register_new_work_item_creates_a_work_item(name, due_date, content):
    work_item = register_new_work_item(name, due_date, content)
    assert work_item.name == name
    assert work_item.due_date == due_date
    assert work_item.content == content


@given(due_date=one_of(dates(), none()), content=text())
def test_register_new_work_item_with_invalid_name_raises_value_error(
        due_date, content):
    with raises(ValueError):
        register_new_work_item("", due_date, content)


@given(initial_name=text(min_size=1),
       changed_name=text(min_size=1),
       due_date=one_of(dates(), none()),
       content=text())
def test_name_setter_changes_name(initial_name, changed_name, due_date,
                                  content):
    work_item = register_new_work_item(initial_name, due_date, content)
    work_item.name = changed_name
def test_min_year_is_respected():
    assert minimal(dates(min_value=dt.date.min.replace(2003))).year == 2003
def test_max_year_is_respected():
    assert minimal(dates(max_value=dt.date.min.replace(1998))).year == 1998
def test_single_date(val):
    assert find_any(dates(val, val)) is val
def test_can_find_after_the_year_2000():
    assert minimal(dates(), lambda x: x.year > 2000).year == 2001
def test_can_find_each_month():
    for month in hrange(1, 13):
        find_any(dates(), lambda x: x.month == month)
Exemple #27
0
PYPY = platform.python_implementation() == "PyPy"
HAS_FOLD = getattr(pdt.datetime, "fold", False)

xfail_date_bounds = pytest.mark.xfail(
    sys.version_info < (3, 6),
    reason=
    "Date bounds were not checked in the C constructor prior to version 3.6",
)


# Tests
def test_date():
    assert rdt.make_date(2017, 9, 1) == pdt.date(2017, 9, 1)


@given(d=st.dates())
def test_date_accessors(d):
    act = rdt.get_date_tuple(d)
    exp = (d.year, d.month, d.day)

    assert act == exp


@xfail_date_bounds
def test_invalid_date_fails():
    with pytest.raises(ValueError):
        rdt.make_date(2017, 2, 30)


@given(d=st.dates(MIN_DATETIME_FROM_TIMESTAMP.date(),
                  MAX_DATETIME_FROM_TIMESTAMP.date()))
def test_max_year_is_respected():
    assert minimal(dates(max_value=dt.date.min.replace(1998))).year == 1998
Exemple #29
0
        return (dt - pdt.datetime(1970, 1, 1)).total_seconds()


xfail_date_bounds = pytest.mark.xfail(
    sys.version_info < (3, 6),
    reason=
    "Date bounds were not checked in the C constructor prior to version 3.6",
)


# Tests
def test_date():
    assert rdt.make_date(2017, 9, 1) == pdt.date(2017, 9, 1)


@given(d=st.dates())
def test_date_accessors(d):
    act = rdt.get_date_tuple(d)
    exp = (d.year, d.month, d.day)

    assert act == exp


@xfail_date_bounds
def test_invalid_date_fails():
    with pytest.raises(ValueError):
        rdt.make_date(2017, 2, 30)


@given(d=dates())
def test_date_from_timestamp(d):
def test_deprecated_min_date_is_respected():
    assert minimal(dates(min_date=dt.date.min.replace(2003))).year == 2003
Exemple #31
0
def list_of_dates(draw):
    return draw(st.iterables(st.dates(), min_size=1, max_size=100))
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

import pytest

import hypothesis.strategies as st
from hypothesis import given, reject, example
from hypothesis.errors import InvalidArgument

base_reusable_strategies = (
    st.text(),
    st.binary(),
    st.dates(),
    st.times(),
    st.timedeltas(),
    st.booleans(),
    st.complex_numbers(),
    st.floats(),
    st.floats(-1.0, 1.0),
    st.integers(),
    st.integers(1, 10),
    st.integers(1),
)


@st.deferred
def reusable():
    return st.one_of(
Exemple #33
0
class ParserTestCase(TestCase):
    def setUp(self):
        self.now = datetime(2016, 10, 15)
        self.parser = Parser(self.now)

    @given(dates(min_value=MIN_DATE))
    def test_extract_year(self, d):
        s = d.strftime('%Y')
        year = self.parser.extract_year(s)
        self.assertEqual(year, d.year)

    @given(dates(min_value=MIN_DATE), just('%Y'),
           sampled_from(['%m', '%b', '%B']))
    def test_extract_month(self, d, y_code, m_code):
        for perm in permutations([y_code, m_code]):
            s = d.strftime(' '.join(perm))
            year, month = self.parser.extract_month(s)
            self.assertEqual(year, d.year)
            self.assertEqual(month, d.month)

        s = d.strftime(m_code)
        year, month = self.parser.extract_month(s)
        self.assertEqual(year, self.now.year)
        self.assertEqual(month, d.month)

    def test_extract_week(self):
        monday, sunday = self.parser.extract_week('')
        self.assertEqual(monday, date(2016, 10, 10))
        self.assertEqual(sunday, date(2016, 10, 16))

        monday, sunday = self.parser.extract_week('this')
        self.assertEqual(monday, date(2016, 10, 10))
        self.assertEqual(sunday, date(2016, 10, 16))

        monday, sunday = self.parser.extract_week('last')
        self.assertEqual(monday, date(2016, 10, 3))
        self.assertEqual(sunday, date(2016, 10, 9))

    @given(dates(min_value=MIN_DATE), just('%Y'), sampled_from(['%b', '%B']),
           sampled_from(['%d']))
    def test_extract_date(self, d, y_code, m_code, d_code):
        for perm in permutations([y_code, m_code, d_code]):
            s = d.strftime(' '.join(perm))
            res = self.parser.extract_date(s)
            self.assertEqual(res.year, d.year)
            self.assertEqual(res.month, d.month)
            self.assertEqual(res.day, d.day)

        for perm in permutations([m_code, d_code]):
            s = d.strftime(' '.join(perm))
            res = self.parser.extract_date(s)
            self.assertEqual(res.year, self.now.year)
            self.assertEqual(res.month, d.month)
            self.assertEqual(res.day, d.day)

        s = d.strftime(d_code)
        res = self.parser.extract_date(s)
        self.assertEqual(res.year, self.now.year)
        self.assertEqual(res.month, self.now.month)
        self.assertEqual(res.day, d.day)

    @given(dates(min_value=MIN_DATE))
    def test_extract_date_iso(self, d):
        res = self.parser.extract_date(d.isoformat())
        self.assertEqual(res.year, d.year)
        self.assertEqual(res.month, d.month)
        self.assertEqual(res.day, d.day)

    def test_extract_words(self):
        year = self.parser.extract_year('last')
        self.assertEqual(year, self.now.year - 1)

        for word in ['', 'this']:
            year = self.parser.extract_year(word)
            self.assertEqual(year, self.now.year)

        year, month = self.parser.extract_month('last')
        self.assertEqual(year, self.now.year)
        self.assertEqual(month, self.now.month - 1)

        for word in ['', 'this']:
            year, month = self.parser.extract_month(word)
            self.assertEqual(year, self.now.year)
            self.assertEqual(month, self.now.month)

        for word in ['last', 'yesterday']:
            res = self.parser.extract_date(word)
            self.assertEqual(res.year, self.now.year)
            self.assertEqual(res.month, self.now.month)
            self.assertEqual(res.day, self.now.day - 1)

        for word in ['', 'this', 'today']:
            res = self.parser.extract_date(word)
            self.assertEqual(res.year, self.now.year)
            self.assertEqual(res.month, self.now.month)
            self.assertEqual(res.day, self.now.day)

    @given(datetimes(min_value=MIN_DATETIME))
    @example(datetime(2017, 1, 1))
    def test_extract_month_words(self, dt):
        parser = Parser(dt)

        last_month = dt.month - 1 or 12
        last_month_year = dt.year - 1 if last_month == 12 else dt.year

        for word in ['last']:
            year, month = parser.extract_month(word)
            self.assertEqual(year, last_month_year)
            self.assertEqual(month, last_month)

        for word in ['', 'this']:
            year, month = parser.extract_month(word)
            self.assertEqual(year, dt.year)
            self.assertEqual(month, dt.month)

    @given(datetimes(min_value=MIN_DATETIME))
    @example(datetime(2016, 10, 1))
    def test_extract_date_words(self, dt):
        parser = Parser(dt)
        today = dt.date()
        yesterday = dt.date() - timedelta(days=1)

        for word in ['last', 'yesterday']:
            res = parser.extract_date(word)
            self.assertEqual(res, yesterday)

        for word in ['', 'this', 'today']:
            res = parser.extract_date(word)
            self.assertEqual(res, today)

    @given(datetimes())
    def test_extract_datetime(self, dt):
        res = self.parser.extract_datetime(dt.isoformat())

        for prop in ['year', 'month', 'day', 'hour', 'minute']:
            self.assertEqual(getattr(res, prop), getattr(dt, prop))

    def test_extract_span_errors(self):
        with self.assertRaises(ValueError):
            self.parser.extract_span('')

        with self.assertRaises(ValueError):
            self.parser.extract_span('10 sep sep')

        with self.assertRaises(ValueError):
            self.parser.extract_span('10 2016 sep sep')

        with self.assertRaises(ValueError):
            self.parser.extract_span('sep 2016')

    def test_extract_span(self):
        d1, d2 = self.parser.extract_span('10')
        self.assertEqual(d1, date(2016, 10, 10))
        self.assertEqual(d2, date(2016, 10, 15))

        d1, d2 = self.parser.extract_span('10 12')
        self.assertEqual(d1, date(2016, 10, 10))
        self.assertEqual(d2, date(2016, 10, 12))

        d1, d2 = self.parser.extract_span('10 12 sep')
        self.assertEqual(d1, date(2016, 9, 10))
        self.assertEqual(d2, date(2016, 9, 12))

        d1, d2 = self.parser.extract_span('10 sep 12 oct')
        self.assertEqual(d1, date(2016, 9, 10))
        self.assertEqual(d2, date(2016, 10, 12))

        d1, d2 = self.parser.extract_span('10 sep 12 oct 2015')
        self.assertEqual(d1, date(2015, 9, 10))
        self.assertEqual(d2, date(2015, 10, 12))

        d1, d2 = self.parser.extract_span('10 sep 2014 12 oct 2015')
        self.assertEqual(d1, date(2014, 9, 10))
        self.assertEqual(d2, date(2015, 10, 12))
        '''d1, d2 = self.parser.extract_span('2014-09-10 2015-10-12')
        self.assertEqual(d1, date(2014, 9, 10))
        self.assertEqual(d2, date(2015, 10, 12))'''

    @given(dates(min_value=MIN_DATE, max_value=date(2015, 1, 1)))
    def test_extract_span_one_date(self, d):
        assume(d < self.now.date())

        for perm in permutations(['%Y', '%b', '%d']):
            d1, d2 = self.parser.extract_span(d.strftime(' '.join(perm)))
            self.assertEqual(d1, d)
            self.assertEqual(d2, self.now.date())
        '''d1, d2 = self.parser.extract_span(d.isoformat())
def test_can_find_before_the_year_2000():
    assert minimal(dates(), lambda x: x.year < 2000).year == 1999

def test_can_find_each_month():
    for month in hrange(1, 13):
        find_any(dates(), lambda x: x.month == month)


def test_min_year_is_respected():
    assert minimal(dates(min_value=dt.date.min.replace(2003))).year == 2003


def test_max_year_is_respected():
    assert minimal(dates(max_value=dt.date.min.replace(1998))).year == 1998


@given(dates())
def test_single_date(val):
    assert find_any(dates(val, val)) is val


def test_can_find_midnight():
    find_any(times(), lambda x: x.hour == x.minute == x.second == 0)


def test_can_find_non_midnight():
    assert minimal(times(), lambda x: x.hour != 0).hour == 1


def test_can_find_on_the_minute():
    find_any(times(), lambda x: x.second == 0)
Exemple #36
0
        # TS ±2147483648 (2**31)
        MIN_DATETIME = pdt.datetime(1901, 12, 13, 20, 45, 52)
        MAX_DATETIME = pdt.datetime(2038, 1, 19, 3, 14, 8)
    else:
        MIN_DATETIME = pdt.datetime(1, 1, 2, 0, 0)
        MAX_DATETIME = pdt.datetime(9999, 12, 31, 18, 59, 59)

PYPY = platform.python_implementation() == "PyPy"


# Tests
def test_date():
    assert rdt.make_date(2017, 9, 1) == pdt.date(2017, 9, 1)


@given(d=st.dates())
def test_date_accessors(d):
    act = rdt.get_date_tuple(d)
    exp = (d.year, d.month, d.day)

    assert act == exp


def test_invalid_date_fails():
    with pytest.raises(ValueError):
        rdt.make_date(2017, 2, 30)


@given(d=st.dates(MIN_DATETIME.date(), MAX_DATETIME.date()))
def test_date_from_timestamp(d):
    if PYPY and d < pdt.date(1900, 1, 1):
def test_can_find_before_the_year_2000():
    assert minimal(dates(), lambda x: x.year < 2000).year == 1999
Exemple #38
0
    """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
def test_min_year_is_respected():
    assert minimal(dates(min_value=dt.date.min.replace(2003))).year == 2003
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

import pytest

import hypothesis.strategies as st
from hypothesis import given, reject, example
from hypothesis.errors import InvalidArgument

base_reusable_strategies = (
    st.text(), st.binary(), st.dates(),
    st.times(), st.timedeltas(), st.booleans(), st.complex_numbers(),
    st.floats(), st.floats(-1.0, 1.0),
    st.integers(), st.integers(1, 10), st.integers(1),
)


@st.deferred
def reusable():
    return st.one_of(
        st.sampled_from(base_reusable_strategies),

        st.builds(
            st.floats, min_value=st.none() | st.floats(),
            max_value=st.none() | st.floats(), allow_infinity=st.booleans(),
            allow_nan=st.booleans()
def test_single_date(val):
    assert find_any(dates(val, val)) is val
if False:
    from datetime import tzinfo  # noqa
    from typing import Any, Type, Optional, List, Text, Callable, Union  # noqa


# Mapping of field types, to strategy objects or functions of (type) -> strategy
_global_field_lookup = {
    dm.SmallIntegerField: st.integers(-32768, 32767),
    dm.IntegerField: st.integers(-2147483648, 2147483647),
    dm.BigIntegerField: st.integers(-9223372036854775808, 9223372036854775807),
    dm.PositiveIntegerField: st.integers(0, 2147483647),
    dm.PositiveSmallIntegerField: st.integers(0, 32767),
    dm.BinaryField: st.binary(),
    dm.BooleanField: st.booleans(),
    dm.DateField: st.dates(),
    dm.EmailField: emails(),
    dm.FloatField: st.floats(),
    dm.NullBooleanField: st.one_of(st.none(), st.booleans()),
    dm.URLField: urls(),
    dm.UUIDField: st.uuids(),
    df.DateField: st.dates(),
    df.DurationField: st.timedeltas(),
    df.EmailField: emails(),
    df.FloatField: st.floats(allow_nan=False, allow_infinity=False),
    df.IntegerField: st.integers(-2147483648, 2147483647),
    df.NullBooleanField: st.one_of(st.none(), st.booleans()),
    df.URLField: urls(),
    df.UUIDField: st.uuids(),
}
Exemple #43
0
def arrays(draw, type, size=None):
    if isinstance(type, st.SearchStrategy):
        type = draw(type)
    elif not isinstance(type, pa.DataType):
        raise TypeError('Type must be a pyarrow DataType')

    if isinstance(size, st.SearchStrategy):
        size = draw(size)
    elif size is None:
        size = draw(_default_array_sizes)
    elif not isinstance(size, int):
        raise TypeError('Size must be an integer')

    shape = (size,)

    if pa.types.is_list(type):
        offsets = draw(npst.arrays(np.uint8(), shape=shape)).cumsum() // 20
        offsets = np.insert(offsets, 0, 0, axis=0)  # prepend with zero
        values = draw(arrays(type.value_type, size=int(offsets.sum())))
        return pa.ListArray.from_arrays(offsets, values)

    if pa.types.is_struct(type):
        h.assume(len(type) > 0)
        names, child_arrays = [], []
        for field in type:
            names.append(field.name)
            child_arrays.append(draw(arrays(field.type, size=size)))
        # fields' metadata are lost here, because from_arrays doesn't accept
        # a fields argumentum, only names
        return pa.StructArray.from_arrays(child_arrays, names=names)

    if (pa.types.is_boolean(type) or pa.types.is_integer(type) or
            pa.types.is_floating(type)):
        values = npst.arrays(type.to_pandas_dtype(), shape=(size,))
        np_arr = draw(values)
        if pa.types.is_floating(type):
            # Workaround ARROW-4952: no easy way to assert array equality
            # in a NaN-tolerant way.
            np_arr[np.isnan(np_arr)] = -42.0
        return pa.array(np_arr, type=type)

    if pa.types.is_null(type):
        value = st.none()
    elif pa.types.is_time(type):
        value = st.times()
    elif pa.types.is_date(type):
        value = st.dates()
    elif pa.types.is_timestamp(type):
        tz = pytz.timezone(type.tz) if type.tz is not None else None
        value = st.datetimes(timezones=st.just(tz))
    elif pa.types.is_binary(type):
        value = st.binary()
    elif pa.types.is_string(type):
        value = st.text()
    elif pa.types.is_decimal(type):
        # TODO(kszucs): properly limit the precision
        # value = st.decimals(places=type.scale, allow_infinity=False)
        h.reject()
    else:
        raise NotImplementedError(type)

    values = st.lists(value, min_size=size, max_size=size)
    return pa.array(draw(values), type=type)
Exemple #44
0
    return st.one_of(strategies)


_global_type_lookup = {
    # Types with core Hypothesis strategies
    type(None): st.none(),
    bool: st.booleans(),
    int: st.integers(),
    float: st.floats(),
    complex: st.complex_numbers(),
    fractions.Fraction: st.fractions(),
    decimal.Decimal: st.decimals(),
    text_type: st.text(),
    bytes: st.binary(),
    datetime.datetime: st.datetimes(),
    datetime.date: st.dates(),
    datetime.time: st.times(),
    datetime.timedelta: st.timedeltas(),
    uuid.UUID: st.uuids(),
    tuple: st.builds(tuple),
    list: st.builds(list),
    set: st.builds(set),
    frozenset: st.builds(frozenset),
    dict: st.builds(dict),
    # Built-in types
    type: st.sampled_from([type(None), bool, int, str, list, set, dict]),
    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!
Exemple #45
0
    return st.one_of(strategies)


_global_type_lookup = {
    # Types with core Hypothesis strategies
    type(None): st.none(),
    bool: st.booleans(),
    int: st.integers(),
    float: st.floats(),
    complex: st.complex_numbers(),
    fractions.Fraction: st.fractions(),
    decimal.Decimal: st.decimals(),
    text_type: st.text(),
    binary_type: st.binary(),
    datetime.datetime: st.datetimes(),
    datetime.date: st.dates(),
    datetime.time: st.times(),
    datetime.timedelta: st.timedeltas(),
    uuid.UUID: st.uuids(),
    tuple: st.builds(tuple),
    list: st.builds(list),
    set: st.builds(set),
    frozenset: st.builds(frozenset),
    dict: st.builds(dict),
    type(lambda: None): st.functions(),
    # Built-in types
    type(Ellipsis): st.just(Ellipsis),
    type(NotImplemented): st.just(NotImplemented),
    bytearray: st.binary().map(bytearray),
    memoryview: st.binary().map(memoryview),
    numbers.Real: st.floats(),
def test_deprecated_min_date_is_respected():
    assert minimal(dates(min_date=dt.date.min.replace(2003))).year == 2003