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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions nmdc_runtime/api/core/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
NAMES_OF_COLLECTIONS_ALLOWING_DOCUMENTS_HAVING_PROVENANCE_METADATA_FIELD: Set[str] = {
"biosample_set",
"data_generation_set",
"organism_sample_set",
"study_set",
}

Expand All @@ -20,6 +21,7 @@
"nmdc:DataGeneration",
"nmdc:MassSpectrometry",
"nmdc:NucleotideSequencing",
"nmdc:OrganismSample",
"nmdc:Study",
}

Expand Down
61 changes: 61 additions & 0 deletions tests/lib/faker.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
NucleotideSequencing,
NucleotideSequencingEnum,
OntologyClass,
OrganismSample,
ProcessingInstitutionEnum,
ReadQcAnalysis,
Study,
Expand Down Expand Up @@ -227,6 +228,66 @@ def generate_biosamples(self, quantity: int, associated_studies: List[str], **ov
return documents


def generate_organism_samples(self, quantity: int, associated_studies: List[str], **overrides) -> List[dict]:
"""
Generates the specified number of schema-compliant `organism_sample_set` documents.
The documents comply with schema v11.26.0.

Unless overridden, the `name` value will be unique for each document generated
by a given `Faker` instance.

Reference: https://microbiomedata.github.io/nmdc-schema/OrganismSample/

:param quantity: Number of documents to create
:param associated_studies: IDs of studies associated with each organism sample
:param overrides: Fields, if any, to add or override in each document
:return: The generated documents

>>> f = Faker()
>>> organism_samples = f.generate_organism_samples(1, associated_studies=['nmdc:sty-00-000001'])
>>> len(organism_samples)
1
>>> organism_samples[0]['id']
'nmdc:osm-00-000001'
>>> organism_samples[0]['associated_studies']
['nmdc:sty-00-000001']
>>> organism_samples[0]['type']
'nmdc:OrganismSample'

# Test: Omitting a required parameter.
>>> f.generate_organism_samples(1)
Traceback (most recent call last):
...
TypeError: Faker.generate_organism_samples() missing 1 required positional argument: 'associated_studies'

# Test: Generating an invalid document.
>>> f.generate_organism_samples(1, associated_studies=['nmdc:sty-00-000001'], ploidy='no_such_ploidy')
Traceback (most recent call last):
...
ValueError: Unknown PloidyEnum enumeration code: no_such_ploidy
"""

documents = []
for i in range(quantity):
organism_sample_id = self.make_unique_id("nmdc:osm-00-")
params = {
"id": organism_sample_id,
"type": OrganismSample.class_class_curie,
"associated_studies": associated_studies,
"name": f"name_{self.counts['nmdc:osm-00-']}",
**overrides,
}

# Validate the parameters by attempting to instantiate an `OrganismSample`.
instance = OrganismSample(**params)

# Dump the instance to a `dict` (technically, to a `JsonObj`).
document = json_dumper.to_dict(instance)
documents.append(document)

return documents


def generate_metagenome_annotations(self, quantity: int, was_informed_by: List[str], has_input: List[str], **overrides) -> List[dict]:
"""
Generates the specified number of documents representing `MetagenomeAnnotation` instances,
Expand Down
108 changes: 71 additions & 37 deletions tests/test_api/test_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1837,100 +1837,134 @@ def test_queries_run_allows_update_of_existing_biosample(api_user_client):
if did_insert_allowance:
allowances_collection.delete_many(allow_spec)

def test_queries_run_populates_provenance_metadata(api_user_client):
@pytest.mark.parametrize("collection_name", ["study_set", "organism_sample_set"])
def test_queries_run_populates_provenance_metadata(api_user_client, collection_name):
"""
Submit a request containing an update command and confirm that the endpoint populates the
`mod_date` field the way we expect.
"""

mdb = get_mongo_db()
collection = mdb.get_collection(collection_name)
study_set = mdb.get_collection("study_set")
allowances_collection = mdb.get_collection("_runtime.api.allow")
allow_spec = {
"username": api_user_client.username,
"action": "/queries:run(query_cmd:DeleteCommand)",
}
did_insert_allowance: bool = False # keep track of whether we'll clean it up later

# Generate study documents.
# Initialize flags that we can use to keep track of what we need to clean up later.
did_insert_allowance: bool = False
did_insert_referenced_study: bool = False

# Generate test documents (and a referenced study if needed for referential integrity).
faker = Faker()
study_a, study_b = faker.generate_studies(2)
study_a["id"] = "nmdc:sty-00-distinct"
study_b["id"] = "nmdc:sty-00-distinct2"
referenced_study = None
if collection_name == "study_set":
doc_a, doc_b = faker.generate_studies(2)
doc_a["id"] = "nmdc:sty-00-distinct"
doc_b["id"] = "nmdc:sty-00-distinct2"
elif collection_name == "organism_sample_set":
referenced_study = faker.generate_studies(1, id="nmdc:sty-00-distinct")[0]
doc_a, doc_b = faker.generate_organism_samples(
2, associated_studies=[referenced_study["id"]]
)
doc_a["id"] = "nmdc:osm-00-distinct"
doc_b["id"] = "nmdc:osm-00-distinct2"
else:
raise ValueError(f"Unsupported test collection: {collection_name}")

try:
if allowances_collection.count_documents(allow_spec) == 0:
allowances_collection.insert_one(allow_spec)
did_insert_allowance = True

# If we generated a "referenced study" above, insert it into "study_set" now.
if referenced_study is not None:
assert study_set.count_documents({"id": referenced_study["id"]}) == 0
study_set.insert_one(referenced_study)
did_insert_referenced_study = True

# Test 1: Confirm the endpoint populates the `provenance_metadata.mod_date` field.
try:
# Seed the database with a document that we can later update via the API.
assert study_set.count_documents({"id": study_a["id"]}) == 0
study_set.insert_one(study_a)
assert "provenance_metadata" not in study_a
assert collection.count_documents({"id": doc_a["id"]}) == 0
collection.insert_one(doc_a)
assert "provenance_metadata" not in doc_a

# Update the document via the API.
new_description = "NEW DESCRIPTION"
operations_document = {"$set": {"description": new_description}}
an_update_statement = {"q": {"id": study_a["id"]}, "u": operations_document}
_ = api_user_client.request(
an_update_statement = {"q": {"id": doc_a["id"]}, "u": operations_document}
response = api_user_client.request(
"POST",
"/queries:run",
{
"update": "study_set",
"update": collection_name,
"updates": [an_update_statement],
},
)
assert response.status_code == status.HTTP_200_OK

# Check that the endpoint populated the `provenance_metadata.mod_date` field.
updated_study_a = study_set.find_one({"id": study_a["id"]})
assert updated_study_a is not None
assert updated_study_a["description"] == new_description
assert "provenance_metadata" in updated_study_a
assert "mod_date" in updated_study_a["provenance_metadata"]
assert isinstance(updated_study_a["provenance_metadata"]["mod_date"], str)
assert updated_study_a["provenance_metadata"]["type"] == "nmdc:ProvenanceMetadata"
updated_doc_a = collection.find_one({"id": doc_a["id"]})
assert updated_doc_a is not None
assert updated_doc_a["description"] == new_description
assert "provenance_metadata" in updated_doc_a
assert "mod_date" in updated_doc_a["provenance_metadata"]
assert isinstance(updated_doc_a["provenance_metadata"]["mod_date"], str)
assert (
updated_doc_a["provenance_metadata"]["type"]
== "nmdc:ProvenanceMetadata"
)
finally:
study_set.delete_many({"id": study_a["id"]})
collection.delete_many({"id": doc_a["id"]})

# Test 2: Confirm the endpoint preserves the existing `provenance_metadata.add_date` value.
try:
# Seed the database with a document that we can later update via the API.
original_add_date = "2020-01-01T00:00:00Z"
study_b["provenance_metadata"] = {
doc_b["provenance_metadata"] = {
"add_date": original_add_date,
"type": "nmdc:ProvenanceMetadata",
}
assert study_set.count_documents({"id": study_b["id"]}) == 0
study_set.insert_one(study_b)
assert study_set.count_documents({"id": study_b["id"]}) == 1
assert collection.count_documents({"id": doc_b["id"]}) == 0
collection.insert_one(doc_b)
assert collection.count_documents({"id": doc_b["id"]}) == 1

# Update the document via the API.
an_update_statement = {"q": {"id": study_b["id"]}, "u": operations_document}
_ = api_user_client.request(
an_update_statement = {"q": {"id": doc_b["id"]}, "u": operations_document}
response = api_user_client.request(
"POST",
"/queries:run",
{
"update": "study_set",
"update": collection_name,
"updates": [an_update_statement],
},
)
assert response.status_code == status.HTTP_200_OK

# Check that the endpoint populated the `provenance_metadata.mod_date` field
# and preserved the original `provenance_metadata.add_date` value.
updated_study_b = study_set.find_one({"id": study_b["id"]})
assert updated_study_b is not None
assert updated_study_b["description"] == new_description
assert "provenance_metadata" in updated_study_b
assert "mod_date" in updated_study_b["provenance_metadata"]
assert isinstance(updated_study_b["provenance_metadata"]["mod_date"], str)
assert "add_date" in updated_study_b["provenance_metadata"]
assert updated_study_b["provenance_metadata"]["add_date"] == original_add_date
assert updated_study_b["provenance_metadata"]["type"] == "nmdc:ProvenanceMetadata"
updated_doc_b = collection.find_one({"id": doc_b["id"]})
assert updated_doc_b is not None
assert updated_doc_b["description"] == new_description
assert "provenance_metadata" in updated_doc_b
assert "mod_date" in updated_doc_b["provenance_metadata"]
assert isinstance(updated_doc_b["provenance_metadata"]["mod_date"], str)
assert "add_date" in updated_doc_b["provenance_metadata"]
assert (
updated_doc_b["provenance_metadata"]["add_date"] == original_add_date
)
assert (
updated_doc_b["provenance_metadata"]["type"]
== "nmdc:ProvenanceMetadata"
)
finally:
study_set.delete_many({"id": study_b["id"]})
collection.delete_many({"id": doc_b["id"]})
finally:
if did_insert_referenced_study and referenced_study is not None:
study_set.delete_many({"id": referenced_study["id"]})
if did_insert_allowance:
allowances_collection.delete_many(allow_spec)

Expand Down