using System.Text.Json.Nodes;
using Anubis.Data;
using Anubis.Db;
using Anubis.News;
namespace Anubis.Tests;
///
/// Broken input never stops the news (issue #61, the independent review): answers of the model that are not valid
/// Unicode or have another shape, requests that fail in unforeseen ways, articles that cannot be stored.
///
public sealed partial class NewsAnalystTests
{
// Six characters of JSON: an escape that stands for half a character (a lone surrogate).
private const string Lone = "\\" + "ud83d";
///
/// Valid JSON that is not valid Unicode, which a hostile title can ask for, is refused like any other value outside
/// the schema, wherever it stands.
///
[TestMethod]
[TestCategory(Category.Unit)]
public void BrokenUnicodeInAnAnswerIsRefusedNotThrown()
{
AnalystItem[] items = [new(1, "Solana upgrade delayed", [], ["SOL"]), new(2, "Ether ETF approved", [], ["ETH"])];
static JsonObject V(int item) => Verdict(new JsonObject { ["item"] = item }, ["SOL"], "negative", 3);
var first = V(1).ToJsonString();
var second = V(2).ToJsonString();
static string Answer(string one, string two) => "{\"verdicts\":[" + one + "," + two + "]}";
Assert.IsTrue(NewsVerdicts.Parse(Answer(first, second), items).All(o => o.Verdict is not null));
foreach (var field in new[] { "summary_it", "scope", "event_type", "direction" })
{
var start = $"\"{field}\":\"";
StringAssert.Contains(first, start);
var outcomes = NewsVerdicts.Parse(Answer(first.Replace(start, start + Lone, StringComparison.Ordinal), second), items);
Assert.IsTrue(outcomes[0].Verdict is null && outcomes[0].Problem is not null, field);
Assert.IsNotNull(outcomes[1].Verdict, "The other verdict stands: " + field);
}
foreach (var (what, broken) in new[]
{
("instrument", first.Replace("[\"SOL\"]", $"[\"{Lone}\"]", StringComparison.Ordinal)),
("field name", first.Replace("\"scope\"", $"\"{Lone}\"", StringComparison.Ordinal)),
})
{
Assert.AreNotEqual(first, broken, what);
var outcomes = NewsVerdicts.Parse(Answer(broken, second), items);
Assert.IsTrue(outcomes[0].Verdict is null && outcomes[0].Problem is not null, what);
}
var root = NewsVerdicts.Parse(Answer(first, second).Replace("\"verdicts\"", $"\"{Lone}\"", StringComparison.Ordinal), items);
Assert.IsTrue(root.All(o => o.Verdict is null && o.Problem is not null), "root name");
}
/// The summary carries no address in any form, and no character that changes the direction of the text.
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSummaryHasNoAddressAndNoInvisibleCharacter()
{
foreach (var bad in new[] { "Verifica su coinbase-support.com", "Vai su t.me/aiuto", "Scrivi a evil.example/x", "Testoalla rovescia", "Testonascosto" })
{
Assert.IsNull(NewsVerdicts.CleanSummary(bad), bad);
}
foreach (var good in new[] { "Solana rinvia l'aggiornamento di una settimana.", "Il titolo scende del 3.5% dopo i conti.", "Utile a 1.200 milioni.La guida resta." })
{
Assert.IsNotNull(NewsVerdicts.CleanSummary(good), good);
}
}
/// A service answer of any shape cannot be used: it is billed, with a problem, never an exception.
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AServiceAnswerOfAnyShapeNeverThrows()
{
string[] bodies =
[
"[]", "\"x\"", "1", "null", "{}", "{\"content\":[\"x\"]}", "{\"content\":[{\"type\":1,\"text\":\"x\"}]}", "{\"content\":[{\"type\":\"text\",\"text\":5}]}",
"{\"content\":[{\"type\":\"text\",\"text\":\"" + Lone + "\"}]}", "{\"stop_reason\":\"" + Lone + "\"}", "{\"choices\":[\"x\"]}", "{\"choices\":[null]}",
"{\"choices\":[{\"finish_reason\":\"" + Lone + "\"}]}", "{\"choices\":[{\"message\":{\"content\":\"" + Lone + "\"}}]}", "{\"choices\":[{\"message\":[]}]}",
];
foreach (var provider in new[] { NewsModelProviders.Anthropic, NewsModelProviders.OpenAi })
{
var config = new NewsModelConfig(provider, "m", NewsModelProviders.DefaultAddress(provider), 1m, 1m, 1m);
foreach (var body in bodies)
{
var answer = await new LanguageModel(new FakeHttp().On(_ => true, _ => FakeHttp.Respond(body)).Client(), config, "k").AskAsync(Request(), _none);
Assert.IsTrue(answer.Billed && answer.Text is null && answer.Problem is not null, provider + " " + body);
}
}
}
///
/// A billed answer that cannot be read is counted and never paid twice, a model that fails in an unforeseen way
/// pauses, and in both cases the diary of the news is written in the same round (10.5).
///
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ABrokenAnswerIsPaidOnceAndNeverStopsTheDiary()
{
await using var test = await DatabaseTests.MigratedAsync();
var (clock, settings, specs) = await SetUpAsync(test.Db);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_sources SET enabled = @off", _none, ("off", false)), _none);
using var http = new FakeHttp();
var model = new FakeModel(r => Reply(Answer(r, i => Verdict(i, ["SOL"], "negative", 4)).Replace("\"summary_it\":\"", "\"summary_it\":\"" + Lone, StringComparison.Ordinal)));
using (var collector = Collector(http, test.Db, clock, settings, model))
{
await collector.RunOnceAsync(_none);
clock.Advance(TimeSpan.FromMinutes(2));
await collector.RunOnceAsync(_none);
}
Assert.AreEqual(1, model.Requests.Count, "Paid once.");
Assert.AreEqual(1, await CountAsync(test.Db, "news_model_calls"));
Assert.AreEqual(1, await CountAsync(test.Db, "journal"), "The restriction is in the diary.");
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana validator fraud case opened", clock.UtcNow.AddMinutes(-5), 4, -0.9, "CoinDesk", trusted: true);
var failing = new FakeModel(_ => throw new InvalidOperationException("prova"));
using (var collector = Collector(http, test.Db, clock, settings, failing))
{
await collector.RunOnceAsync(_none);
await collector.RunOnceAsync(_none);
}
Assert.AreEqual(1, failing.Requests.Count, "Not asked again at once: the pause after a failure.");
Assert.AreEqual(2, await CountAsync(test.Db, "news_model_calls"), "What may have been billed is counted.");
Assert.AreEqual(2, await CountAsync(test.Db, "journal"));
}
/// A stop of the bot while the model answers keeps the cost: the estimate is written before the request leaves.
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStopDuringARequestKeepsItsCost()
{
await using var test = await DatabaseTests.MigratedAsync();
var (clock, settings, specs) = await SetUpAsync(test.Db);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana story", Now.AddHours(-1), 2, 0.1, "CoinDesk", trusted: true);
using var stop = new CancellationTokenSource();
var model = new FakeModel(_ =>
{
stop.Cancel();
throw new OperationCanceledException(stop.Token);
});
var analyst = Analyst(test.Db, clock, settings, TestKey, model);
await Assert.ThrowsExactlyAsync(() => analyst.RunOnceAsync(stop.Token));
var spending = await analyst.SpendingAsync(_none);
Assert.IsTrue(spending.Spent > 0m);
Assert.AreEqual(0, spending.Judged);
}
/// An article cut in the middle of an emoji or with a zero character is stored, and one bad source never stops the others.
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ABadArticleNeverStopsTheRound()
{
var emoji = string.Concat(Enumerable.Repeat("\U0001F600", 400));
foreach (var offset in new[] { "", "a" })
{
var cut = FeedParser.Text(offset + emoji, 300)!;
Assert.IsTrue(cut.Length <= 300);
Assert.AreEqual(cut, cut.Normalize(), "Whole characters only.");
}
Assert.AreEqual("a b", FeedParser.Text("ab", 100));
await using var test = await DatabaseTests.MigratedAsync();
var (clock, settings, specs) = await SetUpAsync(test.Db);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true);
var feed = "x" + emoji + "https://example.test/emojia�" + emoji +
"";
using var http = new FakeHttp().On(_ => true, r => r.RequestUri!.Host.Contains("coindesk", StringComparison.Ordinal) ? throw new InvalidOperationException("prova") : FakeHttp.Respond(feed));
using var collector = new NewsCollector(http.Client(), test.Db, clock) { Pause = TimeSpan.Zero, Watcher = new NewsWatcher(test.Db, clock, settings) };
await collector.RunOnceAsync(_none);
var sources = await collector.Store.ListSourcesAsync(_none);
Assert.IsTrue(sources.Where(s => s.Enabled && s.Kind == NewsSourceKinds.Rss).All(s => s.LastCheckedAt is not null), "Every source was tried.");
Assert.IsTrue(sources.Any(s => s.Failures > 0) && sources.Any(s => s.LastOkAt is not null));
Assert.AreEqual(2, await CountAsync(test.Db, "news_items"));
Assert.AreEqual(1, await CountAsync(test.Db, "journal"), "The diary line is written anyway.");
}
private static NewsCollector Collector(FakeHttp http, Database db, Core.IClock clock, Core.SettingsStore settings, FakeModel model) =>
new(http.Client(), db, clock) { Pause = TimeSpan.Zero, Analyst = Analyst(db, clock, settings, TestKey, model), Watcher = new NewsWatcher(db, clock, settings) };
}