Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
252 changes: 252 additions & 0 deletions VisualPinball.Engine.DOF.Test/DofConfigToolClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
// Visual Pinball Engine
// Copyright (C) 2026 freezy and VPE Team
//
// SPDX-License-Identifier: GPL-3.0-or-later

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using VisualPinball.Engine.DOF.Configuration;

namespace VisualPinball.Engine.DOF.Test
{
/// <summary>The Config Tool download, against answers like the Config Tool's; nothing is sent to it.</summary>
[TestFixture]
public class DofConfigToolClientTests
{
private const string Key = "AbCdEfGhIjKlMnOpQrSt";
private static readonly byte[] Zip = ZipOf("directoutputconfig30.ini", "tablemappings.xml");

private static byte[] ZipOf(params string[] entries)
{
using var memory = new MemoryStream();
using (var zip = new ZipArchive(memory, ZipArchiveMode.Create, true)) {
foreach (var entry in entries) {
using var writer = new StreamWriter(zip.CreateEntry(entry).Open());
writer.Write("content");
}
}
return memory.ToArray();
}

/// <summary>
/// A body that stops coming, after what it is given, and that doesn't end on a cancelled read either: only when it is
/// let go of, with an error or, as some runtimes do, as if it had ended.
/// </summary>
private sealed class Stalling : Stream
{
private readonly TaskCompletionSource<int> _disposed = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly byte[] _first;
private readonly bool _endsOnDispose;
private bool _given;

public Stalling(byte[] first = null, bool endsOnDispose = false)
{
_first = first;
_endsOnDispose = endsOnDispose;
}

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellation)
{
if (_first != null && !_given) {
_given = true;
Array.Copy(_first, 0, buffer, offset, _first.Length);
return Task.FromResult(_first.Length);
}
return _disposed.Task;
}

public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, default).GetAwaiter().GetResult();

protected override void Dispose(bool disposing)
{
if (_endsOnDispose) {
_disposed.TrySetResult(0);
} else {
_disposed.TrySetException(new ObjectDisposedException(nameof(Stalling)));
}
base.Dispose(disposing);
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}

/// <summary>Answers every request with what a test says, and keeps the requests.</summary>
internal sealed class Answering : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, HttpResponseMessage> _answer;
public readonly List<HttpRequestMessage> Requests = new List<HttpRequestMessage>();

public Answering(Func<HttpRequestMessage, HttpResponseMessage> answer) => _answer = answer;

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellation)
{
cancellation.ThrowIfCancellationRequested();
Requests.Add(request);
return Task.FromResult(_answer(request));
}
}

internal static HttpResponseMessage Answer(HttpStatusCode status, byte[] body) => new HttpResponseMessage(status) { Content = new ByteArrayContent(body) };

internal static HttpResponseMessage Answer(HttpStatusCode status, string body) => Answer(status, Encoding.UTF8.GetBytes(body));

private static byte[] Download(Answering handler, string key = Key)
{
using var client = new DofConfigToolClient("VisualPinballEngine-DOF/test", handler);
return client.DownloadAsync(key).GetAwaiter().GetResult();
}

private static string Refused(Answering handler, string key = Key)
{
var e = Assert.Throws<DofException>(() => Download(handler, key));
Assert.That(e.Message, Does.Not.Contain(key.Trim()), "the key stays out of what is shown and logged");
return e.Message;
}

[Test]
public void DownloadsTheCabinetsZipWithItsKey()
{
var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
Assert.That(Download(handler, " " + Key + "\n"), Is.EqualTo(Zip));
var request = handler.Requests[0];
Assert.That(request.Method, Is.EqualTo(HttpMethod.Get));
Assert.That(request.RequestUri.ToString(), Is.EqualTo("https://configtool.vpuniverse.com/api.php?query=getconfig&apikey=" + Key));
Assert.That(request.Headers.UserAgent.ToString(), Is.EqualTo("VisualPinballEngine-DOF/test"));
}

[Test]
public void SendsTheKeyOnlyAsItsValue()
{
var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
Download(handler, "a&query=x#y");
Assert.That(handler.Requests[0].RequestUri.Query, Is.EqualTo("?query=getconfig&apikey=a%26query%3Dx%23y"));
}

[Test]
public void RefusesWhatIsNoKeyWithoutAsking()
{
var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
Assert.That(DofConfigToolClient.CheckKey(" "), Does.Contain("Cabinets page"));
Assert.That(DofConfigToolClient.CheckKey("two words"), Does.Contain("one word"));
Assert.That(DofConfigToolClient.CheckKey(new string('a', 257)), Is.Not.Null);
Assert.That(DofConfigToolClient.CheckKey(" " + Key + " "), Is.Null);
Assert.That(Assert.Throws<DofException>(() => Download(handler, "")).Message, Does.Contain("Enter your cabinet's API key"));
Assert.That(handler.Requests, Is.Empty);
}

[Test]
public void SaysWhenTheConfigToolDoesNotKnowTheKey()
{
var message = Refused(new Answering(_ => Answer(HttpStatusCode.Unauthorized, "API Error: Invalid API key passed")));
Assert.That(message, Does.Contain("doesn't know this API key"));
}

[Test]
public void SaysWhenTheDownloadIsTurnedAway()
{
var challenge = Answer(HttpStatusCode.Forbidden, "<!DOCTYPE html><html><title>Just a moment...</title></html>");
challenge.Headers.Add("cf-mitigated", "challenge");
Assert.That(Refused(new Answering(_ => challenge)), Does.Contain("turned the download away").And.Contain("browser"));
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.ServiceUnavailable, "down"))), Does.Contain("503"));
// the reason phrase is the server's: it may say anything, the key too
var echoing = Answer(HttpStatusCode.ServiceUnavailable, "down");
echoing.ReasonPhrase = "No cabinet " + Key;
Assert.That(Refused(new Answering(_ => echoing)), Does.Contain("status 503"));
}

[Test]
public void KeepsTheKeyOutOfACutAnswer()
{
// the key across the place the answer is cut at
var said = Refused(new Answering(_ => Answer(HttpStatusCode.OK, "API Error: " + new string('x', 180) + " " + Key + " " + new string('y', 100))));
Assert.That(said, Does.Not.Contain(Key.Substring(0, 6)));
}

[Test]
public void TakesNoZipWithoutIniFiles()
{
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, ZipOf("tablemappings.xml")))), Does.Contain("without DOF ini files"));
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, new byte[] { (byte)'P', (byte)'K', 3, 4, 1, 2 }))), Does.Contain("without DOF ini files"));
Assert.That(Download(new Answering(_ => Answer(HttpStatusCode.OK, ZipOf("Config/directoutputconfig.ini")))), Is.Not.Empty);
}

[Test]
public void GivesUpOnABodyThatStopsComing()
{
var handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling()) });
using var client = new DofConfigToolClient("test", handler, TimeSpan.FromMilliseconds(300));
var task = client.DownloadAsync(Key);
// the deadline covers the body
var e = Assert.Throws<AggregateException>(() => task.Wait(TimeSpan.FromSeconds(10)));
Assert.That(e.InnerException, Is.InstanceOf<DofException>().With.Message.Contain("in time"));

// a whole zip, then nothing until the deadline lets go of it, which reads as the end: still too late
handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling(Zip, true)) });
using var ending = new DofConfigToolClient("test", handler, TimeSpan.FromMilliseconds(300));
e = Assert.Throws<AggregateException>(() => ending.DownloadAsync(Key).Wait(TimeSpan.FromSeconds(10)));
Assert.That(e.InnerException, Is.InstanceOf<DofException>().With.Message.Contain("in time"));
}

[Test]
public void StopsABodyThatStopsComingWhenCancelled()
{
var handler = new Answering(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new Stalling()) });
using var client = new DofConfigToolClient("test", handler);
using var cancellation = new CancellationTokenSource(300);
var task = client.DownloadAsync(Key, cancellation.Token);
Assert.That(() => task.Wait(TimeSpan.FromSeconds(10)), Throws.InstanceOf<AggregateException>().With.InnerException.InstanceOf<OperationCanceledException>());
}

[Test]
public void TakesOnlyAZip()
{
// what the API says instead of a zip is shown, a web page isn't
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, "API Error: no cabinet for " + Key))),
Does.Contain("sent no configuration: API Error: no cabinet for …"));
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, "<html><body>Maintenance</body></html>"))),
Does.EndWith("sent no configuration."));
Assert.That(Refused(new Answering(_ => Answer(HttpStatusCode.OK, Array.Empty<byte>()))), Does.Contain("sent no configuration"));
}

[Test]
public void StopsAtTheLimit()
{
var handler = new Answering(_ => Answer(HttpStatusCode.OK, new byte[2048]));
using var client = new DofConfigToolClient("test", handler) { MaxBytes = 1024 };
Assert.That(Assert.Throws<DofException>(() => client.DownloadAsync(Key).GetAwaiter().GetResult()).Message, Does.Contain("larger than"));
}

[Test]
public void SaysWhenTheConfigToolCanNotBeReached()
{
var handler = new Answering(request => throw new HttpRequestException("No such host is known. (" + request.RequestUri + ")"));
var message = Refused(handler);
Assert.That(message, Does.StartWith("Could not reach the DOF Config Tool: No such host is known."));
}

[Test]
public void StopsWhenCancelled()
{
var handler = new Answering(_ => Answer(HttpStatusCode.OK, Zip));
using var client = new DofConfigToolClient("test", handler);
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
Assert.That(() => client.DownloadAsync(Key, cancellation.Token).GetAwaiter().GetResult(), Throws.InstanceOf<OperationCanceledException>());
}
}
}
15 changes: 15 additions & 0 deletions VisualPinball.Engine.DOF.Test/DofGameTriggersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,20 @@ public void KeepsTriggersPerRowDeviceAndPort()
reset.Save(_root);
Assert.That(File.Exists(Path.Combine(_root, DofGameTriggers.FileName)), Is.False, "no file for nothing changed");
}

[Test]
public void PutsOneGamesTriggersBackAndKeepsTheOthers()
{
var before = DofGameTriggers.None.With("afm", 30, 7, "S6").With("t2", 30, 1, "S1");
var now = before.With("afm", 30, 7, "S9").With("afm", 30, 2, "L3").With("t2", 30, 1, "S2").With("mm", 30, 4, "S4");
var back = now.WithRowsOf(before, new[] { "AFM " });
Assert.That(back.Of("afm", 30), Is.EqualTo(new[] { (7, "S6") }), "the game's as they were, the one it added gone");
Assert.That((back.SettingOf("t2", 30, 1), back.SettingOf("mm", 30, 4)), Is.EqualTo(("S2", "S4")), "the other games' as they are");
Assert.That(DofGameTriggers.Parse(back.Text).Text, Is.EqualTo(back.Text), "read as written");
Assert.That(DofGameTriggers.Parse("afm\t30\t7\tS6\r\n").SettingOf("afm", 30, 7), Is.EqualTo("S6"));
var cr = DofGameTriggers.Parse("afm\t30\t7\tS6\rt2\t30\t1\tS1\r");
Assert.That((cr.SettingOf("afm", 30, 7), cr.SettingOf("t2", 30, 1)), Is.EqualTo(("S6", "S1")), "a byte order mark and lines that end in CR alone");
Assert.That(DofGameTriggers.Parse(null).IsEmpty, Is.True);
}
}
}
Loading
Loading