Le prove cadevano a ogni carico della CI, ogni volta prove diverse. Dietro alcune c'erano difetti veri: FebeDatabase lasciava i file aperti dopo DisposeAsync (comandi SQLite non chiusi, pool di lettura chiuso dopo lo scrittore), e il WAL spariva durante lo spostamento della cartella Dati; la scheda dell'account senza statistiche leggeva i file di tutta la libreria; l'arresto di FebeApp non aspettava i lavori aggiunti da un avvio in corso. Chromium ha 120 s per avviarsi e aprire la prima scheda, e il ricollegamento smette appena il processo cambia. Nelle prove i limiti di tempo diventano protezioni contro un blocco: attese per condizione con un aiuto comune, limiti per classe nella prova di scala con il tempo migliore, porta 0 e stderr di Chromium nel browser delle prove, e la prova di «Scollega» di WebView2 controlla che il processo esca davvero. Provato su Windows con tutti i core occupati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
209 lines
13 KiB
C#
209 lines
13 KiB
C#
using System.Text;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Import;
|
|
using Febe.Tests.Import.Support;
|
|
using Febe.Tests.Support;
|
|
|
|
namespace Febe.Tests.Import;
|
|
|
|
[TestClass]
|
|
public sealed class MediaReaderTests
|
|
{
|
|
private static readonly DateTimeOffset Now = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero);
|
|
|
|
[TestMethod]
|
|
public void TheTypeComesFromTheContentNotFromTheExtension()
|
|
{
|
|
var jpeg = ImportTestFiles.Photo(1, 64, 48);
|
|
var png = ImportTestFiles.Png(2, 64, 48);
|
|
Assert.AreEqual("image/jpeg", MediaSniffer.Detect(jpeg, ".png")?.ContentType, "Un JPEG chiamato .png resta un JPEG.");
|
|
Assert.AreEqual(".jpg", MediaSniffer.Detect(jpeg, ".jpeg")?.Extension);
|
|
Assert.AreEqual("image/png", MediaSniffer.Detect(png, ".jpg")?.ContentType);
|
|
Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("GIF89a\x01\0\x01\0"u8.ToArray())?.Kind);
|
|
Assert.AreEqual("image/webp", MediaSniffer.Detect("RIFF\0\0\0\0WEBPVP8 "u8.ToArray())?.ContentType);
|
|
Assert.AreEqual("video/x-msvideo", MediaSniffer.Detect("RIFF\0\0\0\0AVI LIST"u8.ToArray())?.ContentType);
|
|
|
|
Assert.AreEqual("image/heic", MediaSniffer.Detect(Ftyp("heic", "mif1", "heic"))?.ContentType);
|
|
Assert.AreEqual("image/heif", MediaSniffer.Detect(Ftyp("mif1", "mif1"))?.ContentType);
|
|
Assert.AreEqual("image/avif", MediaSniffer.Detect(Ftyp("avif", "mif1", "avif"))?.ContentType);
|
|
Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("isom", "isom", "mp41"))?.ContentType);
|
|
Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("mp42", "mp42"))?.ContentType);
|
|
Assert.AreEqual("video/quicktime", MediaSniffer.Detect(Ftyp("qt ", "qt "))?.ContentType);
|
|
Assert.AreEqual("video/quicktime", MediaSniffer.Detect(ImportTestFiles.Mp4(Now, withFtyp: false))?.ContentType, "MOV senza ftyp, che comincia con moov.");
|
|
Assert.AreEqual("video/webm", MediaSniffer.Detect([0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42, 0x82, 0x84, .. "webm"u8])?.ContentType);
|
|
Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Kind);
|
|
Assert.AreEqual(".dng", MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Extension, "I formati raw tengono la loro estensione.");
|
|
|
|
Assert.IsNull(MediaSniffer.Detect(Ftyp("M4A ", "M4A ", "mp42")), "Solo audio: né foto né video.");
|
|
Assert.IsNull(MediaSniffer.Detect(Encoding.UTF8.GetBytes("Appunti del viaggio, non una foto.")));
|
|
Assert.IsNull(MediaSniffer.Detect("%PDF-1.7\n"u8.ToArray()));
|
|
Assert.IsNull(MediaSniffer.Detect([]));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheShootingDateIsReadFromExifWrittenByHand()
|
|
{
|
|
var zone = TestZones.Rome;
|
|
var jpeg = ImportTestFiles.PhotoWithExifDate(3, new DateTime(2021, 5, 6, 7, 8, 9), width: 64, height: 48);
|
|
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), ExifDateReader.Read(jpeg, zone), "Ora locale di Roma (estate, +2).");
|
|
|
|
var withOffset = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("2021:05:06 07:08:09", offsetOriginal: "-05:00", littleEndian: true));
|
|
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 12, 8, 9, TimeSpan.Zero), ExifDateReader.Read(withOffset, zone)?.ToUniversalTime(), "Il fuso scritto dalla fotocamera vince.");
|
|
|
|
var onlyCreate = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff(null, createDate: "2019:12:31 23:59:58"));
|
|
Assert.AreEqual(new DateTimeOffset(2019, 12, 31, 22, 59, 58, TimeSpan.Zero), ExifDateReader.Read(onlyCreate, zone), "Senza DateTimeOriginal si usa CreateDate.");
|
|
|
|
var png = ImportTestFiles.PngWithExif(ImportTestFiles.Png(4, 32, 24), ImportTestFiles.Tiff("2018:02:03 10:00:00"));
|
|
Assert.AreEqual(new DateTimeOffset(2018, 2, 3, 9, 0, 0, TimeSpan.Zero), ExifDateReader.Read(png, zone), "PNG con il blocco eXIf.");
|
|
|
|
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.Photo(3, 64, 48), zone), "Nessun EXIF: nessuna data.");
|
|
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("0000:00:00 00:00:00")), zone));
|
|
|
|
// A damaged block (offsets beyond the end) gives no date, never an exception.
|
|
var damaged = ImportTestFiles.Tiff("2021:05:06 07:08:09");
|
|
damaged.AsSpan(36, 4).Fill(0xFF); // the offset of the date value points far beyond the block
|
|
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged), zone));
|
|
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged.AsSpan(0, 20).ToArray()), zone));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void CreationTimeDurationAndSizeComeFromTheMp4Header()
|
|
{
|
|
var created = new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero);
|
|
var info = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1080, 1920, 15_500)), Now);
|
|
Assert.IsNotNull(info);
|
|
Assert.AreEqual(created, info.CreatedAt);
|
|
Assert.AreEqual(TimeSpan.FromMilliseconds(15_500), info.Duration);
|
|
Assert.AreEqual(1080, info.Width);
|
|
Assert.AreEqual(1920, info.Height);
|
|
|
|
var atEnd = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, moovAtEnd: true)), Now);
|
|
Assert.AreEqual(created, atEnd?.CreatedAt, "Il moov dopo i dati si trova saltando mdat.");
|
|
|
|
var rotated = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1920, 1080, rotated: true)), Now);
|
|
Assert.AreEqual((1080, 1920), (rotated?.Width, rotated?.Height), "Un video ruotato di 90° si mostra in verticale.");
|
|
|
|
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(null)), Now)?.CreatedAt, "Zero: data non scritta.");
|
|
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(new DateTimeOffset(1904, 1, 2, 0, 0, 0, TimeSpan.Zero))), Now)?.CreatedAt, "Una data del 1904 non è plausibile.");
|
|
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(Now.AddDays(10))), Now)?.CreatedAt, "Una data nel futuro non è plausibile.");
|
|
Assert.IsNull(Mp4Reader.Read(new MemoryStream("not a movie at all"u8.ToArray()), Now));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A 64-bit box size close to 2^63 overflows «offset + size»: the reader must stop on it, not walk backwards
|
|
/// forever (the analysis would hang and every «Riprendi» would hit the same file again).
|
|
/// </summary>
|
|
[TestMethod]
|
|
public void AHugeSixtyFourBitBoxSizeEndsTheReadingInsteadOfLooping()
|
|
{
|
|
static byte[] Box(string type, params byte[][] parts) =>
|
|
[.. BigEndian((uint)(8 + parts.Sum(p => p.Length))), .. Encoding.ASCII.GetBytes(type), .. parts.SelectMany(p => p)];
|
|
static byte[] BigEndian(uint value) => [(byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value];
|
|
byte[] huge = [0, 0, 0, 1, .. "xxxx"u8, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8];
|
|
var ftyp = Box("ftyp", "isom"u8.ToArray(), [0, 0, 2, 0]);
|
|
|
|
// Inside moov: a valid «free» box, then the damaged one.
|
|
byte[] insideMoov = [.. ftyp, .. Box("moov", Box("free"), huge)];
|
|
|
|
// At the top level, after ftyp.
|
|
byte[] topLevel = [.. ftyp, .. huge, .. new byte[32]];
|
|
|
|
foreach (var (name, bytes) in new[] { ("moov", insideMoov), ("primo livello", topLevel) })
|
|
{
|
|
// A thread of its own (not the pool, which the parallel tests may keep busy) and a generous limit: only an
|
|
// endless loop fails it (#46).
|
|
var reading = Task.Factory.StartNew(() => Mp4Reader.Read(new MemoryStream(bytes), Now), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
|
Assert.IsTrue(reading.Wait(TimeSpan.FromSeconds(60)), $"{name}: la lettura deve finire.");
|
|
var info = reading.Result;
|
|
Assert.IsNull(info?.CreatedAt, name);
|
|
Assert.IsNull(info?.Width, name);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void AnMp4MadeByFfmpegCarriesItsCreationTime()
|
|
{
|
|
using var temp = new TempFolder("mp4");
|
|
var path = temp.Combine("prova.mp4");
|
|
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero);
|
|
if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created))
|
|
{
|
|
Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore.");
|
|
}
|
|
|
|
Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType);
|
|
var info = Mp4Reader.ReadFile(path, Now);
|
|
Assert.AreEqual(created, info?.CreatedAt);
|
|
Assert.AreEqual(64, info?.Width);
|
|
Assert.AreEqual(48, info?.Height);
|
|
Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task FfprobeIsAnOptionalExtra()
|
|
{
|
|
var parsed = FfprobeVideoMetadataProbe.Parse("""
|
|
{"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}],
|
|
"format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}}
|
|
""");
|
|
Assert.AreEqual(new DateTimeOffset(2020, 8, 9, 10, 11, 12, TimeSpan.Zero), parsed?.CreatedAt);
|
|
Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration);
|
|
Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height));
|
|
Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json"));
|
|
Assert.AreEqual(640, FfprobeVideoMetadataProbe.Parse("""{"streams":[{"codec_type":"video","width":640,"height":480,"tags":{"rotate":0}}],"format":{"tags":{"creation_time":5}}}""")?.Width, "Valori di tipo inatteso non fanno fallire la lettura.");
|
|
|
|
var probe = FfprobeVideoMetadataProbe.TryCreate();
|
|
if (probe is null)
|
|
{
|
|
Assert.Inconclusive("ffprobe non è installato.");
|
|
return;
|
|
}
|
|
|
|
using var temp = new TempFolder("ffprobe");
|
|
var path = temp.Combine("prova.mp4");
|
|
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero);
|
|
if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created))
|
|
{
|
|
Assert.Inconclusive("ffmpeg non è installato.");
|
|
}
|
|
|
|
var metadata = await probe.ProbeAsync(path);
|
|
Assert.AreEqual(created, metadata?.CreatedAt);
|
|
Assert.AreEqual(64, metadata?.Width);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void DatesAreFoundInCommonFileNames()
|
|
{
|
|
var zone = TestZones.Rome;
|
|
static DateTimeOffset Rome(int y, int mo, int d, int h, int mi, int s) => new DateTimeOffset(y, mo, d, h, mi, s, TimeSpan.Zero).AddHours(mo is >= 4 and <= 10 ? -2 : -1);
|
|
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("IMG_20210506_070809", zone, Now)?.Instant);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("VID_20210506_070809", zone, Now)?.Instant);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("PXL_20210506_070809123", zone, Now)?.Instant);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("2021-05-06 07.08.09", zone, Now)?.Instant);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("WhatsApp Image 2021-05-06 at 07.08.09", zone, Now)?.Instant);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("Screenshot_2021-05-06-07-08-09", zone, Now)?.Instant);
|
|
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 7, 8, 9, TimeSpan.Zero), FileNameDates.Find("2021-05-06_07-08-09_UTC", zone, Now)?.Instant, "«_UTC» dice che l'ora è universale.");
|
|
|
|
var dayOnly = FileNameDates.Find("IMG-20210506-WA0001", zone, Now);
|
|
Assert.IsTrue(dayOnly?.DayOnly);
|
|
Assert.AreEqual(Rome(2021, 5, 6, 12, 0, 0), dayOnly?.Instant);
|
|
|
|
Assert.IsNull(FileNameDates.Find("2567890123456789012_123456", zone, Now), "Le cifre di un identificativo non sono una data.");
|
|
Assert.IsNull(FileNameDates.Find("IMG_20211306_070809", zone, Now), "Mese 13: non è una data.");
|
|
Assert.IsNull(FileNameDates.Find("IMG_20300506_070809", zone, Now), "Una data nel futuro non è plausibile.");
|
|
Assert.IsNull(FileNameDates.Find("vacanze al mare", zone, Now));
|
|
}
|
|
|
|
private static byte[] Ftyp(string major, params string[] compatible)
|
|
{
|
|
var body = Encoding.ASCII.GetBytes(major).Concat(new byte[] { 0, 0, 0, 0 }).Concat(compatible.SelectMany(Encoding.ASCII.GetBytes)).ToArray();
|
|
var box = new byte[8 + body.Length + 16];
|
|
System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(box, (uint)(8 + body.Length));
|
|
"ftyp"u8.CopyTo(box.AsSpan(4));
|
|
body.CopyTo(box.AsSpan(8));
|
|
return box;
|
|
}
|
|
}
|