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
2 changes: 1 addition & 1 deletion .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9', '3.10', '3.11', '3.12']
python-version: ['3.11', '3.12', '3.13']

steps:
- uses: actions/checkout@v3
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/quick-pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
max-parallel: 4
matrix:
python-version: ['3.11']
python-version: ['3.13']

steps:
- uses: actions/checkout@v3
Expand Down
13 changes: 13 additions & 0 deletions pori_python/ipr/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@ def command_interface() -> None:
type=file_path,
help='TSV without header, with two columns: transcripts and flags (comma-separated list of flags eg "MANE"). If header is included, it will be skipped. Matching uses direct string comparison, so transcript identifiers must match exactly, including version numbers (e.g., if input variants use ENST00000390477.1, this file must also use ENST00000390477.1, not ENST00000390477).',
)
parser.add_argument(
'--state',
required=False,
choices=['ready', 'nonproduction'],
help="Status to create the report with if not default (ready). If 'nonproduction', the report will be created with state='nonproduction' in the uploaded report content.",
)
args = parser.parse_args()

with open(args.content, 'r') as fh:
Expand All @@ -213,6 +219,7 @@ def command_interface() -> None:
validate_json=args.validate_json,
ignore_extra_fields=args.ignore_extra_fields,
transcript_flags=args.transcript_flags,
state=args.state,
)


Expand Down Expand Up @@ -350,6 +357,7 @@ def ipr_report(
ignore_extra_fields: bool = False,
tmb_high: float = TMB_SIGNATURE_HIGH_THRESHOLD,
transcript_flags: str = '',
state: str | None = None,
) -> dict:
"""Run the matching and create the report JSON for upload to IPR.

Expand Down Expand Up @@ -380,6 +388,7 @@ def ipr_report(
allow_partial_matches: allow matches to statements where not all conditions are satisfied
tmb_high: mutation burden threshold/cutoff to qualify as 'high'
transcript_flags: path to a tsv file with two columns (no header) of transcript identifiers and flags to be added to any observed variants with matching transcript in the report upload. If header is included, it will be skipped. Matching uses direct string comparison, so transcript identifiers must match exactly, including version numbers (e.g., if input variants use ENST00000390477.1, this file must also use ENST00000390477.1, not ENST00000390477).
state: optional report state override ('ready' or 'nonproduction'). When supplied, overrides the state in content, including when uploading precreated report JSON. When omitted, preserves any state in content; if neither supplies a state, the server default ('ready') applies.
Returns:
ipr_conn.upload_report return dictionary
"""
Expand All @@ -398,6 +407,10 @@ def ipr_report(
else:
logger.warning('No ipr_url given')

if state:
# copy so the caller's content is not mutated
content = {**content, 'state': state}

# Verify upload permission before doing any expensive processing
if ipr_upload and ipr_conn:
ipr_conn.check_upload_permission(content['project'])
Expand Down
180 changes: 142 additions & 38 deletions tests/test_ipr/test_main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import json
import os
import pandas as pd
import pytest
import sys
from typing import Dict
from unittest.mock import MagicMock, patch

import pandas as pd
import pytest

from pori_python.ipr.connection import IprConnection
from pori_python.ipr.main import command_interface, load_transcript_flags
from pori_python.ipr.main import (
command_interface,
create_report,
ipr_report,
load_transcript_flags,
)
from pori_python.types import IprGene

from .constants import EXCLUDE_INTEGRATION_TESTS
Expand Down Expand Up @@ -52,8 +57,99 @@ def test_accepts_file_with_header(self, tmp_path) -> None:
]


class TestStateArgument:
"""Unit tests (no network) for the report state option"""

@staticmethod
def run_cli(tmp_path, extra_args: list[str]) -> MagicMock:
json_file = tmp_path / 'content.json'
json_file.write_text(json.dumps({'project': 'TEST'}))
argv = ['ipr', '--username', 'user', '--password', 'pass', '--content', str(json_file)]
with (
patch.object(sys, 'argv', [*argv, *extra_args]),
patch('pori_python.ipr.main.ipr_report') as mock_ipr_report,
):
command_interface()
return mock_ipr_report

@staticmethod
def upload_content_for(report_function, input_content=None, **kwargs) -> dict:
"""Run report_function up to the json upload step and return the uploaded content"""
with patch('pori_python.ipr.main.IprConnection') as mock_conn_class:
report_function(
username='user',
password='pass',
content=input_content if input_content is not None else {'project': 'TEST'},
ipr_url='http://fake.url.ca',
upload_json=True,
**kwargs,
)
mock_conn = mock_conn_class.return_value
assert mock_conn.upload_report.called
return mock_conn.upload_report.call_args[0][0]

def test_cli_passes_state_to_ipr_report(self, tmp_path) -> None:
mock_ipr_report = self.run_cli(tmp_path, ['--state', 'nonproduction'])

assert mock_ipr_report.call_args.kwargs['state'] == 'nonproduction'

def test_cli_state_not_set_by_default(self, tmp_path) -> None:
mock_ipr_report = self.run_cli(tmp_path, [])

assert mock_ipr_report.call_args.kwargs['state'] is None

def test_cli_rejects_invalid_state(self, tmp_path) -> None:
with pytest.raises(SystemExit):
self.run_cli(tmp_path, ['--state', 'bogus'])

@pytest.mark.parametrize('report_function', [ipr_report, create_report])
def test_state_arg_set_in_output_content(self, report_function) -> None:
content = self.upload_content_for(report_function, state='nonproduction')

assert content['state'] == 'nonproduction'

@pytest.mark.parametrize('report_function', [ipr_report, create_report])
def test_state_omitted_does_not_add_state(self, report_function) -> None:
content = self.upload_content_for(report_function)

assert 'state' not in content

@pytest.mark.parametrize('report_function', [ipr_report, create_report])
@pytest.mark.parametrize('input_state', ['ready', 'nonproduction'])
def test_state_omitted_preserves_input_state(self, report_function, input_state) -> None:
content = self.upload_content_for(
report_function, input_content={'project': 'TEST', 'state': input_state}
)

assert content['state'] == input_state

@pytest.mark.parametrize('report_function', [ipr_report, create_report])
def test_state_arg_overrides_input_state(self, report_function) -> None:
content = self.upload_content_for(
report_function,
input_content={'project': 'TEST', 'state': 'ready'},
state='nonproduction',
)

assert content['state'] == 'nonproduction'

def test_input_content_not_mutated(self) -> None:
original = {'project': 'TEST'}
with patch('pori_python.ipr.main.IprConnection'):
ipr_report(
username='user',
password='pass',
content=original,
ipr_url='http://fake.url.ca',
upload_json=True,
state='nonproduction',
)

assert 'state' not in original


@pytest.fixture(scope='module')
def report_upload_content(tmp_path_factory) -> Dict:
def report_upload_content(tmp_path_factory) -> dict:
mock = MagicMock()
json_file = tmp_path_factory.mktemp('inputs') / 'content.json'
json_file.write_text(
Expand Down Expand Up @@ -118,32 +214,36 @@ def side_effect_function(*args, **kwargs):
else:
return []

with patch.object(
sys,
'argv',
[
'ipr',
'--username',
os.environ.get('IPR_USER', os.environ['USER']),
'--password',
os.environ['IPR_PASS'],
'--ipr_url',
'http://fake.url.ca',
'--graphkb_username',
os.environ.get('GRAPHKB_USER', os.environ['USER']),
'--graphkb_password',
os.environ.get('GRAPHKB_PASS', os.environ['IPR_PASS']),
'--graphkb_url',
os.environ.get('GRAPHKB_URL', False),
'--content',
str(json_file),
'--therapeutics',
],
with (
patch.object(
sys,
'argv',
[
'ipr',
'--username',
os.environ.get('IPR_USER', os.environ['USER']),
'--password',
os.environ['IPR_PASS'],
'--ipr_url',
'http://fake.url.ca',
'--graphkb_username',
os.environ.get('GRAPHKB_USER', os.environ['USER']),
'--graphkb_password',
os.environ.get('GRAPHKB_PASS', os.environ['IPR_PASS']),
'--graphkb_url',
os.environ.get('GRAPHKB_URL', False),
'--content',
str(json_file),
'--therapeutics',
'--state',
'nonproduction',
],
),
patch.object(IprConnection, 'upload_report', new=mock),
):
with patch.object(IprConnection, 'upload_report', new=mock):
with patch.object(IprConnection, 'get_spec', return_value=get_test_spec()):
with patch.object(IprConnection, 'get', side_effect=side_effect_function):
command_interface()
with patch.object(IprConnection, 'get_spec', return_value=get_test_spec()):
with patch.object(IprConnection, 'get', side_effect=side_effect_function):
command_interface()

assert mock.called

Expand All @@ -153,7 +253,7 @@ def side_effect_function(*args, **kwargs):

@pytest.mark.skipif(EXCLUDE_INTEGRATION_TESTS, reason='excluding long running integration tests')
class TestCreateReport:
def test_main_sections_present(self, report_upload_content: Dict) -> None:
def test_main_sections_present(self, report_upload_content: dict) -> None:
sections = set(report_upload_content.keys())

for section in [
Expand All @@ -166,7 +266,11 @@ def test_main_sections_present(self, report_upload_content: Dict) -> None:
]:
assert section in sections

def test_kept_low_quality_fusion(self, report_upload_content: Dict) -> None:
def test_state_set(self, report_upload_content: dict) -> None:
# the fixture passes --state nonproduction on the command line
assert report_upload_content['state'] == 'nonproduction'

def test_kept_low_quality_fusion(self, report_upload_content: dict) -> None:
fusions = [(sv['gene1'], sv['gene2']) for sv in report_upload_content['structuralVariants']]
if (
EXCLUDE_BCGSC_TESTS
Expand All @@ -175,32 +279,32 @@ def test_kept_low_quality_fusion(self, report_upload_content: Dict) -> None:
else:
assert ('SARM1', 'SUZ12') in fusions

def test_pass_through_content_added(self, report_upload_content: Dict) -> None:
def test_pass_through_content_added(self, report_upload_content: dict) -> None:
# check the passthorough content was added
assert 'blargh' in report_upload_content

def test_found_fusion_partner_gene(self, report_upload_content: Dict) -> None:
def test_found_fusion_partner_gene(self, report_upload_content: dict) -> None:
genes = report_upload_content['genes']
# eg, A1BG
assert any([g.get('knownFusionPartner', False) for g in genes])

@pytest.mark.skipif(EXCLUDE_ONCOKB_TESTS, reason='excluding tests that depend on oncokb data')
def test_found_oncogene(self, report_upload_content: Dict) -> None:
def test_found_oncogene(self, report_upload_content: dict) -> None:
genes = report_upload_content['genes']
# eg, ZBTB20
assert any([g.get('oncogene', False) for g in genes])

@pytest.mark.skipif(EXCLUDE_ONCOKB_TESTS, reason='excluding tests that depend on oncokb data)')
def test_found_tumour_supressor(self, report_upload_content: Dict) -> None:
def test_found_tumour_supressor(self, report_upload_content: dict) -> None:
genes = report_upload_content['genes']
# eg, ZNRF3
assert any([g.get('tumourSuppressor', False) for g in genes])

def test_found_kb_statement_related_gene(self, report_upload_content: Dict) -> None:
def test_found_kb_statement_related_gene(self, report_upload_content: dict) -> None:
genes = report_upload_content['genes']
assert any([g.get('kbStatementRelated', False) for g in genes])

@pytest.mark.skipif(EXCLUDE_ONCOKB_TESTS, reason='excluding tests that depend on oncokb data')
def test_found_cancer_gene_list_match_gene(self, report_upload_content: Dict) -> None:
def test_found_cancer_gene_list_match_gene(self, report_upload_content: dict) -> None:
genes = report_upload_content['genes']
assert any([g.get('cancerGeneListMatch', False) for g in genes])
Loading
Loading