2022-06-22 18:11:22 +00:00
|
|
|
import httpx
|
2022-06-29 18:43:17 +00:00
|
|
|
import pytest
|
2022-06-22 18:11:22 +00:00
|
|
|
import respx
|
2022-06-29 18:43:17 +00:00
|
|
|
from sqlalchemy import func
|
|
|
|
from sqlalchemy import select
|
|
|
|
from sqlalchemy.orm import Session
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
from app import models
|
|
|
|
from app.actor import fetch_actor
|
2022-06-29 18:43:17 +00:00
|
|
|
from app.database import AsyncSession
|
2022-06-22 18:11:22 +00:00
|
|
|
from tests import factories
|
|
|
|
|
|
|
|
|
2022-06-29 18:43:17 +00:00
|
|
|
@pytest.mark.asyncio
|
|
|
|
async def test_fetch_actor(async_db_session: AsyncSession, respx_mock) -> None:
|
2022-06-22 18:11:22 +00:00
|
|
|
# Given a remote actor
|
|
|
|
ra = factories.RemoteActorFactory(
|
|
|
|
base_url="https://example.com",
|
|
|
|
username="toto",
|
|
|
|
public_key="pk",
|
|
|
|
)
|
|
|
|
respx_mock.get(ra.ap_id).mock(return_value=httpx.Response(200, json=ra.ap_actor))
|
2022-12-19 19:49:19 +00:00
|
|
|
respx_mock.get(
|
|
|
|
"https://example.com/.well-known/webfinger",
|
|
|
|
params={"resource": "acct%3Atoto%40example.com"},
|
|
|
|
).mock(return_value=httpx.Response(200, json={"subject": "acct:toto@example.com"}))
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
# When fetching this actor for the first time
|
2022-06-29 18:43:17 +00:00
|
|
|
saved_actor = await fetch_actor(async_db_session, ra.ap_id)
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
# Then it has been fetched and saved in DB
|
2022-12-19 19:49:19 +00:00
|
|
|
assert respx.calls.call_count == 2
|
2022-06-29 18:43:17 +00:00
|
|
|
assert (
|
|
|
|
await async_db_session.execute(select(models.Actor))
|
|
|
|
).scalar_one().ap_id == saved_actor.ap_id
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
# When fetching it a second time
|
2022-06-29 18:43:17 +00:00
|
|
|
actor_from_db = await fetch_actor(async_db_session, ra.ap_id)
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
# Then it's read from the DB
|
|
|
|
assert actor_from_db.ap_id == ra.ap_id
|
2022-06-29 18:43:17 +00:00
|
|
|
assert (
|
|
|
|
await async_db_session.execute(select(func.count(models.Actor.id)))
|
|
|
|
).scalar_one() == 1
|
2022-12-19 19:49:19 +00:00
|
|
|
assert respx.calls.call_count == 2
|
2022-06-22 18:11:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_sqlalchemy_factory(db: Session) -> None:
|
|
|
|
ra = factories.RemoteActorFactory(
|
|
|
|
base_url="https://example.com",
|
|
|
|
username="toto",
|
|
|
|
public_key="pk",
|
|
|
|
)
|
|
|
|
actor_in_db = factories.ActorFactory(
|
|
|
|
ap_type=ra.ap_type,
|
|
|
|
ap_actor=ra.ap_actor,
|
|
|
|
ap_id=ra.ap_id,
|
|
|
|
)
|
2022-09-02 21:47:23 +00:00
|
|
|
assert actor_in_db.id == db.execute(select(models.Actor)).scalar_one().id
|