using System.Diagnostics.CodeAnalysis;
using System.Net;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
///
/// The API of the profile search (issue #37): what the window sends, what it reads, the photos from Febe's memory,
/// the local suggestions with the accounts not followed, and adding a found profile with its identifier.
///
[TestClass]
public sealed class SearchApiTests
{
private const string Client = "0123456789abcdef";
[TestMethod]
public async Task WithoutTheEngineTheSearchSaysOnlyLocalSuggestionsWork()
{
await using var server = await WebTestServer.StartAsync();
var (status, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual("non-pronto", view.Str("state"));
Assert.IsTrue(view.Bool("mine"));
StringAssert.Contains(view.Str("message"), "profili che segui");
Assert.AreEqual("non-pronto", (await server.GetJsonAsync($"/api/ricerca?client={Client}")).Str("state"));
Assert.IsFalse((await server.GetJsonAsync("/api/ricerca?client=fedcba9876543210")).Bool("mine"));
}
[TestMethod]
public async Task BadRequestsAreRefused()
{
await using var server = await WebTestServer.StartAsync();
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = "x", text = "mario" })).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = new string('a', 61) })).Status);
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/nonunachiave")).Status);
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/0123456789abcdef0123456789abcdef")).Status);
using var end = server.Request(HttpMethod.Post, "/api/ricerca/fine", new { client = Client });
using var ended = await server.Client.SendAsync(end);
Assert.AreEqual(HttpStatusCode.NoContent, ended.StatusCode);
// Without the Origin of the interface a page of another site cannot make Febe type.
using var foreign = server.Request(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" }, origin: "http://altro.esempio");
using var refused = await server.Client.SendAsync(foreign);
Assert.AreNotEqual(HttpStatusCode.OK, refused.StatusCode);
}
[TestMethod]
public async Task HitsAreEnrichedWithWhatFebeKnowsAndPhotosComeFromMemory()
{
var fake = new FixedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton(fake));
var renamed = await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
var (_, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "nome" });
Assert.AreEqual("pronta", view.Str("state"));
var hits = view.Items("hits").ToList();
Assert.HasCount(3, hits);
Assert.AreEqual(renamed.Id, hits[0].Long("accountId"), "found by identifier under its new name");
Assert.IsTrue(hits[1].Bool("followed"));
Assert.AreEqual(System.Text.Json.JsonValueKind.Null, hits[2].GetProperty("accountId").ValueKind);
Assert.IsTrue(hits[2].Bool("photoReady"));
using var photo = await server.Client.GetAsync($"/api/ricerca/foto/{hits[2].Str("photo")}");
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
Assert.IsTrue(photo.Headers.CacheControl?.NoStore == true, "the photos stay in Febe's memory, never on the disk of the viewer's browser");
}
[TestMethod]
public async Task TheLocalSuggestionsAlsoHoldTheAccountsNotFollowed()
{
await using var server = await WebTestServer.StartAsync();
var added = await server.Db.Accounts.AddAsync(Make.Account("aggiunto.per.nome"));
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
var following = await server.GetJsonAsync("/api/following");
Assert.AreEqual(1, following.Int("total"), "the count is of the followed profiles");
var profiles = following.Items("profiles").ToList();
Assert.HasCount(2, profiles);
Assert.IsTrue(profiles[0].Bool("followed"));
Assert.AreEqual("200", profiles[0].Str("instagramId"));
Assert.AreEqual("aggiunto.per.nome", profiles[1].Str("username"));
Assert.IsFalse(profiles[1].Bool("followed"));
Assert.AreEqual(added.Id, profiles[1].Long("accountId"));
}
[TestMethod]
public async Task AFoundProfileIsAddedWithItsIdentifierAndARenamedOneIsReported()
{
var fake = new FixedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton(fake));
await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "nuovo.nome", "senza.nome" }, start = "newOnly" });
Assert.AreEqual(HttpStatusCode.OK, status);
Assert.AreEqual(1, result.Int("added"));
StringAssert.Contains(result.Str("message"), "con un altro nome");
var account = await server.Db.Accounts.FindByUsernameAsync("senza.nome");
Assert.AreEqual("300", account!.InstagramId);
Assert.AreEqual("Senza Nome", account.DisplayName);
Assert.IsNull(await server.Db.Accounts.FindByUsernameAsync("nuovo.nome"), "the same profile is not added twice");
}
/// A search that always shows the same three results.
private sealed class FixedSearch : IProfileSearch
{
private const string PhotoKey = "abcdefabcdefabcdefabcdefabcdef12";
private static readonly SearchHit[] Hits =
[
new(0, "100", "nuovo.nome", "Nuovo Nome", false, null, false),
new(1, "200", "seguito.uno", null, false, null, false),
new(2, "300", "senza.nome", "Senza Nome", true, PhotoKey, true),
];
public SearchView Current { get; private set; } = SearchView.Initial;
public SearchView Update(string client, string text) =>
Current = new SearchView(Current.Version + 1, client, text, SearchState.Ready, null, Hits, null);
public void End(string client)
{
}
public SearchHit? Known(string username) => Hits.FirstOrDefault(h => h.Username == username);
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
{
stream = key == PhotoKey ? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 1, 32, 32)) : null;
return stream is not null;
}
}
}