import json import os import pytest from doi2dataset import Config, MetadataProcessor class FakeResponse: """ A fake response object to simulate an API response. """ def __init__(self, json_data, status_code=200): self._json = json_data self.status_code = status_code def json(self): return self._json def raise_for_status(self): pass @pytest.fixture(autouse=True) def load_config_test(): """ Automatically load the configuration from 'config_test.yaml' located in the same directory as this test file. """ config_path = os.path.join(os.path.dirname(__file__), "config_test.yaml") Config.load_config(config_path=config_path) @pytest.fixture def fake_openalex_response(): """ Load the saved JSON response from the file 'srep45389.json' located in the same directory as this test file. """ json_path = os.path.join(os.path.dirname(__file__), "srep45389.json") with open(json_path, "r", encoding="utf-8") as f: data = json.load(f) return data def test_fetch_doi_data_with_file(mocker, fake_openalex_response): """ Test fetching DOI metadata by simulating the API call with a locally saved JSON response. The APIClient.make_request method is patched to return a fake response built from the contents of 'srep45389.json', ensuring that the configuration is loaded from 'config_test.yaml'. """ doi = "10.1038/srep45389" fake_response = FakeResponse(fake_openalex_response, 200) # Patch the make_request method of APIClient to return our fake_response. mocker.patch("doi2dataset.APIClient.make_request", return_value=fake_response) # Instantiate MetadataProcessor without upload and progress. processor = MetadataProcessor(doi=doi, upload=False) # Call _fetch_data(), which should now return our fake JSON data. data = processor._fetch_data() # Verify that the fetched data matches the fake JSON data. assert data == fake_openalex_response