Skip to content

Commit

Permalink
refactored tests, added backstage check script
Browse files Browse the repository at this point in the history
  • Loading branch information
charlottekostelic committed Apr 24, 2024
1 parent 85cea39 commit 82ee791
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 64 deletions.
58 changes: 0 additions & 58 deletions acc_lcsh_check/sheet.py

This file was deleted.

68 changes: 62 additions & 6 deletions backstage_deletes.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,71 @@
import os.path
from pymarc import MARCReader
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from acc_lcsh_check.lcsh import LCTerm
from acc_lcsh_check.sheet import write_delete_sheet


def write_delete_sheet(
spreadsheet_id, range_name, value_input_option, insert_data_option, values
):
"""
A function to append data to a google sheet
"""
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
cred_path = os.path.join(
os.environ["USERPROFILE"], ".cred/.google/lcsh-checker.json"
)
token_path = os.path.join(
os.environ["USERPROFILE"], ".cred/.google/lcsh-token.json"
)

if os.path.exists(token_path):
creds = Credentials.from_authorized_user_file(token_path, SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(cred_path, SCOPES)
creds = flow.run_local_server()
with open(token_path, "w") as token:
token.write(creds.to_json())

try:
service = build("sheets", "v4", credentials=creds)

body = {
"majorDimension": "ROWS",
"range": range_name,
"values": values,
}
result = (
service.spreadsheets()
.values()
.append(
spreadsheetId=spreadsheet_id,
range=range_name,
valueInputOption=value_input_option,
insertDataOption=insert_data_option,
body=body,
)
.execute()
)
return result
except HttpError as error:
return error


if __name__ in "__main__":
file_list = [
"SUBJ-Q-230627DEL.MRC",
"NAME-DEL-Q-230926.MRC",
"NAME-Q-230627DEL.MRC",
"NAME.DEL-Q-231226.MRC",
"NAME-DEL-Q-230926.MRC",
"SUBJ.DEL-Q-231226.MRC",
"SUBJDEL-Q-230926.MRC",
"SUBJ-Q-230627DEL.MRC",
]
id_list = []
for file in file_list:
Expand All @@ -30,9 +89,6 @@
file,
)
)
with open("data/backstage_out.csv", "a") as outfile:
for item in id_list:
outfile.write(f"{item[0]}\n")
print(len(id_list))
for item in id_list:
term = LCTerm(item[0], item[1])
Expand Down
40 changes: 40 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

import pytest
import requests
from pymarc import Record, Field, Subfield


class MockLCResponseRevised:
"""Mock response from id.loc.gov for a current term"""

def __init__(self):
self.status_code = 200
self.ok = True

def json(self):
return [
Expand Down Expand Up @@ -47,6 +49,7 @@ class MockLCResponseDeprecated:

def __init__(self):
self.status_code = 200
self.ok = True

def json(self):
return [
Expand Down Expand Up @@ -85,6 +88,7 @@ class MockLCResponseNew:

def __init__(self):
self.status_code = 200
self.ok = True

def json(self):
change_date = datetime.datetime.strftime(
Expand All @@ -111,6 +115,20 @@ def json(self):
]


class MockLCResponseError:
"""Simulates auth server response to successful token request"""

def __init__(self):
self.status_code = 404
self.ok = False

def json(self):
return {
"code": 404,
"message": "Term not found.",
}


@pytest.fixture
def mock_revised_response(monkeypatch):
def mock_lc_response(*args, **kwargs):
Expand All @@ -133,3 +151,25 @@ def mock_lc_response(*args, **kwargs):
return MockLCResponseNew()

monkeypatch.setattr(requests, "get", mock_lc_response)


@pytest.fixture
def mock_error_response(monkeypatch):
def mock_lc_response(*args, **kwargs):
return MockLCResponseError()

monkeypatch.setattr(requests, "get", mock_lc_response)


@pytest.fixture
def mock_marc():
record = Record()
record.add_field(
Field(tag="001", data="n 123456789"),
Field(
tag="100",
indicators=[" ", " "],
subfields=[Subfield(code="a", value="Bar, Foo")],
),
)
return record
13 changes: 13 additions & 0 deletions tests/test_lcsh.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,16 @@ def test_new_term(heading_id, mock_new_response):
assert term.recent_change is False
assert term.is_deprecated is False
assert term.revised_heading is False


def test_heading_not_found(mock_error_response):
term = LCTerm(id="n123", old_heading="n321")
assert term.skos_json is None
assert term.is_deprecated is None
assert term.status_code == 404


def test_fromMarcFile(mock_marc, mock_new_response):
term = LCTerm.fromMarcFile(record=mock_marc)
assert term.old_heading == "Bar, Foo"
assert term.id == "n123456789"

0 comments on commit 82ee791

Please sign in to comment.