# Copyright (C) 2018  The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information

from hypothesis import given
from hypothesis.strategies import sets

from swh.scheduler.updater.events import SWHEvent

from . import from_regex


@given(urls=sets(
    from_regex(
        r'^https://somewhere[.]org/[a-z0-9]{5,7}/[a-z0-9]{3,10}$'),
    min_size=10, max_size=15))
def test_cache_read(urls, swh_scheduler_updater):
    # beware that the fixture is only called once for all the tests
    # generated by hypothesis, so the db is not cleared between calls.
    # see the end of
    #   https://hypothesis.works/articles/hypothesis-pytest-fixtures/
    def gen_events(urls):
        for url in urls:
            yield SWHEvent({
                'url': url,
                'type': 'create',
                'origin_type': 'git',
            })
    known_urls = set(e['url'] for e in
                     swh_scheduler_updater.cache_read(limit=1000000))
    swh_scheduler_updater.cache_put(gen_events(urls))
    new_urls = {u.strip() for u in urls} - known_urls
    all_urls = set(e['url'] for e in
                   swh_scheduler_updater.cache_read(limit=1000000))
    assert (all_urls - known_urls) == new_urls
