# retoor from datetime import datetime, timedelta, timezone import uuid_utils from devplacepy.database import get_table from devplacepy.services.messaging import active_conversation def _make_user(): uid = str(uuid_utils.uuid7()) get_table("users").insert( { "uid": uid, "username": f"actconv_{uid[:8]}", "email": f"{uid[:8]}@actconv.test", "terms_version": "1", } ) return uid def test_touch_writes_marker_then_throttles(local_db): viewer = _make_user() other = _make_user() active_conversation._last_write.pop(f"{viewer}:{other}", None) active_conversation.touch_active_conversation(viewer, other) row = get_table("users").find_one(uid=viewer) assert row["active_conversation_uid"] == other first_stamp = row["active_conversation_at"] assert first_stamp active_conversation.touch_active_conversation(viewer, other) assert get_table("users").find_one(uid=viewer)["active_conversation_at"] == first_stamp active_conversation._last_write[f"{viewer}:{other}"] = ( active_conversation.time.monotonic() - active_conversation.WRITE_THROTTLE_SECONDS - 1 ) active_conversation.touch_active_conversation(viewer, other) second_stamp = get_table("users").find_one(uid=viewer)["active_conversation_at"] assert second_stamp >= first_stamp def test_touch_is_a_noop_without_both_uids(local_db): viewer = _make_user() active_conversation.touch_active_conversation("", "someone") active_conversation.touch_active_conversation(viewer, "") row = get_table("users").find_one(uid=viewer) assert not row.get("active_conversation_uid") def test_is_actively_viewing_true_when_fresh(local_db): viewer = _make_user() other = _make_user() get_table("users").update( { "uid": viewer, "active_conversation_uid": other, "active_conversation_at": datetime.now(timezone.utc).isoformat(), }, ["uid"], ) assert active_conversation.is_actively_viewing(viewer, other) is True def test_is_actively_viewing_false_when_stale(local_db): viewer = _make_user() other = _make_user() stale = datetime.now(timezone.utc) - timedelta( seconds=active_conversation.FRESH_SECONDS + 5 ) get_table("users").update( { "uid": viewer, "active_conversation_uid": other, "active_conversation_at": stale.isoformat(), }, ["uid"], ) assert active_conversation.is_actively_viewing(viewer, other) is False def test_is_actively_viewing_false_for_a_different_conversation(local_db): viewer = _make_user() other = _make_user() someone_else = _make_user() get_table("users").update( { "uid": viewer, "active_conversation_uid": someone_else, "active_conversation_at": datetime.now(timezone.utc).isoformat(), }, ["uid"], ) assert active_conversation.is_actively_viewing(viewer, other) is False def test_is_actively_viewing_false_when_missing_or_unknown(local_db): assert active_conversation.is_actively_viewing("", "other") is False assert active_conversation.is_actively_viewing("viewer", "") is False assert active_conversation.is_actively_viewing(str(uuid_utils.uuid7()), "other") is False