Skip to content

Commit

Permalink
nit
Browse files Browse the repository at this point in the history
  • Loading branch information
chrabyrd committed Apr 1, 2024
1 parent bac8e3a commit 324a766
Show file tree
Hide file tree
Showing 9 changed files with 260 additions and 0 deletions.
Binary file added .coverage
Binary file not shown.
15 changes: 15 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[run]
source =
arches_rdm_example_project/

[report]
omit =
*/python?.?/*
*/migrations/*
*/tests/*
*/celery.py
*/settings*.py
*/wsgi.py
*/urls.py

show_missing = true
Empty file.
Empty file added tests/__init__.py
Empty file.
155 changes: 155 additions & 0 deletions tests/base_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import os
from contextlib import contextmanager

from django.test import TestCase
from arches.app.models.graph import Graph
from arches.app.models.models import Ontology
from arches.app.models.system_settings import settings
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
from arches.app.utils.data_management.resource_graphs.importer import import_graph as ResourceGraphImporter
from arches.app.utils.data_management.resources.importer import BusinessDataImporter
from tests import test_settings
from arches.app.utils.context_processors import app_settings
from django.db import connection
from django.core import management
from django.test.runner import DiscoverRunner

from arches.app.search.mappings import (
prepare_terms_index,
delete_terms_index,
prepare_concepts_index,
delete_concepts_index,
prepare_search_index,
delete_search_index,
)

# these tests can be run from the command line via
# python manage.py test tests --pattern="*.py" --settings="tests.test_settings"

OAUTH_CLIENT_ID = "AAac4uRQSqybRiO6hu7sHT50C4wmDp9fAmsPlCj9"
OAUTH_CLIENT_SECRET = "7fos0s7qIhFqUmalDI1QiiYj0rAtEdVMY4hYQDQjOxltbRCBW3dIydOeMD4MytDM9ogCPiYFiMBW6o6ye5bMh5dkeU7pg1cH86wF6B\
ap9Ke2aaAZaeMPejzafPSj96ID"
CREATE_TOKEN_SQL = """
INSERT INTO public.oauth2_provider_accesstoken(
token, expires, scope, application_id, user_id, created, updated)
VALUES ('{token}', '1-1-2068', 'read write', 44, {user_id}, '1-1-2018', '1-1-2018');
"""
DELETE_TOKEN_SQL = "DELETE FROM public.oauth2_provider_accesstoken WHERE application_id = 44;"


class ArchesTestRunner(DiscoverRunner):
def __init__(self, *args, **kwargs) -> None:
kwargs["debug_mode"] = True
# Unless the user has something other than the Django default, give them
# what they probably want.
if kwargs["pattern"] == "test*.py":
kwargs["pattern"] = "*.py"
super().__init__(*args, **kwargs)

def setup_databases(self, **kwargs):
ret = super().setup_databases(**kwargs)

app_settings() # adds languages to system
prepare_terms_index(create=True)
prepare_concepts_index(create=True)
prepare_search_index(create=True)

return ret

def teardown_databases(self, old_config, **kwargs):
delete_terms_index()
delete_concepts_index()
delete_search_index()

super().teardown_databases(old_config, **kwargs)

class ArchesTestCase(TestCase):
def __init__(self, *args, **kwargs):
super(ArchesTestCase, self).__init__(*args, **kwargs)
if settings.DEFAULT_BOUNDS is None:
management.call_command("migrate")
with open(os.path.join("tests/fixtures/system_settings/Arches_System_Settings_Model.json"), "r") as f:
archesfile = JSONDeserializer().deserialize(f)
ResourceGraphImporter(archesfile["graph"], True)
BusinessDataImporter("tests/fixtures/system_settings/Arches_System_Settings_Local.json").import_business_data()
settings.update_from_db()

@classmethod
def loadOntology(cls):
ontologies_count = Ontology.objects.exclude(ontologyid__isnull=True).count()
if ontologies_count == 0:
management.call_command("load_ontology", source=test_settings.ONTOLOGY_PATH)

@classmethod
def setUpClass(cls):
cursor = connection.cursor()
sql = """
INSERT INTO public.oauth2_provider_application(
id, client_id, redirect_uris, client_type, authorization_grant_type,
client_secret,
name, user_id, skip_authorization, created, updated, algorithm)
VALUES (
44, '{oauth_client_id}', 'http://localhost:8000/test', 'public', 'client-credentials',
'{oauth_client_secret}',
'TEST APP', {user_id}, false, '1-1-2000', '1-1-2000', '{jwt_algorithm}');
"""

sql = sql.format(
user_id=1,
oauth_client_id=OAUTH_CLIENT_ID,
oauth_client_secret=OAUTH_CLIENT_SECRET,
jwt_algorithm=test_settings.JWT_ALGORITHM,
)
cursor.execute(sql)

@classmethod
def tearDownClass(cls):
cursor = connection.cursor()
sql = "DELETE FROM public.oauth2_provider_application WHERE id = 44;"
cursor.execute(sql)

@classmethod
def deleteGraph(cls, root):
graph = Graph.objects.get(graphid=str(root))
graph.delete()

def setUp(self):
pass

def tearDown(self):
pass


@contextmanager
def sync_overridden_test_settings_to_arches():
"""Django's @override_settings test util acts on django.conf.settings,
which is not enough for us, because we use SystemSettings at runtime.
This context manager swaps in the overridden django.conf.settings for SystemSettings.
"""
from django.conf import settings as patched_settings

original_settings_wrapped = settings._wrapped
try:
settings._wrapped = patched_settings._wrapped
yield
finally:
settings._wrapped = original_settings_wrapped
39 changes: 39 additions & 0 deletions tests/run_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""


import sys
import os
from django.test.utils import get_runner
from tests import test_settings


def run_all(argv=None):
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.test_settings"

if argv is None or len(argv[1:]) == 0:
argv = ["tests"]

TestRunner = get_runner(test_settings)
test_runner = TestRunner([], interactive=True)
failures = test_runner.run_tests(argv)
sys.exit(failures)


if __name__ == "__main__":
run_all(sys.argv)
2 changes: 2 additions & 0 deletions tests/search_indexes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# these tests can be run from the command line via
# python manage.py test tests/views --pattern="*.py" --settings="tests.test_settings"
24 changes: 24 additions & 0 deletions tests/search_indexes/sample_index_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from unittest.mock import Mock

from arches.app.search.base_index import BaseIndex
from arches_rdm_example_project.arches_rdm_example_project.search_indexes.sample_index import SampleIndex
from tests.base_test import ArchesTestCase

class TestSampleIndex(ArchesTestCase):
def test_prepare_index(self):
sample_index = SampleIndex(index_name="Sample Index")
sample_index.prepare_index()

expected_index_metadata = {"mappings": {"properties": {"tile_count": {"type": "keyword"}, "graph_id": {"type": "keyword"}}}}
self.assertEqual(sample_index.index_metadata, expected_index_metadata)

def test_get_documents_to_index(self):
sample_index = SampleIndex(index_name="Sample Index")

mock_resourceinstance = Mock(graph_id="test_graph_id")
mock_tiles = [Mock(), Mock(), Mock()] # Mock tiles list

documents, doc_id = sample_index.get_documents_to_index(mock_resourceinstance, mock_tiles)

self.assertEqual(documents, {"tile_count": len(mock_tiles), "graph_id": mock_resourceinstance.graph_id})
self.assertEqual(doc_id, str(mock_resourceinstance.resourceinstanceid))
25 changes: 25 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

import os
import inspect

from arches.test_settings import *

APP_ROOT = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PACKAGE_NAME = "arches_rdm_example_project"

0 comments on commit 324a766

Please sign in to comment.