From 939f182c59af6f8445fa3b04dddb97afc6b0f931 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Mon, 5 Oct 2026 23:10:39 -0400 Subject: [PATCH 01/18] test: serve hgvs UTA lookups from a recorded cache in tests Add VRS_HGVS_CACHE_MODE/VRS_HGVS_CACHE_FILE to enable the hgvs data provider cache, default tests to run mode with tests/data/hgvs_cache.pkl, and add `make record-hgvs-cache` to re-record it against UTA and a seqrepo-rest-service. --- Makefile | 6 ++++ src/ga4gh/vrs/utils/hgvs_tools.py | 40 ++++++++++++++++++++-- tests/conftest.py | 10 ++++++ tests/data/hgvs_cache.pkl | Bin 0 -> 17169 bytes tests/extras/test_hgvs_tools.py | 53 +++++++++++++++++++++++++++++- 5 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 tests/data/hgvs_cache.pkl diff --git a/Makefile b/Makefile index fcf3502b..7edef708 100644 --- a/Makefile +++ b/Makefile @@ -128,6 +128,12 @@ cleanest: cleaner clean-cassettes: find ./tests -type f -path '*/cassettes/*.yaml' -print0 | ${XRM} +#=> record-hgvs-cache: re-record tests/data/hgvs_cache.pkl (needs UTA_DB_URL and a running seqrepo-rest-service at SEQREPO_REST_URL; VCR cassettes are not touched) +.PHONY: record-hgvs-cache +record-hgvs-cache: + rm -f tests/data/hgvs_cache.pkl + HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn pytest --disable-vcr + ## ## Copyright 2016 Source Code Committers diff --git a/src/ga4gh/vrs/utils/hgvs_tools.py b/src/ga4gh/vrs/utils/hgvs_tools.py index 42d81f86..027a9689 100644 --- a/src/ga4gh/vrs/utils/hgvs_tools.py +++ b/src/ga4gh/vrs/utils/hgvs_tools.py @@ -1,6 +1,8 @@ """Provide extra tools for working with hgvs expressions.""" +import functools import logging +import os import re import hgvs @@ -16,6 +18,21 @@ _logger = logging.getLogger(__name__) +HGVS_CACHE_MODES = ("learn", "run", "verify") + + +@functools.cache +def _connect_with_cache( + mode: str, cache_file: str +) -> hgvs.dataproviders.uta.UTA_postgresql: + """Return the data provider shared by every `HgvsTools` using this cache. + + Each data provider keeps its own in-memory copy of the cache file and, in learn + mode, rewrites the whole file after every miss, so separate providers writing the + same file would drop each other's entries. + """ + return hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) + class HgvsTools: """A convenience class that exposes only the tools needed by vrs-python for working with HGVS (Human Genome Variation Society) notation. @@ -34,10 +51,28 @@ class HgvsTools: def __init__(self, data_proxy: _DataProxy | None = None) -> None: """Initialize object. + The hgvs data provider (UTA) cache can be enabled with environment variables: + ``VRS_HGVS_CACHE_MODE`` (``learn``, ``run``, or ``verify``) and + ``VRS_HGVS_CACHE_FILE`` (path to the cache file). In ``run`` mode, lookups are + served only from the cache file and no UTA connection is made. + :param data_proxy: GA4GH data proxy instance """ self.parser = hgvs.parser.Parser() - self.uta_conn = hgvs.dataproviders.uta.connect() + cache_mode = os.environ.get("VRS_HGVS_CACHE_MODE") or None + cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") or None + if cache_mode: + if cache_mode not in HGVS_CACHE_MODES: + msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES}, got {cache_mode!r}" + raise ValueError(msg) + if not cache_file: + msg = "VRS_HGVS_CACHE_FILE must be set when VRS_HGVS_CACHE_MODE is set" + raise ValueError(msg) + self.uta_conn = _connect_with_cache(cache_mode, cache_file) + self._owns_uta_conn = False + else: + self.uta_conn = hgvs.dataproviders.uta.connect() + self._owns_uta_conn = True self.normalizer = hgvs.normalizer.Normalizer(self.uta_conn, validate=True) self.variant_mapper = hgvs.variantmapper.VariantMapper(self.uta_conn) self.data_proxy = data_proxy @@ -50,7 +85,8 @@ def close(self) -> None: self.normalizer = None self.variant_mapper = None self.data_proxy = None - if self.uta_conn is not None: + # A cache-backed data provider is shared with other instances; leave it open + if self.uta_conn is not None and self._owns_uta_conn: self.uta_conn.close() # convenience methods for hgvs parsing, normalization, and some mappings diff --git a/tests/conftest.py b/tests/conftest.py index 4c843539..8f407de1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,20 @@ import os +from pathlib import Path import pytest from biocommons.seqrepo import SeqRepo from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy +# Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a +# recorded cache by default, so tests don't need a UTA database or network access. To +# re-record, run `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and +# a seqrepo-rest-service running at SEQREPO_REST_URL. +os.environ.setdefault("VRS_HGVS_CACHE_MODE", "run") +os.environ.setdefault( + "VRS_HGVS_CACHE_FILE", str(Path(__file__).parent / "data" / "hgvs_cache.pkl") +) + def remove_request_headers(request): """Remove all headers from VCR request before recording.""" diff --git a/tests/data/hgvs_cache.pkl b/tests/data/hgvs_cache.pkl new file mode 100644 index 0000000000000000000000000000000000000000..5ee7e7eb3d3cdc0ea65efd766dfa8a6cf0e229ff GIT binary patch literal 17169 zcmeI43v?URoyH|gvTRFn5`#m4gp!oJ6UVY0KOm4ehIP2ZgpfG2C8UaD3twFv+sFzb zoA69qwlE|>R33#wfKUj9@P350bQ{|8Y|GMicY6xuQRr?9fj&6w0^PFTH+s$7aoTby z=d66z$@z_?|I9Ztzk6q7`(EjS;8)5!eD>G5nVHt1vhVESy52<3V5&Pkm>RC@Pi=_z zboa+uz9tc%4m;_w~s`o$zbhOBU3A{`$_D!1`>=v&mc)Ww=IBJ2|Z zQ31%1tg_c^&#fuPWQ&s=#oG4v4t}+FbavriM+g3Qbsix4mJd%1h+RM-x+@=DBkbZM zj$&nRC%(FnpH1&L&{6MU^xeg+WhCoE9wP2yXVyKCz#()& zFb}q1ZL;XnVy&{SeAUvrLc=5+X(Nz3Qdyllf@#7obrwrjZ9DeW*-r6j0{%n0=KFzF zz05=(i#0aJ>KoeXVj1+UgW0#z=fsn}iGg%7y(yj?IAhT6XyKm0p-rhoAG&Tlg$_S3 zoK9`%L8nLOw#E((Z$iDVp)PSwI@LX#vBJkEd(tZgH?mr>ZbPy^ogBc^!T#iM8qcl4 z)u8X*`$QG828Mf5$)R+{xXOG!ip|Wueq*b#(b#ERVHn18!!ph?o;6k)=NS*<-)emS z7@nDJj7L3bG#icP&QB$*isj3f$5zA|mShqaXI60ca)E4?Eq1DGm2C+t(lglKpXf>B zYQ%v?PEPeEQi)!k1~1K%>` zr@K?>crs%ItV%vk4D|9*&C$xRx}~gcEX2xW0R6C^^s<9~{b_67B(O@||B-kFI3e^_g;>te1@= zHc!4E*2n5%^%<*tc&ICoV;4`j*hlPM;q8upO~9Gi-qbJG%YnRyTnqcOPT_ZT zin2o23KY9m(A%{_j(&pEk`m_=&7Du;9QIqi5sT;KxCE?VQ*$#~Q11nWJB`-DhTrfR zK3sSrbmZ8mcx=kpC?c9-$7Yr-6IXmD>Jy1I!1W7~J~4SCaQx#-e1&dto;+V(ATN{` z$*m&<$uIn+j9h0bAKtWn-C#ejyqr%zUj+vexKHtd%U_s(#hz8gYZdpc?g4C8ZUqKY zSca`CT-SxmwZf{v!`#(cX+^S|w)%jWOZ$bK}j zxv)&UKWki6oI86QS~=FJxANE6%15x3r#M^rM!8eoByX0t$X#e;RZ_j6eS(ulys-OOYV_( z%X{R#kmN~{_qil#A*CcK07K@=fH>hKNO~PWPin5$B;80!M^e%pr=-2|QTa{zE%|Nv z7$kX;w2)Gg6oeu3wSWk(fTU{xNNQT3N!m$CQz&VoQ_>IQ6Y@#A*JLf z3_)fjB;q}A^aj9-O_y{FB^^achdL$gmv70plB9){lB5b4GPi`p z6N8Y{I%G?VHEMUHU6eG9l8$ytdS8AZ|0MrM{#kwqNuDI-^ZR@*Pg+hXd8&jYb7{Fa zY70F54zPj^^-Y?mTj^;!JuP&2Qek*d6+|UbMMQ`w0CS#fH3kKjIW4)A%vC{~d0n|k zUJP^J0&uI+JJ{DLZU)62;}mx=CDjrWh(m~p#GwGhd7{-}D7eIF$)zMN0&C`>VbQz| z;vN8S|7vK~y4-CvH6w8v||T#TDXvx53=z z+ebFHo91TI+%%`TV`yn1aV&8hv4~g&rwWHuNrzMw?xoT)LU#$=emyC~!s{t#} zrvD;+2gS{yxcN?TODX9@LJ$UV5@7-m=ZRL!P;iOUl1oY4SXeXnREjBG5Vs!~>6P^x zG&h&#W;)HSqNP)b&k&y_K1ZAez?>&rtwzCRPD?H&bK{`R?5`5LPKUX5YiKUkrvHF@ zC(X^Hx#>=G>u9Nm=p_=w8AKldbDnG^QE-{ll1s_lcxW?UtP*=6P0aqhZO-#k?_D%k zM{|cc%?;Ah5OEffB8G`H0CS#fwE+c}IW4)A%+)}f8IFkbI+(iwumVjD+Rr3=C~iK* zO?8UfLP_Tm=Mm=<7Z4W$5a)?j7op%1rzMw?xPxHLoEQ7#nn^X zVyCz-Q_>~GrG!OXMr;Eh&J(S+qu>&!C6|)8gJI3w9TDxl5cfPV(%;PPp}82%&2XB# zik7Y>t|6`^zDisNz?>&rU5|pxoR(Zl=4zqMgtUDMm~*CWu3rC3+PyT_Ky!yX&D}yv zyNFwfuM@Wsw*xTe$yU2jaGBGROUc{>Xfu~a#Zwz$?nA%|EYN@1zmMV?DQ>b;+&z?Z zFL57nKk)$ZAOLZmX!Q^ZE^%6NDTzA-*38XOG4))CTLnOz{!{S%6xT#?4Nh_2rliM+ z?-2h?e3#ey&K~EPeEL$wZ2XNZT|tPTR?S_oa&yY zre}y}i60U_B7O`&ohMv9hk{F;mi)=7D~!=|I>VOyqz6u0!IUA)k!k0AAuKqDr7#~R zf@v$U)>unht378$&c>j3aTMQGwcL-K^GQsf-%N!$p(NzTw2||TlZ|fUGGowKYiu^Q z8JmogjJPr1IL=%gN?0MIW7#RO!c+(K3;KM4coE1(sbBK(OF(|?KR+z}NzNBhKj#6w z6*S)t=4USX3-h*IXFt*$57!EX;s4mk6Fk%(c!GZ<-udWf=^nCn?>Lg5>=vtQ!yKV? z{oU!J>pydc9}>Q@f?M?-o-lmseJ=d!11{`Y9|!ITx%qVVF7&x8DvW4VK~#RMopfSC zRcl-00`$znq?7zi2sMuRyKMw|6HE4h=(UvyTmv8A;MGqRkQ{ek)_?r)r`67q{N z+o$M0`1iw!_U5lwIFa0orKU&?~=M#(WTUeN?qUKV;Jfe=6Pt+4J zV1#JZfah`NJYaD4&WWDz|MOQk-Q@uDS3YKg`_bIyTEBSs%IRqF9n*b7ee->0OmeqXBrh9o>omP?AkHQ>66X+` z0J!!QGkEM(O;rpqwM*VEu6A1q}Ypyt;83IFA`q@ zAls9zE=Iv6TT340vddxGyfh##ITNzq10Xx5%YL1*>nXe4DSI2mZYM4$t{|=?b^ws= z$yON@T(Y&~Q7$_S)8-oiu{j0VzW{I-$^P12ykq~Gu48oF=yZJ@yD zFYzb<*`93mO%z$mLRP<9h#pX8Lik76GuzDInY z_yO?*0NI{w^&|=|*;?`_mmPs=b8kpIvuL(Y9I|*ef5_Hv*}tXh1$2G9)Af((^*Q2S zi06r)5I+Ur+7qpQhJwqrmORQ`Mq50pQvbtzJdJlK{r%^p*abdlfp5t79A@@| z9;WIa1keNp_|SmtfM`31Lh%H@_+0)!%h_kM%%8D5q#V!Z7i_5e EUq4F6 Date: Mon, 5 Oct 2026 23:54:54 -0400 Subject: [PATCH 02/18] docs: describe recording VCR cassettes and the hgvs test cache --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/README.md b/README.md index 3e5686de..ecebeac8 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,40 @@ To run tests: make test ``` +#### Recorded test data + +Tests run offline by replaying recorded data, so they don't need a SeqRepo REST +service, a UTA database, or network access. Set `SEQREPO_ROOT_DIR=tests/data/seqrepo/latest` +(as CI does) when running or recording tests. + +- **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to + the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). CI + runs `pytest --vcr-record=none`, so a test making an unrecorded request fails. +- **The hgvs cache** (`tests/data/hgvs_cache.pkl`) replays the hgvs library's UTA + queries and sequence fetches. `tests/conftest.py` enables it by default + (`VRS_HGVS_CACHE_MODE=run`), and a lookup missing from the cache raises + `HGVSDataNotAvailableError`. + +To re-record, start the external services (`docker compose up` starts +seqrepo-rest-service on port 5000 and UTA on port 5432). With an existing local SeqRepo +snapshot, you can instead run just the REST service with it mounted: +`docker run -p 5000:5000 -v /path/to/seqrepo:/usr/local/share/seqrepo:ro biocommons/seqrepo-rest-service:0.2.2 seqrepo-rest-service /usr/local/share/seqrepo/2024-12-20`. +When a change needs new data in both, re-record the hgvs cache first, since cassette +recording reads hgvs data from it: + +```shell +# hgvs cache: needs UTA and seqrepo-rest-service; does not touch cassettes +export UTA_DB_URL=postgresql://anonymous@localhost:5432/uta/uta_20241220 +make record-hgvs-cache + +# VCR cassettes: needs seqrepo-rest-service +make clean-cassettes +pytest --vcr-record=once +``` + +`SEQREPO_REST_URL` (default `http://localhost:5000/seqrepo`) sets the REST service used +by both. + ## Running the Notebooks The notebooks **do not** require you to setup SeqRepo or UTA from From 32064ff9b137071cfd7f7191a6795fd82186cf71 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Mon, 5 Oct 2026 23:54:55 -0400 Subject: [PATCH 03/18] test: re-record hgvs-related cassettes without NCBI sequence requests hgvs sequence fetches are now served from tests/data/hgvs_cache.pkl, so the NCBI E-utilities interactions recorded in these cassettes are no longer used. --- ...NC_000007.14:g.55181220del-expected2].yaml | 36 ---------- ...g.55181230_55181231insGGCT-expected3].yaml | 54 -------------- ...NC_000007.14:g.55181320A>T-expected1].yaml | 36 ---------- ...NC_000013.11:g.32316467dup-expected5].yaml | 36 ---------- ....11:g.32331093_32331094dup-expected4].yaml | 72 ------------------- ...s[NC_000013.11:g.32936732=-expected0].yaml | 18 ----- ....10:g.289464_289465insCACA-expected8].yaml | 72 ------------------- ...0019.10:g.289485_289500del-expected9].yaml | 54 -------------- ...vs[NM_001331029.1:c.722A>G-expected6].yaml | 36 ---------- ...hgvs[NM_181798.1:c.1007G>T-expected7].yaml | 54 -------------- .../extras/cassettes/test_rle_seq_limit.yaml | 38 ---------- 11 files changed, 506 deletions(-) diff --git a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181220del-expected2].yaml b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181220del-expected2].yaml index 01a253d4..9515082d 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181220del-expected2].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181220del-expected2].yaml @@ -59,40 +59,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181220&seq_stop=55181220&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181220-55181220 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - T - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181220&seq_stop=55181240&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181220-55181240 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - TGGAAGGGGTCCATGTGCCCC - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181230_55181231insGGCT-expected3].yaml b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181230_55181231insGGCT-expected3].yaml index dbf9fef6..8e01ba90 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181230_55181231insGGCT-expected3].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181230_55181231insGGCT-expected3].yaml @@ -35,58 +35,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181231&seq_stop=55181231&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181231-55181231 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - C - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181230&seq_stop=55181250&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181230-55181250 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - CCATGTGCCCCTCCTTCTGGC - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181227&seq_stop=55181230&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181227-55181230 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - GGTC - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml index 3c14c730..22b2d38f 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000007.14:g.55181320A>T-expected1].yaml @@ -34,40 +34,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181320&seq_stop=55181320&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181320-55181320 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - A - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000007.14&rettype=fasta&seq_start=55181320&seq_stop=55181340&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000007.14:55181320-55181340 Homo sapiens chromosome 7, GRCh38.p14 - Primary Assembly - - AACCCCCACGTGTGCCGCCTG - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32316467dup-expected5].yaml b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32316467dup-expected5].yaml index 7a529525..dbc79ed2 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32316467dup-expected5].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32316467dup-expected5].yaml @@ -59,40 +59,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32316467&seq_stop=32316467&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32316467-32316467 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - A - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32316467&seq_stop=32316487&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32316467-32316487 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - ATTGGATCCAAAGAGAGGCCA - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32331093_32331094dup-expected4].yaml b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32331093_32331094dup-expected4].yaml index e61ad59e..2a9d5445 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32331093_32331094dup-expected4].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32331093_32331094dup-expected4].yaml @@ -215,76 +215,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331083&seq_stop=32331094&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331083-32331094 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - TTTTTTTTTTTT - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331094&seq_stop=32331094&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331094-32331094 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - T - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331083&seq_stop=32331114&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331083-32331114 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - TTTTTTTTTTTTGAGGTGGAGTCTTGCTCTGT - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331093&seq_stop=32331094&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331093-32331094 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - TT - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32936732=-expected0].yaml b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32936732=-expected0].yaml index bded6051..ab55ae01 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32936732=-expected0].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000013.11:g.32936732=-expected0].yaml @@ -11,22 +11,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32936732&seq_stop=32936732&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32936732-32936732 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - C - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289464_289465insCACA-expected8].yaml b/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289464_289465insCACA-expected8].yaml index 3cf20e71..ff25ea33 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289464_289465insCACA-expected8].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289464_289465insCACA-expected8].yaml @@ -71,76 +71,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289465&seq_stop=289466&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289465-289466 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - CA - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289466&seq_stop=289466&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289466-289466 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - A - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289465&seq_stop=289486&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289465-289486 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - CAGCACTTTGGGAGGCCGAGGC - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289463&seq_stop=289466&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289463-289466 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - CTCA - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289485_289500del-expected9].yaml b/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289485_289500del-expected9].yaml index 96e65209..2a55e187 100644 --- a/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289485_289500del-expected9].yaml +++ b/tests/extras/cassettes/test_hgvs[NC_000019.10:g.289485_289500del-expected9].yaml @@ -119,58 +119,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289481&seq_stop=289501&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289481-289501 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - CGAGGCGGGCAGATCACGAGG - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289501&seq_stop=289501&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289501-289501 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - G - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000019.10&rettype=fasta&seq_start=289481&seq_stop=289521&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000019.10:289481-289521 Homo sapiens chromosome 19, GRCh38.p14 - Primary Assembly - - CGAGGCGGGCAGATCACGAGGTCAGGAGATCGAGACCATCC - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml b/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml index 44352fa1..d86ad12f 100644 --- a/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml +++ b/tests/extras/cassettes/test_hgvs[NM_001331029.1:c.722A>G-expected6].yaml @@ -16,24 +16,6 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NM_001331029.1&rettype=fasta&seq_start=872&seq_stop=872&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NM_001331029.1:872-872 Homo sapiens protein phosphatase 1 regulatory - subunit 12B (PPP1R12B), transcript variant 8, mRNA - - A - - - ' - headers: {} - status: - code: 200 - message: OK - request: body: null headers: {} @@ -63,22 +45,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NM_001331029.1&rettype=fasta&seq_start=872&seq_stop=892&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NM_001331029.1:872-892 Homo sapiens protein phosphatase 1 regulatory - subunit 12B (PPP1R12B), transcript variant 8, mRNA - - ATGAACTCAATGTTCAGGATT - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml b/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml index 20c3a261..34775aab 100644 --- a/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml +++ b/tests/extras/cassettes/test_hgvs[NM_181798.1:c.1007G>T-expected7].yaml @@ -16,24 +16,6 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NM_181798.1&rettype=fasta&seq_start=1263&seq_stop=1263&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NM_181798.1:1263-1263 Homo sapiens potassium voltage-gated channel - subfamily Q member 1 (KCNQ1), transcript variant 2, mRNA - - G - - - ' - headers: {} - status: - code: 200 - message: OK - request: body: null headers: {} @@ -63,40 +45,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NM_181798.1&rettype=fasta&seq_start=1263&seq_stop=1268&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NM_181798.1:1263-1268 Homo sapiens potassium voltage-gated channel - subfamily Q member 1 (KCNQ1), transcript variant 2, mRNA - - GTTCTG - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NR_040711.1&rettype=fasta&seq_start=1263&seq_stop=1263&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NR_040711.1:1263-1263 Homo sapiens potassium voltage-gated channel, - KQT-like subfamily, member 1 (KCNQ1), transcript variant 2, non-coding RNA - - G - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 diff --git a/tests/extras/cassettes/test_rle_seq_limit.yaml b/tests/extras/cassettes/test_rle_seq_limit.yaml index d7046ab8..96521dda 100644 --- a/tests/extras/cassettes/test_rle_seq_limit.yaml +++ b/tests/extras/cassettes/test_rle_seq_limit.yaml @@ -503,42 +503,4 @@ interactions: status: code: 200 message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331043&seq_stop=32331094&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331043-32331094 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - TTTAGTTGAACTACAGGTTTTTTTGTTGTTGTTGTTTTGATTTTTTTTTTTT - - - ' - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=NC_000013.11&rettype=fasta&seq_start=32331043&seq_stop=32331114&tool=bioutils&email=biocommons-dev@googlegroups.com - response: - body: - string: '>NC_000013.11:32331043-32331114 Homo sapiens chromosome 13, GRCh38.p14 - Primary Assembly - - TTTAGTTGAACTACAGGTTTTTTTGTTGTTGTTGTTTTGATTTTTTTTTTTTGAGGTGGAGTCTTGCTCT - - GT - - - ' - headers: {} - status: - code: 200 - message: OK version: 1 From 01c02084f04e7199e8f00ff88d52b1b12e60d980 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 00:01:08 -0400 Subject: [PATCH 04/18] test: explain how the hgvs cache tests work in their docstrings --- tests/extras/test_hgvs_tools.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index 70603c9b..7473927a 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -47,7 +47,12 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): def test_hgvs_cache_run_mode_does_not_connect(monkeypatch): """With the tests' default hgvs cache (run mode), lookups are served from the cache - file without connecting to UTA + file without connecting to UTA. + + Replaces hgvs's `UTA_postgresql._connect` with a function that fails, clears the + memoized shared data provider so a new one is built under the patch, then creates + an `HgvsTools` and does a cached lookup. Skipped outside run mode (e.g. when + re-recording the cache), where connecting is expected. """ if os.environ.get("VRS_HGVS_CACHE_MODE") != "run": pytest.skip("only applies when the hgvs cache is in run mode") @@ -86,7 +91,9 @@ def test_hgvs_cache_data_provider_is_shared(): @pytest.mark.parametrize("case", hgvs_cache_env_invalid_cases, ids=lambda c: c["id"]) def test_hgvs_cache_env_invalid(monkeypatch, case): - """Invalid hgvs cache settings raise rather than silently connecting to UTA""" + """Invalid hgvs cache settings raise rather than silently connecting to UTA: an + unknown `VRS_HGVS_CACHE_MODE`, or a mode set without `VRS_HGVS_CACHE_FILE` + """ for name, value in case["env"].items(): monkeypatch.setenv(name, value) with pytest.raises(ValueError, match=case["match"]): From b1691fc986a9b1be18656138dbeb5e087dcd578f Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 14:30:17 -0400 Subject: [PATCH 05/18] test: check hgvs run mode stays offline through a full translation --- .../test_hgvs_cache_run_mode_is_offline.yaml | 48 +++++++++++++++++++ tests/extras/test_allele_translator.py | 31 ++++++++++++ tests/extras/test_hgvs_tools.py | 28 +---------- 3 files changed, 80 insertions(+), 27 deletions(-) create mode 100644 tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml diff --git a/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml b/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml new file mode 100644 index 00000000..34775aab --- /dev/null +++ b/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml @@ -0,0 +1,48 @@ +interactions: +- request: + body: null + headers: {} + method: GET + uri: http://localhost:5000/seqrepo/1/metadata/refseq:NM_181798.1 + response: + body: + string: "{\n \"added\": \"2016-08-24T05:03:05Z\",\n \"aliases\": [\n \"MD5:93e2dc533ba755782b3affcf53470434\",\n + \ \"NCBI:NM_181798.1\",\n \"refseq:NM_181798.1\",\n \"NCBI:NR_040711.1\",\n + \ \"refseq:NR_040711.1\",\n \"SEGUID:0nrqUDibhGAQBZ4pXR+soOiCOf0\",\n + \ \"SHA1:d27aea50389b846010059e295d1faca0e88239fd\",\n \"VMC:GS_KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n + \ \"sha512t24u:KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n \"ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\"\n + \ ],\n \"alphabet\": \"ACGT\",\n \"length\": 3029\n}\n" + headers: {} + status: + code: 200 + message: OK +- request: + body: null + headers: {} + method: GET + uri: http://localhost:5000/seqrepo/1/metadata/ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg + response: + body: + string: "{\n \"added\": \"2016-08-24T05:03:05Z\",\n \"aliases\": [\n \"MD5:93e2dc533ba755782b3affcf53470434\",\n + \ \"NCBI:NM_181798.1\",\n \"refseq:NM_181798.1\",\n \"NCBI:NR_040711.1\",\n + \ \"refseq:NR_040711.1\",\n \"SEGUID:0nrqUDibhGAQBZ4pXR+soOiCOf0\",\n + \ \"SHA1:d27aea50389b846010059e295d1faca0e88239fd\",\n \"VMC:GS_KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n + \ \"sha512t24u:KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n \"ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\"\n + \ ],\n \"alphabet\": \"ACGT\",\n \"length\": 3029\n}\n" + headers: {} + status: + code: 200 + message: OK +- request: + body: null + headers: {} + method: GET + uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg?start=1262&end=1263 + response: + body: + string: G + headers: {} + status: + code: 200 + message: OK +version: 1 diff --git a/tests/extras/test_allele_translator.py b/tests/extras/test_allele_translator.py index 15f87a89..6c7f5dfc 100644 --- a/tests/extras/test_allele_translator.py +++ b/tests/extras/test_allele_translator.py @@ -1,3 +1,8 @@ +import os +from typing import NoReturn + +import hgvs.dataproviders.seqfetcher +import hgvs.dataproviders.uta import pytest from ga4gh.vrs import models @@ -751,6 +756,32 @@ def test_hgvs(tlr, hgvsexpr, expected): ) +@pytest.mark.vcr +def test_hgvs_cache_run_mode_is_offline( + monkeypatch: pytest.MonkeyPatch, tlr: AlleleTranslator +) -> None: + """With the tests' default hgvs cache (run mode), translating to and from hgvs + makes no UTA queries or hgvs sequence fetches. + + Replaces the two places hgvs reaches outside the process, `UTA_postgresql._get_cursor` + (every UTA query) and `SeqFetcher.fetch_seq` (every sequence fetch), with a function + that fails, then translates a transcript variant both ways. Skipped outside run mode + (e.g. when re-recording the cache), where both are expected. + """ + if os.environ.get("VRS_HGVS_CACHE_MODE") != "run": + pytest.skip("only applies when the hgvs cache is in run mode") + + def fail(*args: object, **kwargs: object) -> NoReturn: # noqa: ARG001 + msg = "hgvs queried UTA or fetched a sequence in hgvs cache run mode" + raise AssertionError(msg) + + monkeypatch.setattr(hgvs.dataproviders.uta.UTA_postgresql, "_get_cursor", fail) + monkeypatch.setattr(hgvs.dataproviders.seqfetcher.SeqFetcher, "fetch_seq", fail) + + allele = tlr.translate_from("NM_181798.1:c.1007G>T", "hgvs") + assert "NM_181798.1:c.1007G>T" in tlr.translate_to(allele, "hgvs") + + @pytest.mark.vcr def test_rle_seq_limit(tlr): """Test that for an ReferenceLengthExpression over 50bp, the sequence is not diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index 7473927a..0b3dea66 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -1,12 +1,9 @@ """Tests for ga4gh.vrs.utils.hgvs_tools.""" -import os - -import hgvs.dataproviders.uta import hgvs.parser import pytest -from ga4gh.vrs.utils.hgvs_tools import HgvsTools, _connect_with_cache +from ga4gh.vrs.utils.hgvs_tools import HgvsTools @pytest.fixture(scope="module") @@ -45,29 +42,6 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): assert hgvs_tools.is_intronic(sv) is expected -def test_hgvs_cache_run_mode_does_not_connect(monkeypatch): - """With the tests' default hgvs cache (run mode), lookups are served from the cache - file without connecting to UTA. - - Replaces hgvs's `UTA_postgresql._connect` with a function that fails, clears the - memoized shared data provider so a new one is built under the patch, then creates - an `HgvsTools` and does a cached lookup. Skipped outside run mode (e.g. when - re-recording the cache), where connecting is expected. - """ - if os.environ.get("VRS_HGVS_CACHE_MODE") != "run": - pytest.skip("only applies when the hgvs cache is in run mode") - - def fail_connect(self): # noqa: ARG001 - msg = "UTA connection attempted in hgvs cache run mode" - raise AssertionError(msg) - - monkeypatch.setattr(hgvs.dataproviders.uta.UTA_postgresql, "_connect", fail_connect) - _connect_with_cache.cache_clear() - - tools = HgvsTools() - assert tools.uta_conn.get_tx_identity_info("NM_181798.1")["tx_ac"] == "NM_181798.1" - - def test_hgvs_cache_data_provider_is_shared(): """HgvsTools instances using the same cache share one data provider, so in learn mode they cannot overwrite each other's cache entries From 0bac5e9670b7d58bc4136ed1ac29da9b6e76970a Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 14:31:29 -0400 Subject: [PATCH 06/18] test: provide the hgvs cache from a conftest fixture --- src/ga4gh/vrs/utils/hgvs_tools.py | 40 ++--------------------- tests/conftest.py | 45 +++++++++++++++++++++----- tests/extras/test_allele_translator.py | 8 +++-- tests/extras/test_hgvs_tools.py | 37 ++++++--------------- 4 files changed, 53 insertions(+), 77 deletions(-) diff --git a/src/ga4gh/vrs/utils/hgvs_tools.py b/src/ga4gh/vrs/utils/hgvs_tools.py index 027a9689..42d81f86 100644 --- a/src/ga4gh/vrs/utils/hgvs_tools.py +++ b/src/ga4gh/vrs/utils/hgvs_tools.py @@ -1,8 +1,6 @@ """Provide extra tools for working with hgvs expressions.""" -import functools import logging -import os import re import hgvs @@ -18,21 +16,6 @@ _logger = logging.getLogger(__name__) -HGVS_CACHE_MODES = ("learn", "run", "verify") - - -@functools.cache -def _connect_with_cache( - mode: str, cache_file: str -) -> hgvs.dataproviders.uta.UTA_postgresql: - """Return the data provider shared by every `HgvsTools` using this cache. - - Each data provider keeps its own in-memory copy of the cache file and, in learn - mode, rewrites the whole file after every miss, so separate providers writing the - same file would drop each other's entries. - """ - return hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) - class HgvsTools: """A convenience class that exposes only the tools needed by vrs-python for working with HGVS (Human Genome Variation Society) notation. @@ -51,28 +34,10 @@ class HgvsTools: def __init__(self, data_proxy: _DataProxy | None = None) -> None: """Initialize object. - The hgvs data provider (UTA) cache can be enabled with environment variables: - ``VRS_HGVS_CACHE_MODE`` (``learn``, ``run``, or ``verify``) and - ``VRS_HGVS_CACHE_FILE`` (path to the cache file). In ``run`` mode, lookups are - served only from the cache file and no UTA connection is made. - :param data_proxy: GA4GH data proxy instance """ self.parser = hgvs.parser.Parser() - cache_mode = os.environ.get("VRS_HGVS_CACHE_MODE") or None - cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") or None - if cache_mode: - if cache_mode not in HGVS_CACHE_MODES: - msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES}, got {cache_mode!r}" - raise ValueError(msg) - if not cache_file: - msg = "VRS_HGVS_CACHE_FILE must be set when VRS_HGVS_CACHE_MODE is set" - raise ValueError(msg) - self.uta_conn = _connect_with_cache(cache_mode, cache_file) - self._owns_uta_conn = False - else: - self.uta_conn = hgvs.dataproviders.uta.connect() - self._owns_uta_conn = True + self.uta_conn = hgvs.dataproviders.uta.connect() self.normalizer = hgvs.normalizer.Normalizer(self.uta_conn, validate=True) self.variant_mapper = hgvs.variantmapper.VariantMapper(self.uta_conn) self.data_proxy = data_proxy @@ -85,8 +50,7 @@ def close(self) -> None: self.normalizer = None self.variant_mapper = None self.data_proxy = None - # A cache-backed data provider is shared with other instances; leave it open - if self.uta_conn is not None and self._owns_uta_conn: + if self.uta_conn is not None: self.uta_conn.close() # convenience methods for hgvs parsing, normalization, and some mappings diff --git a/tests/conftest.py b/tests/conftest.py index 8f407de1..800d2042 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,19 +1,48 @@ import os +from collections.abc import Iterator from pathlib import Path +import hgvs.dataproviders.uta import pytest from biocommons.seqrepo import SeqRepo from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy -# Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a -# recorded cache by default, so tests don't need a UTA database or network access. To -# re-record, run `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and -# a seqrepo-rest-service running at SEQREPO_REST_URL. -os.environ.setdefault("VRS_HGVS_CACHE_MODE", "run") -os.environ.setdefault( - "VRS_HGVS_CACHE_FILE", str(Path(__file__).parent / "data" / "hgvs_cache.pkl") -) +HGVS_CACHE_MODES = ("learn", "run", "verify") +HGVS_CACHE_FILE = Path(__file__).parent / "data" / "hgvs_cache.pkl" + + +@pytest.fixture(scope="session", autouse=True) +def hgvs_cached_data_provider() -> Iterator[hgvs.dataproviders.uta.UTABase | None]: + """Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a + recorded cache, so tests don't need a UTA database or network access. + + Every `HgvsTools` gets this one data provider, so in learn mode they cannot + overwrite each other's cache entries. `VRS_HGVS_CACHE_MODE` is `run` (default), + `learn`, or `verify`, or empty to query UTA directly without the cache, and + `VRS_HGVS_CACHE_FILE` overrides the cache file. In run mode, a lookup missing from + the cache raises `HGVSDataNotAvailableError`. To re-record, run + `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and a + seqrepo-rest-service running at SEQREPO_REST_URL. + """ + mode = os.environ.get("VRS_HGVS_CACHE_MODE", "run") + if not mode: + yield None + return + if mode not in HGVS_CACHE_MODES: + msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" + raise pytest.UsageError(msg) + cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") or str(HGVS_CACHE_FILE) + + provider = hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) + with pytest.MonkeyPatch.context() as mp: + mp.setattr( + hgvs.dataproviders.uta, "connect", lambda *_args, **_kwargs: provider + ) + # HgvsTools.close() closes its data provider, but this one is shared + mp.setattr(provider, "close", lambda: None) + yield provider + provider.close() def remove_request_headers(request): diff --git a/tests/extras/test_allele_translator.py b/tests/extras/test_allele_translator.py index 6c7f5dfc..ce161082 100644 --- a/tests/extras/test_allele_translator.py +++ b/tests/extras/test_allele_translator.py @@ -1,9 +1,9 @@ -import os from typing import NoReturn import hgvs.dataproviders.seqfetcher import hgvs.dataproviders.uta import pytest +from hgvs.decorators.lru_cache import RUN from ga4gh.vrs import models from ga4gh.vrs.dataproxy import DataProxyValidationError @@ -758,7 +758,9 @@ def test_hgvs(tlr, hgvsexpr, expected): @pytest.mark.vcr def test_hgvs_cache_run_mode_is_offline( - monkeypatch: pytest.MonkeyPatch, tlr: AlleleTranslator + monkeypatch: pytest.MonkeyPatch, + tlr: AlleleTranslator, + hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, ) -> None: """With the tests' default hgvs cache (run mode), translating to and from hgvs makes no UTA queries or hgvs sequence fetches. @@ -768,7 +770,7 @@ def test_hgvs_cache_run_mode_is_offline( that fails, then translates a transcript variant both ways. Skipped outside run mode (e.g. when re-recording the cache), where both are expected. """ - if os.environ.get("VRS_HGVS_CACHE_MODE") != "run": + if hgvs_cached_data_provider is None or hgvs_cached_data_provider.mode != RUN: pytest.skip("only applies when the hgvs cache is in run mode") def fail(*args: object, **kwargs: object) -> NoReturn: # noqa: ARG001 diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index 0b3dea66..5d48dbeb 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -1,5 +1,6 @@ """Tests for ga4gh.vrs.utils.hgvs_tools.""" +import hgvs.dataproviders.uta import hgvs.parser import pytest @@ -42,33 +43,13 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): assert hgvs_tools.is_intronic(sv) is expected -def test_hgvs_cache_data_provider_is_shared(): - """HgvsTools instances using the same cache share one data provider, so in learn +def test_hgvs_cache_data_provider_is_shared( + hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, +) -> None: + """Every HgvsTools gets the tests' shared hgvs cache data provider, so in learn mode they cannot overwrite each other's cache entries """ - assert HgvsTools().uta_conn is HgvsTools().uta_conn - - -hgvs_cache_env_invalid_cases = [ - { - "id": "unknown-mode", - "env": {"VRS_HGVS_CACHE_MODE": "lean"}, - "match": "must be one of", - }, - { - "id": "mode-without-file", - "env": {"VRS_HGVS_CACHE_FILE": ""}, - "match": "VRS_HGVS_CACHE_FILE must be set", - }, -] - - -@pytest.mark.parametrize("case", hgvs_cache_env_invalid_cases, ids=lambda c: c["id"]) -def test_hgvs_cache_env_invalid(monkeypatch, case): - """Invalid hgvs cache settings raise rather than silently connecting to UTA: an - unknown `VRS_HGVS_CACHE_MODE`, or a mode set without `VRS_HGVS_CACHE_FILE` - """ - for name, value in case["env"].items(): - monkeypatch.setenv(name, value) - with pytest.raises(ValueError, match=case["match"]): - HgvsTools() + if hgvs_cached_data_provider is None: + pytest.skip("the hgvs cache is disabled") + assert HgvsTools().uta_conn is hgvs_cached_data_provider + assert HgvsTools().uta_conn is hgvs_cached_data_provider From 4c1b65a15a688db180aa7b7bea1091c35c67ce74 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 14:32:21 -0400 Subject: [PATCH 07/18] test: validate the hgvs cache file before loading it --- tests/conftest.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index 800d2042..8e62e9cf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,15 +1,54 @@ import os +import pickle from collections.abc import Iterator from pathlib import Path +from typing import Any import hgvs.dataproviders.uta import pytest from biocommons.seqrepo import SeqRepo +from hgvs.decorators.lru_cache import _make_key from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy HGVS_CACHE_MODES = ("learn", "run", "verify") HGVS_CACHE_FILE = Path(__file__).parent / "data" / "hgvs_cache.pkl" +# The only classes a recorded hgvs cache file is made of: its keys (_HashedSeq), UTA +# rows (DictRow, with an OrderedDict column index), and what pickle rebuilds them with +HGVS_CACHE_ALLOWED_CLASSES = { + ("builtins", "list"), + ("collections", "OrderedDict"), + ("copyreg", "_reconstructor"), + ("hgvs.decorators.lru_cache", "_HashedSeq"), + ("psycopg2.extras", "DictRow"), +} + + +class HgvsCacheUnpickler(pickle.Unpickler): + """Unpickler that refuses any class not in `HGVS_CACHE_ALLOWED_CLASSES`""" + + def find_class(self, module: str, name: str) -> Any: # noqa: ANN401 + if (module, name) not in HGVS_CACHE_ALLOWED_CLASSES: + msg = f"hgvs cache file references a disallowed class: {module}.{name}" + raise pickle.UnpicklingError(msg) + return super().find_class(module, name) + + +def check_hgvs_cache_file(cache_file: str) -> None: + """Check an hgvs cache file before hgvs loads it with an unrestricted `pickle.load` + + The file may only reference the classes in `HGVS_CACHE_ALLOWED_CLASSES`, and its + keys must be in the format this hgvs version builds. Every data provider looks up + `schema_version` when it's created, so a recorded cache always has that key. + """ + with Path(cache_file).open("rb") as f: + cache: dict = HgvsCacheUnpickler(f).load() # cache keys -> recorded results + if _make_key("schema_version", (), {}, False, ()) not in cache: + msg = ( + f"{cache_file} has no schema_version entry in this hgvs version's cache key " + "format; re-record it with `make record-hgvs-cache`" + ) + raise pytest.UsageError(msg) @pytest.fixture(scope="session", autouse=True) @@ -33,6 +72,8 @@ def hgvs_cached_data_provider() -> Iterator[hgvs.dataproviders.uta.UTABase | Non msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" raise pytest.UsageError(msg) cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") or str(HGVS_CACHE_FILE) + if Path(cache_file).exists(): + check_hgvs_cache_file(cache_file) provider = hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) with pytest.MonkeyPatch.context() as mp: From 5385c8ceec1b834dbca333b202ce24408f1c316a Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 14:32:48 -0400 Subject: [PATCH 08/18] build: write the recorded hgvs cache only when recording succeeds --- .gitignore | 3 +++ Makefile | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 5f1c1695..dd645d63 100644 --- a/.gitignore +++ b/.gitignore @@ -158,3 +158,6 @@ notebooks/scratch/ notes lint uta_*.pgd.gz + +# partial hgvs cache from an interrupted `make record-hgvs-cache` +tests/data/hgvs_cache.pkl.new diff --git a/Makefile b/Makefile index 7edef708..c3a5db9c 100644 --- a/Makefile +++ b/Makefile @@ -131,8 +131,9 @@ clean-cassettes: #=> record-hgvs-cache: re-record tests/data/hgvs_cache.pkl (needs UTA_DB_URL and a running seqrepo-rest-service at SEQREPO_REST_URL; VCR cassettes are not touched) .PHONY: record-hgvs-cache record-hgvs-cache: - rm -f tests/data/hgvs_cache.pkl - HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn pytest --disable-vcr + rm -f tests/data/hgvs_cache.pkl.new + HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn VRS_HGVS_CACHE_FILE=$(CURDIR)/tests/data/hgvs_cache.pkl.new pytest --disable-vcr + mv tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.pkl ## From 03a14e22af6ccea6577b7f045a3888394d86706f Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 14:41:07 -0400 Subject: [PATCH 09/18] test: note that live hgvs cache modes need --disable-vcr --- tests/conftest.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index 8e62e9cf..f1326659 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -63,6 +63,10 @@ def hgvs_cached_data_provider() -> Iterator[hgvs.dataproviders.uta.UTABase | Non the cache raises `HGVSDataNotAvailableError`. To re-record, run `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and a seqrepo-rest-service running at SEQREPO_REST_URL. + + Learn and verify modes, and an empty mode, query UTA and fetch sequences live. The + VCR cassettes don't contain those hgvs sequence requests (to HGVS_SEQREPO_URL), so + run these modes with `pytest --disable-vcr`. """ mode = os.environ.get("VRS_HGVS_CACHE_MODE", "run") if not mode: From 94bb78a0596abce138428ba1a532704a77c89b65 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 6 Oct 2026 16:16:34 -0400 Subject: [PATCH 10/18] test: store the hgvs test cache as JSON --- Makefile | 5 +- README.md | 5 +- tests/conftest.py | 70 +- tests/data/hgvs_cache.json | 1457 ++++++++++++++++++++++++++++++++++++ tests/data/hgvs_cache.pkl | Bin 17169 -> 0 bytes tests/hgvs_cache_json.py | 93 +++ 6 files changed, 1578 insertions(+), 52 deletions(-) create mode 100644 tests/data/hgvs_cache.json delete mode 100644 tests/data/hgvs_cache.pkl create mode 100644 tests/hgvs_cache_json.py diff --git a/Makefile b/Makefile index c3a5db9c..a751e490 100644 --- a/Makefile +++ b/Makefile @@ -128,12 +128,13 @@ cleanest: cleaner clean-cassettes: find ./tests -type f -path '*/cassettes/*.yaml' -print0 | ${XRM} -#=> record-hgvs-cache: re-record tests/data/hgvs_cache.pkl (needs UTA_DB_URL and a running seqrepo-rest-service at SEQREPO_REST_URL; VCR cassettes are not touched) +#=> record-hgvs-cache: re-record tests/data/hgvs_cache.json (needs UTA_DB_URL and a running seqrepo-rest-service at SEQREPO_REST_URL; VCR cassettes are not touched) .PHONY: record-hgvs-cache record-hgvs-cache: rm -f tests/data/hgvs_cache.pkl.new HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn VRS_HGVS_CACHE_FILE=$(CURDIR)/tests/data/hgvs_cache.pkl.new pytest --disable-vcr - mv tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.pkl + python tests/hgvs_cache_json.py tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.json + rm tests/data/hgvs_cache.pkl.new ## diff --git a/README.md b/README.md index ecebeac8..ab6d4287 100644 --- a/README.md +++ b/README.md @@ -324,10 +324,11 @@ service, a UTA database, or network access. Set `SEQREPO_ROOT_DIR=tests/data/seq - **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). CI runs `pytest --vcr-record=none`, so a test making an unrecorded request fails. -- **The hgvs cache** (`tests/data/hgvs_cache.pkl`) replays the hgvs library's UTA +- **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA queries and sequence fetches. `tests/conftest.py` enables it by default (`VRS_HGVS_CACHE_MODE=run`), and a lookup missing from the cache raises - `HGVSDataNotAvailableError`. + `HGVSDataNotAvailableError`. hgvs itself reads and writes its cache as a pickle; + `tests/hgvs_cache_json.py` converts between the two. To re-record, start the external services (`docker compose up` starts seqrepo-rest-service on port 5000 and UTA on port 5432). With an existing local SeqRepo diff --git a/tests/conftest.py b/tests/conftest.py index f1326659..fd3d5d9a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,68 +1,37 @@ import os -import pickle from collections.abc import Iterator from pathlib import Path -from typing import Any import hgvs.dataproviders.uta import pytest from biocommons.seqrepo import SeqRepo -from hgvs.decorators.lru_cache import _make_key +from hgvs_cache_json import json_to_pickle from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy HGVS_CACHE_MODES = ("learn", "run", "verify") -HGVS_CACHE_FILE = Path(__file__).parent / "data" / "hgvs_cache.pkl" -# The only classes a recorded hgvs cache file is made of: its keys (_HashedSeq), UTA -# rows (DictRow, with an OrderedDict column index), and what pickle rebuilds them with -HGVS_CACHE_ALLOWED_CLASSES = { - ("builtins", "list"), - ("collections", "OrderedDict"), - ("copyreg", "_reconstructor"), - ("hgvs.decorators.lru_cache", "_HashedSeq"), - ("psycopg2.extras", "DictRow"), -} - - -class HgvsCacheUnpickler(pickle.Unpickler): - """Unpickler that refuses any class not in `HGVS_CACHE_ALLOWED_CLASSES`""" - - def find_class(self, module: str, name: str) -> Any: # noqa: ANN401 - if (module, name) not in HGVS_CACHE_ALLOWED_CLASSES: - msg = f"hgvs cache file references a disallowed class: {module}.{name}" - raise pickle.UnpicklingError(msg) - return super().find_class(module, name) - - -def check_hgvs_cache_file(cache_file: str) -> None: - """Check an hgvs cache file before hgvs loads it with an unrestricted `pickle.load` - - The file may only reference the classes in `HGVS_CACHE_ALLOWED_CLASSES`, and its - keys must be in the format this hgvs version builds. Every data provider looks up - `schema_version` when it's created, so a recorded cache always has that key. - """ - with Path(cache_file).open("rb") as f: - cache: dict = HgvsCacheUnpickler(f).load() # cache keys -> recorded results - if _make_key("schema_version", (), {}, False, ()) not in cache: - msg = ( - f"{cache_file} has no schema_version entry in this hgvs version's cache key " - "format; re-record it with `make record-hgvs-cache`" - ) - raise pytest.UsageError(msg) +HGVS_CACHE_JSON = Path(__file__).parent / "data" / "hgvs_cache.json" @pytest.fixture(scope="session", autouse=True) -def hgvs_cached_data_provider() -> Iterator[hgvs.dataproviders.uta.UTABase | None]: +def hgvs_cached_data_provider( + tmp_path_factory: pytest.TempPathFactory, +) -> Iterator[hgvs.dataproviders.uta.UTABase | None]: """Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a recorded cache, so tests don't need a UTA database or network access. Every `HgvsTools` gets this one data provider, so in learn mode they cannot overwrite each other's cache entries. `VRS_HGVS_CACHE_MODE` is `run` (default), - `learn`, or `verify`, or empty to query UTA directly without the cache, and - `VRS_HGVS_CACHE_FILE` overrides the cache file. In run mode, a lookup missing from - the cache raises `HGVSDataNotAvailableError`. To re-record, run + `learn`, or `verify`, or empty to query UTA directly without the cache. In run + mode, a lookup missing from the cache raises `HGVSDataNotAvailableError`. + + hgvs keeps its cache as a pickle, so in run and verify modes the committed + `tests/data/hgvs_cache.json` is converted to a temporary pickle for hgvs to load + (see `hgvs_cache_json.py`). Learn mode records a new cache, starting empty, into + the pickle file named by `VRS_HGVS_CACHE_FILE`. To re-record, run `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and a - seqrepo-rest-service running at SEQREPO_REST_URL. + seqrepo-rest-service running at SEQREPO_REST_URL; it converts the recorded pickle + to `tests/data/hgvs_cache.json`. Learn and verify modes, and an empty mode, query UTA and fetch sequences live. The VCR cassettes don't contain those hgvs sequence requests (to HGVS_SEQREPO_URL), so @@ -75,9 +44,14 @@ def hgvs_cached_data_provider() -> Iterator[hgvs.dataproviders.uta.UTABase | Non if mode not in HGVS_CACHE_MODES: msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" raise pytest.UsageError(msg) - cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") or str(HGVS_CACHE_FILE) - if Path(cache_file).exists(): - check_hgvs_cache_file(cache_file) + if mode == "learn": + cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") + if not cache_file: + msg = "VRS_HGVS_CACHE_FILE must name the pickle file to record into in learn mode" + raise pytest.UsageError(msg) + else: + cache_file = str(tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl") + json_to_pickle(HGVS_CACHE_JSON, Path(cache_file)) provider = hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) with pytest.MonkeyPatch.context() as mp: diff --git a/tests/data/hgvs_cache.json b/tests/data/hgvs_cache.json new file mode 100644 index 00000000..878d4239 --- /dev/null +++ b/tests/data/hgvs_cache.json @@ -0,0 +1,1457 @@ +[ + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181219, + 55181220 + ], + "value": "T" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181219, + 55181240 + ], + "value": "TGGAAGGGGTCCATGTGCCCC" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181226, + 55181230 + ], + "value": "GGTC" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181229, + 55181250 + ], + "value": "CCATGTGCCCCTCCTTCTGGC" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181230, + 55181231 + ], + "value": "C" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181319, + 55181320 + ], + "value": "A" + }, + { + "func": "get_seq", + "args": [ + "NC_000007.14", + 55181319, + 55181340 + ], + "value": "AACCCCCACGTGTGCCGCCTG" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32316466, + 32316467 + ], + "value": "A" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32316466, + 32316487 + ], + "value": "ATTGGATCCAAAGAGAGGCCA" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331042, + 32331094 + ], + "value": "TTTAGTTGAACTACAGGTTTTTTTGTTGTTGTTGTTTTGATTTTTTTTTTTT" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331042, + 32331114 + ], + "value": "TTTAGTTGAACTACAGGTTTTTTTGTTGTTGTTGTTTTGATTTTTTTTTTTTGAGGTGGAGTCTTGCTCTGT" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331082, + 32331094 + ], + "value": "TTTTTTTTTTTT" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331082, + 32331114 + ], + "value": "TTTTTTTTTTTTGAGGTGGAGTCTTGCTCTGT" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331092, + 32331094 + ], + "value": "TT" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32331093, + 32331094 + ], + "value": "T" + }, + { + "func": "get_seq", + "args": [ + "NC_000013.11", + 32936731, + 32936732 + ], + "value": "C" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289462, + 289466 + ], + "value": "CTCA" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289464, + 289466 + ], + "value": "CA" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289464, + 289486 + ], + "value": "CAGCACTTTGGGAGGCCGAGGC" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289465, + 289466 + ], + "value": "A" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289480, + 289501 + ], + "value": "CGAGGCGGGCAGATCACGAGG" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289480, + 289521 + ], + "value": "CGAGGCGGGCAGATCACGAGGTCAGGAGATCGAGACCATCC" + }, + { + "func": "get_seq", + "args": [ + "NC_000019.10", + 289500, + 289501 + ], + "value": "G" + }, + { + "func": "get_seq", + "args": [ + "NM_001331029.1", + 871, + 872 + ], + "value": "A" + }, + { + "func": "get_seq", + "args": [ + "NM_001331029.1", + 871, + 892 + ], + "value": "ATGAACTCAATGTTCAGGATT" + }, + { + "func": "get_seq", + "args": [ + "NM_181798.1", + 1262, + 1263 + ], + "value": "G" + }, + { + "func": "get_seq", + "args": [ + "NM_181798.1", + 1262, + 1268 + ], + "value": "GTTCTG" + }, + { + "func": "get_seq", + "args": [ + "NR_040711.1", + 1262, + 1263 + ], + "value": "G" + }, + { + "func": "get_seq", + "args": [ + "XM_017001344.1", + 871, + 872 + ], + "value": "A" + }, + { + "func": "get_tx_exons", + "args": [ + "NM_001331029.1", + "NC_000001.10", + "splign" + ], + "value": [ + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 0, + "tx_start_i": 0, + "tx_end_i": 441, + "alt_start_i": 202317829, + "alt_end_i": 202318270, + "cigar": "441=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895004, + "alt_exon_id": 6911773, + "exon_aln_id": 4375364 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 1, + "tx_start_i": 441, + "tx_end_i": 572, + "alt_start_i": 202385914, + "alt_end_i": 202386045, + "cigar": "131=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895005, + "alt_exon_id": 6911774, + "exon_aln_id": 4375329 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 2, + "tx_start_i": 572, + "tx_end_i": 691, + "alt_start_i": 202391747, + "alt_end_i": 202391866, + "cigar": "119=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895006, + "alt_exon_id": 6911775, + "exon_aln_id": 4375326 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 3, + "tx_start_i": 691, + "tx_end_i": 851, + "alt_start_i": 202394693, + "alt_end_i": 202394853, + "cigar": "160=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895007, + "alt_exon_id": 6911776, + "exon_aln_id": 4375339 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 4, + "tx_start_i": 851, + "tx_end_i": 996, + "alt_start_i": 202396167, + "alt_end_i": 202396312, + "cigar": "145=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895008, + "alt_exon_id": 6911777, + "exon_aln_id": 4375320 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 5, + "tx_start_i": 996, + "tx_end_i": 1071, + "alt_start_i": 202397982, + "alt_end_i": 202398057, + "cigar": "75=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895009, + "alt_exon_id": 6911778, + "exon_aln_id": 4375342 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 6, + "tx_start_i": 1071, + "tx_end_i": 1151, + "alt_start_i": 202399858, + "alt_end_i": 202399938, + "cigar": "80=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895010, + "alt_exon_id": 6911779, + "exon_aln_id": 4375348 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 7, + "tx_start_i": 1151, + "tx_end_i": 1291, + "alt_start_i": 202400607, + "alt_end_i": 202400747, + "cigar": "140=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895011, + "alt_exon_id": 6911780, + "exon_aln_id": 4375321 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 8, + "tx_start_i": 1291, + "tx_end_i": 1404, + "alt_start_i": 202403783, + "alt_end_i": 202403896, + "cigar": "113=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895012, + "alt_exon_id": 6911781, + "exon_aln_id": 4375354 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 9, + "tx_start_i": 1404, + "tx_end_i": 1608, + "alt_start_i": 202406948, + "alt_end_i": 202407152, + "cigar": "204=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895013, + "alt_exon_id": 6911782, + "exon_aln_id": 4375356 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 10, + "tx_start_i": 1608, + "tx_end_i": 1691, + "alt_start_i": 202409833, + "alt_end_i": 202409916, + "cigar": "83=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895014, + "alt_exon_id": 6911783, + "exon_aln_id": 4375355 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 11, + "tx_start_i": 1691, + "tx_end_i": 1817, + "alt_start_i": 202411574, + "alt_end_i": 202411700, + "cigar": "126=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895015, + "alt_exon_id": 6911784, + "exon_aln_id": 4375357 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 12, + "tx_start_i": 1817, + "tx_end_i": 2000, + "alt_start_i": 202414173, + "alt_end_i": 202414356, + "cigar": "183=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895016, + "alt_exon_id": 6911785, + "exon_aln_id": 4375347 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 13, + "tx_start_i": 2000, + "tx_end_i": 2183, + "alt_start_i": 202418116, + "alt_end_i": 202418299, + "cigar": "183=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895017, + "alt_exon_id": 6911786, + "exon_aln_id": 4375333 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 14, + "tx_start_i": 2183, + "tx_end_i": 2274, + "alt_start_i": 202457660, + "alt_end_i": 202457751, + "cigar": "91=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895018, + "alt_exon_id": 6911787, + "exon_aln_id": 4375343 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 15, + "tx_start_i": 2274, + "tx_end_i": 2478, + "alt_start_i": 202462241, + "alt_end_i": 202462445, + "cigar": "204=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895019, + "alt_exon_id": 6911788, + "exon_aln_id": 4375336 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 16, + "tx_start_i": 2478, + "tx_end_i": 2668, + "alt_start_i": 202464420, + "alt_end_i": 202464610, + "cigar": "190=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895020, + "alt_exon_id": 6911789, + "exon_aln_id": 4375334 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 17, + "tx_start_i": 2668, + "tx_end_i": 2781, + "alt_start_i": 202464697, + "alt_end_i": 202464810, + "cigar": "113=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895021, + "alt_exon_id": 6911790, + "exon_aln_id": 4375322 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 18, + "tx_start_i": 2781, + "tx_end_i": 2823, + "alt_start_i": 202465908, + "alt_end_i": 202465950, + "cigar": "42=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895022, + "alt_exon_id": 6911791, + "exon_aln_id": 4375330 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 19, + "tx_start_i": 2823, + "tx_end_i": 2840, + "alt_start_i": 202528004, + "alt_end_i": 202528021, + "cigar": "17=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895023, + "alt_exon_id": 6911792, + "exon_aln_id": 4375360 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 20, + "tx_start_i": 2840, + "tx_end_i": 2985, + "alt_start_i": 202531905, + "alt_end_i": 202532050, + "cigar": "145=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895024, + "alt_exon_id": 6911793, + "exon_aln_id": 4375335 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 21, + "tx_start_i": 2985, + "tx_end_i": 3090, + "alt_start_i": 202533570, + "alt_end_i": 202533675, + "cigar": "105=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895025, + "alt_exon_id": 6911794, + "exon_aln_id": 4375323 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 22, + "tx_start_i": 3090, + "tx_end_i": 3144, + "alt_start_i": 202536905, + "alt_end_i": 202536959, + "cigar": "54=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895026, + "alt_exon_id": 6911795, + "exon_aln_id": 4375325 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 23, + "tx_start_i": 3144, + "tx_end_i": 3195, + "alt_start_i": 202538274, + "alt_end_i": 202538325, + "cigar": "51=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895027, + "alt_exon_id": 6911796, + "exon_aln_id": 4375346 + } + }, + { + "psycopg2_dictrow": { + "symbol": "PPP1R12B", + "hgnc": "PPP1R12B", + "gene_id": "4660", + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 24, + "tx_start_i": 3195, + "tx_end_i": 11291, + "alt_start_i": 202549601, + "alt_end_i": 202557697, + "cigar": "8096=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 808849, + "alt_exon_set_id": 810341, + "tx_exon_id": 6895028, + "alt_exon_id": 6911797, + "exon_aln_id": 4375324 + } + } + ] + }, + { + "func": "get_tx_exons", + "args": [ + "NM_181798.1", + "NC_000011.10", + "splign" + ], + "value": [ + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 0, + "tx_start_i": 0, + "tx_end_i": 261, + "alt_start_i": 2461453, + "alt_end_i": 2461714, + "cigar": "261=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773599, + "alt_exon_id": 6791722, + "exon_aln_id": 3977791 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 1, + "tx_start_i": 261, + "tx_end_i": 352, + "alt_start_i": 2527927, + "alt_end_i": 2528018, + "cigar": "91=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773600, + "alt_exon_id": 6791723, + "exon_aln_id": 3977803 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 2, + "tx_start_i": 352, + "tx_end_i": 479, + "alt_start_i": 2570627, + "alt_end_i": 2570754, + "cigar": "127=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773601, + "alt_exon_id": 6791724, + "exon_aln_id": 3977799 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 3, + "tx_start_i": 479, + "tx_end_i": 558, + "alt_start_i": 2571324, + "alt_end_i": 2571403, + "cigar": "79=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773602, + "alt_exon_id": 6791725, + "exon_aln_id": 3977778 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 4, + "tx_start_i": 558, + "tx_end_i": 655, + "alt_start_i": 2572012, + "alt_end_i": 2572109, + "cigar": "97=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773603, + "alt_exon_id": 6791726, + "exon_aln_id": 3977805 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 5, + "tx_start_i": 655, + "tx_end_i": 796, + "alt_start_i": 2572845, + "alt_end_i": 2572986, + "cigar": "141=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773604, + "alt_exon_id": 6791727, + "exon_aln_id": 3977802 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 6, + "tx_start_i": 796, + "tx_end_i": 907, + "alt_start_i": 2583434, + "alt_end_i": 2583545, + "cigar": "111=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773605, + "alt_exon_id": 6791728, + "exon_aln_id": 3977793 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 7, + "tx_start_i": 907, + "tx_end_i": 1003, + "alt_start_i": 2585211, + "alt_end_i": 2585307, + "cigar": "96=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773606, + "alt_exon_id": 6791729, + "exon_aln_id": 3977779 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 8, + "tx_start_i": 1003, + "tx_end_i": 1126, + "alt_start_i": 2587569, + "alt_end_i": 2587692, + "cigar": "123=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773607, + "alt_exon_id": 6791730, + "exon_aln_id": 3977809 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 9, + "tx_start_i": 1126, + "tx_end_i": 1268, + "alt_start_i": 2588712, + "alt_end_i": 2588854, + "cigar": "142=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773608, + "alt_exon_id": 6791731, + "exon_aln_id": 3977801 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 10, + "tx_start_i": 1268, + "tx_end_i": 1389, + "alt_start_i": 2661960, + "alt_end_i": 2662081, + "cigar": "121=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773609, + "alt_exon_id": 6791732, + "exon_aln_id": 3977804 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 11, + "tx_start_i": 1389, + "tx_end_i": 1465, + "alt_start_i": 2768843, + "alt_end_i": 2768919, + "cigar": "76=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773610, + "alt_exon_id": 6791733, + "exon_aln_id": 3977796 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 12, + "tx_start_i": 1465, + "tx_end_i": 1560, + "alt_start_i": 2775959, + "alt_end_i": 2776054, + "cigar": "95=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773611, + "alt_exon_id": 6791734, + "exon_aln_id": 3977784 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 13, + "tx_start_i": 1560, + "tx_end_i": 1607, + "alt_start_i": 2776985, + "alt_end_i": 2777032, + "cigar": "47=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773612, + "alt_exon_id": 6791735, + "exon_aln_id": 3977780 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 14, + "tx_start_i": 1607, + "tx_end_i": 1669, + "alt_start_i": 2777975, + "alt_end_i": 2778037, + "cigar": "62=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773613, + "alt_exon_id": 6791736, + "exon_aln_id": 3977783 + } + }, + { + "psycopg2_dictrow": { + "symbol": "KCNQ1", + "hgnc": "KCNQ1", + "gene_id": "3784", + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign", + "alt_strand": 1, + "ord": 15, + "tx_start_i": 1669, + "tx_end_i": 3013, + "alt_start_i": 2847766, + "alt_end_i": 2849110, + "cigar": "1344=", + "tx_aseq": null, + "alt_aseq": null, + "tx_exon_set_id": 83331, + "alt_exon_set_id": 792010, + "tx_exon_id": 773614, + "alt_exon_id": 6791737, + "exon_aln_id": 3977787 + } + } + ] + }, + { + "func": "get_tx_identity_info", + "args": [ + "NM_001331029.1" + ], + "value": { + "psycopg2_dictrow": { + "tx_ac": "NM_001331029.1", + "alt_ac": "NM_001331029.1", + "alt_aln_method": "transcript", + "cds_start_i": 150, + "cds_end_i": 3282, + "lengths": [ + 441, + 131, + 119, + 160, + 145, + 75, + 80, + 140, + 113, + 204, + 83, + 126, + 183, + 183, + 91, + 204, + 190, + 113, + 42, + 17, + 145, + 105, + 54, + 51, + 8096 + ], + "hgnc": "PPP1R12B" + } + } + }, + { + "func": "get_tx_identity_info", + "args": [ + "NM_181798.1" + ], + "value": { + "psycopg2_dictrow": { + "tx_ac": "NM_181798.1", + "alt_ac": "NM_181798.1", + "alt_aln_method": "transcript", + "cds_start_i": 256, + "cds_end_i": 1906, + "lengths": [ + 261, + 91, + 127, + 79, + 97, + 141, + 111, + 96, + 123, + 142, + 121, + 76, + 95, + 47, + 62, + 1344 + ], + "hgnc": "KCNQ1" + } + } + }, + { + "func": "get_tx_info", + "args": [ + "NM_001331029.1", + "NC_000001.10", + "splign" + ], + "value": { + "psycopg2_dictrow": { + "hgnc": "PPP1R12B", + "cds_start_i": 150, + "cds_end_i": 3282, + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign" + } + } + }, + { + "func": "get_tx_info", + "args": [ + "NM_181798.1", + "NC_000011.10", + "splign" + ], + "value": { + "psycopg2_dictrow": { + "hgnc": "KCNQ1", + "cds_start_i": 256, + "cds_end_i": 1906, + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign" + } + } + }, + { + "func": "get_tx_mapping_options", + "args": [ + "NM_001331029.1" + ], + "value": [ + { + "psycopg2_dictrow": { + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.10", + "alt_aln_method": "splign" + } + }, + { + "psycopg2_dictrow": { + "tx_ac": "NM_001331029.1", + "alt_ac": "NC_000001.11", + "alt_aln_method": "splign" + } + } + ] + }, + { + "func": "get_tx_mapping_options", + "args": [ + "NM_181798.1" + ], + "value": [ + { + "psycopg2_dictrow": { + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.10", + "alt_aln_method": "splign" + } + }, + { + "psycopg2_dictrow": { + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.9", + "alt_aln_method": "blat" + } + }, + { + "psycopg2_dictrow": { + "tx_ac": "NM_181798.1", + "alt_ac": "NC_000011.9", + "alt_aln_method": "splign" + } + }, + { + "psycopg2_dictrow": { + "tx_ac": "NM_181798.1", + "alt_ac": "NG_008935.1", + "alt_aln_method": "splign" + } + } + ] + }, + { + "func": "get_tx_mapping_options", + "args": [ + "NR_040711.1" + ], + "value": [] + }, + { + "func": "get_tx_mapping_options", + "args": [ + "XM_017001344.1" + ], + "value": [] + }, + { + "func": "schema_version", + "args": [], + "value": "1.2" + } +] diff --git a/tests/data/hgvs_cache.pkl b/tests/data/hgvs_cache.pkl deleted file mode 100644 index 5ee7e7eb3d3cdc0ea65efd766dfa8a6cf0e229ff..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17169 zcmeI43v?URoyH|gvTRFn5`#m4gp!oJ6UVY0KOm4ehIP2ZgpfG2C8UaD3twFv+sFzb zoA69qwlE|>R33#wfKUj9@P350bQ{|8Y|GMicY6xuQRr?9fj&6w0^PFTH+s$7aoTby z=d66z$@z_?|I9Ztzk6q7`(EjS;8)5!eD>G5nVHt1vhVESy52<3V5&Pkm>RC@Pi=_z zboa+uz9tc%4m;_w~s`o$zbhOBU3A{`$_D!1`>=v&mc)Ww=IBJ2|Z zQ31%1tg_c^&#fuPWQ&s=#oG4v4t}+FbavriM+g3Qbsix4mJd%1h+RM-x+@=DBkbZM zj$&nRC%(FnpH1&L&{6MU^xeg+WhCoE9wP2yXVyKCz#()& zFb}q1ZL;XnVy&{SeAUvrLc=5+X(Nz3Qdyllf@#7obrwrjZ9DeW*-r6j0{%n0=KFzF zz05=(i#0aJ>KoeXVj1+UgW0#z=fsn}iGg%7y(yj?IAhT6XyKm0p-rhoAG&Tlg$_S3 zoK9`%L8nLOw#E((Z$iDVp)PSwI@LX#vBJkEd(tZgH?mr>ZbPy^ogBc^!T#iM8qcl4 z)u8X*`$QG828Mf5$)R+{xXOG!ip|Wueq*b#(b#ERVHn18!!ph?o;6k)=NS*<-)emS z7@nDJj7L3bG#icP&QB$*isj3f$5zA|mShqaXI60ca)E4?Eq1DGm2C+t(lglKpXf>B zYQ%v?PEPeEQi)!k1~1K%>` zr@K?>crs%ItV%vk4D|9*&C$xRx}~gcEX2xW0R6C^^s<9~{b_67B(O@||B-kFI3e^_g;>te1@= zHc!4E*2n5%^%<*tc&ICoV;4`j*hlPM;q8upO~9Gi-qbJG%YnRyTnqcOPT_ZT zin2o23KY9m(A%{_j(&pEk`m_=&7Du;9QIqi5sT;KxCE?VQ*$#~Q11nWJB`-DhTrfR zK3sSrbmZ8mcx=kpC?c9-$7Yr-6IXmD>Jy1I!1W7~J~4SCaQx#-e1&dto;+V(ATN{` z$*m&<$uIn+j9h0bAKtWn-C#ejyqr%zUj+vexKHtd%U_s(#hz8gYZdpc?g4C8ZUqKY zSca`CT-SxmwZf{v!`#(cX+^S|w)%jWOZ$bK}j zxv)&UKWki6oI86QS~=FJxANE6%15x3r#M^rM!8eoByX0t$X#e;RZ_j6eS(ulys-OOYV_( z%X{R#kmN~{_qil#A*CcK07K@=fH>hKNO~PWPin5$B;80!M^e%pr=-2|QTa{zE%|Nv z7$kX;w2)Gg6oeu3wSWk(fTU{xNNQT3N!m$CQz&VoQ_>IQ6Y@#A*JLf z3_)fjB;q}A^aj9-O_y{FB^^achdL$gmv70plB9){lB5b4GPi`p z6N8Y{I%G?VHEMUHU6eG9l8$ytdS8AZ|0MrM{#kwqNuDI-^ZR@*Pg+hXd8&jYb7{Fa zY70F54zPj^^-Y?mTj^;!JuP&2Qek*d6+|UbMMQ`w0CS#fH3kKjIW4)A%vC{~d0n|k zUJP^J0&uI+JJ{DLZU)62;}mx=CDjrWh(m~p#GwGhd7{-}D7eIF$)zMN0&C`>VbQz| z;vN8S|7vK~y4-CvH6w8v||T#TDXvx53=z z+ebFHo91TI+%%`TV`yn1aV&8hv4~g&rwWHuNrzMw?xoT)LU#$=emyC~!s{t#} zrvD;+2gS{yxcN?TODX9@LJ$UV5@7-m=ZRL!P;iOUl1oY4SXeXnREjBG5Vs!~>6P^x zG&h&#W;)HSqNP)b&k&y_K1ZAez?>&rtwzCRPD?H&bK{`R?5`5LPKUX5YiKUkrvHF@ zC(X^Hx#>=G>u9Nm=p_=w8AKldbDnG^QE-{ll1s_lcxW?UtP*=6P0aqhZO-#k?_D%k zM{|cc%?;Ah5OEffB8G`H0CS#fwE+c}IW4)A%+)}f8IFkbI+(iwumVjD+Rr3=C~iK* zO?8UfLP_Tm=Mm=<7Z4W$5a)?j7op%1rzMw?xPxHLoEQ7#nn^X zVyCz-Q_>~GrG!OXMr;Eh&J(S+qu>&!C6|)8gJI3w9TDxl5cfPV(%;PPp}82%&2XB# zik7Y>t|6`^zDisNz?>&rU5|pxoR(Zl=4zqMgtUDMm~*CWu3rC3+PyT_Ky!yX&D}yv zyNFwfuM@Wsw*xTe$yU2jaGBGROUc{>Xfu~a#Zwz$?nA%|EYN@1zmMV?DQ>b;+&z?Z zFL57nKk)$ZAOLZmX!Q^ZE^%6NDTzA-*38XOG4))CTLnOz{!{S%6xT#?4Nh_2rliM+ z?-2h?e3#ey&K~EPeEL$wZ2XNZT|tPTR?S_oa&yY zre}y}i60U_B7O`&ohMv9hk{F;mi)=7D~!=|I>VOyqz6u0!IUA)k!k0AAuKqDr7#~R zf@v$U)>unht378$&c>j3aTMQGwcL-K^GQsf-%N!$p(NzTw2||TlZ|fUGGowKYiu^Q z8JmogjJPr1IL=%gN?0MIW7#RO!c+(K3;KM4coE1(sbBK(OF(|?KR+z}NzNBhKj#6w z6*S)t=4USX3-h*IXFt*$57!EX;s4mk6Fk%(c!GZ<-udWf=^nCn?>Lg5>=vtQ!yKV? z{oU!J>pydc9}>Q@f?M?-o-lmseJ=d!11{`Y9|!ITx%qVVF7&x8DvW4VK~#RMopfSC zRcl-00`$znq?7zi2sMuRyKMw|6HE4h=(UvyTmv8A;MGqRkQ{ek)_?r)r`67q{N z+o$M0`1iw!_U5lwIFa0orKU&?~=M#(WTUeN?qUKV;Jfe=6Pt+4J zV1#JZfah`NJYaD4&WWDz|MOQk-Q@uDS3YKg`_bIyTEBSs%IRqF9n*b7ee->0OmeqXBrh9o>omP?AkHQ>66X+` z0J!!QGkEM(O;rpqwM*VEu6A1q}Ypyt;83IFA`q@ zAls9zE=Iv6TT340vddxGyfh##ITNzq10Xx5%YL1*>nXe4DSI2mZYM4$t{|=?b^ws= z$yON@T(Y&~Q7$_S)8-oiu{j0VzW{I-$^P12ykq~Gu48oF=yZJ@yD zFYzb<*`93mO%z$mLRP<9h#pX8Lik76GuzDInY z_yO?*0NI{w^&|=|*;?`_mmPs=b8kpIvuL(Y9I|*ef5_Hv*}tXh1$2G9)Af((^*Q2S zi06r)5I+Ur+7qpQhJwqrmORQ`Mq50pQvbtzJdJlK{r%^p*abdlfp5t79A@@| z9;WIa1keNp_|SmtfM`31Lh%H@_+0)!%h_kM%%8D5q#V!Z7i_5e EUq4F6 `` +""" + +import json +import pickle +import sys +from collections import OrderedDict +from pathlib import Path +from typing import Any + +from hgvs.decorators.lru_cache import _make_key +from psycopg2.extras import DictRow + +# hgvs builds each cache key as (*args, "__func__", function name) +_FUNC_MARKER = "__func__" +_DICTROW_TAG = "psycopg2_dictrow" +_JSON_SCALARS = (str, int, float, bool, type(None)) + + +def _encode_value(value: Any) -> Any: # noqa: ANN401 + """Convert a cached hgvs result to a JSON value""" + if isinstance(value, DictRow): + return {_DICTROW_TAG: dict(value.items())} + if isinstance(value, list): + return [_encode_value(v) for v in value] + if isinstance(value, _JSON_SCALARS): + return value + msg = f"can't store a {type(value).__name__} in the hgvs JSON cache: {value!r}" + raise TypeError(msg) + + +def _decode_value(value: Any) -> Any: # noqa: ANN401 + """Convert a JSON value back to the cached hgvs result, rebuilding UTA rows""" + if isinstance(value, dict): + if value.keys() != {_DICTROW_TAG}: + msg = f'expected {{"{_DICTROW_TAG}": {{...}}}}, got {value!r}' + raise ValueError(msg) + columns: dict[str, Any] = value[_DICTROW_TAG] + row = DictRow.__new__(DictRow) + index = OrderedDict((column, i) for i, column in enumerate(columns)) + row.__setstate__((list(columns.values()), index)) + return row + if isinstance(value, list): + return [_decode_value(v) for v in value] + return value + + +def pickle_to_json(pickle_file: Path, json_file: Path) -> None: + """Write the hgvs cache pickle `pickle_file` as JSON to `json_file` + + Only use this on a cache hgvs just recorded: loading a pickle can run code. + """ + with pickle_file.open("rb") as f: + cache: dict = pickle.load(f) # noqa: S301 # hgvs cache key -> cached result + entries = [] + for key in cache: + *args, marker, func = key + if marker != _FUNC_MARKER: + msg = f"unexpected hgvs cache key layout: {key!r}" + raise ValueError(msg) + entries.append({"func": func, "args": args, "value": _encode_value(cache[key])}) + entries.sort(key=lambda e: (e["func"], json.dumps(e["args"]))) + json_file.write_text(json.dumps(entries, indent=2) + "\n") + + +def json_to_pickle(json_file: Path, pickle_file: Path) -> None: + """Write the JSON hgvs cache `json_file` as the pickle hgvs loads to `pickle_file`""" + entries: list[dict[str, Any]] = json.loads(json_file.read_text()) + cache = {} + for e in entries: + try: + value = _decode_value(e["value"]) + except ValueError as err: + msg = f"{json_file}: {e['func']} {e['args']}: {err}" + raise ValueError(msg) from err + cache[_make_key(e["func"], tuple(e["args"]), {}, False, ())] = value + with pickle_file.open("wb") as f: + pickle.dump(cache, f) + + +if __name__ == "__main__": + pickle_to_json(Path(sys.argv[1]), Path(sys.argv[2])) From f38374776e457371ca4c135a3c8b412714ce2d9f Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 20 Oct 2026 17:41:22 -0400 Subject: [PATCH 11/18] test: fail tests that go past recorded data when replaying it --- README.md | 8 +- tests/conftest.py | 87 +++++++++++-- .../test_hgvs_cache_run_mode_is_offline.yaml | 48 -------- tests/extras/test_allele_translator.py | 33 ----- tests/offline_guard.py | 114 ++++++++++++++++++ tests/test_offline_guard.py | 57 +++++++++ 6 files changed, 251 insertions(+), 96 deletions(-) delete mode 100644 tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml create mode 100644 tests/offline_guard.py create mode 100644 tests/test_offline_guard.py diff --git a/README.md b/README.md index ab6d4287..a13f0edc 100644 --- a/README.md +++ b/README.md @@ -323,11 +323,13 @@ service, a UTA database, or network access. Set `SEQREPO_ROOT_DIR=tests/data/seq - **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). CI - runs `pytest --vcr-record=none`, so a test making an unrecorded request fails. + runs `pytest --vcr-record=none`. In that mode, any test that opens a network + connection fails, including HTTP requests from tests not marked `@pytest.mark.vcr` + and Postgres connections (`tests/offline_guard.py`). - **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA queries and sequence fetches. `tests/conftest.py` enables it by default - (`VRS_HGVS_CACHE_MODE=run`), and a lookup missing from the cache raises - `HGVSDataNotAvailableError`. hgvs itself reads and writes its cache as a pickle; + (`VRS_HGVS_CACHE_MODE=run`). In that mode, any test fails if hgvs looks up data + missing from the cache. hgvs itself reads and writes its cache as a pickle; `tests/hgvs_cache_json.py` converts between the two. To re-record, start the external services (`docker compose up` starts diff --git a/tests/conftest.py b/tests/conftest.py index fd3d5d9a..64bea06d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,15 +6,44 @@ import pytest from biocommons.seqrepo import SeqRepo from hgvs_cache_json import json_to_pickle +from offline_guard import OfflineGuard from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy HGVS_CACHE_MODES = ("learn", "run", "verify") HGVS_CACHE_JSON = Path(__file__).parent / "data" / "hgvs_cache.json" +# Run mode never connects to UTA. This URL refuses connections, and being on localhost +# it also keeps hgvs from logging that tests are using remote data. +HGVS_OFFLINE_UTA_URL = "postgresql://anonymous@localhost:1/uta/uta_offline" + + +def _hgvs_cache_mode() -> str | None: + """Return `VRS_HGVS_CACHE_MODE` (default `run`), or None when it's empty""" + return os.environ.get("VRS_HGVS_CACHE_MODE", "run") or None + + +def pytest_configure() -> None: + """Check the hgvs cache settings once, before any test runs""" + mode = _hgvs_cache_mode() + if mode is not None and mode not in HGVS_CACHE_MODES: + msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" + raise pytest.UsageError(msg) + if mode == "learn" and not os.environ.get("VRS_HGVS_CACHE_FILE"): + msg = ( + "VRS_HGVS_CACHE_FILE must name the pickle file to record into in learn mode" + ) + raise pytest.UsageError(msg) + + +@pytest.fixture(scope="session") +def hgvs_cache_mode() -> str | None: + """Return the hgvs cache mode tests run in: `run`, `learn`, `verify`, or None""" + return _hgvs_cache_mode() @pytest.fixture(scope="session", autouse=True) def hgvs_cached_data_provider( + hgvs_cache_mode: str | None, tmp_path_factory: pytest.TempPathFactory, ) -> Iterator[hgvs.dataproviders.uta.UTABase | None]: """Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a @@ -23,7 +52,7 @@ def hgvs_cached_data_provider( Every `HgvsTools` gets this one data provider, so in learn mode they cannot overwrite each other's cache entries. `VRS_HGVS_CACHE_MODE` is `run` (default), `learn`, or `verify`, or empty to query UTA directly without the cache. In run - mode, a lookup missing from the cache raises `HGVSDataNotAvailableError`. + mode, `offline_check` fails any test during which hgvs misses the cache. hgvs keeps its cache as a pickle, so in run and verify modes the committed `tests/data/hgvs_cache.json` is converted to a temporary pickle for hgvs to load @@ -37,23 +66,19 @@ def hgvs_cached_data_provider( VCR cassettes don't contain those hgvs sequence requests (to HGVS_SEQREPO_URL), so run these modes with `pytest --disable-vcr`. """ - mode = os.environ.get("VRS_HGVS_CACHE_MODE", "run") - if not mode: + if hgvs_cache_mode is None: yield None return - if mode not in HGVS_CACHE_MODES: - msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" - raise pytest.UsageError(msg) - if mode == "learn": - cache_file = os.environ.get("VRS_HGVS_CACHE_FILE") - if not cache_file: - msg = "VRS_HGVS_CACHE_FILE must name the pickle file to record into in learn mode" - raise pytest.UsageError(msg) + if hgvs_cache_mode == "learn": + cache_file = os.environ["VRS_HGVS_CACHE_FILE"] else: cache_file = str(tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl") json_to_pickle(HGVS_CACHE_JSON, Path(cache_file)) - provider = hgvs.dataproviders.uta.connect(mode=mode, cache=cache_file) + db_url = HGVS_OFFLINE_UTA_URL if hgvs_cache_mode == "run" else None + provider = hgvs.dataproviders.uta.connect( + db_url=db_url, mode=hgvs_cache_mode, cache=cache_file + ) with pytest.MonkeyPatch.context() as mp: mp.setattr( hgvs.dataproviders.uta, "connect", lambda *_args, **_kwargs: provider @@ -64,6 +89,44 @@ def hgvs_cached_data_provider( provider.close() +@pytest.fixture(scope="session") +def offline_guard( + request: pytest.FixtureRequest, + hgvs_cache_mode: str | None, + hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, +) -> Iterator[OfflineGuard]: + """Guard the session against going past recorded data (see `offline_guard.py`) + + With `--vcr-record=none`, network connections are blocked; other record modes + record cassettes, which needs the network. With the hgvs cache in run mode, hgvs + cache misses are recorded. + """ + guard = OfflineGuard() + with pytest.MonkeyPatch.context() as mp: + if request.config.getoption("--vcr-record") == "none": + guard.block_network(mp) + if hgvs_cache_mode == "run": + guard.record_hgvs_cache_misses(mp, hgvs_cached_data_provider) + yield guard + + +@pytest.fixture(autouse=True) +def offline_check(offline_guard: OfflineGuard) -> Iterator[None]: + """Fail a test, at teardown, if a network connection was opened or the hgvs cache + was missed since the previous test's check, which includes the setup and teardown + of wider-scoped fixtures + """ + yield + if violations := offline_guard.violations[:]: + offline_guard.violations.clear() + pytest.fail( + "This test, or a fixture set up or torn down before it, went past its " + "recorded data. Record its HTTP requests in a VCR cassette " + "(`@pytest.mark.vcr`), and re-record hgvs data with " + "`make record-hgvs-cache`.\n" + "\n".join(violations) + ) + + def remove_request_headers(request): """Remove all headers from VCR request before recording.""" request.headers = {} diff --git a/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml b/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml deleted file mode 100644 index 34775aab..00000000 --- a/tests/extras/cassettes/test_hgvs_cache_run_mode_is_offline.yaml +++ /dev/null @@ -1,48 +0,0 @@ -interactions: -- request: - body: null - headers: {} - method: GET - uri: http://localhost:5000/seqrepo/1/metadata/refseq:NM_181798.1 - response: - body: - string: "{\n \"added\": \"2016-08-24T05:03:05Z\",\n \"aliases\": [\n \"MD5:93e2dc533ba755782b3affcf53470434\",\n - \ \"NCBI:NM_181798.1\",\n \"refseq:NM_181798.1\",\n \"NCBI:NR_040711.1\",\n - \ \"refseq:NR_040711.1\",\n \"SEGUID:0nrqUDibhGAQBZ4pXR+soOiCOf0\",\n - \ \"SHA1:d27aea50389b846010059e295d1faca0e88239fd\",\n \"VMC:GS_KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n - \ \"sha512t24u:KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n \"ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\"\n - \ ],\n \"alphabet\": \"ACGT\",\n \"length\": 3029\n}\n" - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: http://localhost:5000/seqrepo/1/metadata/ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg - response: - body: - string: "{\n \"added\": \"2016-08-24T05:03:05Z\",\n \"aliases\": [\n \"MD5:93e2dc533ba755782b3affcf53470434\",\n - \ \"NCBI:NM_181798.1\",\n \"refseq:NM_181798.1\",\n \"NCBI:NR_040711.1\",\n - \ \"refseq:NR_040711.1\",\n \"SEGUID:0nrqUDibhGAQBZ4pXR+soOiCOf0\",\n - \ \"SHA1:d27aea50389b846010059e295d1faca0e88239fd\",\n \"VMC:GS_KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n - \ \"sha512t24u:KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\",\n \"ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg\"\n - \ ],\n \"alphabet\": \"ACGT\",\n \"length\": 3029\n}\n" - headers: {} - status: - code: 200 - message: OK -- request: - body: null - headers: {} - method: GET - uri: http://localhost:5000/seqrepo/1/sequence/ga4gh:SQ.KN07u-RFqd1dTyOWOG98HnOq87Nq-ZIg?start=1262&end=1263 - response: - body: - string: G - headers: {} - status: - code: 200 - message: OK -version: 1 diff --git a/tests/extras/test_allele_translator.py b/tests/extras/test_allele_translator.py index ea42ad24..4c8dcdcd 100644 --- a/tests/extras/test_allele_translator.py +++ b/tests/extras/test_allele_translator.py @@ -1,9 +1,4 @@ -from typing import NoReturn - -import hgvs.dataproviders.seqfetcher -import hgvs.dataproviders.uta import pytest -from hgvs.decorators.lru_cache import RUN from pydantic import ValidationError from ga4gh.vrs import models @@ -773,34 +768,6 @@ def test_hgvs(tlr, hgvsexpr, expected): ) -@pytest.mark.vcr -def test_hgvs_cache_run_mode_is_offline( - monkeypatch: pytest.MonkeyPatch, - tlr: AlleleTranslator, - hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, -) -> None: - """With the tests' default hgvs cache (run mode), translating to and from hgvs - makes no UTA queries or hgvs sequence fetches. - - Replaces the two places hgvs reaches outside the process, `UTA_postgresql._get_cursor` - (every UTA query) and `SeqFetcher.fetch_seq` (every sequence fetch), with a function - that fails, then translates a transcript variant both ways. Skipped outside run mode - (e.g. when re-recording the cache), where both are expected. - """ - if hgvs_cached_data_provider is None or hgvs_cached_data_provider.mode != RUN: - pytest.skip("only applies when the hgvs cache is in run mode") - - def fail(*args: object, **kwargs: object) -> NoReturn: # noqa: ARG001 - msg = "hgvs queried UTA or fetched a sequence in hgvs cache run mode" - raise AssertionError(msg) - - monkeypatch.setattr(hgvs.dataproviders.uta.UTA_postgresql, "_get_cursor", fail) - monkeypatch.setattr(hgvs.dataproviders.seqfetcher.SeqFetcher, "fetch_seq", fail) - - allele = tlr.translate_from("NM_181798.1:c.1007G>T", "hgvs") - assert "NM_181798.1:c.1007G>T" in tlr.translate_to(allele, "hgvs") - - @pytest.mark.vcr def test_rle_seq_limit(tlr): """Test that for an ReferenceLengthExpression over 50bp, the sequence is not diff --git a/tests/offline_guard.py b/tests/offline_guard.py new file mode 100644 index 00000000..7ff1909a --- /dev/null +++ b/tests/offline_guard.py @@ -0,0 +1,114 @@ +"""Keep tests from going past their recorded data. + +Tests replay recorded data: VCR cassettes for HTTP requests, and the hgvs cache for +hgvs's UTA queries and sequence fetches. `conftest.py` installs an `OfflineGuard` for +the session that: + +- with `--vcr-record=none` (as in CI), blocks network connections, both through Python + sockets (all HTTP clients) and `psycopg2.connect` (libpq connects in C). VCR serves + recorded requests without opening a connection, so any connection is a request + missing from a cassette, or from a test not marked `@pytest.mark.vcr`. +- with the hgvs cache in run mode (the default), records cache misses, which + `HgvsTools` would otherwise catch and only log. + +Each violation is recorded as well as raised, because library code catches some +errors, so a raised error alone could be swallowed. `conftest.py` fails the test during +which a violation was recorded. +""" + +import functools +import socket +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any, NoReturn + +import hgvs.dataproviders.uta +import psycopg2 +import pytest +from hgvs.exceptions import HGVSDataNotAvailableError + +# Socket families that reach the network; others, like Unix sockets, are local IPC +_NETWORK_FAMILIES = (socket.AF_INET, socket.AF_INET6) + + +class OfflineError(AssertionError): + """A test opened a network connection while tests replay recorded data""" + + +def _describe_call(name: str, args: tuple, kwargs: dict[str, Any]) -> str: + params = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()] + return f"{name}({', '.join(params)})" + + +@dataclass +class OfflineGuard: + """Blocks network connections and records hgvs cache misses while installed""" + + violations: list[str] = field(default_factory=list) + blocking_network: bool = False + recording_hgvs_cache_misses: bool = False + + def block_network(self, mp: pytest.MonkeyPatch) -> None: + """Make network connections raise `OfflineError`""" + for name in ("connect", "connect_ex"): + mp.setattr(socket.socket, name, self._blocked_socket_method(name)) + mp.setattr(psycopg2, "connect", self._blocked("psycopg2.connect")) + self.blocking_network = True + + def record_hgvs_cache_misses( + self, mp: pytest.MonkeyPatch, provider: hgvs.dataproviders.uta.UTABase + ) -> None: + """Record cache misses of `provider`, which must use the hgvs cache in run mode + + hgvs wraps each of its lookups in its own `lru_cache`, stored as an instance + attribute. In run mode that wrapper raises `HGVSDataNotAvailableError` on a miss + without calling the lookup, so any such error coming out of these methods is a + cache miss. + """ + cached_lookups = { + name: method + for name, method in vars(provider).items() + if hasattr(method, "cache_info") + } + if not cached_lookups: + msg = "found no cached hgvs data provider lookups to guard" + raise RuntimeError(msg) + for name, method in cached_lookups.items(): + mp.setattr(provider, name, self._recording_misses(name, method)) + self.recording_hgvs_cache_misses = True + + def _block(self, call: str) -> NoReturn: + self.violations.append(f"blocked: {call}") + msg = f"{call} opens a network connection while tests replay recorded data" + raise OfflineError(msg) + + def _blocked(self, name: str) -> Callable[..., NoReturn]: + def blocked(*args: object, **kwargs: object) -> NoReturn: + self._block(_describe_call(name, args, kwargs)) + + return blocked + + def _blocked_socket_method(self, name: str) -> Callable[..., Any]: + original = getattr(socket.socket, name) + + def blocked_socket_method(sock: socket.socket, *args: object) -> Any: # noqa: ANN401 + if sock.family in _NETWORK_FAMILIES: + self._block(_describe_call(f"socket.{name}", args, {})) + return original(sock, *args) + + return blocked_socket_method + + def _recording_misses( + self, name: str, method: Callable[..., Any] + ) -> Callable[..., Any]: + @functools.wraps(method) + def recording_misses(*args: object, **kwargs: object) -> Any: # noqa: ANN401 + try: + return method(*args, **kwargs) + except HGVSDataNotAvailableError: + self.violations.append( + f"hgvs cache miss: {_describe_call(name, args, kwargs)}" + ) + raise + + return recording_misses diff --git a/tests/test_offline_guard.py b/tests/test_offline_guard.py new file mode 100644 index 00000000..f5ae73e4 --- /dev/null +++ b/tests/test_offline_guard.py @@ -0,0 +1,57 @@ +"""Tests for the session's offline guard (tests/offline_guard.py).""" + +from typing import Any + +import hgvs.dataproviders.uta +import psycopg2 +import pytest +import requests +from hgvs.exceptions import HGVSDataNotAvailableError +from offline_guard import OfflineError, OfflineGuard + +offline_guard_cases: list[dict[str, Any]] = [ + { + "id": "http-request", + "active_when": "blocking_network", + "call": lambda _provider: requests.get("http://127.0.0.1:1/", timeout=1), + "raises": OfflineError, + "violation": "blocked: socket.connect(('127.0.0.1', 1))", + }, + { + "id": "postgres-connect", + "active_when": "blocking_network", + "call": lambda _provider: psycopg2.connect( + "postgresql://anonymous@127.0.0.1:1/uta" + ), + "raises": OfflineError, + "violation": "blocked: psycopg2.connect('postgresql://anonymous@127.0.0.1:1/uta')", + }, + { + "id": "hgvs-cache-miss", + "active_when": "recording_hgvs_cache_misses", + "call": lambda provider: provider.get_tx_info( + "NM_000000.0", "NC_000001.11", "splign" + ), + "raises": HGVSDataNotAvailableError, + "violation": "hgvs cache miss: get_tx_info('NM_000000.0', 'NC_000001.11', 'splign')", + }, +] + + +@pytest.mark.parametrize("case", offline_guard_cases, ids=lambda c: c["id"]) +def test_offline_guard( + case: dict[str, Any], + offline_guard: OfflineGuard, + hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, +) -> None: + """The offline guard blocks network connections and records hgvs cache misses, each + as one violation + """ + if not getattr(offline_guard, case["active_when"]): + pytest.skip(f"the offline guard isn't {case['active_when'].replace('_', ' ')}") + start = len(offline_guard.violations) + with pytest.raises(case["raises"]): + case["call"](hgvs_cached_data_provider) + assert offline_guard.violations[start:] == [case["violation"]] + # these violations are expected; keep them from failing this test at teardown + del offline_guard.violations[start:] From d0ffc5fa588a23785fe383d22494db276aaa082e Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 20 Oct 2026 17:41:22 -0400 Subject: [PATCH 12/18] build: require UTA_DB_URL and ignore HGVS_SEQREPO_DIR when recording the hgvs cache --- Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index a751e490..5bd3535a 100644 --- a/Makefile +++ b/Makefile @@ -130,9 +130,11 @@ clean-cassettes: #=> record-hgvs-cache: re-record tests/data/hgvs_cache.json (needs UTA_DB_URL and a running seqrepo-rest-service at SEQREPO_REST_URL; VCR cassettes are not touched) .PHONY: record-hgvs-cache +# hgvs fetches sequences from HGVS_SEQREPO_DIR instead of HGVS_SEQREPO_URL when it's set, so it's unset for the recording run record-hgvs-cache: + @test -n "$${UTA_DB_URL}" || { echo "record-hgvs-cache: set UTA_DB_URL to the UTA instance to record from" >&2; exit 1; } rm -f tests/data/hgvs_cache.pkl.new - HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn VRS_HGVS_CACHE_FILE=$(CURDIR)/tests/data/hgvs_cache.pkl.new pytest --disable-vcr + env -u HGVS_SEQREPO_DIR HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn VRS_HGVS_CACHE_FILE=$(CURDIR)/tests/data/hgvs_cache.pkl.new pytest --disable-vcr python tests/hgvs_cache_json.py tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.json rm tests/data/hgvs_cache.pkl.new From f2b8ed07026b51ca7c99f117ba425a99bf2a38fc Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 20 Oct 2026 17:41:23 -0400 Subject: [PATCH 13/18] test: check value types and row widths when writing the hgvs JSON cache --- tests/hgvs_cache_json.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/tests/hgvs_cache_json.py b/tests/hgvs_cache_json.py index b1c84033..e861d5f9 100644 --- a/tests/hgvs_cache_json.py +++ b/tests/hgvs_cache_json.py @@ -31,7 +31,11 @@ def _encode_value(value: Any) -> Any: # noqa: ANN401 """Convert a cached hgvs result to a JSON value""" if isinstance(value, DictRow): - return {_DICTROW_TAG: dict(value.items())} + columns = dict(value.items()) + if len(columns) != len(value): + msg = f"row has {len(value)} values but {len(columns)} column names: {value!r}" + raise ValueError(msg) + return {_DICTROW_TAG: {c: _encode_value(v) for c, v in columns.items()}} if isinstance(value, list): return [_encode_value(v) for v in value] if isinstance(value, _JSON_SCALARS): @@ -69,7 +73,16 @@ def pickle_to_json(pickle_file: Path, json_file: Path) -> None: if marker != _FUNC_MARKER: msg = f"unexpected hgvs cache key layout: {key!r}" raise ValueError(msg) - entries.append({"func": func, "args": args, "value": _encode_value(cache[key])}) + try: + entry = { + "func": func, + "args": _encode_value(args), + "value": _encode_value(cache[key]), + } + except (TypeError, ValueError) as err: + msg = f"{pickle_file}: {func} {args}: {err}" + raise type(err)(msg) from err + entries.append(entry) entries.sort(key=lambda e: (e["func"], json.dumps(e["args"]))) json_file.write_text(json.dumps(entries, indent=2) + "\n") From 7fbe20df3787046baa9b4b4c7898b3c1a342a811 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 20 Oct 2026 18:32:42 -0400 Subject: [PATCH 14/18] test: fail immediately on offline violations and simplify cache modes --- README.md | 14 ++-- tests/conftest.py | 127 ++++++++++++-------------------- tests/extras/test_hgvs_tools.py | 4 +- tests/offline_guard.py | 119 +++++++----------------------- tests/test_offline_guard.py | 94 +++++++++++------------ 5 files changed, 123 insertions(+), 235 deletions(-) diff --git a/README.md b/README.md index a13f0edc..1bab33ce 100644 --- a/README.md +++ b/README.md @@ -323,14 +323,16 @@ service, a UTA database, or network access. Set `SEQREPO_ROOT_DIR=tests/data/seq - **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). CI - runs `pytest --vcr-record=none`. In that mode, any test that opens a network - connection fails, including HTTP requests from tests not marked `@pytest.mark.vcr` - and Postgres connections (`tests/offline_guard.py`). + runs `pytest --vcr-record=none`. In that mode, attempts to open Python socket + connections or connect through psycopg2 fail immediately, including HTTP requests + from tests not marked `@pytest.mark.vcr` (`tests/offline_guard.py`). - **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA queries and sequence fetches. `tests/conftest.py` enables it by default - (`VRS_HGVS_CACHE_MODE=run`). In that mode, any test fails if hgvs looks up data - missing from the cache. hgvs itself reads and writes its cache as a pickle; - `tests/hgvs_cache_json.py` converts between the two. + (`VRS_HGVS_CACHE_MODE=run`). A missing entry fails immediately, even when + production code would normally catch the HGVS error. The only other supported + mode is `learn`, used by `make record-hgvs-cache` to record live data. hgvs itself + reads and writes its cache as a pickle; `tests/hgvs_cache_json.py` converts between + the two. To re-record, start the external services (`docker compose up` starts seqrepo-rest-service on port 5000 and UTA on port 5432). With an existing local SeqRepo diff --git a/tests/conftest.py b/tests/conftest.py index 64bea06d..2287e11d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,27 +6,30 @@ import pytest from biocommons.seqrepo import SeqRepo from hgvs_cache_json import json_to_pickle -from offline_guard import OfflineGuard +from offline_guard import block_network, require_recorded_data from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy -HGVS_CACHE_MODES = ("learn", "run", "verify") +HGVS_CACHE_MODES = ("learn", "run") HGVS_CACHE_JSON = Path(__file__).parent / "data" / "hgvs_cache.json" # Run mode never connects to UTA. This URL refuses connections, and being on localhost # it also keeps hgvs from logging that tests are using remote data. HGVS_OFFLINE_UTA_URL = "postgresql://anonymous@localhost:1/uta/uta_offline" -def _hgvs_cache_mode() -> str | None: - """Return `VRS_HGVS_CACHE_MODE` (default `run`), or None when it's empty""" - return os.environ.get("VRS_HGVS_CACHE_MODE", "run") or None +def _hgvs_cache_mode() -> str: + """Return `VRS_HGVS_CACHE_MODE` (default `run`)""" + return os.environ.get("VRS_HGVS_CACHE_MODE", "run") -def pytest_configure() -> None: +def pytest_configure(config: pytest.Config) -> None: """Check the hgvs cache settings once, before any test runs""" mode = _hgvs_cache_mode() - if mode is not None and mode not in HGVS_CACHE_MODES: - msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES} or empty, got {mode!r}" + if mode not in HGVS_CACHE_MODES: + msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES}, got {mode!r}" + raise pytest.UsageError(msg) + if mode == "learn" and config.getoption("--vcr-record") == "none": + msg = "HGVS recording requires live connections; use --disable-vcr without --vcr-record=none." raise pytest.UsageError(msg) if mode == "learn" and not os.environ.get("VRS_HGVS_CACHE_FILE"): msg = ( @@ -36,39 +39,33 @@ def pytest_configure() -> None: @pytest.fixture(scope="session") -def hgvs_cache_mode() -> str | None: - """Return the hgvs cache mode tests run in: `run`, `learn`, `verify`, or None""" +def hgvs_cache_mode() -> str: + """Return the hgvs cache mode tests run in: `run` or `learn`""" return _hgvs_cache_mode() +@pytest.fixture(scope="session") +def network_blocked(request: pytest.FixtureRequest) -> Iterator[bool]: + """Block live connections before provider setup when replaying VCR cassettes""" + blocked = request.config.getoption("--vcr-record") == "none" + with pytest.MonkeyPatch.context() as mp: + if blocked: + block_network(mp) + yield blocked + + @pytest.fixture(scope="session", autouse=True) def hgvs_cached_data_provider( - hgvs_cache_mode: str | None, + hgvs_cache_mode: str, + network_blocked: bool, # noqa: ARG001 # Install blockers before provider setup. tmp_path_factory: pytest.TempPathFactory, -) -> Iterator[hgvs.dataproviders.uta.UTABase | None]: - """Serve hgvs data provider lookups (UTA queries and hgvs sequence fetches) from a - recorded cache, so tests don't need a UTA database or network access. - - Every `HgvsTools` gets this one data provider, so in learn mode they cannot - overwrite each other's cache entries. `VRS_HGVS_CACHE_MODE` is `run` (default), - `learn`, or `verify`, or empty to query UTA directly without the cache. In run - mode, `offline_check` fails any test during which hgvs misses the cache. - - hgvs keeps its cache as a pickle, so in run and verify modes the committed - `tests/data/hgvs_cache.json` is converted to a temporary pickle for hgvs to load - (see `hgvs_cache_json.py`). Learn mode records a new cache, starting empty, into - the pickle file named by `VRS_HGVS_CACHE_FILE`. To re-record, run - `make record-hgvs-cache` with UTA_DB_URL pointing at a UTA instance and a - seqrepo-rest-service running at SEQREPO_REST_URL; it converts the recorded pickle - to `tests/data/hgvs_cache.json`. - - Learn and verify modes, and an empty mode, query UTA and fetch sequences live. The - VCR cassettes don't contain those hgvs sequence requests (to HGVS_SEQREPO_URL), so - run these modes with `pytest --disable-vcr`. +) -> Iterator[hgvs.dataproviders.uta.UTABase]: + """Share one provider for HGVS replay or recording. + + Replay (`run`, the default) loads the committed JSON via a temporary pickle and + fails immediately on missing data. `make record-hgvs-cache` uses `learn` with + VRS_HGVS_CACHE_FILE and live services to record a replacement. """ - if hgvs_cache_mode is None: - yield None - return if hgvs_cache_mode == "learn": cache_file = os.environ["VRS_HGVS_CACHE_FILE"] else: @@ -79,52 +76,22 @@ def hgvs_cached_data_provider( provider = hgvs.dataproviders.uta.connect( db_url=db_url, mode=hgvs_cache_mode, cache=cache_file ) - with pytest.MonkeyPatch.context() as mp: - mp.setattr( - hgvs.dataproviders.uta, "connect", lambda *_args, **_kwargs: provider - ) - # HgvsTools.close() closes its data provider, but this one is shared - mp.setattr(provider, "close", lambda: None) - yield provider - provider.close() - - -@pytest.fixture(scope="session") -def offline_guard( - request: pytest.FixtureRequest, - hgvs_cache_mode: str | None, - hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, -) -> Iterator[OfflineGuard]: - """Guard the session against going past recorded data (see `offline_guard.py`) - - With `--vcr-record=none`, network connections are blocked; other record modes - record cassettes, which needs the network. With the hgvs cache in run mode, hgvs - cache misses are recorded. - """ - guard = OfflineGuard() - with pytest.MonkeyPatch.context() as mp: - if request.config.getoption("--vcr-record") == "none": - guard.block_network(mp) - if hgvs_cache_mode == "run": - guard.record_hgvs_cache_misses(mp, hgvs_cached_data_provider) - yield guard - - -@pytest.fixture(autouse=True) -def offline_check(offline_guard: OfflineGuard) -> Iterator[None]: - """Fail a test, at teardown, if a network connection was opened or the hgvs cache - was missed since the previous test's check, which includes the setup and teardown - of wider-scoped fixtures - """ - yield - if violations := offline_guard.violations[:]: - offline_guard.violations.clear() - pytest.fail( - "This test, or a fixture set up or torn down before it, went past its " - "recorded data. Record its HTTP requests in a VCR cassette " - "(`@pytest.mark.vcr`), and re-record hgvs data with " - "`make record-hgvs-cache`.\n" + "\n".join(violations) - ) + try: + with pytest.MonkeyPatch.context() as mp: + if hgvs_cache_mode == "run": + # In run mode, these wrappers raise HGVSDataNotAvailableError only + # for cache misses; ordinary domain errors occur above this layer. + for name, method in vars(provider).items(): + if hasattr(method, "cache_info"): + mp.setattr(provider, name, require_recorded_data(method)) + mp.setattr( + hgvs.dataproviders.uta, "connect", lambda *_args, **_kwargs: provider + ) + # HgvsTools.close() closes its data provider, but this one is shared. + mp.setattr(provider, "close", lambda: None) + yield provider + finally: + provider.close() def remove_request_headers(request): diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index 5d48dbeb..cc1ce73d 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -44,12 +44,10 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): def test_hgvs_cache_data_provider_is_shared( - hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, + hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase, ) -> None: """Every HgvsTools gets the tests' shared hgvs cache data provider, so in learn mode they cannot overwrite each other's cache entries """ - if hgvs_cached_data_provider is None: - pytest.skip("the hgvs cache is disabled") assert HgvsTools().uta_conn is hgvs_cached_data_provider assert HgvsTools().uta_conn is hgvs_cached_data_provider diff --git a/tests/offline_guard.py b/tests/offline_guard.py index 7ff1909a..22a3ac1b 100644 --- a/tests/offline_guard.py +++ b/tests/offline_guard.py @@ -1,114 +1,45 @@ -"""Keep tests from going past their recorded data. +"""Fail immediately on live connections or missing HGVS recordings. -Tests replay recorded data: VCR cassettes for HTTP requests, and the hgvs cache for -hgvs's UTA queries and sequence fetches. `conftest.py` installs an `OfflineGuard` for -the session that: - -- with `--vcr-record=none` (as in CI), blocks network connections, both through Python - sockets (all HTTP clients) and `psycopg2.connect` (libpq connects in C). VCR serves - recorded requests without opening a connection, so any connection is a request - missing from a cassette, or from a test not marked `@pytest.mark.vcr`. -- with the hgvs cache in run mode (the default), records cache misses, which - `HgvsTools` would otherwise catch and only log. - -Each violation is recorded as well as raised, because library code catches some -errors, so a raised error alone could be swallowed. `conftest.py` fails the test during -which a violation was recorded. +pytest.fail raises outside Exception, so production fallback handlers cannot swallow +these failures. VCR replay does not open sockets; psycopg2 needs its own patch because +libpq opens connections in C. """ import functools import socket from collections.abc import Callable -from dataclasses import dataclass, field from typing import Any, NoReturn -import hgvs.dataproviders.uta import psycopg2 import pytest from hgvs.exceptions import HGVSDataNotAvailableError -# Socket families that reach the network; others, like Unix sockets, are local IPC -_NETWORK_FAMILIES = (socket.AF_INET, socket.AF_INET6) - - -class OfflineError(AssertionError): - """A test opened a network connection while tests replay recorded data""" - - -def _describe_call(name: str, args: tuple, kwargs: dict[str, Any]) -> str: - params = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()] - return f"{name}({', '.join(params)})" - - -@dataclass -class OfflineGuard: - """Blocks network connections and records hgvs cache misses while installed""" - - violations: list[str] = field(default_factory=list) - blocking_network: bool = False - recording_hgvs_cache_misses: bool = False - - def block_network(self, mp: pytest.MonkeyPatch) -> None: - """Make network connections raise `OfflineError`""" - for name in ("connect", "connect_ex"): - mp.setattr(socket.socket, name, self._blocked_socket_method(name)) - mp.setattr(psycopg2, "connect", self._blocked("psycopg2.connect")) - self.blocking_network = True - - def record_hgvs_cache_misses( - self, mp: pytest.MonkeyPatch, provider: hgvs.dataproviders.uta.UTABase - ) -> None: - """Record cache misses of `provider`, which must use the hgvs cache in run mode - - hgvs wraps each of its lookups in its own `lru_cache`, stored as an instance - attribute. In run mode that wrapper raises `HGVSDataNotAvailableError` on a miss - without calling the lookup, so any such error coming out of these methods is a - cache miss. - """ - cached_lookups = { - name: method - for name, method in vars(provider).items() - if hasattr(method, "cache_info") - } - if not cached_lookups: - msg = "found no cached hgvs data provider lookups to guard" - raise RuntimeError(msg) - for name, method in cached_lookups.items(): - mp.setattr(provider, name, self._recording_misses(name, method)) - self.recording_hgvs_cache_misses = True - def _block(self, call: str) -> NoReturn: - self.violations.append(f"blocked: {call}") - msg = f"{call} opens a network connection while tests replay recorded data" - raise OfflineError(msg) +def block_network(mp: pytest.MonkeyPatch) -> None: + """Block Python socket connections and psycopg2 for offline tests""" - def _blocked(self, name: str) -> Callable[..., NoReturn]: - def blocked(*args: object, **kwargs: object) -> NoReturn: - self._block(_describe_call(name, args, kwargs)) + def forbidden_connection(*_args: object, **_kwargs: object) -> NoReturn: + pytest.fail("Live network connections are disabled in offline tests.") - return blocked + def forbidden_postgres(*_args: object, **_kwargs: object) -> NoReturn: + pytest.fail("Live PostgreSQL connections are disabled in offline tests.") - def _blocked_socket_method(self, name: str) -> Callable[..., Any]: - original = getattr(socket.socket, name) + mp.setattr(socket.socket, "connect", forbidden_connection) + mp.setattr(socket.socket, "connect_ex", forbidden_connection) + mp.setattr(psycopg2, "connect", forbidden_postgres) - def blocked_socket_method(sock: socket.socket, *args: object) -> Any: # noqa: ANN401 - if sock.family in _NETWORK_FAMILIES: - self._block(_describe_call(f"socket.{name}", args, {})) - return original(sock, *args) - return blocked_socket_method +def require_recorded_data(method: Callable[..., Any]) -> Callable[..., Any]: + """Make a replay-mode provider cache miss fatal, even inside HGVS fallbacks""" - def _recording_misses( - self, name: str, method: Callable[..., Any] - ) -> Callable[..., Any]: - @functools.wraps(method) - def recording_misses(*args: object, **kwargs: object) -> Any: # noqa: ANN401 - try: - return method(*args, **kwargs) - except HGVSDataNotAvailableError: - self.violations.append( - f"hgvs cache miss: {_describe_call(name, args, kwargs)}" - ) - raise + @functools.wraps(method) + def wrapped(*args: object, **kwargs: object) -> Any: # noqa: ANN401 + try: + return method(*args, **kwargs) + except HGVSDataNotAvailableError as exc: + pytest.fail( + f"Missing HGVS recording: {exc}\nRun make record-hgvs-cache.", + pytrace=False, + ) - return recording_misses + return wrapped diff --git a/tests/test_offline_guard.py b/tests/test_offline_guard.py index f5ae73e4..1e19cb44 100644 --- a/tests/test_offline_guard.py +++ b/tests/test_offline_guard.py @@ -1,57 +1,47 @@ -"""Tests for the session's offline guard (tests/offline_guard.py).""" +"""Check that forbidden operations fail at the call, including HGVS fallbacks.""" -from typing import Any +import socket -import hgvs.dataproviders.uta import psycopg2 import pytest import requests -from hgvs.exceptions import HGVSDataNotAvailableError -from offline_guard import OfflineError, OfflineGuard - -offline_guard_cases: list[dict[str, Any]] = [ - { - "id": "http-request", - "active_when": "blocking_network", - "call": lambda _provider: requests.get("http://127.0.0.1:1/", timeout=1), - "raises": OfflineError, - "violation": "blocked: socket.connect(('127.0.0.1', 1))", - }, - { - "id": "postgres-connect", - "active_when": "blocking_network", - "call": lambda _provider: psycopg2.connect( - "postgresql://anonymous@127.0.0.1:1/uta" - ), - "raises": OfflineError, - "violation": "blocked: psycopg2.connect('postgresql://anonymous@127.0.0.1:1/uta')", - }, - { - "id": "hgvs-cache-miss", - "active_when": "recording_hgvs_cache_misses", - "call": lambda provider: provider.get_tx_info( - "NM_000000.0", "NC_000001.11", "splign" - ), - "raises": HGVSDataNotAvailableError, - "violation": "hgvs cache miss: get_tx_info('NM_000000.0', 'NC_000001.11', 'splign')", - }, -] - - -@pytest.mark.parametrize("case", offline_guard_cases, ids=lambda c: c["id"]) -def test_offline_guard( - case: dict[str, Any], - offline_guard: OfflineGuard, - hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase | None, -) -> None: - """The offline guard blocks network connections and records hgvs cache misses, each - as one violation - """ - if not getattr(offline_guard, case["active_when"]): - pytest.skip(f"the offline guard isn't {case['active_when'].replace('_', ' ')}") - start = len(offline_guard.violations) - with pytest.raises(case["raises"]): - case["call"](hgvs_cached_data_provider) - assert offline_guard.violations[start:] == [case["violation"]] - # these violations are expected; keep them from failing this test at teardown - del offline_guard.violations[start:] + +from ga4gh.vrs import models +from ga4gh.vrs.utils.hgvs_tools import HgvsTools + + +@pytest.mark.parametrize("client", ["http", "connect_ex", "postgres"]) +def test_live_connections_fail(network_blocked: bool, client: str) -> None: + if not network_blocked: + pytest.skip("live connections are enabled for recording") + message = "Live PostgreSQL" if client == "postgres" else "Live network" + + def connect_with_fallback() -> None: + # An ordinary application error handler must not hide the failure. + try: + if client == "http": + requests.get("http://127.0.0.1:1/", timeout=1) + elif client == "connect_ex": + with socket.socket() as sock: + sock.connect_ex(("127.0.0.1", 1)) + else: + psycopg2.connect("postgresql://anonymous@127.0.0.1:1/uta") + except Exception: + return + + with pytest.raises(pytest.fail.Exception, match=message): + connect_with_fallback() + + +def test_hgvs_cache_miss_fails_through_fallback(hgvs_cache_mode: str) -> None: + if hgvs_cache_mode != "run": + pytest.skip("HGVS recording uses live data") + # An insertion needs no data-proxy fetch before reaching HGVS normalization. + # This accession is deliberately absent from the recorded provider data. + allele = models.Allele( + location=models.SequenceLocation(start=10, end=10), + state=models.LiteralSequenceExpression(sequence="A"), + ) + tools = HgvsTools() + with pytest.raises(pytest.fail.Exception, match="Missing HGVS recording"): + tools._to_sequence_variant(allele, "c", "unused", "NM_000000.0") From 11285aabdd2006044fd10bc0961c622b772854f9 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 10 Nov 2026 14:39:26 -0500 Subject: [PATCH 15/18] test: move offline guard into conftest and replace cache env vars with --record-hgvs-cache --- Makefile | 2 +- README.md | 30 ++++---- pyproject.toml | 2 +- tests/conftest.py | 128 ++++++++++++++++++-------------- tests/extras/test_hgvs_tools.py | 22 +++--- tests/offline_guard.py | 45 ----------- tests/test_offline_guard.py | 47 ------------ tests/test_vcr.py | 21 ++++++ 8 files changed, 124 insertions(+), 173 deletions(-) delete mode 100644 tests/offline_guard.py delete mode 100644 tests/test_offline_guard.py diff --git a/Makefile b/Makefile index 5bd3535a..eda883cc 100644 --- a/Makefile +++ b/Makefile @@ -134,7 +134,7 @@ clean-cassettes: record-hgvs-cache: @test -n "$${UTA_DB_URL}" || { echo "record-hgvs-cache: set UTA_DB_URL to the UTA instance to record from" >&2; exit 1; } rm -f tests/data/hgvs_cache.pkl.new - env -u HGVS_SEQREPO_DIR HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" VRS_HGVS_CACHE_MODE=learn VRS_HGVS_CACHE_FILE=$(CURDIR)/tests/data/hgvs_cache.pkl.new pytest --disable-vcr + env -u HGVS_SEQREPO_DIR HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" pytest --record-hgvs-cache=$(CURDIR)/tests/data/hgvs_cache.pkl.new --disable-vcr python tests/hgvs_cache_json.py tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.json rm tests/data/hgvs_cache.pkl.new diff --git a/README.md b/README.md index 1bab33ce..d4bf0f0d 100644 --- a/README.md +++ b/README.md @@ -317,22 +317,21 @@ make test #### Recorded test data -Tests run offline by replaying recorded data, so they don't need a SeqRepo REST -service, a UTA database, or network access. Set `SEQREPO_ROOT_DIR=tests/data/seqrepo/latest` -(as CI does) when running or recording tests. +`pytest` and `make test` default to offline replay of recorded data, so they do not +need a SeqRepo REST service, a UTA database, or network access. Set +`SEQREPO_ROOT_DIR=tests/data/seqrepo/latest` (as CI does) when running or recording tests. - **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to - the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). CI - runs `pytest --vcr-record=none`. In that mode, attempts to open Python socket - connections or connect through psycopg2 fail immediately, including HTTP requests - from tests not marked `@pytest.mark.vcr` (`tests/offline_guard.py`). + the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). + The default `--vcr-record=none` matches CI. Unless VCR is disabled, opening Python + socket connections or connecting through psycopg2 fails immediately, including HTTP + requests from tests not marked `@pytest.mark.vcr` (`tests/conftest.py`). - **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA - queries and sequence fetches. `tests/conftest.py` enables it by default - (`VRS_HGVS_CACHE_MODE=run`). A missing entry fails immediately, even when - production code would normally catch the HGVS error. The only other supported - mode is `learn`, used by `make record-hgvs-cache` to record live data. hgvs itself - reads and writes its cache as a pickle; `tests/hgvs_cache_json.py` converts between - the two. + queries and sequence fetches. A missing entry fails immediately, even when + production code would normally catch the HGVS error. `make record-hgvs-cache` + uses `--record-hgvs-cache=PATH --disable-vcr` to record live data + to a temporary pickle, then converts it to JSON if tests pass. hgvs itself reads + and writes pickles; `tests/hgvs_cache_json.py` converts between the two formats. To re-record, start the external services (`docker compose up` starts seqrepo-rest-service on port 5000 and UTA on port 5432). With an existing local SeqRepo @@ -351,6 +350,11 @@ make clean-cassettes pytest --vcr-record=once ``` +`--disable-vcr` allows live connections and bypasses HTTP cassette replay and writing, +even with the default `--vcr-record=none`. HGVS still replays its cache unless +`--record-hgvs-cache=PATH` is also supplied. The recording target uses both flags, +so it records HGVS data without changing HTTP cassettes. + `SEQREPO_REST_URL` (default `http://localhost:5000/seqrepo`) sets the REST service used by both. diff --git a/pyproject.toml b/pyproject.toml index e7da4062..6fa445c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -92,7 +92,7 @@ where = ["src"] [tool.setuptools_scm] [tool.pytest.ini_options] -addopts = "--cov-report=term-missing --cov=ga4gh" +addopts = "--cov-report=term-missing --cov=ga4gh --vcr-record=none" testpaths = ["tests", "src"] doctest_optionflags = "ALLOW_UNICODE ALLOW_BYTES ELLIPSIS IGNORE_EXCEPTION_DETAIL NORMALIZE_WHITESPACE" diff --git a/tests/conftest.py b/tests/conftest.py index 2287e11d..db352113 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,97 +1,111 @@ +import functools import os -from collections.abc import Iterator +import socket +from collections.abc import Callable, Iterator from pathlib import Path +from typing import Any, NoReturn import hgvs.dataproviders.uta +import psycopg2 import pytest from biocommons.seqrepo import SeqRepo +from hgvs.exceptions import HGVSDataNotAvailableError from hgvs_cache_json import json_to_pickle -from offline_guard import block_network, require_recorded_data from ga4gh.vrs.dataproxy import SeqRepoDataProxy, SeqRepoRESTDataProxy -HGVS_CACHE_MODES = ("learn", "run") HGVS_CACHE_JSON = Path(__file__).parent / "data" / "hgvs_cache.json" # Run mode never connects to UTA. This URL refuses connections, and being on localhost # it also keeps hgvs from logging that tests are using remote data. HGVS_OFFLINE_UTA_URL = "postgresql://anonymous@localhost:1/uta/uta_offline" -def _hgvs_cache_mode() -> str: - """Return `VRS_HGVS_CACHE_MODE` (default `run`)""" - return os.environ.get("VRS_HGVS_CACHE_MODE", "run") +def pytest_addoption(parser: pytest.Parser) -> None: + """Expose explicit HGVS recording; ordinary test runs replay committed data""" + parser.addoption( + "--record-hgvs-cache", + metavar="PATH", + type=Path, + help="Record HGVS data to a pickle file (requires --disable-vcr).", + ) def pytest_configure(config: pytest.Config) -> None: - """Check the hgvs cache settings once, before any test runs""" - mode = _hgvs_cache_mode() - if mode not in HGVS_CACHE_MODES: - msg = f"VRS_HGVS_CACHE_MODE must be one of {HGVS_CACHE_MODES}, got {mode!r}" - raise pytest.UsageError(msg) - if mode == "learn" and config.getoption("--vcr-record") == "none": - msg = "HGVS recording requires live connections; use --disable-vcr without --vcr-record=none." - raise pytest.UsageError(msg) - if mode == "learn" and not os.environ.get("VRS_HGVS_CACHE_FILE"): - msg = ( - "VRS_HGVS_CACHE_FILE must name the pickle file to record into in learn mode" - ) + """Reject recording settings that would block or replay live requests""" + if config.getoption("--record-hgvs-cache") and not config.getoption( + "--disable-vcr" + ): + msg = "HGVS recording requires --disable-vcr." raise pytest.UsageError(msg) -@pytest.fixture(scope="session") -def hgvs_cache_mode() -> str: - """Return the hgvs cache mode tests run in: `run` or `learn`""" - return _hgvs_cache_mode() +def _forbidden_connection(_sock: socket.socket, address: object) -> NoReturn: + pytest.fail( + f"Live connection to {address!r} is disabled. " + "Record HTTP requests in a VCR cassette (@pytest.mark.vcr) with --vcr-record=once." + ) -@pytest.fixture(scope="session") -def network_blocked(request: pytest.FixtureRequest) -> Iterator[bool]: - """Block live connections before provider setup when replaying VCR cassettes""" - blocked = request.config.getoption("--vcr-record") == "none" - with pytest.MonkeyPatch.context() as mp: - if blocked: - block_network(mp) - yield blocked +def _forbidden_postgres(*_args: object, **_kwargs: object) -> NoReturn: + pytest.fail("Live PostgreSQL connections are disabled. Run make record-hgvs-cache.") + + +def _require_recorded_data(method: Callable[..., Any]) -> Callable[..., Any]: + """Make cache misses fatal even inside production HGVS fallback handlers""" + + @functools.wraps(method) + def wrapped(*args: object, **kwargs: object) -> Any: # noqa: ANN401 + try: + return method(*args, **kwargs) + except HGVSDataNotAvailableError as exc: + pytest.fail(f"Missing HGVS recording: {exc}\nRun make record-hgvs-cache.") + + return wrapped @pytest.fixture(scope="session", autouse=True) def hgvs_cached_data_provider( - hgvs_cache_mode: str, - network_blocked: bool, # noqa: ARG001 # Install blockers before provider setup. + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory, ) -> Iterator[hgvs.dataproviders.uta.UTABase]: - """Share one provider for HGVS replay or recording. + """Share one provider so recording instances cannot overwrite each other's entries. - Replay (`run`, the default) loads the committed JSON via a temporary pickle and - fails immediately on missing data. `make record-hgvs-cache` uses `learn` with - VRS_HGVS_CACHE_FILE and live services to record a replacement. + Replay converts committed JSON to a temporary pickle and blocks live connections + unless HTTP recording or --disable-vcr explicitly enables them. """ - if hgvs_cache_mode == "learn": - cache_file = os.environ["VRS_HGVS_CACHE_FILE"] - else: - cache_file = str(tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl") - json_to_pickle(HGVS_CACHE_JSON, Path(cache_file)) - - db_url = HGVS_OFFLINE_UTA_URL if hgvs_cache_mode == "run" else None - provider = hgvs.dataproviders.uta.connect( - db_url=db_url, mode=hgvs_cache_mode, cache=cache_file - ) - try: - with pytest.MonkeyPatch.context() as mp: - if hgvs_cache_mode == "run": - # In run mode, these wrappers raise HGVSDataNotAvailableError only + recording = request.config.getoption("--record-hgvs-cache") + cache_file = recording or tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl" + if not recording: + json_to_pickle(HGVS_CACHE_JSON, cache_file) + + with pytest.MonkeyPatch.context() as mp: + if request.config.getoption( + "--vcr-record" + ) == "none" and not request.config.getoption("--disable-vcr"): + # VCR replays without connecting. libpq bypasses Python sockets, so + # psycopg2 needs its own patch. pytest.fail escapes except Exception. + mp.setattr(socket.socket, "connect", _forbidden_connection) + mp.setattr(socket.socket, "connect_ex", _forbidden_connection) + mp.setattr(psycopg2, "connect", _forbidden_postgres) + provider = hgvs.dataproviders.uta.connect( + db_url=None if recording else HGVS_OFFLINE_UTA_URL, + mode="learn" if recording else "run", + cache=str(cache_file), + ) + close = provider.close + try: + if not recording: + # In run mode, these methods raise HGVSDataNotAvailableError only # for cache misses; ordinary domain errors occur above this layer. for name, method in vars(provider).items(): if hasattr(method, "cache_info"): - mp.setattr(provider, name, require_recorded_data(method)) - mp.setattr( - hgvs.dataproviders.uta, "connect", lambda *_args, **_kwargs: provider - ) - # HgvsTools.close() closes its data provider, but this one is shared. + mp.setattr(provider, name, _require_recorded_data(method)) + mp.setattr(hgvs.dataproviders.uta, "connect", lambda *_a, **_kw: provider) + # HgvsTools.close() must not close the shared provider between tests. mp.setattr(provider, "close", lambda: None) yield provider - finally: - provider.close() + finally: + close() def remove_request_headers(request): diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index cc1ce73d..ee9975fd 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -1,9 +1,9 @@ """Tests for ga4gh.vrs.utils.hgvs_tools.""" -import hgvs.dataproviders.uta import hgvs.parser import pytest +from ga4gh.vrs import models from ga4gh.vrs.utils.hgvs_tools import HgvsTools @@ -43,11 +43,15 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): assert hgvs_tools.is_intronic(sv) is expected -def test_hgvs_cache_data_provider_is_shared( - hgvs_cached_data_provider: hgvs.dataproviders.uta.UTABase, -) -> None: - """Every HgvsTools gets the tests' shared hgvs cache data provider, so in learn - mode they cannot overwrite each other's cache entries - """ - assert HgvsTools().uta_conn is hgvs_cached_data_provider - assert HgvsTools().uta_conn is hgvs_cached_data_provider +def test_hgvs_cache_miss_fails_through_fallback(request: pytest.FixtureRequest) -> None: + if request.config.getoption("--record-hgvs-cache"): + pytest.skip("HGVS recording uses live data") + # An insertion needs no data-proxy fetch before reaching HGVS normalization. + # This accession is deliberately absent from the recorded provider data. + allele = models.Allele( + location=models.SequenceLocation(start=10, end=10), + state=models.LiteralSequenceExpression(sequence="A"), + ) + tools = HgvsTools() + with pytest.raises(pytest.fail.Exception, match="Missing HGVS recording"): + tools._to_sequence_variant(allele, "c", "unused", "NM_000000.0") diff --git a/tests/offline_guard.py b/tests/offline_guard.py deleted file mode 100644 index 22a3ac1b..00000000 --- a/tests/offline_guard.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Fail immediately on live connections or missing HGVS recordings. - -pytest.fail raises outside Exception, so production fallback handlers cannot swallow -these failures. VCR replay does not open sockets; psycopg2 needs its own patch because -libpq opens connections in C. -""" - -import functools -import socket -from collections.abc import Callable -from typing import Any, NoReturn - -import psycopg2 -import pytest -from hgvs.exceptions import HGVSDataNotAvailableError - - -def block_network(mp: pytest.MonkeyPatch) -> None: - """Block Python socket connections and psycopg2 for offline tests""" - - def forbidden_connection(*_args: object, **_kwargs: object) -> NoReturn: - pytest.fail("Live network connections are disabled in offline tests.") - - def forbidden_postgres(*_args: object, **_kwargs: object) -> NoReturn: - pytest.fail("Live PostgreSQL connections are disabled in offline tests.") - - mp.setattr(socket.socket, "connect", forbidden_connection) - mp.setattr(socket.socket, "connect_ex", forbidden_connection) - mp.setattr(psycopg2, "connect", forbidden_postgres) - - -def require_recorded_data(method: Callable[..., Any]) -> Callable[..., Any]: - """Make a replay-mode provider cache miss fatal, even inside HGVS fallbacks""" - - @functools.wraps(method) - def wrapped(*args: object, **kwargs: object) -> Any: # noqa: ANN401 - try: - return method(*args, **kwargs) - except HGVSDataNotAvailableError as exc: - pytest.fail( - f"Missing HGVS recording: {exc}\nRun make record-hgvs-cache.", - pytrace=False, - ) - - return wrapped diff --git a/tests/test_offline_guard.py b/tests/test_offline_guard.py deleted file mode 100644 index 1e19cb44..00000000 --- a/tests/test_offline_guard.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Check that forbidden operations fail at the call, including HGVS fallbacks.""" - -import socket - -import psycopg2 -import pytest -import requests - -from ga4gh.vrs import models -from ga4gh.vrs.utils.hgvs_tools import HgvsTools - - -@pytest.mark.parametrize("client", ["http", "connect_ex", "postgres"]) -def test_live_connections_fail(network_blocked: bool, client: str) -> None: - if not network_blocked: - pytest.skip("live connections are enabled for recording") - message = "Live PostgreSQL" if client == "postgres" else "Live network" - - def connect_with_fallback() -> None: - # An ordinary application error handler must not hide the failure. - try: - if client == "http": - requests.get("http://127.0.0.1:1/", timeout=1) - elif client == "connect_ex": - with socket.socket() as sock: - sock.connect_ex(("127.0.0.1", 1)) - else: - psycopg2.connect("postgresql://anonymous@127.0.0.1:1/uta") - except Exception: - return - - with pytest.raises(pytest.fail.Exception, match=message): - connect_with_fallback() - - -def test_hgvs_cache_miss_fails_through_fallback(hgvs_cache_mode: str) -> None: - if hgvs_cache_mode != "run": - pytest.skip("HGVS recording uses live data") - # An insertion needs no data-proxy fetch before reaching HGVS normalization. - # This accession is deliberately absent from the recorded provider data. - allele = models.Allele( - location=models.SequenceLocation(start=10, end=10), - state=models.LiteralSequenceExpression(sequence="A"), - ) - tools = HgvsTools() - with pytest.raises(pytest.fail.Exception, match="Missing HGVS recording"): - tools._to_sequence_variant(allele, "c", "unused", "NM_000000.0") diff --git a/tests/test_vcr.py b/tests/test_vcr.py index e82d68ed..64e19985 100644 --- a/tests/test_vcr.py +++ b/tests/test_vcr.py @@ -1,4 +1,6 @@ +import psycopg2 import pytest +import requests @pytest.mark.vcr @@ -6,3 +8,22 @@ def test_vcrtest(rest_dataproxy): seq = rest_dataproxy.get_sequence("NC_000013.11", 50_000_000, 50_000_050) assert len(seq) == 50 assert seq == "TTAGGTGTTTAGATGATTTCTAAGATGCTTTTAAGCCCAGTATTTCTATT" + + +@pytest.mark.parametrize( + "connect", + [ + pytest.param(lambda: requests.get("http://127.0.0.1:1/", timeout=1), id="http"), + pytest.param( + lambda: psycopg2.connect(host="127.0.0.1", port=1, connect_timeout=1), + id="postgres", + ), + ], +) +def test_live_connections_blocked(request, connect): + if request.config.getoption("--vcr-record") != "none" or request.config.getoption( + "--disable-vcr" + ): + pytest.skip("live connections are enabled") + with pytest.raises(pytest.fail.Exception): + connect() From e1db3bb9e902f3385557177656b061018d75cbab Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 10 Nov 2026 15:18:24 -0500 Subject: [PATCH 16/18] test: move live-connection blocking into its own fixture and validate --record-hgvs-cache paths --- README.md | 8 ++++--- tests/conftest.py | 59 +++++++++++++++++++++++++++++++++-------------- tests/test_vcr.py | 6 ++--- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index d4bf0f0d..9804481c 100644 --- a/README.md +++ b/README.md @@ -323,9 +323,11 @@ need a SeqRepo REST service, a UTA database, or network access. Set - **VCR cassettes** (`tests/**/cassettes/*.yaml`) replay vrs-python's HTTP requests to the [SeqRepo REST service](https://github.com/biocommons/seqrepo-rest-service). - The default `--vcr-record=none` matches CI. Unless VCR is disabled, opening Python - socket connections or connecting through psycopg2 fails immediately, including HTTP - requests from tests not marked `@pytest.mark.vcr` (`tests/conftest.py`). + The default `--vcr-record=none` matches CI. In that mode (without `--disable-vcr`), + opening a Python socket connection or connecting through psycopg2 fails the test + immediately, including HTTP requests from tests not marked `@pytest.mark.vcr` + (`block_live_connections` in `tests/conftest.py`). Connections opened by other C + libraries are not intercepted. - **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA queries and sequence fetches. A missing entry fails immediately, even when production code would normally catch the HGVS error. `make record-hgvs-cache` diff --git a/tests/conftest.py b/tests/conftest.py index db352113..17443123 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -26,17 +26,28 @@ def pytest_addoption(parser: pytest.Parser) -> None: "--record-hgvs-cache", metavar="PATH", type=Path, - help="Record HGVS data to a pickle file (requires --disable-vcr).", + help=( + "Record live hgvs lookups into the pickle file PATH, adding to it if it " + "exists (requires --disable-vcr)." + ), ) def pytest_configure(config: pytest.Config) -> None: - """Reject recording settings that would block or replay live requests""" - if config.getoption("--record-hgvs-cache") and not config.getoption( - "--disable-vcr" - ): + """Reject --record-hgvs-cache settings that would fail only after tests start""" + record_path: Path | None = config.getoption("--record-hgvs-cache") + if record_path is None: + return + if not config.getoption("--disable-vcr"): msg = "HGVS recording requires --disable-vcr." raise pytest.UsageError(msg) + # hgvs opens the file only after the first cache miss, so check it upfront. + if record_path.exists() and not record_path.is_file(): + msg = f"--record-hgvs-cache must name a regular file: {record_path}" + raise pytest.UsageError(msg) + if not record_path.parent.is_dir(): + msg = f"--record-hgvs-cache directory does not exist: {record_path.parent}" + raise pytest.UsageError(msg) def _forbidden_connection(_sock: socket.socket, address: object) -> NoReturn: @@ -50,6 +61,26 @@ def _forbidden_postgres(*_args: object, **_kwargs: object) -> NoReturn: pytest.fail("Live PostgreSQL connections are disabled. Run make record-hgvs-cache.") +@pytest.fixture(scope="session", autouse=True) +def block_live_connections(request: pytest.FixtureRequest) -> Iterator[bool]: + """Fail any test that opens a live connection while VCR replays cassettes. + + Active with `--vcr-record=none` (the default) unless `--disable-vcr` is given. + Yields whether connections are blocked. + """ + blocked = request.config.getoption( + "--vcr-record" + ) == "none" and not request.config.getoption("--disable-vcr") + with pytest.MonkeyPatch.context() as mp: + if blocked: + # VCR replays without connecting. libpq bypasses Python sockets, so + # psycopg2 needs its own patch. pytest.fail escapes except Exception. + mp.setattr(socket.socket, "connect", _forbidden_connection) + mp.setattr(socket.socket, "connect_ex", _forbidden_connection) + mp.setattr(psycopg2, "connect", _forbidden_postgres) + yield blocked + + def _require_recorded_data(method: Callable[..., Any]) -> Callable[..., Any]: """Make cache misses fatal even inside production HGVS fallback handlers""" @@ -67,26 +98,20 @@ def wrapped(*args: object, **kwargs: object) -> Any: # noqa: ANN401 def hgvs_cached_data_provider( request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory, + block_live_connections: bool, # noqa: ARG001 # Block before provider setup. ) -> Iterator[hgvs.dataproviders.uta.UTABase]: """Share one provider so recording instances cannot overwrite each other's entries. - Replay converts committed JSON to a temporary pickle and blocks live connections - unless HTTP recording or --disable-vcr explicitly enables them. + Replay converts committed JSON to a temporary pickle; recording + (`--record-hgvs-cache`) writes live data to the given pickle. """ - recording = request.config.getoption("--record-hgvs-cache") - cache_file = recording or tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl" + record_path: Path | None = request.config.getoption("--record-hgvs-cache") + recording = record_path is not None + cache_file = record_path or tmp_path_factory.mktemp("hgvs_cache") / "hgvs_cache.pkl" if not recording: json_to_pickle(HGVS_CACHE_JSON, cache_file) with pytest.MonkeyPatch.context() as mp: - if request.config.getoption( - "--vcr-record" - ) == "none" and not request.config.getoption("--disable-vcr"): - # VCR replays without connecting. libpq bypasses Python sockets, so - # psycopg2 needs its own patch. pytest.fail escapes except Exception. - mp.setattr(socket.socket, "connect", _forbidden_connection) - mp.setattr(socket.socket, "connect_ex", _forbidden_connection) - mp.setattr(psycopg2, "connect", _forbidden_postgres) provider = hgvs.dataproviders.uta.connect( db_url=None if recording else HGVS_OFFLINE_UTA_URL, mode="learn" if recording else "run", diff --git a/tests/test_vcr.py b/tests/test_vcr.py index 64e19985..4cda8086 100644 --- a/tests/test_vcr.py +++ b/tests/test_vcr.py @@ -20,10 +20,8 @@ def test_vcrtest(rest_dataproxy): ), ], ) -def test_live_connections_blocked(request, connect): - if request.config.getoption("--vcr-record") != "none" or request.config.getoption( - "--disable-vcr" - ): +def test_live_connections_blocked(block_live_connections: bool, connect) -> None: + if not block_live_connections: pytest.skip("live connections are enabled") with pytest.raises(pytest.fail.Exception): connect() From 6566ccd4f54e35bd1b1da3d8011810f7e15a29d5 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 10 Nov 2026 17:14:06 -0500 Subject: [PATCH 17/18] test: record and replay hgvs "no data" lookups in the test cache hgvs caches only returned values, so a lookup that raised HGVSDataNotAvailableError was missing from recordings and failed replay as a cache miss, even where tests or production code expect the error. Store those results in learn mode and raise them again on replay; only never-recorded lookups fail. Recording now requires UTA_DB_URL. --- Makefile | 1 - README.md | 6 +++-- tests/conftest.py | 56 ++++++++++++++++++++++++++++++++-------- tests/hgvs_cache_json.py | 17 +++++++++--- tests/test_hgvs_cache.py | 31 ++++++++++++++++++++++ 5 files changed, 94 insertions(+), 17 deletions(-) create mode 100644 tests/test_hgvs_cache.py diff --git a/Makefile b/Makefile index eda883cc..4d54ae7b 100644 --- a/Makefile +++ b/Makefile @@ -132,7 +132,6 @@ clean-cassettes: .PHONY: record-hgvs-cache # hgvs fetches sequences from HGVS_SEQREPO_DIR instead of HGVS_SEQREPO_URL when it's set, so it's unset for the recording run record-hgvs-cache: - @test -n "$${UTA_DB_URL}" || { echo "record-hgvs-cache: set UTA_DB_URL to the UTA instance to record from" >&2; exit 1; } rm -f tests/data/hgvs_cache.pkl.new env -u HGVS_SEQREPO_DIR HGVS_SEQREPO_URL="$${SEQREPO_REST_URL:-http://localhost:5000/seqrepo}" pytest --record-hgvs-cache=$(CURDIR)/tests/data/hgvs_cache.pkl.new --disable-vcr python tests/hgvs_cache_json.py tests/data/hgvs_cache.pkl.new tests/data/hgvs_cache.json diff --git a/README.md b/README.md index 9804481c..202a2039 100644 --- a/README.md +++ b/README.md @@ -329,8 +329,10 @@ need a SeqRepo REST service, a UTA database, or network access. Set (`block_live_connections` in `tests/conftest.py`). Connections opened by other C libraries are not intercepted. - **The hgvs cache** (`tests/data/hgvs_cache.json`) replays the hgvs library's UTA - queries and sequence fetches. A missing entry fails immediately, even when - production code would normally catch the HGVS error. `make record-hgvs-cache` + queries and sequence fetches. Lookups that found no data are recorded too, and + replay as the same `HGVSDataNotAvailableError`. A lookup that was never recorded + fails immediately, even when production code would normally catch the HGVS error. + `make record-hgvs-cache` uses `--record-hgvs-cache=PATH --disable-vcr` to record live data to a temporary pickle, then converts it to JSON if tests pass. hgvs itself reads and writes pickles; `tests/hgvs_cache_json.py` converts between the two formats. diff --git a/tests/conftest.py b/tests/conftest.py index 17443123..cdccd631 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,7 @@ import psycopg2 import pytest from biocommons.seqrepo import SeqRepo +from hgvs.decorators.lru_cache import _make_key from hgvs.exceptions import HGVSDataNotAvailableError from hgvs_cache_json import json_to_pickle @@ -48,6 +49,10 @@ def pytest_configure(config: pytest.Config) -> None: if not record_path.parent.is_dir(): msg = f"--record-hgvs-cache directory does not exist: {record_path.parent}" raise pytest.UsageError(msg) + # Without it, hgvs silently records from its built-in public UTA. + if not os.environ.get("UTA_DB_URL"): + msg = "HGVS recording requires UTA_DB_URL to name the UTA instance to record from." + raise pytest.UsageError(msg) def _forbidden_connection(_sock: socket.socket, address: object) -> NoReturn: @@ -81,15 +86,45 @@ def block_live_connections(request: pytest.FixtureRequest) -> Iterator[bool]: yield blocked -def _require_recorded_data(method: Callable[..., Any]) -> Callable[..., Any]: - """Make cache misses fatal even inside production HGVS fallback handlers""" +def _wrap_cached_method( + provider: hgvs.dataproviders.uta.UTABase, + method: Callable[..., Any], + recording: bool, +) -> Callable[..., Any]: + """Record and replay "no data" results, and fail on lookups never recorded. + + hgvs caches only returned values. Without this, a lookup that raised + HGVSDataNotAvailableError would be missing from the recording, and replaying it + would look the same as a cache miss. A recorded result is stored as the exception + itself, which hgvs's cache returns like any other value. + + hgvs reports a SeqRepo outage as HGVSDataNotAvailableError too. An outage while + recording fails tests, so no JSON is written, and any that slips through shows in + the JSON diff. + """ + name: str = method.__wrapped__.__name__ # hgvs keys cache entries by this name @functools.wraps(method) def wrapped(*args: object, **kwargs: object) -> Any: # noqa: ANN401 try: - return method(*args, **kwargs) + result = method(*args, **kwargs) except HGVSDataNotAvailableError as exc: - pytest.fail(f"Missing HGVS recording: {exc}\nRun make record-hgvs-cache.") + if not recording: + # Replay never queries a data source, so only a cache miss raises. + # pytest.fail escapes the production handlers that catch this error. + pytest.fail( + f"Missing HGVS recording: {exc}\nRun make record-hgvs-cache." + ) + # Keep the message: hgvs's Normalizer.is_valid_pos reads it. + provider.cache[_make_key(name, args, kwargs, False, ())] = ( + HGVSDataNotAvailableError(str(exc)) + ) + provider.cache.sync() + raise + if isinstance(result, HGVSDataNotAvailableError): + # A fresh instance, so tracebacks don't pile up on the cached one. + raise HGVSDataNotAvailableError(str(result)) + return result return wrapped @@ -113,18 +148,17 @@ def hgvs_cached_data_provider( with pytest.MonkeyPatch.context() as mp: provider = hgvs.dataproviders.uta.connect( - db_url=None if recording else HGVS_OFFLINE_UTA_URL, + db_url=os.environ["UTA_DB_URL"] if recording else HGVS_OFFLINE_UTA_URL, mode="learn" if recording else "run", cache=str(cache_file), ) close = provider.close try: - if not recording: - # In run mode, these methods raise HGVSDataNotAvailableError only - # for cache misses; ordinary domain errors occur above this layer. - for name, method in vars(provider).items(): - if hasattr(method, "cache_info"): - mp.setattr(provider, name, _require_recorded_data(method)) + for name, method in vars(provider).items(): + if hasattr(method, "cache_info"): + mp.setattr( + provider, name, _wrap_cached_method(provider, method, recording) + ) mp.setattr(hgvs.dataproviders.uta, "connect", lambda *_a, **_kw: provider) # HgvsTools.close() must not close the shared provider between tests. mp.setattr(provider, "close", lambda: None) diff --git a/tests/hgvs_cache_json.py b/tests/hgvs_cache_json.py index e861d5f9..d0db291d 100644 --- a/tests/hgvs_cache_json.py +++ b/tests/hgvs_cache_json.py @@ -6,7 +6,9 @@ Each cache entry is stored as ``{"func": ..., "args": [...], "value": ...}``. Values are strings, numbers, None, lists, and UTA rows (`psycopg2.extras.DictRow`), which are -stored as ``{"psycopg2_dictrow": {column: value, ...}}`` in column order. +stored as ``{"psycopg2_dictrow": {column: value, ...}}`` in column order. A lookup that +found no data is stored as the `HGVSDataNotAvailableError` it raised (see +`tests/conftest.py`), written as ``{"hgvs_data_not_available": message}``. Usage, to convert a cache hgvs just recorded: ``python tests/hgvs_cache_json.py `` @@ -20,16 +22,20 @@ from typing import Any from hgvs.decorators.lru_cache import _make_key +from hgvs.exceptions import HGVSDataNotAvailableError from psycopg2.extras import DictRow # hgvs builds each cache key as (*args, "__func__", function name) _FUNC_MARKER = "__func__" _DICTROW_TAG = "psycopg2_dictrow" +_NOT_AVAILABLE_TAG = "hgvs_data_not_available" _JSON_SCALARS = (str, int, float, bool, type(None)) def _encode_value(value: Any) -> Any: # noqa: ANN401 """Convert a cached hgvs result to a JSON value""" + if isinstance(value, HGVSDataNotAvailableError): + return {_NOT_AVAILABLE_TAG: str(value)} if isinstance(value, DictRow): columns = dict(value.items()) if len(columns) != len(value): @@ -45,10 +51,15 @@ def _encode_value(value: Any) -> Any: # noqa: ANN401 def _decode_value(value: Any) -> Any: # noqa: ANN401 - """Convert a JSON value back to the cached hgvs result, rebuilding UTA rows""" + """Convert a JSON value back to the cached hgvs result, rebuilding tagged values""" if isinstance(value, dict): + if value.keys() == {_NOT_AVAILABLE_TAG}: + return HGVSDataNotAvailableError(value[_NOT_AVAILABLE_TAG]) if value.keys() != {_DICTROW_TAG}: - msg = f'expected {{"{_DICTROW_TAG}": {{...}}}}, got {value!r}' + msg = ( + f'expected {{"{_DICTROW_TAG}": {{...}}}} or ' + f'{{"{_NOT_AVAILABLE_TAG}": "..."}}, got {value!r}' + ) raise ValueError(msg) columns: dict[str, Any] = value[_DICTROW_TAG] row = DictRow.__new__(DictRow) diff --git a/tests/test_hgvs_cache.py b/tests/test_hgvs_cache.py new file mode 100644 index 00000000..65820ef6 --- /dev/null +++ b/tests/test_hgvs_cache.py @@ -0,0 +1,31 @@ +"""Test recording hgvs lookups, which CI otherwise never runs (see conftest.py)""" + +from collections.abc import Callable +from pathlib import Path +from types import SimpleNamespace +from typing import Any, NoReturn + +import pytest +from conftest import _wrap_cached_method +from hgvs.decorators.lru_cache import LEARN, RUN, lru_cache +from hgvs.exceptions import HGVSDataNotAvailableError +from hgvs.utils.PersistentDict import PersistentDict +from hgvs_cache_json import json_to_pickle, pickle_to_json + + +def test_not_found_survives_record_and_replay(tmp_path: Path) -> None: + def get_tx_identity_info(ac: str) -> NoReturn: + msg = f"No data for {ac}" + raise HGVSDataNotAvailableError(msg) + + def wrap(cache: PersistentDict, mode: int) -> Callable[[str], Any]: + cached = lru_cache(maxsize=None, mode=mode, cache=cache)(get_tx_identity_info) + return _wrap_cached_method(SimpleNamespace(cache=cache), cached, mode == LEARN) + + with pytest.raises(HGVSDataNotAvailableError): + wrap(PersistentDict(str(tmp_path / "rec.pkl")), LEARN)("NM_X") + pickle_to_json(tmp_path / "rec.pkl", tmp_path / "c.json") + json_to_pickle(tmp_path / "c.json", tmp_path / "rep.pkl") + # An unrecorded lookup would fail the test here rather than raise this error. + with pytest.raises(HGVSDataNotAvailableError, match="^No data for NM_X$"): + wrap(PersistentDict(str(tmp_path / "rep.pkl"), flag="r"), RUN)("NM_X") From a95af49692332fba93efa2bade8fa8ec5507b546 Mon Sep 17 00:00:00 2001 From: Kyle Ferriter Date: Tue, 10 Nov 2026 17:14:07 -0500 Subject: [PATCH 18/18] test: re-record hgvs cache with a missing-accession fallback test --- tests/data/hgvs_cache.json | 18 ++++++++++++++++++ tests/extras/test_hgvs_tools.py | 29 +++++++++++++++++++++++------ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/tests/data/hgvs_cache.json b/tests/data/hgvs_cache.json index 878d4239..f26aea13 100644 --- a/tests/data/hgvs_cache.json +++ b/tests/data/hgvs_cache.json @@ -242,6 +242,17 @@ ], "value": "GTTCTG" }, + { + "func": "get_seq", + "args": [ + "NM_999999.1", + 10, + 11 + ], + "value": { + "hgvs_data_not_available": "Failed to fetch NM_999999.1 from SeqRepo REST (http://localhost:5000/seqrepo) ('NM_999999.1')" + } + }, { "func": "get_seq", "args": [ @@ -1435,6 +1446,13 @@ } ] }, + { + "func": "get_tx_mapping_options", + "args": [ + "NM_999999.1" + ], + "value": [] + }, { "func": "get_tx_mapping_options", "args": [ diff --git a/tests/extras/test_hgvs_tools.py b/tests/extras/test_hgvs_tools.py index ee9975fd..45c764fa 100644 --- a/tests/extras/test_hgvs_tools.py +++ b/tests/extras/test_hgvs_tools.py @@ -1,5 +1,7 @@ """Tests for ga4gh.vrs.utils.hgvs_tools.""" +import logging + import hgvs.parser import pytest @@ -43,15 +45,30 @@ def test_is_intronic(hgvs_tools, hgvs_expr, expected): assert hgvs_tools.is_intronic(sv) is expected +# An insertion needs no data-proxy fetch before reaching HGVS normalization. +INSERTION = models.Allele( + location=models.SequenceLocation(start=10, end=10), + state=models.LiteralSequenceExpression(sequence="A"), +) + + def test_hgvs_cache_miss_fails_through_fallback(request: pytest.FixtureRequest) -> None: if request.config.getoption("--record-hgvs-cache"): pytest.skip("HGVS recording uses live data") - # An insertion needs no data-proxy fetch before reaching HGVS normalization. # This accession is deliberately absent from the recorded provider data. - allele = models.Allele( - location=models.SequenceLocation(start=10, end=10), - state=models.LiteralSequenceExpression(sequence="A"), - ) tools = HgvsTools() with pytest.raises(pytest.fail.Exception, match="Missing HGVS recording"): - tools._to_sequence_variant(allele, "c", "unused", "NM_000000.0") + tools._to_sequence_variant(INSERTION, "c", "unused", "NM_000000.0") + + +def test_missing_accession_falls_back_unnormalized( + caplog: pytest.LogCaptureFixture, +) -> None: + # Neither SeqRepo nor UTA has this accession; the recording keeps its "no data" + # results. It must differ from the accession the cache-miss test keeps unrecorded. + accession = "NM_999999.1" + tools = HgvsTools() + with caplog.at_level(logging.WARNING, logger="ga4gh.vrs.utils.hgvs_tools"): + var = tools._to_sequence_variant(INSERTION, "c", "unused", accession) + assert f"No data found for accession {accession}" in caplog.text + assert str(var) == f"{accession}:n.10_11insA" # left as n., not normalized