Skip to content

Commit

Permalink
Convert most of the unittest-based tests to plain assert or `pytest…
Browse files Browse the repository at this point in the history
….raises`
  • Loading branch information
ialarmedalien committed Dec 22, 2023
1 parent ecf0c31 commit 9c2ec3d
Show file tree
Hide file tree
Showing 35 changed files with 1,327 additions and 1,513 deletions.
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 3 additions & 4 deletions src/biokbase/narrative/contents/narrativeio.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,14 @@ def narrative_exists(self, ref):
except WorkspaceError as err:
if err.http_code == 404:
return False
else:
raise
raise

def _validate_nar_type(self, t, ref):
if not t.startswith(NARRATIVE_TYPE):
err = "Expected a Narrative object"
if ref is not None:
err += " with reference {}".format(ref)
err += ", got a {}".format(t)
err += f" with reference {ref}"
err += f", got a {t}"
raise HTTPError(500, err)

def read_narrative(self, ref, content=True, include_metadata=True):
Expand Down
52 changes: 39 additions & 13 deletions src/biokbase/narrative/tests/job_test_constants.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
import copy
from typing import Any

from biokbase.narrative.jobs.job import TERMINAL_STATUSES

from .util import ConfigTests

config = ConfigTests()
TEST_JOBS = config.load_json_file(config.get("jobs", "ee2_job_test_data_file"))


def generate_error(job_id, err_type):
TEST_JOBS: dict[str, dict] = config.load_json_file(
config.get("jobs", "ee2_job_test_data_file")
)


def generate_error(job_id: str, err_type: str) -> str:
"""Given a job id and an error type, generate the appropriate error string.
:param job_id: job ID
:type job_id: str
:param err_type: error type
:type err_type: str
:raises KeyError: if the error type does not exist
:return: error string
:rtype: str
"""
user_id = None
status = None

Expand All @@ -32,11 +45,25 @@ def generate_error(job_id, err_type):
return error_strings[err_type]


def get_test_job(job_id):
def get_test_job(job_id: str) -> dict[str, Any]:
"""Given a job ID, fetch the appropriate job.
:param job_id: job ID
:type job_id: str
:return: job data
:rtype: dict[str, Any]
"""
return copy.deepcopy(TEST_JOBS[job_id])


def get_test_jobs(job_ids):
def get_test_jobs(job_ids: list[str]) -> dict[str, dict[str, Any]]:
"""Given a list of job IDs, fetch the appropriate jobs.
:param job_ids: list of job IDs
:type job_ids: list[str]
:return: dict of jobs keyed by job ID
:rtype: dict[str, dict[str, Any]]
"""
return {job_id: get_test_job(job_id) for job_id in job_ids}


Expand Down Expand Up @@ -93,16 +120,15 @@ def get_test_jobs(job_ids):
BATCH_RETRY_ERROR,
]

BATCH_PARENT_CHILDREN = [BATCH_PARENT] + BATCH_CHILDREN
BATCH_PARENT_CHILDREN = [BATCH_PARENT, *BATCH_CHILDREN]

JOB_TERMINAL_STATE = {
job_id: TEST_JOBS[job_id]["status"] in TERMINAL_STATUSES
for job_id in TEST_JOBS.keys()
JOB_TERMINAL_STATE: dict[str, bool] = {
job_id: TEST_JOBS[job_id]["status"] in TERMINAL_STATUSES for job_id in TEST_JOBS
}

TERMINAL_JOBS = []
ACTIVE_JOBS = []
REFRESH_STATE = {}
TERMINAL_JOBS: list[str] = []
ACTIVE_JOBS: list[str] = []
REFRESH_STATE: dict[str, bool] = {}
for key, value in JOB_TERMINAL_STATE.items():
if value:
TERMINAL_JOBS.append(key)
Expand Down
18 changes: 7 additions & 11 deletions src/biokbase/narrative/tests/narrative_mock/mockclients.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_my_function(self):
config = ConfigTests()
_job_state_data = TEST_JOBS

def __init__(self, client_name=None, token=None):
def __init__(self, client_name=None, token=None) -> None:
if token is not None:
assert isinstance(token, str)
self.client_name = client_name
Expand Down Expand Up @@ -326,9 +326,7 @@ def log_gen(log_params, total_lines=MAX_LOG_LINES):
lines = []
if skip < total_lines:
for i in range(total_lines - skip):
lines.append(
{"is_error": 0, "line": "This is line {}".format(i + skip)}
)
lines.append({"is_error": 0, "line": f"This is line {i + skip}"})
return {"last_line_number": max(total_lines, skip), "lines": lines}

if job_id == JOB_COMPLETED:
Expand All @@ -355,6 +353,7 @@ def log_gen(log_params, total_lines=MAX_LOG_LINES):
def sync_call(self, call, params):
if call == "NarrativeService.list_objects_with_sets":
return self._mock_ns_list_objects_with_sets(params)
return None

def _mock_ns_list_objects_with_sets(self, params):
"""
Expand All @@ -374,7 +373,7 @@ def _mock_ns_list_objects_with_sets(self, params):
if params.get("workspaces"):
ws_name = params["workspaces"][0]
dp_id = 999
dp_ref = "{}/{}".format(ws_id, dp_id)
dp_ref = f"{ws_id}/{dp_id}"

data = {
"data": [
Expand Down Expand Up @@ -511,10 +510,7 @@ def _mock_ns_list_objects_with_sets(self, params):
data["data"] = list(
filter(
lambda x: any(
[
x["object_info"][2].lower().startswith(t.lower())
for t in types
]
x["object_info"][2].lower().startswith(t.lower()) for t in types
),
data["data"],
)
Expand All @@ -535,7 +531,7 @@ def get_failing_mock_client(client_name, token=None):


class FailingMockClient:
def __init__(self, token=None):
def __init__(self, token=None) -> None:
pass

def check_workspace_jobs(self, params):
Expand Down Expand Up @@ -590,7 +586,7 @@ class assert_obj_method_called:
)
"""

def __init__(self, target, method_name, call_status=True):
def __init__(self, target, method_name, call_status=True) -> None:
self.target = target
self.method_name = method_name
self.call_status = call_status
Expand Down
2 changes: 1 addition & 1 deletion src/biokbase/narrative/tests/narrative_mock/mockcomm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class MockComm:
analyzed during the test.
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
"""Mock the init"""
self.messages = []

Expand Down
23 changes: 11 additions & 12 deletions src/biokbase/narrative/tests/test_app_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@
"""
import copy
import os
import re
from unittest import mock

import pytest
import re
from biokbase.narrative.common.url_config import URLS
from biokbase.workspace.client import Workspace

from biokbase.narrative.app_util import (
app_param,
check_tag,
Expand All @@ -19,10 +16,11 @@
map_outputs_from_state,
transform_param_value,
)

from biokbase.narrative.tests.conftest import narrative_vcr as vcr
from biokbase.narrative.common.url_config import URLS
from biokbase.narrative.tests import util
from biokbase.narrative.tests.conftest import narrative_vcr as vcr
from biokbase.narrative.upa import is_upa
from biokbase.workspace.client import Workspace

config = util.ConfigTests()
user_name = config.get("users", "test_user")
Expand Down Expand Up @@ -74,7 +72,7 @@ def set_ws_name(ws_name):
]


@pytest.mark.parametrize("result,path,expected", get_result_sub_path_cases)
@pytest.mark.parametrize(("result", "path", "expected"), get_result_sub_path_cases)
def test_get_result_sub_path(result, path, expected):
assert get_result_sub_path(result, path) == expected

Expand Down Expand Up @@ -275,7 +273,7 @@ def test_map_outputs_from_state_bad_spec(workspace_name):
]


@pytest.mark.parametrize("field_type,spec_add,expect_add", app_param_cases)
@pytest.mark.parametrize(("field_type", "spec_add", "expect_add"), app_param_cases)
def test_app_param(field_type, spec_add, expect_add):
spec_param = copy.deepcopy(base_app_param)
expected = copy.deepcopy(base_expect)
Expand Down Expand Up @@ -307,7 +305,8 @@ def test_app_param(field_type, spec_add, expect_add):


@pytest.mark.parametrize(
"transform_type,value,spec_param,expected", transform_param_value_simple_cases
("transform_type", "value", "spec_param", "expected"),
transform_param_value_simple_cases,
)
def test_transform_param_value_simple(transform_type, value, spec_param, expected):
assert transform_param_value(transform_type, value, spec_param) == expected
Expand All @@ -328,7 +327,7 @@ def test_transform_param_value_fail():
]


@pytest.mark.parametrize("value,expected", textsubdata_cases)
@pytest.mark.parametrize(("value", "expected"), textsubdata_cases)
def test_transform_param_value_textsubdata(value, expected):
spec = {"type": "textsubdata"}
assert transform_param_value(None, value, spec) == expected
Expand Down Expand Up @@ -506,7 +505,7 @@ def get_workspace(_):


class RefChainWorkspace:
def __init__(self):
def __init__(self) -> None:
pass

def get_object_info3(self, params):
Expand Down Expand Up @@ -568,7 +567,7 @@ def get_ref_path_mock_ws(name="workspace"):
)
@mock.patch("biokbase.narrative.app_util.clients.get", get_ref_path_mock_ws)
def test_transform_param_value_upa_path(tf_type):
upa_path = f"69375/2/2;67729/2/2"
upa_path = "69375/2/2;67729/2/2"
assert transform_param_value(tf_type, upa_path, None) == upa_path


Expand Down
23 changes: 13 additions & 10 deletions src/biokbase/narrative/tests/test_appeditor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import unittest

import pytest
from biokbase.narrative.appeditor import generate_app_cell

from .util import ConfigTests
Expand All @@ -22,24 +23,26 @@ def setUpClass(cls):

def test_gen_app_cell_post_validation(self):
js = generate_app_cell(validated_spec=self.specs_list[0])
self.assertIsNotNone(js)
assert js is not None

def test_gen_app_cell_pre_valid(self):
js = generate_app_cell(
spec_tuple=(json.dumps(self.spec_json), self.display_yaml)
)
self.assertIsNotNone(js)
self.assertIsNotNone(js.data)
self.assertIn(
"A description string, with &quot;quoted&quot; values, shouldn&apos;t fail.",
js.data,
assert js is not None
assert js.data is not None
assert (
"A description string, with &quot;quoted&quot; values, shouldn&apos;t fail."
in js.data
)
self.assertIn("Test Simple Inputs with &quot;quotes&quot;", js.data)
self.assertIn("A simple test spec with a single &apos;input&apos;.", js.data)
assert "Test Simple Inputs with &quot;quotes&quot;" in js.data
assert "A simple test spec with a single &apos;input&apos;." in js.data

def test_gen_app_cell_fail_validation(self):
with self.assertRaisesRegexp(
with pytest.raises(
Exception,
re.escape("Can't find sub-node [categories] within path [/] in spec.json"),
match=re.escape(
"Can't find sub-node [categories] within path [/] in spec.json"
),
):
generate_app_cell(spec_tuple=("{}", self.display_yaml))
Loading

0 comments on commit 9c2ec3d

Please sign in to comment.