Skip to content

gerodp/hermes-productivity-skills / analytics/umami-report

umami-report

Verified

Per-site visitor & pageview reports from a private (self-hosted) Umami instance.

FileKindSize
SKILL.mdskill md4.9 KB
scripts/test_umami_report.pyexecutablescript13.6 KB
scripts/umami_report.pyexecutablescript16.7 KB

scripts/test_umami_report.py

View on GitHub
#!/usr/bin/env python3
"""Offline unit tests for umami_report — no network, API responses stubbed.

Run: python3 test_umami_report.py
"""
import contextlib
import io
import json
import os
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import umami_report as u  # noqa: E402

DAY = u.DAY_MS
# 2026-06-25 12:00:00 UTC, a fixed "now" so tests are deterministic.
NOW = 1782734400000


class ComputeRange(unittest.TestCase):
    def test_default_is_last_7_days(self):
        s, e = u.compute_range(NOW)
        self.assertEqual(e, NOW)
        self.assertEqual(s, NOW - 7 * DAY)

    def test_days_override(self):
        s, e = u.compute_range(NOW, days=30)
        self.assertEqual(s, NOW - 30 * DAY)

    def test_days_zero_is_start_of_today(self):
        s, e = u.compute_range(NOW, days=0)
        self.assertEqual(e, NOW)
        self.assertEqual(u.fmt_date(s), u.fmt_date(NOW))
        self.assertLess(s, NOW)

    def test_since_presets(self):
        self.assertEqual(u.compute_range(NOW, since="30d")[0], NOW - 30 * DAY)
        self.assertEqual(u.compute_range(NOW, since="today")[1], NOW)

    def test_explicit_range_inclusive_end(self):
        s, e = u.compute_range(NOW, start="2026-06-01", end="2026-06-07")
        self.assertEqual(u.fmt_date(s), "2026-06-01")
        self.assertEqual(u.fmt_date(e), "2026-06-07")  # end-of-day, still the 7th
        self.assertEqual(e - s, 7 * DAY - 1)

    def test_negative_days_rejected(self):
        with self.assertRaises(u.UmamiError):
            u.compute_range(NOW, days=-1)

    def test_start_without_end_rejected(self):
        with self.assertRaises(u.UmamiError):
            u.compute_range(NOW, start="2026-06-01")

    def test_end_before_start_rejected(self):
        with self.assertRaises(u.UmamiError):
            u.compute_range(NOW, start="2026-06-07", end="2026-06-01")

    def test_bad_date_format_rejected(self):
        with self.assertRaises(u.UmamiError):
            u.compute_range(NOW, start="06/01/2026", end="06/07/2026")

    def test_yesterday_range(self):
        s, e = u.yesterday_range(NOW)
        sod = u._start_of_day_ms(NOW)
        self.assertEqual(e, sod - 1)            # ends just before today
        self.assertEqual(s, sod - DAY)          # one full day long
        self.assertEqual(u.fmt_date(s), u.fmt_date(sod - DAY))


class ParseStats(unittest.TestCase):
    def test_comparison_object_shape(self):
        cur, prev = u.parse_stats({
            "pageviews": 100, "visitors": 40, "visits": 50,
            "bounces": 10, "totaltime": 999,
            "comparison": {"pageviews": 80, "visitors": 30, "visits": 45,
                           "bounces": 9, "totaltime": 800},
        })
        self.assertEqual(cur["pageviews"], 100)
        self.assertEqual(prev["pageviews"], 80)
        self.assertEqual(prev["visitors"], 30)

    def test_value_prev_shape(self):
        cur, prev = u.parse_stats({
            "pageviews": {"value": 100, "prev": 80},
            "visitors": {"value": 40, "prev": 30},
            "visits": {"value": 50, "prev": 45},
            "bounces": {"value": 10, "prev": 9},
            "totaltime": {"value": 999, "prev": 800},
        })
        self.assertEqual(cur["visits"], 50)
        self.assertEqual(prev["visits"], 45)

    def test_missing_fields_default_to_zero(self):
        cur, prev = u.parse_stats({"pageviews": 5})
        self.assertEqual(cur["visitors"], 0)
        self.assertEqual(prev["pageviews"], 0)


class NormalizeWebsites(unittest.TestCase):
    def test_data_wrapper(self):
        sites = u.normalize_websites({"data": [
            {"id": "a", "name": "Site A", "domain": "a.com"},
            {"id": "b", "domain": "b.com"},
        ]})
        self.assertEqual(len(sites), 2)
        self.assertEqual(sites[0]["name"], "Site A")
        self.assertEqual(sites[1]["name"], "b.com")  # falls back to domain

    def test_bare_list(self):
        sites = u.normalize_websites([{"id": "x", "name": "X"}])
        self.assertEqual(sites[0]["id"], "x")

    def test_entries_without_id_skipped(self):
        sites = u.normalize_websites({"data": [{"name": "no id"}, {"id": "ok"}]})
        self.assertEqual([s["id"] for s in sites], ["ok"])

    def test_team_website_wrapper(self):
        sites = u.normalize_websites({"data": [
            {"website": {"id": "w1", "name": "Wrapped", "domain": "w.com"}},
        ]})
        self.assertEqual(sites[0]["id"], "w1")
        self.assertEqual(sites[0]["name"], "Wrapped")


class TeamsAndMerge(unittest.TestCase):
    def test_normalize_teams_shapes(self):
        self.assertEqual(u.normalize_teams({"data": [{"id": "t1"}, {"teamId": "t2"}]}),
                         ["t1", "t2"])
        self.assertEqual(u.normalize_teams({"data": [{"team": {"id": "t3"}}]}), ["t3"])

    def test_merge_dedupes_by_id_preserving_order(self):
        a = [{"id": "1", "name": "A"}, {"id": "2", "name": "B"}]
        b = [{"id": "2", "name": "B-dup"}, {"id": "3", "name": "C"}]
        merged = u.merge_websites(a, b)
        self.assertEqual([m["id"] for m in merged], ["1", "2", "3"])
        self.assertEqual(merged[1]["name"], "B")  # first occurrence wins


class Formatting(unittest.TestCase):
    def test_bounce_pct(self):
        self.assertEqual(u.bounce_pct(10, 50), 20.0)
        self.assertEqual(u.bounce_pct(5, 0), 0.0)  # no divide-by-zero

    def test_format_delta_increase(self):
        self.assertEqual(u.format_delta(110, 100), "110 ▲10.0%")

    def test_format_delta_decrease(self):
        self.assertEqual(u.format_delta(90, 100), "90 ▼10.0%")

    def test_format_delta_from_zero(self):
        self.assertEqual(u.format_delta(5, 0), "5 ▲new")
        self.assertEqual(u.format_delta(0, 0), "0 —")

    def test_format_delta_thousands_separator(self):
        self.assertIn("1,234", u.format_delta(1234, 1000))


class Rendering(unittest.TestCase):
    def _rows(self):
        stats = [
            ({"id": "site-alpha", "name": "Alpha", "domain": "alpha.com"},
             {"pageviews": 300, "visitors": 100, "visits": 120, "bounces": 30, "totaltime": 1},
             {"pageviews": 200, "visitors": 90, "visits": 110, "bounces": 25, "totaltime": 1},
             7),   # yesterday visitors
            ({"id": "site-beta", "name": "Beta", "domain": "beta.com"},
             {"pageviews": 50, "visitors": 20, "visits": 25, "bounces": 10, "totaltime": 1},
             {"pageviews": 80, "visitors": 30, "visits": 35, "bounces": 12, "totaltime": 1},
             3),
        ]
        return u.build_rows(stats)

    def test_rows_sorted_by_pageviews_desc(self):
        rows = self._rows()
        self.assertEqual([r["name"] for r in rows], ["Alpha", "Beta"])

    def test_yesterday_carried_through(self):
        rows = self._rows()
        self.assertEqual(rows[0]["yesterday"], 7)
        self.assertEqual(rows[1]["yesterday"], 3)

    def test_table_has_total_sites_and_yesterday_column(self):
        out = u.render_table(self._rows(), NOW - 7 * DAY, NOW)
        for token in ("Alpha", "Beta", "TOTAL", "Pageviews", "Yesterday"):
            self.assertIn(token, out)
        # Yesterday comes before Visitors in the header row
        header = out.splitlines()[2]
        self.assertLess(header.index("Yesterday"), header.index("Visitors"))

    def test_delta_only_on_visitors(self):
        out = u.render_table(self._rows(), NOW - 7 * DAY, NOW)
        alpha = next(l for l in out.splitlines() if l.startswith("Alpha"))
        # exactly one delta arrow on the row → only the Visitors column has it
        self.assertEqual(sum(alpha.count(a) for a in ("▲", "▼", "—")), 1)
        self.assertIn("100 ▲11.1%", alpha)  # visitors 100 vs prev 90

    def test_table_empty(self):
        out = u.render_table([], NOW - 7 * DAY, NOW)
        self.assertIn("no websites found", out)

    def test_json_has_yesterday_and_is_deterministic(self):
        out = u.render_json(self._rows(), NOW - 7 * DAY, NOW)
        parsed = json.loads(out)
        self.assertEqual(parsed["sites"][0]["name"], "Alpha")
        self.assertEqual(parsed["sites"][0]["yesterday_visitors"], 7)
        self.assertEqual(parsed["sites"][0]["site_id"], "site-alpha")
        self.assertEqual(parsed["range"]["start"], u.fmt_date(NOW - 7 * DAY))
        # sort_keys=True → stable output across runs
        self.assertEqual(out, u.render_json(self._rows(), NOW - 7 * DAY, NOW))


class Config(unittest.TestCase):
    def test_missing_vars_raise(self):
        with self.assertRaises(u.UmamiError):
            u.get_config(env={"UMAMI_URL": "https://x"})

    def test_scheme_required(self):
        with self.assertRaises(u.UmamiError):
            u.get_config(env={"UMAMI_URL": "analytics.example.com",
                              "UMAMI_USERNAME": "a", "UMAMI_PASSWORD": "b"})

    def test_trailing_slash_stripped(self):
        base, user, pw = u.get_config(env={
            "UMAMI_URL": "https://analytics.example.com/",
            "UMAMI_USERNAME": "admin", "UMAMI_PASSWORD": "secret",
        })
        self.assertEqual(base, "https://analytics.example.com")
        self.assertEqual(user, "admin")


class TestCheckSmoke(unittest.TestCase):
    """Hermetic smoke tests for the `check` subcommand contract.

    No real network is opened: `login`/`list_websites` are patched at the
    module level, and env is manipulated via patch.dict so the test never
    depends on the developer's shell configuration.
    """

    # --- unconfigured → graceful non-zero, no traceback --------------------- #
    def test_check_unconfigured_returns_1_no_traceback(self):
        out, err = io.StringIO(), io.StringIO()
        with mock.patch.dict(os.environ, {}, clear=True):
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
                rc = u.main(["check"])
        self.assertIsInstance(rc, int)
        self.assertEqual(rc, 1)  # graceful, not a crash / not 0
        combined = out.getvalue() + err.getvalue()
        self.assertNotIn("Traceback", combined)  # no leaked traceback
        self.assertIn("error:", err.getvalue())  # user-facing error printed

    def test_check_unconfigured_pops_only_umami_vars(self):
        # Even if unrelated vars exist in the environment, check must still
        # fail gracefully when the UMAMI_* vars specifically are absent.
        base_env = {"PATH": os.environ.get("PATH", ""), "HOME": "/tmp"}
        out, err = io.StringIO(), io.StringIO()
        with mock.patch.dict(os.environ, base_env, clear=True):
            for var in u.ENV_VARS:
                os.environ.pop(var, None)
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
                rc = u.main(["check"])
        self.assertEqual(rc, 1)
        self.assertNotIn("Traceback", out.getvalue() + err.getvalue())

    # --- configured → 0, network fully stubbed ------------------------------ #
    def test_check_configured_returns_0_with_stubbed_network(self):
        env = {"UMAMI_URL": "https://analytics.example.com",
               "UMAMI_USERNAME": "admin", "UMAMI_PASSWORD": "secret"}
        out, err = io.StringIO(), io.StringIO()
        with mock.patch.dict(os.environ, env, clear=True), \
                mock.patch.object(u, "login", return_value=("tok", "uid")) as m_login, \
                mock.patch.object(u, "list_websites",
                                  return_value=[{"id": "a", "name": "A", "domain": "a.com"}]) as m_ls:
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
                rc = u.main(["check"])
        self.assertEqual(rc, 0)
        m_login.assert_called_once()  # login was exercised (but stubbed)
        m_ls.assert_called_once()
        self.assertIn("OK", out.getvalue())
        self.assertNotIn("Traceback", out.getvalue() + err.getvalue())

    def test_check_configured_zero_websites_still_ok(self):
        # 0 visible websites is a note on stderr, not a failure.
        env = {"UMAMI_URL": "https://analytics.example.com",
               "UMAMI_USERNAME": "admin", "UMAMI_PASSWORD": "secret"}
        out, err = io.StringIO(), io.StringIO()
        with mock.patch.dict(os.environ, env, clear=True), \
                mock.patch.object(u, "login", return_value=("tok", "uid")), \
                mock.patch.object(u, "list_websites", return_value=[]):
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
                rc = u.main(["check"])
        self.assertEqual(rc, 0)
        self.assertNotIn("Traceback", out.getvalue() + err.getvalue())

    # --- documented contract: `check` is text-only (no --json flag) --------- #
    def test_check_rejects_json_flag(self):
        # The check subparser intentionally has no --json; argparse must reject
        # it with SystemExit(2) rather than silently accept it.
        with self.assertRaises(SystemExit) as ctx:
            with contextlib.redirect_stdout(io.StringIO()), \
                    contextlib.redirect_stderr(io.StringIO()):
                u.main(["check", "--json"])
        self.assertEqual(ctx.exception.code, 2)


class HttpsRequired(unittest.TestCase):
    def test_http_non_localhost_rejected(self):
        # http:// would send the password in cleartext.
        with self.assertRaises(u.UmamiError):
            u.get_config(env={"UMAMI_URL": "http://analytics.example.com",
                              "UMAMI_USERNAME": "a", "UMAMI_PASSWORD": "b"})

    def test_http_localhost_allowed(self):
        base, _, _ = u.get_config(env={"UMAMI_URL": "http://localhost:3000",
                                       "UMAMI_USERNAME": "a",
                                       "UMAMI_PASSWORD": "b"})
        self.assertEqual(base, "http://localhost:3000")


if __name__ == "__main__":
    unittest.main(verbosity=2)
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall