Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,15 @@ jobs:
pytest -v --ckan-ini=/srv/app/ckan.ini \
--cov=dcor_shared \
--cov-report=xml \
--cov-report=term-missing \
--cov-append \
tests

- name: Install Codecov requirements
run: apt-get update && apt-get install -y curl gpg

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
files: ./coverage.xml
flags: ${{ matrix.dcor_control }}
6 changes: 6 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
1.1.1
- tests: increase coverage (parse, RQJob, config helpers,
`wait_for_resource`, S3 helpers)
- tests: actually run `test_iter_buckets_keep_non_circle`
- tests: remove unused `requests_toolbelt` requirement
- ci: report coverage to Codecov
1.1.0
- BREAKING: remove unused `paths.get_nginx_config_path`,
`paths.get_supervisord_worker_config_path`, `paths.get_uwsgi_config_path`,
Expand Down
1 change: 0 additions & 1 deletion tests/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
pytest
requests
requests_toolbelt
dclab[s3]
pytest_factoryboy
36 changes: 36 additions & 0 deletions tests/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,39 @@ def test_wait_resource_not_available(monkeypatch):
# Should raise an exception
with pytest.raises(OSError, match="Data import seems to take too long"):
wait_for_resource(res_id, timeout=1)


def test_wait_for_resource_invalid_id():
with pytest.raises(ValueError, match="Invalid resource id"):
wait_for_resource("peter")


def test_wait_for_resource_artifact_exists(monkeypatch):
res_id = str(uuid.uuid4())
monkeypatch.setattr(dcor_shared.data, "admin_context",
lambda: {"ignore_auth": True})
monkeypatch.setattr(logic, "get_action",
lambda x: lambda context, data_dict: {"id": res_id})
monkeypatch.setattr(dcor_shared.s3cc, "artifact_exists",
lambda rid: rid == res_id)
# Should not raise an exception
wait_for_resource(res_id)


def test_wait_for_resource_not_found_first(monkeypatch):
res_id = str(uuid.uuid4())
calls = []

def resource_show(context, data_dict):
calls.append(data_dict["id"])
if len(calls) == 1:
# resource is not yet in the database
raise logic.NotFound()
return {"id": res_id, "s3_available": True}

monkeypatch.setattr(dcor_shared.data, "admin_context",
lambda: {"ignore_auth": True})
monkeypatch.setattr(logic, "get_action", lambda x: resource_show)
monkeypatch.setattr(dcor_shared.data.time, "sleep", lambda x: None)
wait_for_resource(res_id)
assert calls == [res_id, res_id]
27 changes: 27 additions & 0 deletions tests/test_parse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import pytest

from dcor_shared.parse import (
ConfigOptionNotFoundError, get_ini_config_option, parse_ini_config
)


def test_parse_ini_config(tmp_path):
path = tmp_path / "test.ini"
path.write_text("[app:main]\n"
"# comment = ignored\n"
"ckan.site_id = default\n"
"sqlalchemy.url=postgresql://user:pass@host/db?a=b\n"
"no equals sign here\n")
opts = parse_ini_config(path)
assert opts == {
"ckan.site_id": "default",
"sqlalchemy.url": "postgresql://user:pass@host/db?a=b",
}


def test_get_ini_config_option(tmp_path):
path = tmp_path / "test.ini"
path.write_text("[app:main]\nckan.storage_path = /data\n")
assert get_ini_config_option("ckan.storage_path", path) == "/data"
with pytest.raises(ConfigOptionNotFoundError, match="ckan.site_id"):
get_ini_config_option("ckan.site_id", path)
91 changes: 91 additions & 0 deletions tests/test_rqjob.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from unittest import mock

import pytest

from dcor_shared import RQJob, rqjob_register


@pytest.fixture
def clean_rqjob_instances(monkeypatch):
monkeypatch.setattr(RQJob, "_instances", [])


def job_a(resource):
"""Run job A

More details
"""


def job_b(resource):
"""Run job B"""


def job_c(resource):
"""Run job C"""


@pytest.mark.usefixtures("clean_rqjob_instances")
def test_rqjob_register():
func = rqjob_register(ckanext="test_ext", queue="dcor-normal",
timeout=120)(job_a)
assert func is job_a
job, = RQJob._instances
assert job.method is job_a
assert job.name == "job_a"
assert job.title == "Run job A"
assert job.ckanext == "test_ext"
assert job.queue == "dcor-normal"
assert job.timeout == 120
assert job.depends_on == []
assert not job.at_front


@pytest.mark.usefixtures("clean_rqjob_instances")
def test_rqjob_get_all_job_methods_in_order():
# register in reverse order of dependencies
RQJob(job_c, ckanext="test_ext", depends_on=["job_b"])
RQJob(job_b, ckanext="test_ext", depends_on=["job_a"])
RQJob(job_a, ckanext="test_ext")
RQJob(job_a, ckanext="other_ext")
jobs = RQJob.get_all_job_methods_in_order(ckanext="test_ext")
assert [j.name for j in jobs] == ["job_a", "job_b", "job_c"]


@pytest.mark.usefixtures("clean_rqjob_instances")
def test_rqjob_get_all_job_methods_in_order_unmet_dependency():
RQJob(job_a, ckanext="test_ext")
RQJob(job_b, ckanext="test_ext", depends_on=["job_unknown"])
with pytest.raises(NotImplementedError, match="job_b"):
RQJob.get_all_job_methods_in_order(ckanext="test_ext")


@pytest.mark.usefixtures("clean_rqjob_instances")
def test_rqjob_enqueue_all_jobs():
RQJob(job_a, ckanext="test_ext", queue="dcor-short", at_front=True)
RQJob(job_b, ckanext="test_ext", timeout=10)
RQJob(job_c, ckanext="other_ext")
resource = {"package_id": "pkg", "position": 0}
with mock.patch("ckan.lib.jobs._connect"), \
mock.patch("rq.job.Job.exists", return_value=False), \
mock.patch("ckan.plugins.toolkit.enqueue_job") as enqueue_job:
RQJob.enqueue_all_jobs(resource, ckanext="test_ext")
assert enqueue_job.call_count == 2
call_a, call_b = enqueue_job.call_args_list
assert call_a.args == (job_a, [resource])
assert call_a.kwargs["title"] == "Run job A"
assert call_a.kwargs["queue"] == "dcor-short"
assert call_a.kwargs["rq_kwargs"] == {
"timeout": 60, "at_front": True, "job_id": "pkg_0_job_a"}
assert call_b.kwargs["rq_kwargs"] == {
"timeout": 10, "at_front": False, "job_id": "pkg_0_job_b"}


@pytest.mark.usefixtures("clean_rqjob_instances")
def test_rqjob_enqueue_job_exists():
job = RQJob(job_a, ckanext="test_ext")
with mock.patch("rq.job.Job.exists", return_value=True), \
mock.patch("ckan.plugins.toolkit.enqueue_job") as enqueue_job:
job.enqueue_job({"package_id": "pkg", "position": 0},
redis_connect=mock.MagicMock())
enqueue_job.assert_not_called()
31 changes: 28 additions & 3 deletions tests/test_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ def test_create_bucket_again():
assert bucket3 is not bucket, "new object"


def iter_buckets_keep_non_circle():
def test_iter_buckets_keep_non_circle():
bucket_prefix = get_ckan_config_option(
"dcor_object_store.bucket_name").format(organization_id="")
bucket_backup = f"{bucket_prefix}-backups"
bucket_backup = f"{bucket_prefix}backups"
s3.require_bucket(bucket_backup)
bucket_circle = f"{bucket_prefix}-13748aef-a5b5-a7b4-b86d-8a0c1ff49035"
bucket_circle = f"{bucket_prefix}13748aef-a5b5-a7b4-b86d-8a0c1ff49035"
s3.require_bucket(bucket_circle)

buckets_default = list(s3.iter_buckets())
Expand Down Expand Up @@ -602,3 +602,28 @@ def test_upload_wrong_sha256():
path=path,
sha256="INCORRECT-CHECKSUM",
private=False)


def test_iter_bucket_objects_no_such_bucket():
bucket_name = f"test-circle-{uuid.uuid4()}"
assert list(s3.iter_bucket_objects(bucket_name)) == []


def test_presigned_url_filename():
path = data_path / "calibration_beads_47.rtdc"
bucket_name = f"test-circle-{uuid.uuid4()}"
rid = str(uuid.uuid4())
object_name = f"resource/{rid[:3]}/{rid[3:6]}/{rid[6:]}"
s3.upload_file(
bucket_name=bucket_name,
object_name=object_name,
path=path,
sha256=sha256sum(path),
private=True)
ps_url = s3.create_presigned_url(bucket_name=bucket_name,
object_name=object_name,
filename="peter.rtdc")
response = requests.get(ps_url)
assert response.ok
assert response.headers["Content-Disposition"] == \
"attachment; filename = peter.rtdc"
26 changes: 25 additions & 1 deletion tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import requests

from dcor_shared.testing import (
make_dataset_via_s3, make_resource_via_s3, activate_dataset
make_dataset_via_s3, make_resource_via_s3, activate_dataset,
synchronous_enqueue_job
)
from dcor_shared import s3cc, sha256sum

Expand Down Expand Up @@ -73,3 +74,26 @@ def test_make_resource_via_s3_name(tmp_path):

res_dict = helpers.call_action("resource_show", id=rid)
assert res_dict["name"] == "peter.rtdc"


@pytest.mark.ckan_config('ckan.plugins', 'dcor_schemas')
@pytest.mark.usefixtures('clean_db', 'with_request_context')
def test_make_resource_via_s3_ret_dict():
ds_dict = make_dataset_via_s3(activate=False)
res_dict = make_resource_via_s3(
resource_path=data_path / "calibration_beads_47.rtdc",
organization_id=ds_dict["organization"]["id"],
dataset_id=ds_dict["id"],
ret_dict=True,
)
assert res_dict["package_id"] == ds_dict["id"]
assert res_dict["name"] == "calibration_beads_47.rtdc"
assert res_dict["s3_available"]


def test_synchronous_enqueue_job():
calls = []
synchronous_enqueue_job(lambda *args, **kwargs: calls.append(
(args, kwargs)), args=[1], kwargs={"a": 2})
synchronous_enqueue_job(lambda: calls.append("no args"))
assert calls == [((1,), {"a": 2}), "no args"]
36 changes: 36 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import pathlib

from dcor_shared import ckan, DC_MIME_TYPES, paths
from dcor_shared.dcinst import get_dc_instance

import pytest


def test_dc_mime_types():
assert DC_MIME_TYPES["RT-DC"] == ".rtdc"


def test_get_ckan_config_option_from_ini(monkeypatch, tmp_path):
ini = tmp_path / "ckan.ini"
ini.write_text("[app:main]\nckan.storage_path = /data/ckan\n"
"ckan.webassets.path = /data/webassets\n")
monkeypatch.setenv("CKAN_INI", str(ini))
# simulate a CKAN configuration that has not been loaded
monkeypatch.setattr("ckan.common.config", {})
assert paths.get_ckan_config_path() == ini
assert ckan.get_ckan_config_option("ckan.storage_path") == "/data/ckan"
assert paths.get_ckan_storage_path() == pathlib.Path("/data/ckan")
assert paths.get_ckan_webassets_path() == pathlib.Path("/data/webassets")


def test_get_ckan_config_path_default(monkeypatch):
monkeypatch.delenv("CKAN_INI", raising=False)
assert ckan.get_ckan_config_path() == pathlib.Path(
"/etc/ckan/default/ckan.ini")


def test_get_dc_instance_missing(monkeypatch):
monkeypatch.setattr("dcor_shared.s3cc.artifact_exists",
lambda rid: False)
with pytest.raises(ValueError, match="Could not find resource"):
get_dc_instance("6d2e6b14-6bf0-4c8b-8d2d-2e6f8f1b8f3a")
Loading