Files
saints/tests/test_get_saint_of_the_day.py
T

516 lines
16 KiB
Python

"""Tests for get_saint_of_the_day.py.
These tests never touch the real CSV, the real pics/ folder, the real .env,
the real clock, or the real Mastodon server. Fixtures below swap each of
those for a stand-in the test controls.
"""
import sys
from datetime import datetime
import pytest
from mastodon import MastodonNetworkError
import get_saint_of_the_day as saint_of_the_day
CSV_HEADER = "Date,Saint Name,French Name,Notes\n"
# --- Fixtures ---------------------------------------------------------------
# A fixture is a function pytest runs before a test that asks for it by name
# (as a parameter). `monkeypatch` and `tmp_path` are built-in fixtures:
# `tmp_path` is a fresh empty folder per test, and `monkeypatch` swaps an
# attribute for the length of one test, then puts the original back.
@pytest.fixture
def project_dir(tmp_path, monkeypatch):
"""Make the script look for its CSV, pics/ and .env inside tmp_path.
The script finds its files with Path(__file__).parent, so pointing the
module's __file__ into tmp_path moves all three at once.
"""
monkeypatch.setattr(
saint_of_the_day, "__file__", str(tmp_path / "get_saint_of_the_day.py")
)
(tmp_path / "pics").mkdir()
# Start with no Mastodon credentials in the environment, so values from
# your shell can't leak in. Setting each variable before deleting it
# makes monkeypatch remember the original state, so afterwards it also
# undoes anything load_dotenv() wrote during the test.
for name in ("MASTODON_INSTANCE_URL", "MASTODON_ACCESS_TOKEN"):
monkeypatch.setenv(name, "placeholder")
monkeypatch.delenv(name)
return tmp_path
def write_csv(project_dir, rows):
"""Write a small saints CSV into the test's project folder."""
(project_dir / "saints_days_france.csv").write_text(
CSV_HEADER + "".join(row + "\n" for row in rows), encoding="utf-8"
)
@pytest.fixture
def set_today(monkeypatch):
"""Return a function that freezes 'now' to a chosen date."""
def _set_today(year, month, day):
class FrozenDatetime(datetime):
@classmethod
def now(cls, tz=None):
return cls(year, month, day, 8, 0)
monkeypatch.setattr(saint_of_the_day, "datetime", FrozenDatetime)
return _set_today
# --- get_standardized_name / get_wikipedia_url -----------------------------
def test_standardized_name_replaces_spaces_with_underscores():
assert (
saint_of_the_day.get_standardized_name("Francis de Sales") == "Francis_de_Sales"
)
def test_wikipedia_url_points_at_english_wikipedia_article():
assert (
saint_of_the_day.get_wikipedia_url("Francis de Sales")
== "https://en.wikipedia.org/wiki/Francis_de_Sales"
)
def test_wikipedia_url_percent_encodes_accents_and_apostrophes():
assert (
saint_of_the_day.get_wikipedia_url("Mary Magdalene de' Pazzi of Ávila")
== "https://en.wikipedia.org/wiki/Mary_Magdalene_de%27_Pazzi_of_%C3%81vila"
)
# --- get_saint_picture_path ------------------------------------------------
def test_picture_path_finds_jpg_named_after_saint(project_dir):
picture = project_dir / "pics" / "Francis_de_Sales.jpg"
picture.write_bytes(b"fake image")
assert saint_of_the_day.get_saint_picture_path("Francis de Sales") == picture
def test_picture_path_finds_png_named_after_saint(project_dir):
picture = project_dir / "pics" / "Aloysius_Gonzaga.png"
picture.write_bytes(b"fake image")
assert saint_of_the_day.get_saint_picture_path("Aloysius Gonzaga") == picture
def test_picture_path_is_none_when_saint_has_no_picture(project_dir):
(project_dir / "pics" / "Someone_Else.jpg").write_bytes(b"fake image")
assert saint_of_the_day.get_saint_picture_path("Francis de Sales") is None
# --- get_saints_for_today --------------------------------------------------
def test_saints_for_today_returns_todays_saint_with_details(project_dir, set_today):
write_csv(
project_dir,
[
"January 21,Agnes,Sainte Agnès,Virgin and Martyr",
"January 22,Vincent of Saragossa,Saint Vincent,Deacon and Martyr",
],
)
picture = project_dir / "pics" / "Agnes.jpg"
picture.write_bytes(b"fake image")
set_today(2026, 1, 21)
assert saint_of_the_day.get_saints_for_today() == [
{
"name": "Agnes",
"french_name": "Sainte Agnès",
"notes": "Virgin and Martyr",
"wikipedia_url": "https://en.wikipedia.org/wiki/Agnes",
"picture_path": picture,
}
]
def test_saints_for_today_returns_every_saint_sharing_the_date(project_dir, set_today):
write_csv(
project_dir,
[
"January 20,Fabian,Saint Fabien,",
"January 20,Sebastian,Saint Sébastien,",
],
)
set_today(2026, 1, 20)
names = [saint["name"] for saint in saint_of_the_day.get_saints_for_today()]
assert names == ["Fabian", "Sebastian"]
def test_saints_for_today_skips_feast_days_that_are_not_people(project_dir, set_today):
write_csv(
project_dir,
[
"December 8,Immaculate Conception,Immaculée Conception,Solemnity",
"December 9,Juan Diego,Saint Juan Diego,",
],
)
set_today(2026, 12, 8)
assert saint_of_the_day.get_saints_for_today() == []
def test_saints_for_today_matches_single_digit_day_exactly(project_dir, set_today):
# "January 2" must match "January 2" only: not "January 02",
# and not "January 20" or "January 21".
write_csv(
project_dir,
[
"January 2,Basil the Great and Gregory Nazianzen,Saints Basile et Grégoire,",
"January 20,Fabian,Saint Fabien,",
"January 21,Agnes,Sainte Agnès,",
],
)
set_today(2026, 1, 2)
names = [saint["name"] for saint in saint_of_the_day.get_saints_for_today()]
assert names == ["Basil the Great and Gregory Nazianzen"]
def test_saints_for_today_is_empty_when_no_saint_has_the_date(project_dir, set_today):
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,"])
set_today(2026, 3, 1)
assert saint_of_the_day.get_saints_for_today() == []
def test_saints_for_today_has_no_picture_path_when_picture_missing(
project_dir, set_today
):
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,"])
set_today(2026, 1, 21)
[saint] = saint_of_the_day.get_saints_for_today()
assert saint["picture_path"] is None
# --- format_mastodon_post --------------------------------------------------
AGNES = {
"name": "Agnes",
"french_name": "Sainte Agnès",
"notes": "Virgin and Martyr",
"wikipedia_url": "https://en.wikipedia.org/wiki/Agnes",
"picture_path": None,
}
def test_mastodon_post_names_date_saint_link_and_hashtags(set_today):
set_today(2026, 1, 21)
assert saint_of_the_day.format_mastodon_post(AGNES) == (
"January 21: the Feast of Saint Agnes\n"
"https://en.wikipedia.org/wiki/Agnes\n"
"\n"
"#saints #hagiography"
)
def test_mastodon_post_does_not_zero_pad_single_digit_days(set_today):
set_today(2026, 11, 8)
first_line = saint_of_the_day.format_mastodon_post(AGNES).splitlines()[0]
assert first_line == "November 8: the Feast of Saint Agnes"
# --- Fake Mastodon ---------------------------------------------------------
# The real Mastodon client talks to a server. These fixtures swap it for a
# fake that records what it was asked to do, so tests can check exactly what
# would have been posted, and nothing ever reaches a real account.
INSTANCE_URL = "https://example.social"
ACCESS_TOKEN = "test-token-123"
POSTED_URL = "https://example.social/@saints/222"
@pytest.fixture
def mastodon_calls(monkeypatch):
"""Replace Mastodon with a fake; return the list of calls it receives."""
calls = []
class FakeMastodon:
def __init__(self, access_token=None, api_base_url=None):
calls.append(("connect", access_token, api_base_url))
def media_post(self, media_file, mime_type=None, description=None):
calls.append(("media_post", media_file, description))
return {"id": "111", "type": "image", "description": description}
def status_post(self, status, media_ids=None, visibility=None):
calls.append(("status_post", status, media_ids, visibility))
return {"id": "222", "url": POSTED_URL, "visibility": visibility}
monkeypatch.setattr(saint_of_the_day, "Mastodon", FakeMastodon)
return calls
@pytest.fixture
def mastodon_that_fails(monkeypatch):
"""Replace Mastodon with a fake whose server can't be reached."""
class UnreachableMastodon:
def __init__(self, access_token=None, api_base_url=None):
pass
def media_post(self, media_file, mime_type=None, description=None):
return {"id": "111", "type": "image", "description": description}
def status_post(self, status, media_ids=None, visibility=None):
raise MastodonNetworkError("Could not connect to server")
monkeypatch.setattr(saint_of_the_day, "Mastodon", UnreachableMastodon)
@pytest.fixture
def credentials(project_dir, monkeypatch):
monkeypatch.setenv("MASTODON_INSTANCE_URL", INSTANCE_URL)
monkeypatch.setenv("MASTODON_ACCESS_TOKEN", ACCESS_TOKEN)
# --- post_to_mastodon ------------------------------------------------------
def test_post_sends_public_status_without_media_when_no_picture(
credentials, mastodon_calls, set_today
):
set_today(2026, 1, 21)
saint_of_the_day.post_to_mastodon(AGNES)
assert mastodon_calls == [
("connect", ACCESS_TOKEN, INSTANCE_URL),
(
"status_post",
"January 21: the Feast of Saint Agnes\n"
"https://en.wikipedia.org/wiki/Agnes\n"
"\n"
"#saints #hagiography",
None,
"public",
),
]
def test_post_uploads_picture_and_attaches_it_to_status(
project_dir, credentials, mastodon_calls, set_today
):
picture = project_dir / "pics" / "Agnes.jpg"
picture.write_bytes(b"fake image")
set_today(2026, 1, 21)
saint_of_the_day.post_to_mastodon(AGNES | {"picture_path": picture})
assert mastodon_calls[1:] == [
("media_post", str(picture), "Image of Agnes"),
(
"status_post",
"January 21: the Feast of Saint Agnes\n"
"https://en.wikipedia.org/wiki/Agnes\n"
"\n"
"#saints #hagiography",
["111"],
"public",
),
]
def test_post_reads_credentials_from_env_file_next_to_script(
project_dir, mastodon_calls
):
(project_dir / ".env").write_text(
"MASTODON_INSTANCE_URL=https://from-env-file.social\n"
"MASTODON_ACCESS_TOKEN=token-from-env-file\n"
)
saint_of_the_day.post_to_mastodon(AGNES)
assert mastodon_calls[0] == (
"connect",
"token-from-env-file",
"https://from-env-file.social",
)
def test_post_refuses_when_instance_url_is_missing(
project_dir, monkeypatch, mastodon_calls
):
monkeypatch.setenv("MASTODON_ACCESS_TOKEN", ACCESS_TOKEN)
with pytest.raises(ValueError, match="Missing Mastodon credentials"):
saint_of_the_day.post_to_mastodon(AGNES)
assert mastodon_calls == []
def test_post_refuses_when_access_token_is_missing(
project_dir, monkeypatch, mastodon_calls
):
monkeypatch.setenv("MASTODON_INSTANCE_URL", INSTANCE_URL)
with pytest.raises(ValueError, match="Missing Mastodon credentials"):
saint_of_the_day.post_to_mastodon(AGNES)
assert mastodon_calls == []
def test_post_refuses_placeholder_access_token(
project_dir, monkeypatch, mastodon_calls
):
monkeypatch.setenv("MASTODON_INSTANCE_URL", INSTANCE_URL)
monkeypatch.setenv("MASTODON_ACCESS_TOKEN", "your_access_token_here")
with pytest.raises(ValueError, match="update the MASTODON_ACCESS_TOKEN"):
saint_of_the_day.post_to_mastodon(AGNES)
assert mastodon_calls == []
# --- main (running the script) ---------------------------------------------
# These call main() the way the command line does: by setting sys.argv.
# `capsys` is a built-in fixture that captures what the script prints.
def run_script(monkeypatch, *args):
monkeypatch.setattr(sys, "argv", ["get_saint_of_the_day.py", *args])
saint_of_the_day.main()
def test_script_prints_todays_saint_and_does_not_post(
project_dir, set_today, mastodon_calls, monkeypatch, capsys
):
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,Virgin and Martyr"])
picture = project_dir / "pics" / "Agnes.jpg"
picture.write_bytes(b"fake image")
set_today(2026, 1, 21)
run_script(monkeypatch)
assert capsys.readouterr().out == (
"Saint: Agnes\n"
"French: Sainte Agnès\n"
"Notes: Virgin and Martyr\n"
"Wikipedia: https://en.wikipedia.org/wiki/Agnes\n"
f"Picture: {picture}\n"
"\n"
)
assert mastodon_calls == []
def test_script_leaves_out_notes_and_says_when_no_picture(
project_dir, set_today, mastodon_calls, monkeypatch, capsys
):
write_csv(project_dir, ["January 20,Fabian,Saint Fabien,"])
set_today(2026, 1, 20)
run_script(monkeypatch)
assert capsys.readouterr().out == (
"Saint: Fabian\n"
"French: Saint Fabien\n"
"Wikipedia: https://en.wikipedia.org/wiki/Fabian\n"
"Picture: (none available)\n"
"\n"
)
def test_script_says_so_when_there_is_no_saint_today(
project_dir, set_today, mastodon_calls, monkeypatch, capsys
):
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,"])
set_today(2026, 3, 1)
run_script(monkeypatch, "--post")
assert capsys.readouterr().out == (
"No saint's day today (or today is a holiday/feast day).\n"
)
assert mastodon_calls == []
def test_script_with_post_flag_posts_saint_and_prints_link(
project_dir, credentials, set_today, mastodon_calls, monkeypatch, capsys
):
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,"])
(project_dir / "pics" / "Agnes.jpg").write_bytes(b"fake image")
set_today(2026, 1, 21)
run_script(monkeypatch, "--post")
assert [call[0] for call in mastodon_calls] == [
"connect",
"media_post",
"status_post",
]
assert f" Posted! URL: {POSTED_URL}\n" in capsys.readouterr().out
def test_script_with_post_flag_posts_every_saint_sharing_the_date(
project_dir, credentials, set_today, mastodon_calls, monkeypatch
):
write_csv(
project_dir,
[
"January 20,Fabian,Saint Fabien,",
"January 20,Sebastian,Saint Sébastien,",
],
)
(project_dir / "pics" / "Fabian.jpg").write_bytes(b"fake image")
(project_dir / "pics" / "Sebastian.jpg").write_bytes(b"fake image")
set_today(2026, 1, 20)
run_script(monkeypatch, "--post")
posted = [call[1] for call in mastodon_calls if call[0] == "status_post"]
assert posted == [
"January 20: the Feast of Saint Fabian\n"
"https://en.wikipedia.org/wiki/Fabian\n"
"\n"
"#saints #hagiography",
"January 20: the Feast of Saint Sebastian\n"
"https://en.wikipedia.org/wiki/Sebastian\n"
"\n"
"#saints #hagiography",
]
def test_script_with_post_flag_skips_saint_without_picture(
project_dir, credentials, set_today, mastodon_calls, monkeypatch, capsys
):
write_csv(project_dir, ["January 20,Fabian,Saint Fabien,"])
set_today(2026, 1, 20)
run_script(monkeypatch, "--post")
assert mastodon_calls == []
assert "Skipping Mastodon post (no picture available)" in capsys.readouterr().out
def test_script_fails_loudly_when_mastodon_post_fails(
project_dir, credentials, set_today, mastodon_that_fails, monkeypatch, capsys
):
# The error must escape main() so the script exits non-zero: otherwise
# systemd treats the run as a success and never triggers OnFailure.
write_csv(project_dir, ["January 21,Agnes,Sainte Agnès,"])
(project_dir / "pics" / "Agnes.jpg").write_bytes(b"fake image")
set_today(2026, 1, 21)
with pytest.raises(MastodonNetworkError):
run_script(monkeypatch, "--post")
assert " Error posting: Could not connect to server\n" in capsys.readouterr().out