<commit_before>##
# See the file COPYRIGHT for copyright information.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

"""
Tests for :mod:`ranger-ims-server.store.sqlite._store`
"""

from datetime import (
    datetime as DateTime,
    timedelta as TimeDelta,
    timezone as TimeZone,
)
from io import StringIO
from pathlib import Path
from sqlite3 import IntegrityError
from textwrap import dedent
from typing import Optional
from unittest.mock import patch

from hypothesis import given, settings
from hypothesis.strategies import integers

from ims.ext.sqlite import (
    Connection,
    SQLITE_MAX_INT,
    SQLITE_MIN_INT,
    SQLiteError,
    createDB,
    printSchema,
)
from ims.ext.trial import AsynchronousTestCase, TestCase

from .base import TestDataStore
from .. import _store
from .._store import DataStore
from ..._exceptions import StorageError


__all__ = ()


class DataStoreCoreTests(AsynchronousTestCase):
    """
    Tests for :class:`DataStore` base functionality.
    """

    def test_loadSchema(self) -> None:
        """
        :meth:`DataStore.loadSchema` caches and returns the schema.
        """
        store = TestDataStore(dbPath=None)
        schema = store.loadSchema()

        self.assertStartsWith(schema, "create table SCHEMA_INFO (")

    def test_printSchema(self) -> None:
        """
        :meth:`DataStore.printSchema` prints the expected schema.
        """
        out = StringIO()
        DataStore.printSchema(out)
        schemaInfo = out.getvalue()

        self.maxDiff = None
        self.assertEqual(
            dedent(
                """
                Version: 4
                ACCESS_MODE:
                  0: ID(text) not null *1
                CONCENTRIC_STREET:
                  0: EVENT(integer) not null *1
                  1: ID(text) not null *2
                  2: NAME(text) not null
                EVENT:
                  0: ID(integer) not null *1
                  1: NAME(text) not null
                EVENT_ACCESS:
                  0: EVENT(integer) not null *1
                  1: EXPRESSION(text) not null *2
                  2: MODE(text) not null
                INCIDENT:
                  0: EVENT(integer) not null *1
                  1: NUMBER(integer) not null *2
                  2: CREATED(real) not null
                  3: PRIORITY(integer) not null
                  4: STATE(integer) not null
                  5: SUMMARY(text)
                  6: LOCATION_NAME(text)
                  7: LOCATION_CONCENTRIC(text)
                  8: LOCATION_RADIAL_HOUR(integer)
                  9: LOCATION_RADIAL_MINUTE(integer)
                  10: LOCATION_DESCRIPTION(text)
                INCIDENT_REPORT:
                  0: EVENT(integer) not null *1
                  1: NUMBER(integer) not null *2
                  2: CREATED(real) not null
                  3: SUMMARY(text)
                  4: INCIDENT_NUMBER(integer)
                INCIDENT_REPORT__REPORT_ENTRY:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_REPORT_NUMBER(integer) not null *2
                  2: REPORT_ENTRY(integer) not null *3
                INCIDENT_STATE:
                  0: ID(text) not null *1
                INCIDENT_TYPE:
                  0: ID(integer) not null *1
                  1: NAME(text) not null
                  2: HIDDEN(numeric) not null
                INCIDENT__INCIDENT_TYPE:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: INCIDENT_TYPE(integer) not null *3
                INCIDENT__RANGER:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: RANGER_HANDLE(text) not null *3
                INCIDENT__REPORT_ENTRY:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: REPORT_ENTRY(integer) not null *3
                REPORT_ENTRY:
                  0: ID(integer) not null *1
                  1: AUTHOR(text) not null
                  2: TEXT(text) not null
                  3: CREATED(real) not null
                  4: GENERATED(numeric) not null
                  5: STRICKEN(numeric) not null
                SCHEMA_INFO:
                  0: VERSION(integer) not null
                """[
                    1:
                ]
            ),
            schemaInfo,
        )

    def test_printQueries(self) -> None:
        """
        :meth:`DataStore.printQueries` prints the queries in use.
        """
        out = StringIO()
        DataStore.printQueries(out)
        queryInfo = out.getvalue()

        self.maxDiff = None
        self.assertStartsWith(
            queryInfo,
            "\n".join(
                (
                    "addEventAccess:",
                    "",
                    "  -- query --",
                    "",
                    "    insert into EVENT_ACCESS (EVENT, EXPRESSION, MODE)",
                    "    values "
                    "((select ID from EVENT where NAME = :eventID), "
                    ":expression, :mode)",
                    "",
                    "  -- query plan --",
                    "",
                    "    [None,None] You did not supply a value for binding 1.",
                    "",
                    "attachIncidentReportToIncident:",
                    "",
                    "  -- query --",
                    "",
                    "    update INCIDENT_REPORT set INCIDENT_NUMBER = :value",
                    "    where EVENT = "
                    "(select ID from EVENT where NAME = :eventID) "
                    "and NUMBER = :incidentReportNumber",
                    "",
                    "  -- query plan --",
                    "",
                    "    [None,None] You did not supply a value for binding 1.",
                    "",
                )
            ),
        )

    def test_dbSchemaVersion(self) -> None:
        """
        :meth:`DataStore._dbSchemaVersion` returns the schema version for the
        given database.
        """
        for version in range(<commit_msg>Handle change in SQLite output in Python 3.10<commit_after>##
# See the file COPYRIGHT for copyright information.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

"""
Tests for :mod:`ranger-ims-server.store.sqlite._store`
"""

from datetime import (
    datetime as DateTime,
    timedelta as TimeDelta,
    timezone as TimeZone,
)
from io import StringIO
from pathlib import Path
from sqlite3 import IntegrityError
from textwrap import dedent
from typing import Optional
from unittest.mock import patch

from hypothesis import given, settings
from hypothesis.strategies import integers

from ims.ext.sqlite import (
    Connection,
    SQLITE_MAX_INT,
    SQLITE_MIN_INT,
    SQLiteError,
    createDB,
    printSchema,
)
from ims.ext.trial import AsynchronousTestCase, TestCase

from .base import TestDataStore
from .. import _store
from .._store import DataStore
from ..._exceptions import StorageError


__all__ = ()


class DataStoreCoreTests(AsynchronousTestCase):
    """
    Tests for :class:`DataStore` base functionality.
    """

    def test_loadSchema(self) -> None:
        """
        :meth:`DataStore.loadSchema` caches and returns the schema.
        """
        store = TestDataStore(dbPath=None)
        schema = store.loadSchema()

        self.assertStartsWith(schema, "create table SCHEMA_INFO (")

    def test_printSchema(self) -> None:
        """
        :meth:`DataStore.printSchema` prints the expected schema.
        """
        out = StringIO()
        DataStore.printSchema(out)
        schemaInfo = out.getvalue()

        self.maxDiff = None
        self.assertEqual(
            dedent(
                """
                Version: 4
                ACCESS_MODE:
                  0: ID(text) not null *1
                CONCENTRIC_STREET:
                  0: EVENT(integer) not null *1
                  1: ID(text) not null *2
                  2: NAME(text) not null
                EVENT:
                  0: ID(integer) not null *1
                  1: NAME(text) not null
                EVENT_ACCESS:
                  0: EVENT(integer) not null *1
                  1: EXPRESSION(text) not null *2
                  2: MODE(text) not null
                INCIDENT:
                  0: EVENT(integer) not null *1
                  1: NUMBER(integer) not null *2
                  2: CREATED(real) not null
                  3: PRIORITY(integer) not null
                  4: STATE(integer) not null
                  5: SUMMARY(text)
                  6: LOCATION_NAME(text)
                  7: LOCATION_CONCENTRIC(text)
                  8: LOCATION_RADIAL_HOUR(integer)
                  9: LOCATION_RADIAL_MINUTE(integer)
                  10: LOCATION_DESCRIPTION(text)
                INCIDENT_REPORT:
                  0: EVENT(integer) not null *1
                  1: NUMBER(integer) not null *2
                  2: CREATED(real) not null
                  3: SUMMARY(text)
                  4: INCIDENT_NUMBER(integer)
                INCIDENT_REPORT__REPORT_ENTRY:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_REPORT_NUMBER(integer) not null *2
                  2: REPORT_ENTRY(integer) not null *3
                INCIDENT_STATE:
                  0: ID(text) not null *1
                INCIDENT_TYPE:
                  0: ID(integer) not null *1
                  1: NAME(text) not null
                  2: HIDDEN(numeric) not null
                INCIDENT__INCIDENT_TYPE:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: INCIDENT_TYPE(integer) not null *3
                INCIDENT__RANGER:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: RANGER_HANDLE(text) not null *3
                INCIDENT__REPORT_ENTRY:
                  0: EVENT(integer) not null *1
                  1: INCIDENT_NUMBER(integer) not null *2
                  2: REPORT_ENTRY(integer) not null *3
                REPORT_ENTRY:
                  0: ID(integer) not null *1
                  1: AUTHOR(text) not null
                  2: TEXT(text) not null
                  3: CREATED(real) not null
                  4: GENERATED(numeric) not null
                  5: STRICKEN(numeric) not null
                SCHEMA_INFO:
                  0: VERSION(integer) not null
                """[
                    1:
                ]
            ),
            schemaInfo,
        )

    def test_printQueries(self) -> None:
        """
        :meth:`DataStore.printQueries` prints the queries in use.
        """
        out = StringIO()
        DataStore.printQueries(out)
        queryInfo = out.getvalue()

        expected = (
            r"addEventAccess:",
            r"",
            r"  -- query --",
            r"",
            r"    insert into EVENT_ACCESS \(EVENT, EXPRESSION, MODE\)",
            r"    values \("
            r"\(select ID from EVENT where NAME = :eventID\), "
            r":expression, :mode"
            r"\)",
            r"",
            r"  -- query plan --",
            r"",
            r"    \[None,None\] You did not supply a value for binding"
            r".*",
            r"",
            r"attachIncidentReportToIncident:",
            r"",
            r"  -- query --",
            r"",
            r"    update INCIDENT_REPORT set INCIDENT_NUMBER = :value",
            r"    where EVENT = "
            r"\(select ID from EVENT where NAME = :eventID\) "
            r"and NUMBER = :incidentReportNumber",
            r"",
            r"  -- query plan --",
            r"",
            r"    \[None,None\] You did not supply a value for binding"
            r".*",
            r"",
        )

        self.maxDiff = None
        self.assertRegex(queryInfo, "\n".join(expected))

    def test_dbSchemaVersion(self) -> None:
        """
        :meth:`DataStore._dbSchemaVersion` returns the schema version for the
        given database.
        """
        for version in range(
{'fraction_non_alphanumeric': 0.08454634587827137, 'fraction_numerical': 0.012595218342258088, 'mean_word_length': 1.441988950276243, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5386114', 'n_tokens_mistral': 3679, 'n_tokens_neox': 3401, 'n_words': 1067}