Il registro delle decisioni era insieme troppo grande e troppo povero: 102.656 aste fermate dalla soglia delle puntate residue scrivevano una riga identica a ogni ciclo, mentre di una puntata non si sapeva a quanti millisecondi dalla scadenza fosse partita né perché una puntata decisa non fosse partita. In Osserva un paletto zittiva il modello, così non si poteva sapere se il paletto costava aste. Migrazione 0004 (solo colonne nuove): - bot_decisions: repeat_count, last_ts, last_price (Data/DecisionRuns: la stessa decisione senza parere ciclo dopo ciclo resta una riga; il conteggio si scrive a fine serie, ogni 60 ripetizioni e alla chiusura), model_action, fire_note. ts è ora l'istante della decisione, non della scrittura (anche per bids, resets e my_bids.local_ts). - my_bids: millisecondi alla scadenza al verdetto, all'invio e alla risposta, stato HTTP, risposta di Bidoo ripulita, qualità dell'orologio e trace con le ultime letture prima e dopo. Tutto calcolato dopo la risposta: nulla di nuovo sul percorso caldo. - auctions: decisions, decisions_bid, decisions_model_bid alla chiusura, che restano anche quando il tetto dei dati cancella le decisioni. BidStrategy: in Osserva, con l'apprendimento acceso, un paletto ferma la puntata ma il modello dà lo stesso il parere (numeri, model_action, motivo «senza il paletto il modello punterebbe…»). Il verdetto non cambia. Scelta voluta: queste decisioni hanno la chiave del contesto, quindi il bandit impara anche da loro. La pausa dopo una puntata ora viene prima della soglia delle puntate residue. Lettori aggiornati: esito di una serie sull'ultimo prezzo, LossReasons pesato per le ripetizioni e con il parere del modello, Storico, esportazioni (quattro colonne nuove e conteggi pesati), LEGGIMI dello scaricamento. my_bids.trace contiene nomi: nello scaricamento il campo «ultimo» diventa pseudonimo. Test: DecisionRuns, parere sotto i paletti (Osserva sì, dal vivo e con l'apprendimento spento no), motivi pesati, pseudonimi del trace e una prova su PostgreSQL (200 cicli bloccati = una riga con 200, esito dall'ultimo prezzo, conteggi dell'asta, tempi della puntata, fire_note). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
411 lines
22 KiB
C#
411 lines
22 KiB
C#
using System.IO.Compression;
|
|
using System.Text;
|
|
using System.Text.Json.Nodes;
|
|
using System.Text.RegularExpressions;
|
|
using Mimante.Data;
|
|
using Mimante.Data.Archive;
|
|
using Npgsql;
|
|
using Xunit;
|
|
|
|
namespace Mimante.Tests;
|
|
|
|
public class PseudonymsTests
|
|
{
|
|
private const string Salt = "00112233445566778899aabbccddeeff";
|
|
|
|
[Fact]
|
|
public void Lo_stesso_nome_da_sempre_lo_stesso_pseudonimo_e_i_miei_diventano_io()
|
|
{
|
|
var p = new Pseudonyms(Salt, new[] { "sirbietole23" });
|
|
var anna = p.Of("anna")!;
|
|
Assert.Matches("^u_[0-9a-f]{12}$", anna);
|
|
Assert.Equal(anna, new Pseudonyms(Salt, Array.Empty<string>()).Of("anna"));
|
|
Assert.NotEqual(anna, p.Of("bob"));
|
|
Assert.NotEqual(anna, new Pseudonyms("ffeeddccbbaa99887766554433221100", Array.Empty<string>()).Of("anna"));
|
|
Assert.Equal(Pseudonyms.Me, p.Of("sirbietole23"));
|
|
Assert.Null(p.Of(null));
|
|
Assert.Equal("", p.Of(""));
|
|
}
|
|
|
|
[Fact]
|
|
public void Spenti_restituiscono_i_nomi_veri()
|
|
{
|
|
var p = new Pseudonyms(Salt, new[] { "io_vero" }, enabled: false);
|
|
Assert.Equal("anna", p.Of("anna"));
|
|
Assert.Equal("username", p.Sql("username"));
|
|
Assert.Equal("vinta da anna", p.Text("vinta da anna"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Nei_testi_cambiano_solo_i_nomi_dopo_vinta_da_e_coperta_da()
|
|
{
|
|
var p = new Pseudonyms(Salt, new[] { "sirbietole23" });
|
|
Assert.Equal($"vinta da {p.Of("anna")} a 3,21 €", p.Text("vinta da anna a 3,21 €"));
|
|
Assert.Equal($"coperta da {p.Of("bob_77")} (a mano); poi vinta da io", p.Text("coperta da bob_77 (a mano); poi vinta da sirbietole23"));
|
|
Assert.Equal("coperta dall'autopuntata", p.Text("coperta dall'autopuntata"));
|
|
Assert.Equal("P bassa, serve 0,3%", p.Text("P bassa, serve 0,3%"));
|
|
Assert.Null(p.Text(null));
|
|
}
|
|
|
|
[Fact]
|
|
public void Il_sale_deve_essere_esadecimale()
|
|
{
|
|
Assert.Throws<ArgumentException>(() => new Pseudonyms("'; DROP TABLE bids; --", Array.Empty<string>()));
|
|
Assert.Throws<ArgumentException>(() => new Pseudonyms("abc", Array.Empty<string>()));
|
|
Assert.Matches("^[0-9a-f]{32}$", Pseudonyms.NewSalt());
|
|
}
|
|
|
|
[Fact]
|
|
public void I_nomi_miei_con_un_apice_restano_letterali_sql_validi()
|
|
{
|
|
var sql = new Pseudonyms(Salt, new[] { "o'brien" }).Sql("username");
|
|
Assert.Contains("'o''brien'", sql);
|
|
}
|
|
}
|
|
|
|
public class DayRangesTests
|
|
{
|
|
/// <summary>Un archivio finto: id con buchi, tempi crescenti; conta le letture.</summary>
|
|
private sealed class FakeTable((long Id, DateTime At)[] rows)
|
|
{
|
|
public int Probes { get; private set; }
|
|
|
|
public Task<(long Id, DateTime CreatedUtc)?> Probe(long atLeast, CancellationToken ct)
|
|
{
|
|
Probes++;
|
|
foreach (var r in rows)
|
|
if (r.Id >= atLeast) return Task.FromResult<(long, DateTime)?>((r.Id, r.At));
|
|
return Task.FromResult<(long, DateTime)?>(null);
|
|
}
|
|
}
|
|
|
|
private static readonly DateTime T0 = new(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
|
|
[Fact]
|
|
public async Task Trova_il_primo_id_di_ogni_giorno_saltando_i_buchi()
|
|
{
|
|
var rows = new[]
|
|
{
|
|
(10L, T0.AddHours(1)), (11L, T0.AddHours(20)), (50L, T0.AddDays(1).AddHours(2)), (51L, T0.AddDays(1).AddHours(3)),
|
|
(900L, T0.AddDays(3).AddHours(5)), (901L, T0.AddDays(3).AddHours(6))
|
|
};
|
|
var table = new FakeTable(rows);
|
|
Assert.Equal(10, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0, CancellationToken.None));
|
|
Assert.Equal(50, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(1), CancellationToken.None));
|
|
// Un giorno senza righe: il primo id «del giorno o dopo» è quello del giorno dopo, e il file del giorno è vuoto.
|
|
Assert.Equal(900, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(2), CancellationToken.None));
|
|
Assert.Equal(900, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 50, 902, T0.AddDays(3), CancellationToken.None));
|
|
Assert.Equal(902, await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 10, 902, T0.AddDays(4), CancellationToken.None));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Con_un_milione_di_id_bastano_poche_letture()
|
|
{
|
|
var rows = Enumerable.Range(0, 1_000_000).Select(i => ((long)i * 3 + 7, T0.AddSeconds(i))).ToArray();
|
|
var table = new FakeTable(rows);
|
|
var target = T0.AddSeconds(654_321);
|
|
var id = await DayRanges.FirstIdAtOrAfterAsync(table.Probe, 7, rows[^1].Item1 + 1, target, CancellationToken.None);
|
|
Assert.Equal(654_321L * 3 + 7, id);
|
|
Assert.InRange(table.Probes, 1, 45);
|
|
}
|
|
|
|
[Fact]
|
|
public void L_inizio_del_giorno_locale_segue_l_ora_legale()
|
|
{
|
|
var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
|
Assert.Equal(new DateTime(2026, 7, 9, 22, 0, 0, DateTimeKind.Utc), DayRanges.StartUtc(new DateOnly(2026, 7, 10), rome));
|
|
Assert.Equal(new DateTime(2026, 11, 9, 23, 0, 0, DateTimeKind.Utc), DayRanges.StartUtc(new DateOnly(2026, 11, 10), rome));
|
|
}
|
|
|
|
[Fact]
|
|
public void I_giorni_vanno_dal_primo_a_ieri_dentro_da_e_a_e_sono_definitivi_dopo_il_margine()
|
|
{
|
|
var today = new DateOnly(2026, 11, 24);
|
|
var days = ArchiveDownloader.Days(new DateOnly(2026, 11, 20), today, null, null).ToList();
|
|
Assert.Equal(new DateOnly(2026, 11, 20), days[0]);
|
|
Assert.Equal(new DateOnly(2026, 11, 23), days[^1]);
|
|
Assert.Equal(new[] { new DateOnly(2026, 11, 21), new DateOnly(2026, 11, 22) },
|
|
ArchiveDownloader.Days(new DateOnly(2026, 11, 20), today, new DateOnly(2026, 11, 21), new DateOnly(2026, 11, 22)));
|
|
Assert.Empty(ArchiveDownloader.Days(new DateOnly(2026, 11, 24), today, null, null));
|
|
Assert.True(ArchiveDownloader.IsFinal(new DateOnly(2026, 11, 21), today, 2));
|
|
Assert.False(ArchiveDownloader.IsFinal(new DateOnly(2026, 11, 22), today, 2));
|
|
}
|
|
}
|
|
|
|
public class BulkCopyTests
|
|
{
|
|
[Fact]
|
|
public async Task Un_record_scritto_si_rilegge_uguale_con_null_vuoti_virgolette_e_a_capo()
|
|
{
|
|
var records = new[]
|
|
{
|
|
new string?[] { "id", "testo", "nulla" },
|
|
new string?[] { "1", "semplice", null },
|
|
new string?[] { "2", "", "x" },
|
|
new string?[] { "3", "con, virgola e \"virgolette\"", null },
|
|
new string?[] { "4", "su\ndue righe\r\ne tre", "" }
|
|
};
|
|
var sb = new StringBuilder();
|
|
foreach (var r in records) BulkCopy.WriteRecord(sb, r);
|
|
var reader = new BulkCopy.CsvRecords(new StringReader(sb.ToString()));
|
|
foreach (var expected in records)
|
|
Assert.Equal(expected, await reader.NextAsync(CancellationToken.None));
|
|
Assert.Null(await reader.NextAsync(CancellationToken.None));
|
|
}
|
|
|
|
[Fact]
|
|
public void Il_contatore_non_conta_gli_a_capo_fra_virgolette_anche_a_pezzi()
|
|
{
|
|
const string text = "a,b\n1,\"x\ny\"\n2,\"z\"\"\n\"\n3,w";
|
|
foreach (var size in new[] { 1, 2, 3, 7, 100 })
|
|
{
|
|
var c = new BulkCopy.RecordCounter();
|
|
for (var i = 0; i < text.Length; i += size) c.Feed(text.AsSpan(i, Math.Min(size, text.Length - i)));
|
|
Assert.Equal(4, c.Total);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class ManifestTests
|
|
{
|
|
[Fact]
|
|
public void Si_salva_si_rilegge_e_dice_quali_file_non_vanno_riscaricati()
|
|
{
|
|
using var dir = new TempDir();
|
|
var m = new Manifest { Program = "2.0.0", Schema = 3 };
|
|
var t = m.Table("bids", "IdDay");
|
|
var file = Path.Combine(dir.Path, "a.csv.gz");
|
|
File.WriteAllBytes(file, new byte[] { 1, 2, 3 });
|
|
t.Files["tabelle/bids/2026-10/2026-10-01.csv.gz"] = new Manifest.FileEntry { Rows = 5, Bytes = 3, Sha256 = "ab", Final = true, IdFrom = 1, IdTo = 6, Day = "2026-10-01" };
|
|
m.Save(dir.Path);
|
|
|
|
var back = Manifest.Load(dir.Path)!;
|
|
var e = back.Tables["bids"].Files["tabelle/bids/2026-10/2026-10-01.csv.gz"];
|
|
Assert.Equal(6, e.IdTo);
|
|
Assert.True(Manifest.IsDone(e, file));
|
|
Assert.False(Manifest.IsDone(new Manifest.FileEntry { Bytes = 3, Final = false }, file));
|
|
Assert.False(Manifest.IsDone(new Manifest.FileEntry { Bytes = 4, Final = true }, file));
|
|
Assert.False(Manifest.IsDone(e, Path.Combine(dir.Path, "manca.csv.gz")));
|
|
Assert.False(File.Exists(Path.Combine(dir.Path, Manifest.FileName + ".tmp")));
|
|
}
|
|
}
|
|
|
|
public class ArchiveTableTests
|
|
{
|
|
/// <summary>Le tabelle che lo scaricamento non porta mai fuori, per scelta (oggi nessuna).</summary>
|
|
private static readonly HashSet<string> NotExported = new(StringComparer.Ordinal);
|
|
|
|
[Fact]
|
|
public void Ogni_tabella_delle_migrazioni_e_nel_catalogo_o_esclusa_apposta()
|
|
{
|
|
var asm = typeof(Migrations).Assembly;
|
|
var tables = new HashSet<string>(StringComparer.Ordinal) { "schema_migrations" };
|
|
foreach (var res in asm.GetManifestResourceNames().Where(r => r.EndsWith(".sql", StringComparison.Ordinal)))
|
|
{
|
|
using var reader = new StreamReader(asm.GetManifestResourceStream(res)!);
|
|
foreach (Match m in Regex.Matches(reader.ReadToEnd(), @"CREATE TABLE IF NOT EXISTS (\w+)\s*\(", RegexOptions.IgnoreCase))
|
|
tables.Add(m.Groups[1].Value);
|
|
}
|
|
Assert.NotEmpty(tables);
|
|
foreach (var t in tables)
|
|
Assert.True(ArchiveTable.Find(t) != null || NotExported.Contains(t), $"La tabella {t} non è in ArchiveTable.All: aggiungila (con i nomi da pseudonimizzare) o escludila apposta.");
|
|
}
|
|
|
|
[Fact]
|
|
public void I_percorsi_non_dipendono_dalla_cultura()
|
|
{
|
|
var bids = ArchiveTable.Find("bids")!;
|
|
Assert.Equal("tabelle/bids/2026-01/2026-01-05.csv.gz", bids.RelativePath(new DateOnly(2026, 1, 5)));
|
|
Assert.Equal("tabelle/items.csv.gz", ArchiveTable.Find("items")!.RelativePath(null));
|
|
}
|
|
|
|
[Fact]
|
|
public void La_select_riscrive_solo_le_colonne_con_un_nome_o_un_segreto()
|
|
{
|
|
var p = new Pseudonyms("00112233445566778899aabbccddeeff", Array.Empty<string>());
|
|
var list = ArchiveTable.Find("bids")!.SelectList(new[] { "bid_id", "username", "price_after" }, p);
|
|
Assert.StartsWith("bid_id, (CASE WHEN username", list);
|
|
Assert.EndsWith(" AS username, price_after", list);
|
|
Assert.Contains("value - 'TelegramBotToken' - 'TelegramChatId' AS value", ArchiveTable.Find("settings")!.SelectList(new[] { "id", "value" }, p));
|
|
}
|
|
}
|
|
|
|
[Collection("Database")]
|
|
public class ArchiveDownloaderTests(DatabaseFixture fx)
|
|
{
|
|
private const string Salt = "00112233445566778899aabbccddeeff";
|
|
private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
|
|
|
private static async Task<NpgsqlConnection> OpenAsync()
|
|
{
|
|
var conn = new NpgsqlConnection(ArchiveDownloader.ReadOnlyBuilder(TestDb.Config, 5).ConnectionString);
|
|
await conn.OpenAsync();
|
|
return conn;
|
|
}
|
|
|
|
[DbFact]
|
|
public async Task Gli_pseudonimi_di_postgresql_sono_quelli_del_programma()
|
|
{
|
|
await using var conn = await OpenAsync();
|
|
var p = new Pseudonyms(Salt, new[] { "sirbietole23" });
|
|
foreach (var name in new[] { "anna", "Bob_77", "ünïcode", "sirbietole23" })
|
|
{
|
|
await using var cmd = new NpgsqlCommand($"SELECT {p.Sql("$1::text")}", conn) { Parameters = { new NpgsqlParameter { Value = name } } };
|
|
Assert.Equal(p.Of(name), (string?)await cmd.ExecuteScalarAsync());
|
|
}
|
|
await using (var keys = new NpgsqlCommand($"SELECT {p.SqlJsonKeys("'{\"anna\": 3, \"sirbietole23\": 1}'::jsonb")}::text", conn))
|
|
{
|
|
var o = JsonNode.Parse((string)(await keys.ExecuteScalarAsync())!)!.AsObject();
|
|
Assert.Equal(3, (int)o[p.Of("anna")!]!);
|
|
Assert.Equal(1, (int)o[Pseudonyms.Me]!);
|
|
}
|
|
await using (var field = new NpgsqlCommand($"SELECT {p.SqlJsonField("'{\"lastBidder\": \"anna\", \"price\": 1.5}'::jsonb", "lastBidder")}::text", conn))
|
|
{
|
|
var o = JsonNode.Parse((string)(await field.ExecuteScalarAsync())!)!.AsObject();
|
|
Assert.Equal(p.Of("anna"), (string?)o["lastBidder"]);
|
|
Assert.Equal(1.5, (double)o["price"]!);
|
|
}
|
|
const string trace = "'{\"prima\": [{\"t\": 1, \"ultimo\": \"anna\"}, {\"t\": 2, \"ultimo\": null}], \"dopo\": [{\"t\": 3, \"ultimo\": \"sirbietole23\"}]}'::jsonb";
|
|
await using (var arrays = new NpgsqlCommand($"SELECT {p.SqlJsonArraysField(trace, "ultimo", "prima", "dopo")}::text", conn))
|
|
{
|
|
var o = JsonNode.Parse((string)(await arrays.ExecuteScalarAsync())!)!.AsObject();
|
|
Assert.Equal(p.Of("anna"), (string?)o["prima"]![0]!["ultimo"]);
|
|
Assert.Equal(1, (int)o["prima"]![0]!["t"]!);
|
|
Assert.Null(o["prima"]![1]!["ultimo"]);
|
|
Assert.Equal(2, (int)o["prima"]![1]!["t"]!);
|
|
Assert.Equal(Pseudonyms.Me, (string?)o["dopo"]![0]!["ultimo"]);
|
|
}
|
|
await using (var none = new NpgsqlCommand($"SELECT {p.SqlJsonArraysField("NULL::jsonb", "ultimo", "prima", "dopo")} IS NULL", conn))
|
|
Assert.True((bool)(await none.ExecuteScalarAsync())!);
|
|
}
|
|
|
|
[DbFact]
|
|
public async Task La_connessione_dello_strumento_non_puo_scrivere()
|
|
{
|
|
await using var conn = await OpenAsync();
|
|
await using var cmd = new NpgsqlCommand("INSERT INTO items(product_key) VALUES ('scrittura-vietata')", conn);
|
|
var e = await Assert.ThrowsAsync<PostgresException>(() => cmd.ExecuteNonQueryAsync());
|
|
Assert.Equal("25006", e.SqlState); // read_only_sql_transaction
|
|
}
|
|
|
|
[DbFact]
|
|
public async Task Scarica_per_giorno_locale_con_pseudonimi_riassunti_dossier_e_verifica()
|
|
{
|
|
await fx.TruncateAsync();
|
|
var db = fx.Db!;
|
|
foreach (var t in Partitions.Tables)
|
|
await db.ExecuteAsync($"CREATE TABLE IF NOT EXISTS {t}_2020_01 PARTITION OF {t} FOR VALUES FROM ('2020-01-01') TO ('2020-02-01')");
|
|
|
|
await db.ExecuteAsync("INSERT INTO settings(id, value) VALUES (1, '{\"TelegramBotToken\": \"123:segreto\", \"TelegramChatId\": \"42\", \"MaxBids\": 5}') " +
|
|
"ON CONFLICT (id) DO UPDATE SET value = excluded.value");
|
|
await db.ExecuteAsync("INSERT INTO documents(key, value) VALUES ('ml/pesi', '{\"w\": [1, 2]}'), ('monitor/auctions', '[{\"winner\": \"anna\"}]')");
|
|
await db.ExecuteAsync(
|
|
"INSERT INTO auctions(auction_id, name, product_key, type, outcome, final_price, end_time, me, winner_user, my_bids, observed_from_start, observed_to_end, bids_by_user, loss_reason) VALUES " +
|
|
"('A1', 'Buono', 'buono', 'normal', 'lost', 1.02, '2020-01-11 10:00:00+00', 'sirbietole23', 'anna', 1, true, true, '{\"anna\": 2, \"sirbietole23\": 1}', 'vinta da anna'), " +
|
|
"('A2', 'Buono', 'buono', 'normal', 'lost', 0.51, '2020-01-12 10:00:00+00', 'sirbietole23', 'bob', 0, true, true, '{\"bob\": 1}', 'coperta da bob (a mano)')");
|
|
// Il 10 gennaio alle 23:30 UTC a Roma è già l'11: deve finire nel file dell'11.
|
|
await db.ExecuteAsync(
|
|
"INSERT INTO bids(auction_id, username, price_after, created_at) VALUES " +
|
|
"('A1', 'anna', 1.00, '2020-01-10 12:00:00+00'), ('A1', 'sirbietole23', 1.01, '2020-01-10 23:30:00+00'), ('A1', 'anna', 1.02, '2020-01-11 09:00:00+00'), " +
|
|
"('A2', 'bob', 0.51, '2020-01-12 09:00:00+00')");
|
|
await db.ExecuteAsync("INSERT INTO resets(auction_id, t, bidder, created_at) VALUES ('A1', 1, 'anna', '2020-01-10 12:00:00+00'), ('A2', 2, 'bob', '2020-01-12 09:00:00+00')");
|
|
await db.ExecuteAsync(
|
|
"INSERT INTO bot_decisions(decision_id, auction_id, ts, kind, p_win, outcome, reason_detail, state, created_at) VALUES " +
|
|
"(1, 'A1', '2020-01-10 12:00:01+00', 'punta', 0.05, 'covered', 'coperta da anna', '{\"lastBidder\": \"anna\"}', '2020-01-10 12:00:01+00'), " +
|
|
"(2, 'A2', '2020-01-12 09:00:01+00', 'esplora', 0.02, 'missed', 'P bassa', '{\"lastBidder\": \"bob\"}', '2020-01-12 09:00:01+00')");
|
|
await db.ExecuteAsync("INSERT INTO auction_forecasts(auction_id, ts, is_initial, forecast_close, actual_close, error_close, in_interval) VALUES ('A1', '2020-01-10 12:00:00+00', true, 1.1, 1.02, 0.08, true)");
|
|
await db.ExecuteAsync("INSERT INTO my_bids(auction_id, t, local_ts, price, success, answered_by, decision_id) VALUES ('A1', 5, '2020-01-10 23:30:00+00', 1.01, true, 'anna', 1)");
|
|
await db.ExecuteAsync("INSERT INTO bidders(username, n_bids) VALUES ('anna', 2), ('bob', 1)");
|
|
|
|
using var dir = new TempDir();
|
|
var lines = new List<string>();
|
|
var options = new ArchiveDownloader.Options
|
|
{
|
|
Folder = dir.Path, Today = new DateOnly(2020, 1, 20), MegabytesPerSecond = 0, ReserveGb = 0, PauseForMaintenance = false, Sample = 10
|
|
};
|
|
await File.WriteAllTextAsync(Path.Combine(dir.Path, ".sale"), Salt);
|
|
var p = new Pseudonyms(Salt, new[] { "sirbietole23" });
|
|
|
|
await using (var conn = await OpenAsync())
|
|
{
|
|
var tool = new ArchiveDownloader(conn, options, lines.Add, Rome);
|
|
await tool.DownloadAsync(CancellationToken.None);
|
|
await tool.SummariesAsync(CancellationToken.None);
|
|
await tool.DossierAsync(CancellationToken.None);
|
|
|
|
var manifest = Manifest.Load(dir.Path)!;
|
|
var bids = manifest.Tables["bids"].Files;
|
|
Assert.Equal(new long[] { 1, 2, 1 }, new[] { "10", "11", "12" }.Select(d => bids[$"tabelle/bids/2020-01/2020-01-{d}.csv.gz"].Rows));
|
|
Assert.True(bids["tabelle/bids/2020-01/2020-01-17.csv.gz"].Final);
|
|
Assert.False(bids["tabelle/bids/2020-01/2020-01-18.csv.gz"].Final); // a due giorni da «oggi» gli esiti possono ancora arrivare
|
|
Assert.Equal(0, bids["tabelle/bids/2020-01/2020-01-19.csv.gz"].Rows);
|
|
Assert.False(bids.ContainsKey("tabelle/bids/2020-01/2020-01-20.csv.gz"));
|
|
Assert.Equal(1, manifest.Tables["bot_decisions"].Files["tabelle/bot_decisions/2020-01/2020-01-12.csv.gz"].Rows);
|
|
|
|
var day11 = Gunzip(Path.Combine(dir.Path, "tabelle", "bids", "2020-01", "2020-01-11.csv.gz"));
|
|
Assert.StartsWith("bid_id,auction_id,username,", day11);
|
|
Assert.Contains($",{Pseudonyms.Me},1.01,", day11);
|
|
Assert.Contains($",{p.Of("anna")},1.02,", day11);
|
|
|
|
var all = string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.gz", SearchOption.AllDirectories).Select(Gunzip))
|
|
+ string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.csv", SearchOption.AllDirectories).Select(File.ReadAllText))
|
|
+ string.Join("\n", Directory.EnumerateFiles(dir.Path, "*.jsonl", SearchOption.AllDirectories).Select(File.ReadAllText));
|
|
foreach (var secret in new[] { "anna", "bob", "sirbietole23", "123:segreto", "monitor/auctions" })
|
|
Assert.DoesNotContain(secret, all);
|
|
Assert.Contains("MaxBids", all);
|
|
Assert.Contains($"vinta da {p.Of("anna")}", all);
|
|
Assert.Contains($"coperta da {p.Of("bob")} (a mano)", all);
|
|
|
|
Assert.True(File.Exists(Path.Combine(dir.Path, "riassunti", "calibrazione.csv")));
|
|
Assert.Equal(1, manifest.Other["riassunti/mie_puntate.csv"].Rows);
|
|
var dossier = await File.ReadAllLinesAsync(Path.Combine(dir.Path, "dossier", "mie", "A1.jsonl"));
|
|
Assert.Equal(new[] { "asta", "previsione", "decisione", "mia_puntata", "puntata", "puntata", "puntata", "reset" },
|
|
dossier.Select(l => (string)JsonNode.Parse(l)!["tipo"]!));
|
|
Assert.True(File.Exists(Path.Combine(dir.Path, "dossier", "osservate", "A2.jsonl")));
|
|
var readme = await File.ReadAllTextAsync(Path.Combine(dir.Path, "LEGGIMI.md"));
|
|
Assert.Contains("### bot_decisions", readme);
|
|
Assert.Contains("| `reason_detail` | text |", readme);
|
|
|
|
Assert.Empty(await ArchiveDownloader.VerifyAsync(dir.Path, conn, lines.Add, CancellationToken.None));
|
|
|
|
// La seconda volta i file definitivi non si riscaricano; quelli interi sì.
|
|
var before = manifest.Tables["bids"].Files["tabelle/bids/2020-01/2020-01-11.csv.gz"].DownloadedUtc;
|
|
await tool.DownloadAsync(CancellationToken.None);
|
|
var again = Manifest.Load(dir.Path)!;
|
|
Assert.Equal(before, again.Tables["bids"].Files["tabelle/bids/2020-01/2020-01-11.csv.gz"].DownloadedUtc);
|
|
Assert.True(again.Tables["auctions"].Files["tabelle/auctions.csv.gz"].DownloadedUtc > manifest.Tables["auctions"].Files["tabelle/auctions.csv.gz"].DownloadedUtc);
|
|
|
|
var estimate = await tool.EstimateAsync(CancellationToken.None);
|
|
Assert.Equal(new DateOnly(2020, 1, 10), estimate.Single(r => r.Table == "bids").FirstDay);
|
|
}
|
|
|
|
// Un file rovinato si vede senza database.
|
|
var damaged = Path.Combine(dir.Path, "tabelle", "bids", "2020-01", "2020-01-10.csv.gz");
|
|
var bytes = await File.ReadAllBytesAsync(damaged);
|
|
bytes[^1] ^= 0xFF;
|
|
await File.WriteAllBytesAsync(damaged, bytes);
|
|
var problems = await ArchiveDownloader.VerifyAsync(dir.Path, null, _ => { }, CancellationToken.None);
|
|
Assert.Single(problems);
|
|
Assert.Contains("2020-01-10", problems[0]);
|
|
}
|
|
|
|
[DbFact]
|
|
public async Task Una_cartella_con_pseudonimi_non_riceve_i_nomi_veri()
|
|
{
|
|
await fx.TruncateAsync();
|
|
using var dir = new TempDir();
|
|
await using var conn = await OpenAsync();
|
|
var options = new ArchiveDownloader.Options { Folder = dir.Path, Today = new DateOnly(2020, 1, 20), PauseForMaintenance = false, ReserveGb = 0, Tables = new HashSet<string> { "items" } };
|
|
await new ArchiveDownloader(conn, options, _ => { }, Rome).DownloadAsync(CancellationToken.None);
|
|
var real = new ArchiveDownloader(conn, options with { RealNames = true }, _ => { }, Rome);
|
|
await Assert.ThrowsAsync<InvalidOperationException>(() => real.DownloadAsync(CancellationToken.None));
|
|
}
|
|
|
|
private static string Gunzip(string file)
|
|
{
|
|
using var gz = new GZipStream(File.OpenRead(file), CompressionMode.Decompress);
|
|
using var r = new StreamReader(gz, Encoding.UTF8);
|
|
return r.ReadToEnd();
|
|
}
|
|
}
|