using System.Net;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
///
/// The link to Instagram over (Connection/PROTOCOLLO.md, spec §4.1): the default
/// «browser non disponibile» when the composition registers none, a registered service used as it is, the Origin
/// check on the commands (§13.1), and the configuration problems of /api/capabilities (§8.2, §11).
///
[TestClass]
public sealed class ConnectionApiTests
{
[TestMethod]
public async Task WithoutAServiceTheBrowserIsUnavailableAndCommandsSaySo()
{
await using var server = await Part2.StartAsync();
var status = await server.GetJsonAsync("/api/connection");
Assert.AreEqual("browserUnavailable", status.Str("state"));
Assert.IsFalse(status.Bool("userIsDriving"));
var (beginStatus, begin) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
Assert.AreEqual(HttpStatusCode.BadRequest, beginStatus);
StringAssert.Contains(begin.Str("message"), "browser di Febe non è disponibile");
var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.AreEqual(HttpStatusCode.OK, finishStatus);
Assert.IsFalse(finish.Bool("connected"));
Assert.IsFalse(string.IsNullOrWhiteSpace(finish.Str("message")));
var (cancelStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
Assert.AreEqual(HttpStatusCode.NoContent, cancelStatus);
var (disconnectStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
Assert.AreEqual(HttpStatusCode.BadRequest, disconnectStatus);
}
[TestMethod]
public async Task ARegisteredServiceIsUsedAndHoFinitoLetsRiprendiActivate()
{
var connection = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton(connection));
var status = await server.GetJsonAsync("/api/connection");
Assert.AreEqual("notConnected", status.Str("state"));
Assert.AreEqual("https://www.instagram.com/accounts/login/", status.Str("currentUrl"));
var (beginStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
Assert.AreEqual(HttpStatusCode.NoContent, beginStatus);
Assert.IsTrue((await server.GetJsonAsync("/api/connection")).Bool("userIsDriving"));
var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.AreEqual(HttpStatusCode.OK, finishStatus);
Assert.IsTrue(finish.Bool("connected"));
Assert.AreEqual("connected", (await server.GetJsonAsync("/api/connection")).Str("state"));
Assert.IsNotNull(server.App.Services.GetRequiredService().LastUsedAt, "«Ho finito» counts as having used the browser");
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
}
[TestMethod]
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
{
// Docker: the remote view is the page, leaving it gives the browser back to rest.
var docker = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton(docker)))
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
Assert.AreEqual(HttpStatusCode.NoContent, status);
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
}
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
var windows = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s
.AddSingleton(windows)
.AddSingleton(new SeparateWindow())))
{
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
var (shown, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.OK, shown);
StringAssert.Contains(message.Str("message"), "primo piano");
await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show", new { openLogin = true });
}
CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody()
{
// Chunked, as a body without Content-Length may come (HTTP/2 too): empty is the default, not a 400.
var windows = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s
.AddSingleton(windows)
.AddSingleton(new SeparateWindow()));
foreach (var (path, body) in new[]
{
("/api/connection/begin", ""),
("/api/connection/cancel", ""),
("/api/browser/show", ""),
("/api/connection/cancel", """{"pageLeft":true}"""),
("/api/browser/show", """{"openLogin":true}"""),
})
{
using var request = server.Request(HttpMethod.Post, path);
request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body)));
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
request.Headers.TransferEncodingChunked = true;
using var response = await server.Client.SendAsync(request);
Assert.IsTrue(response.IsSuccessStatusCode, $"{path} «{body}»: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
}
CollectionAssert.AreEqual(new[] { "begin:False", "cancel", "show:False", "release", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task CommandsFromAnotherPageAreRefused()
{
var connection = new RecordingConnection();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton(connection));
foreach (var path in new[] { "/api/connection/begin", "/api/connection/finish", "/api/connection/disconnect" })
{
using var request = server.Request(HttpMethod.Post, path, new { openLogin = true }, origin: "http://altro.example");
using var response = await server.Client.SendAsync(request);
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path);
}
using var crossSite = server.Request(HttpMethod.Post, "/api/connection/disconnect", origin: null);
crossSite.Headers.Add("Sec-Fetch-Site", "cross-site");
using var crossResponse = await server.Client.SendAsync(crossSite);
Assert.AreEqual(HttpStatusCode.Forbidden, crossResponse.StatusCode);
Assert.IsEmpty(connection.Calls, "no command reached the service");
}
[TestMethod]
public async Task CapabilitiesListTheConfigurationProblems()
{
await using (var clean = await Part2.StartAsync())
{
var caps = await clean.GetJsonAsync("/api/capabilities");
Assert.AreEqual(0, caps.GetProperty("problems").GetArrayLength(), "the default registration has no problems");
}
var problem = new ConfigurationProblem("password-mancante", "Manca la password dell'interfaccia", "Il motore non è partito.", "Imposta FEBE_PASSWORD e riavvia.");
await using var server = await Part2.StartAsync(services: s => s.AddSingleton(new FixedProblems(problem)));
var listed = (await server.GetJsonAsync("/api/capabilities")).Items("problems").ToList();
Assert.HasCount(1, listed);
Assert.AreEqual("password-mancante", listed[0].Str("code"));
Assert.AreEqual(problem.Title, listed[0].Str("title"));
Assert.AreEqual(problem.Message, listed[0].Str("message"));
Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
}
/// The browser as a window of its own, as on Windows.
private sealed class SeparateWindow : Febe.Web.Native.IBrowserWindow
{
public bool IsSeparateWindow => true;
}
}