import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
_counter = [0]
def _session():
_counter[0] += 1
name = f"flw{int(time.time() * 1000)}{_counter[0]}"
s = requests.Session()
s.post(f"{BASE_URL}/auth/signup", data={
"username": name, "email": f"{name}@t.dev",
"password": "secret123", "confirm_password": "secret123",
}, allow_redirects=True)
return s, name
def _uid(username):
return get_table("users").find_one(username=username)["uid"]
def test_follow_creates_notification_and_awards_xp(app_server):
s_a, a_name = _session()
_, b_name = _session()
a_uid, b_uid = _uid(a_name), _uid(b_name)
before = get_table("users").find_one(uid=b_uid).get("xp", 0) or 0
s_a.post(f"{BASE_URL}/follow/{b_name}", allow_redirects=False)
assert get_table("follows").count(follower_uid=a_uid, following_uid=b_uid) == 1
assert get_table("notifications").count(user_uid=b_uid, type="follow") == 1
after = get_table("users").find_one(uid=b_uid).get("xp", 0) or 0
assert after - before == 5
def test_duplicate_follow_is_idempotent(app_server):
s_a, a_name = _session()
_, b_name = _session()
a_uid, b_uid = _uid(a_name), _uid(b_name)
s_a.post(f"{BASE_URL}/follow/{b_name}", allow_redirects=False)
s_a.post(f"{BASE_URL}/follow/{b_name}", allow_redirects=False)
assert get_table("follows").count(follower_uid=a_uid, following_uid=b_uid) == 1
assert get_table("notifications").count(user_uid=b_uid, type="follow") == 1
def test_self_follow_rejected(app_server):
s_a, a_name = _session()
a_uid = _uid(a_name)
s_a.post(f"{BASE_URL}/follow/{a_name}", allow_redirects=False)
assert get_table("follows").count(follower_uid=a_uid, following_uid=a_uid) == 0
def test_follow_nonexistent_user_redirects(app_server):
s_a, _ = _session()
r = s_a.post(f"{BASE_URL}/follow/no_such_user_zzz", allow_redirects=False)
assert r.status_code == 302
def test_unfollow_removes_follow(app_server):
s_a, a_name = _session()
_, b_name = _session()
a_uid, b_uid = _uid(a_name), _uid(b_name)
s_a.post(f"{BASE_URL}/follow/{b_name}", allow_redirects=False)
s_a.post(f"{BASE_URL}/follow/unfollow/{b_name}", allow_redirects=False)
assert get_table("follows").count(follower_uid=a_uid, following_uid=b_uid) == 0
r = s_a.post(f"{BASE_URL}/follow/unfollow/{b_name}", allow_redirects=False)
assert r.status_code == 302