diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 7e50dc2..71c9425 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -4,6 +4,7 @@ name: Run all python tests on: + workflow_dispatch: push: branches: [ master, next-minor-release ] pull_request: @@ -12,31 +13,29 @@ on: jobs: lint: name: Linting using flake8 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 with: - python-version: "3.9" + python-version: "3.12" + - name: Install flake8 + run: python -m pip install flake8 - name: Run flake8 - uses: julianwachholz/flake8-action@v2 - with: - checkName: "Python Lint" - path: . - config: flake8.ini - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: python -m flake8 --config flake8.ini . pytest: needs: lint runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: - os: [ ubuntu-latest, macos-latest ] + # Python 3.8/3.9 are unavailable on Ubuntu 26.04 and macOS arm64. + os: [ ubuntu-24.04, macos-15-intel ] python-version: [ '3.8','3.9','3.10','3.11','3.12','3.13' ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - name: Install dependencies @@ -57,12 +56,13 @@ jobs: needs: lint runs-on: windows-latest strategy: + fail-fast: false matrix: python-version: [ '3.8','3.9','3.10','3.11','3.12','3.13' ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - name: Install dependencies diff --git a/AnnotatorCore.py b/AnnotatorCore.py index 2cf33d5..e0e78c6 100755 --- a/AnnotatorCore.py +++ b/AnnotatorCore.py @@ -38,6 +38,14 @@ oncokb_api_bearer_token = "" +ONCOTREE_API_URL = "https://oncotree.mskcc.org/api/tumorTypes" + +# OncoKB also accepts these names (and their underscore-separated enum names). +SPECIAL_TUMOR_TYPES = ( + 'All Tumors', 'All Solid Tumors', 'All Liquid Tumors', 'Germline Disposition', + 'Other Tumor Types', 'Other Solid Tumor Types', 'Other Liquid Tumor Types', +) + # 'U', which no longer has any effect in python 3. 3.11 completely removed the option. # It will throw error if we don't do condition check. # https://stackoverflow.com/questions/56791545/what-is-the-non-deprecated-version-of-open-u-mode @@ -370,6 +378,99 @@ def makeoncokbgetrequest(url): return requests_retry_session(allowed_methods=["HEAD", "GET"]).get(url, headers=headers, timeout=REQUEST_TIMEOUT) +class TumorTypeValidationError(ValueError): + pass + + +def normalize_tumor_type(tumor_type): + return tumor_type.strip() if tumor_type is not None else '' + + +def validate_tumor_types(input_file, default_cancer_type, cancer_type_map, cna_format=None): + """Check supplied tumor types before any annotation or output-file writes.""" + supplied = {} + + def add(tumor_type, source): + tumor_type = normalize_tumor_type(tumor_type) + if tumor_type: + supplied.setdefault(tumor_type, source) + + add(default_cancer_type, '-t') + for sample, tumor_type in cancer_type_map.items(): + if not sampleidsfilter or sample in sampleidsfilter: + add(tumor_type, 'clinical data for sample %s' % sample) + + # GISTIC columns contain samples and numeric calls, not per-row tumor types. + if cna_format != CNA_FILE_FORMAT_GISTIC: + with open(input_file, DEFAULT_READ_FILE_MODE) as infile: + reader = csv.reader(infile, delimiter='\t') + headers = readheaders(reader) + cancer_index = geIndexOfHeader(headers, CANCER_TYPE_HEADERS) + sample_index = geIndexOfHeader(headers, SAMPLE_HEADERS) + if cancer_index >= 0: + for row in reader: + if not row: + continue + sample = row[sample_index] if 0 <= sample_index < len(row) else None + if sampleidsfilter and sample not in sampleidsfilter: + continue + if sample in cancer_type_map: + continue # Clinical data overrides the tumor type in the input row. + if cancer_index >= len(row): + raise TumorTypeValidationError('Missing tumor-type column at input line %s' % reader.line_num) + add(get_cell_content(row, cancer_index), 'input line %s' % reader.line_num) + + if not supplied: + return + + try: + response = makeoncokbgetrequest(oncokb_annotation_api_url + '/info') + response.raise_for_status() + info = response.json() + except (requests.RequestException, ValueError) as error: + raise TumorTypeValidationError( + 'Cannot validate tumor types: unable to load OncoKB /info. Check the server, token and connection.' + ) from error + version = info.get('oncoTreeVersion') if isinstance(info, dict) else None + if not isinstance(version, str) or not version.strip(): + raise TumorTypeValidationError('Cannot validate tumor types: OncoKB /info did not report oncoTreeVersion.') + + try: + # Do not forward the OncoKB Authorization header to the OncoTree service. + response = requests_retry_session().get( + ONCOTREE_API_URL, params={'version': version, 'flat': 'true'}, timeout=REQUEST_TIMEOUT) + response.raise_for_status() + tumor_types = response.json() + except (requests.RequestException, ValueError) as error: + raise TumorTypeValidationError( + 'Cannot validate tumor types: unable to load OncoTree version %s. Check the connection.' % version + ) from error + + if not isinstance(tumor_types, list) or not tumor_types: + raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree response for %s.' % version) + accepted = set() + for tumor_type in tumor_types: + if not isinstance(tumor_type, dict): + raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree entry for %s.' % version) + if tumor_type.get('level') == 0: + continue # The ontology root is not an OncoKB tumor-type code. + values = [tumor_type.get(field) for field in ('code', 'name', 'mainType')] + names = [value.lower() for value in values if isinstance(value, str) and value.strip()] + if not names: + raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree entry for %s.' % version) + accepted.update(names) + if not accepted: + raise TumorTypeValidationError('Cannot validate tumor types: empty OncoTree response for %s.' % version) + for tumor_type in SPECIAL_TUMOR_TYPES: + accepted.update((tumor_type.lower(), tumor_type.replace(' ', '_').lower())) + + for tumor_type, source in supplied.items(): + if tumor_type.lower() not in accepted: + raise TumorTypeValidationError( + "Unknown tumor type %r in %s (OncoTree %s). Use a code, name or main type supported by this release." + % (tumor_type, source, version)) + + _3dhotspots = None @@ -451,6 +552,7 @@ def get_tumor_type_from_row(row, row_index, defaultCancerType, icancertype, canc cancertype = row_cancer_type if sample in cancerTypeMap: cancertype = cancerTypeMap[sample] + cancertype = normalize_tumor_type(cancertype) if cancertype == "": log.info( "Cancer type for the sample should be defined for a more accurate result. \tLine %s" % (row_index)) @@ -1423,14 +1525,14 @@ def process_gistic_data(outf, gistic_data_file, defaultCancerType, cancerTypeMap continue cna_type = get_cna(row[headers[rawsample]], annotate_gain_loss) if cna_type is not None: - cancer_type = defaultCancerType + cancer_type = normalize_tumor_type(defaultCancerType) sample = rawsample if sampleidsfilter and sample not in sampleidsfilter: continue if sample in cancerTypeMap: - cancer_type = cancerTypeMap[sample] + cancer_type = normalize_tumor_type(cancerTypeMap[sample]) rows.append([sample, cancer_type, hugo, cna_type]) queries.append(CNAQuery(hugo, cna_type, cancer_type)) diff --git a/CnaAnnotator.py b/CnaAnnotator.py index 76aec6a..b4e808f 100755 --- a/CnaAnnotator.py +++ b/CnaAnnotator.py @@ -9,6 +9,7 @@ from AnnotatorCore import setoncokbapitoken from AnnotatorCore import readCancerTypes from AnnotatorCore import validate_oncokb_token +from AnnotatorCore import validate_tumor_types, TumorTypeValidationError from AnnotatorCore import process_cna_data from AnnotatorCore import CNA_FILE_FORMAT_GISTIC @@ -31,6 +32,8 @@ def main(argv): ' 1) ONCOTREE_CODE in clinical data file\n' ' 2) ONCOTREE_CODE exist in MAF\n' ' 3) default tumor type (-t)\n' + 'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n' + 'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n' ' We do not annotate Gain and Loss by default, add -z to include the analysis. See https://github.com/oncokb/oncokb-annotator/issues/51 for more information.\n' ' Default OncoKB base url is https://www.oncokb.org' ) @@ -59,6 +62,12 @@ def main(argv): validate_oncokb_token() + try: + validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap, argv.cna_file_format.lower()) + except TumorTypeValidationError as error: + log.error(str(error)) + sys.exit(2) + log.info('annotating %s ...' % argv.input_file) process_cna_data(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.include_descriptions, argv.annotate_gain_loss, argv.cna_file_format.lower()) diff --git a/FusionAnnotator.py b/FusionAnnotator.py index 6982c82..c438962 100755 --- a/FusionAnnotator.py +++ b/FusionAnnotator.py @@ -10,6 +10,7 @@ from AnnotatorCore import setoncokbapitoken from AnnotatorCore import readCancerTypes from AnnotatorCore import validate_oncokb_token +from AnnotatorCore import validate_tumor_types, TumorTypeValidationError from AnnotatorCore import process_fusion logging.basicConfig(level=logging.INFO) @@ -37,6 +38,8 @@ def main(argv): ' 1) ONCOTREE_CODE in clinical data file\n' ' 2) ONCOTREE_CODE exist in Fusion\n' ' 3) default tumor type (-t)\n' + 'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n' + 'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n' ' Default OncoKB base url is https://www.oncokb.org' ) sys.exit() @@ -66,6 +69,12 @@ def main(argv): validate_oncokb_token() + try: + validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap) + except TumorTypeValidationError as error: + log.error(str(error)) + sys.exit(2) + log.info('annotating %s ...' % argv.input_file) process_fusion(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.structural_variant_name_format, argv.include_descriptions) diff --git a/MafAnnotator.py b/MafAnnotator.py index 4de08be..cc5328d 100755 --- a/MafAnnotator.py +++ b/MafAnnotator.py @@ -10,6 +10,7 @@ from AnnotatorCore import setoncokbapitoken from AnnotatorCore import readCancerTypes from AnnotatorCore import validate_oncokb_token +from AnnotatorCore import validate_tumor_types, TumorTypeValidationError from AnnotatorCore import processalterationevents from AnnotatorCore import QueryType from AnnotatorCore import ReferenceGenome @@ -54,6 +55,8 @@ def main(argv): ' 1) ONCOTREE_CODE in clinical data file\n' ' 2) ONCOTREE_CODE exist in MAF\n' ' 3) default tumor type (-t)\n' + 'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n' + 'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n' 'Query type only allows the following values (case-insensitive):\n' ' - HGVSp_Short\n' ' It reads from column HGVSp_Short or Alteration\n' @@ -121,6 +124,12 @@ def main(argv): validate_oncokb_token() + try: + validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap) + except TumorTypeValidationError as error: + log.error(str(error)) + sys.exit(2) + processalterationevents(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.annotate_hotspots, user_input_query_type, default_reference_genome, argv.include_descriptions) diff --git a/README.md b/README.md index 8bc8859..6ff8311 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,30 @@ pip install -r requirements/common.txt -r requirements/pip2.7.txt ## Usage Example input files are under [data](data). An example script is here: [example.sh](example.sh) +### Tumor-type validation + +`MafAnnotator.py`, `CnaAnnotator.py`, `FusionAnnotator.py` and `StructuralVariantAnnotator.py` +validate tumor types before sending annotation requests or creating/overwriting the output file. +They accept OncoTree codes, names and main types case-insensitively, including codes containing +punctuation such as `MDS/MPN`. Surrounding whitespace is removed from the type sent to OncoKB. +OncoKB's special tumor types (for example, `All Solid Tumors` or `ALL_SOLID_TUMORS`) are also accepted. + +- A nonempty default supplied with `-t` is checked. +- Nonempty clinical-file types are checked for samples included by `-s`, or all samples if no filter is specified. +- Input-row types are checked for included samples unless clinical data overrides them. +- The existing priority remains clinical data, then the input row, then `-t`. An omitted/empty tumor type remains optional. + GISTIC input uses the clinical file or `-t`, because its columns contain samples rather than tumor types. + +Validation uses `oncoTreeVersion` from the selected OncoKB server's `/api/v1/info` endpoint and +downloads that release from `https://oncotree.mskcc.org/api/tumorTypes`. It does not use the latest +ontology release implicitly or forward the OncoKB bearer token to OncoTree. Unknown types, +missing version information and unavailable/malformed metadata stop the command with exit status 2 +and an error identifying the source or metadata problem. A custom server supplied with `-u` must +report an OncoTree version available from that service. + +Run `python -m pytest` for the test suite. Tumor-type tests use a local mock HTTP server and synthetic +input files; they do not require an OncoKB token. Existing live-annotation tests still require one. + ### MAF Annotates variants in MAF(https://docs.gdc.cancer.gov/Data/File_Formats/MAF_Format/) with OncoKB™ annotation. Supports both python2 and python3. Get more details on the command line using `python MafAnnotator.py -h`. diff --git a/StructuralVariantAnnotator.py b/StructuralVariantAnnotator.py index af1858e..69a91f8 100755 --- a/StructuralVariantAnnotator.py +++ b/StructuralVariantAnnotator.py @@ -10,6 +10,7 @@ from AnnotatorCore import setoncokbapitoken from AnnotatorCore import readCancerTypes from AnnotatorCore import validate_oncokb_token +from AnnotatorCore import validate_tumor_types, TumorTypeValidationError from AnnotatorCore import process_sv logging.basicConfig(level=logging.INFO) @@ -36,6 +37,8 @@ def main(argv): ' 1) ONCOTREE_CODE in clinical data file\n' ' 2) ONCOTREE_CODE exist in structural variant\n' ' 3) default tumor type (-t)\n' + 'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n' + 'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n' ' Default OncoKB base url is https://www.oncokb.org' ) sys.exit() @@ -65,6 +68,12 @@ def main(argv): validate_oncokb_token() + try: + validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap) + except TumorTypeValidationError as error: + log.error(str(error)) + sys.exit(2) + log.info('annotating %s ...' % argv.input_file) process_sv(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.include_descriptions) diff --git a/test_TumorTypeValidation.py b/test_TumorTypeValidation.py new file mode 100644 index 0000000..41e11be --- /dev/null +++ b/test_TumorTypeValidation.py @@ -0,0 +1,266 @@ +"""Exercise the CLI, files and HTTP requests without an OncoKB token.""" + +import csv +import json +import runpy +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import pytest +import requests + +import AnnotatorCore as core + + +TUMOR_TYPES = [ + {'code': 'LUAD', 'name': 'Lung Adenocarcinoma', 'mainType': 'Non-Small Cell Lung Cancer'}, + {'code': 'BRCA', 'name': 'Invasive Breast Carcinoma', 'mainType': 'Breast Cancer'}, + {'code': 'MDS/MPN', 'name': 'Myelodysplastic/Myeloproliferative Neoplasms', + 'mainType': 'Myeloid Neoplasm'}, + {'code': 'ICPN', 'name': 'Intracholecystic Papillary Neoplasm', 'mainType': 'Biliary Cancer'}, + {'code': 'IPN', 'name': 'Intraductal Papillary Neoplasm of the Bile Duct', 'mainType': 'Biliary Cancer'}, + {'code': 'MBLNWS', 'name': 'Medulloblastoma, Non-WNT, Non-SHH', 'mainType': 'Embryonal Tumor'}, + {'code': 'PANEC', 'name': 'Pancreatic Neuroendocrine Carcinoma', 'mainType': 'Pancreatic Cancer'}, +] + +FORMATS = { + 'maf': ('MafAnnotator.py', [], ['Hugo_Symbol', 'Tumor_Sample_Barcode', 'HGVSp_Short'], + ['BRAF', 'S1', 'p.V600E']), + 'cna': ('CnaAnnotator.py', ['-f', 'individual'], + ['Hugo_Symbol', 'Tumor_Sample_Barcode', 'Copy_Number_Alteration'], ['BRAF', 'S1', '2']), + 'gistic': ('CnaAnnotator.py', [], ['Hugo_Symbol', 'S1'], ['BRAF', '2']), + 'fusion': ('FusionAnnotator.py', [], ['Tumor_Sample_Barcode', 'Fusion'], ['S1', 'BRAF-RAF1']), + 'sv': ('StructuralVariantAnnotator.py', [], + ['Tumor_Sample_Barcode', 'GeneA', 'GeneB', 'Sv_Type'], ['S1', 'BRAF', 'RAF1', 'FUSION']), +} + + +@pytest.fixture +def api(monkeypatch): + state = {'calls': [], 'info': {'oncoTreeVersion': 'oncotree_test'}, 'types': TUMOR_TYPES, + 'tree_status': 200, 'info_status': 200} + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def respond(self, status, body): + self.send_response(status) + self.send_header('Content-Type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps(body).encode()) + + def do_GET(self): + url = urlsplit(self.path) + state['calls'].append(('GET', url.path, parse_qs(url.query), self.headers.get('Authorization'))) + if url.path == '/api/v1/info': + self.respond(state['info_status'], state['info']) + elif url.path == '/oncotree': + self.respond(state['tree_status'], state['types']) + else: + self.respond(404, {}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers['Content-Length']))) + state['calls'].append(('POST', self.path, body, self.headers.get('Authorization'))) + self.respond(200, [{'geneExist': True, 'variantExist': True, 'oncogenic': 'Unknown'} for _ in body]) + + server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': 0.01}, daemon=True) + thread.start() + state['url'] = 'http://127.0.0.1:%s' % server.server_port + monkeypatch.setattr(core, 'ONCOTREE_API_URL', state['url'] + '/oncotree', raising=False) + for name in ['oncokb_api_url', 'oncokb_annotation_api_url', 'oncokb_api_bearer_token', 'sampleidsfilter']: + monkeypatch.setattr(core, name, getattr(core, name)) + core.sampleidsfilter = None + try: + yield state + finally: + server.shutdown() + thread.join() + server.server_close() + + +def run_cli(kind, tmp_path, monkeypatch, api, default='', clinical=None, row_type=None, extra_rows=None, + sample_filter=None, row_header='ONCOTREE_CODE'): + script, options, headers, row = FORMATS[kind] + headers, row = list(headers), list(row) + if row_type is not None: + headers.append(row_header) + row.append(row_type) + input_file, output_file = tmp_path / 'input.tsv', tmp_path / 'output.tsv' + with input_file.open('w', newline='') as handle: + writer = csv.writer(handle, delimiter='\t') + writer.writerows([headers, row] + (extra_rows or [])) + argv = [script, '-i', str(input_file), '-o', str(output_file), '-u', api['url'], '-b', 'test-token'] + options + if default: + argv.extend(['-t', default]) + if clinical is not None: + clinical_file = tmp_path / 'clinical.tsv' + clinical_types = clinical if isinstance(clinical, dict) else {'S1': clinical} + with clinical_file.open('w', newline='') as handle: + writer = csv.writer(handle, delimiter='\t') + writer.writerow(['SAMPLE_ID', 'ONCOTREE_CODE']) + writer.writerows(clinical_types.items()) + argv.extend(['-c', str(clinical_file)]) + if sample_filter is not None: + filter_file = tmp_path / 'samples.txt' + filter_file.write_text('\n'.join(sample_filter)) + argv.extend(['-s', str(filter_file)]) + monkeypatch.setattr(sys, 'argv', argv) + runpy.run_path(str(Path(__file__).parent / script), run_name='__main__') + return output_file + + +@pytest.mark.parametrize('source,kind', [ + (source, kind) for source in ['default', 'clinical', 'row'] for kind in FORMATS + if not (kind == 'gistic' and source == 'row') +]) +def test_cli_rejects_unknown_type_before_annotation_or_output(kind, source, tmp_path, monkeypatch, api, caplog): + kwargs = {source if source != 'row' else 'row_type': 'BLAH'} + with pytest.raises(SystemExit) as error: + run_cli(kind, tmp_path, monkeypatch, api, **kwargs) + assert error.value.code == 2 + assert 'BLAH' in caplog.text + assert not (tmp_path / 'output.tsv').exists() + assert not any(call[0] == 'POST' for call in api['calls']) + + +@pytest.mark.parametrize('kind', FORMATS) +def test_cli_accepts_valid_types_and_preserves_clinical_precedence(kind, tmp_path, monkeypatch, api): + kwargs = {'default': 'lung adenocarcinoma', 'clinical': ' MDS/MPN '} + if kind != 'gistic': + kwargs['row_type'] = 'BRCA' + output = run_cli(kind, tmp_path, monkeypatch, api, **kwargs) + with output.open() as handle: + rows = list(csv.DictReader(handle, delimiter='\t')) + assert len(rows) == 1 + assert rows[0]['ANNOTATED'] == 'True' + posts = [call for call in api['calls'] if call[0] == 'POST'] + assert posts and all(query['tumorType'] == 'MDS/MPN' for call in posts for query in call[2]) + tree_calls = [call for call in api['calls'] if call[1] == '/oncotree'] + assert len(tree_calls) == 1 + assert tree_calls[0][2] == {'version': ['oncotree_test'], 'flat': ['true']} + assert tree_calls[0][3] is None # Never send the OncoKB bearer token to OncoTree. + assert all(call[3] == 'Bearer test-token' for call in api['calls'] if call[1].startswith('/api/')) + + +@pytest.mark.parametrize('tumor_type', [ + 'LUAD', 'luad', 'Lung Adenocarcinoma', 'Non-Small Cell Lung Cancer', 'MDS/MPN', + 'ICPN', 'IPN', 'MBLNWS', 'PANEC', 'All Solid Tumors', 'ALL_SOLID_TUMORS', +]) +def test_cli_accepts_codes_names_main_types_and_special_types(tumor_type, tmp_path, monkeypatch, api): + output = run_cli('maf', tmp_path, monkeypatch, api, default=tumor_type) + assert output.exists() + + +def test_late_invalid_row_preserves_existing_output(tmp_path, monkeypatch, api): + output = tmp_path / 'output.tsv' + output.write_text('previous complete result\n') + extra_rows = [['BRAF', 'S1', 'p.V600E', 'LUAD']] * 205 + [['BRAF', 'S1', 'p.V600E', 'BLAH']] + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, row_type='LUAD', extra_rows=extra_rows) + assert error.value.code == 2 + assert output.read_text() == 'previous complete result\n' + assert not any(call[0] == 'POST' for call in api['calls']) + + +@pytest.mark.parametrize('info', [{}, {'oncoTreeVersion': None}, {'oncoTreeVersion': 2025}, []]) +def test_missing_version_stops_before_output(info, tmp_path, monkeypatch, api, caplog): + api['info'] = info + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, default='LUAD') + assert error.value.code == 2 + assert 'oncoTreeVersion' in caplog.text + assert not (tmp_path / 'output.tsv').exists() + + +@pytest.mark.parametrize('payload', [None, [], {}, [{'unexpected': 'LUAD'}], ['LUAD']]) +def test_malformed_metadata_stops_before_output(payload, tmp_path, monkeypatch, api, caplog): + api['types'] = payload + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, default='LUAD') + assert error.value.code == 2 + assert 'OncoTree' in caplog.text + assert not (tmp_path / 'output.tsv').exists() + + +@pytest.mark.parametrize('service', ['info', 'tree']) +def test_metadata_http_error_stops_before_output(service, tmp_path, monkeypatch, api, caplog): + api[service + '_status'] = 403 + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, default='LUAD') + assert error.value.code == 2 + assert 'validate' in caplog.text + assert 'test-token' not in caplog.text + assert not (tmp_path / 'output.tsv').exists() + + +@pytest.mark.parametrize('tumor_type', ['', ' ']) +def test_missing_optional_tumor_type_needs_no_metadata(tumor_type, tmp_path, monkeypatch, api): + output = run_cli('maf', tmp_path, monkeypatch, api, default=tumor_type) + assert output.exists() + assert not any(call[0] == 'GET' for call in api['calls']) + + +@pytest.mark.parametrize('kind', [kind for kind in FORMATS if kind != 'gistic']) +def test_clinical_type_overrides_unrecognized_row_type(kind, tmp_path, monkeypatch, api): + output = run_cli(kind, tmp_path, monkeypatch, api, clinical='LUAD', row_type='BLAH') + assert output.exists() + assert all(query['tumorType'] == 'LUAD' for call in api['calls'] if call[0] == 'POST' for query in call[2]) + + +def test_sample_filter_excludes_invalid_row_type(tmp_path, monkeypatch, api): + output = run_cli('maf', tmp_path, monkeypatch, api, row_type='LUAD', sample_filter=['S1'], + extra_rows=[['BRAF', 'S2', 'p.V600E', 'BLAH']]) + with output.open() as handle: + rows = list(csv.DictReader(handle, delimiter='\t')) + assert len(rows) == 1 + assert rows[0]['Tumor_Sample_Barcode'] == 'S1' + + +def test_sample_filter_excludes_invalid_clinical_type(tmp_path, monkeypatch, api): + output = run_cli('maf', tmp_path, monkeypatch, api, clinical={'S1': 'LUAD', 'S2': 'BLAH'}, sample_filter=['S1']) + assert output.exists() + + +@pytest.mark.parametrize('kind', [kind for kind in FORMATS if kind != 'gistic']) +@pytest.mark.parametrize('header', ['ONCOTREE_CODE', 'CANCER_TYPE']) +def test_row_type_overrides_default(kind, header, tmp_path, monkeypatch, api): + output = run_cli(kind, tmp_path, monkeypatch, api, default='LUAD', row_type=' PANEC ', row_header=header) + assert output.exists() + assert all(query['tumorType'] == 'PANEC' for call in api['calls'] if call[0] == 'POST' for query in call[2]) + + +def test_ontology_root_is_not_a_tumor_type(tmp_path, monkeypatch, api): + api['types'] = TUMOR_TYPES + [{'code': 'TISSUE', 'name': 'Tissue', 'mainType': 'Tissue', 'level': 0}] + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, default='TISSUE') + assert error.value.code == 2 + + +@pytest.mark.parametrize('service', ['info', 'tree']) +def test_metadata_timeout_is_reported_without_output(service, tmp_path, monkeypatch, api, caplog): + original_session = core.requests_retry_session + + def retry_session(*args, **kwargs): + session = original_session(*args, **kwargs) + original_get = session.get + + def get(url, *get_args, **get_kwargs): + if (service == 'info' and url.endswith('/info')) or (service == 'tree' and url == core.ONCOTREE_API_URL): + raise requests.Timeout('metadata request timed out') + return original_get(url, *get_args, **get_kwargs) + + monkeypatch.setattr(session, 'get', get) + return session + + monkeypatch.setattr(core, 'requests_retry_session', retry_session) + with pytest.raises(SystemExit) as error: + run_cli('maf', tmp_path, monkeypatch, api, default='LUAD') + assert error.value.code == 2 + assert 'Cannot validate tumor types' in caplog.text + assert not (tmp_path / 'output.tsv').exists()