about summary refs log tree commit diff
path: root/Tests/LibMatrix.Tests/Abstractions
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2024-07-15 07:50:36 +0200
committerRory& <root@rory.gay>2024-07-15 07:50:36 +0200
commit107bf85658661631dc5bab26e0d768993ee54165 (patch)
tree010b0d55dd284e4027a30f0894f84efeeb91269d /Tests/LibMatrix.Tests/Abstractions
parentReturn null on TryGetFromJson if a JsonException happens (diff)
downloadLibMatrix-107bf85658661631dc5bab26e0d768993ee54165.tar.xz
Import unit test fixes from dev/home-changes
Diffstat (limited to '')
-rw-r--r--Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs111
-rw-r--r--Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs9
2 files changed, 73 insertions, 47 deletions
diff --git a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
index c9727d6..401223c 100644
--- a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
+++ b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
@@ -1,71 +1,96 @@
 using ArcaneLibs.Extensions;
 using LibMatrix.Homeservers;
 using LibMatrix.Responses;
+using LibMatrix.Services;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+using Xunit.Abstractions;
+using Xunit.Sdk;
 
 namespace LibMatrix.Tests.Abstractions;
 
-public static class HomeserverAbstraction {
-    public static async Task<AuthenticatedHomeserverGeneric> GetHomeserver() {
-        var rhs = await RemoteHomeserver.Create("https://matrixunittests.rory.gay");
-        // string username = Guid.NewGuid().ToString();
-        // string password = Guid.NewGuid().ToString();
-        var username = "@f1a2d2d6-1924-421b-91d0-893b347b2a49:matrixunittests.rory.gay";
-        var password = "d6d782d6-8bc9-4fac-9cd8-78e101b4298b";
+public class HomeserverAbstraction(HomeserverProviderService _hsProvider, Config _config, ILogger<HomeserverAbstraction> _logger) {
+    // private static readonly HomeserverResolverService _hsResolver = new HomeserverResolverService(NullLogger<HomeserverResolverService>.Instance);
+    // private static readonly HomeserverProviderService _hsProvider = new HomeserverProviderService(NullLogger<HomeserverProviderService>.Instance, _hsResolver);
+    
+    private static AuthenticatedHomeserverGeneric? ConfiguredHomeserver { get; set; }
+    private static readonly SemaphoreSlim _lock = new(1, 1);
+    
+    public async Task<AuthenticatedHomeserverGeneric> GetConfiguredHomeserver(ITestOutputHelper? testOutputHelper = null) {
+        Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver));
+        Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername));
+        Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword));
+        
+        _logger.LogDebug("Using homeserver '{0}' with login '{1}' '{2}", _config.TestHomeserver, _config.TestUsername, _config.TestPassword);
+        testOutputHelper?.WriteLine($"Using homeserver '{_config.TestHomeserver}' with login '{_config.TestUsername}' '{_config.TestPassword}'");
+
+        await _lock.WaitAsync();
+        if (ConfiguredHomeserver is not null) {
+            _lock.Release();
+            return ConfiguredHomeserver;
+        }
+
+        var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver);
+        
         LoginResponse reg;
         try {
-            reg = await rhs.LoginAsync(username, password);
+            reg = await rhs.LoginAsync(_config.TestUsername, _config.TestPassword);
         }
         catch (MatrixException e) {
             if (e.ErrorCode == "M_FORBIDDEN") {
                 await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!");
-                reg = await rhs.RegisterAsync(username, password, "Unit tests!");
+                reg = await rhs.RegisterAsync(_config.TestUsername, _config.TestPassword, "Unit tests!");
             }
             else throw new Exception("Failed to register", e);
         }
 
-        var hs = await reg.GetAuthenticatedHomeserver("https://matrixunittests.rory.gay");
-
-        //var rooms = await hs.GetJoinedRooms();
-
-        // var disbandRoomTasks = rooms.Select(async room => {
-        //     // await room.DisbandRoomAsync();
-        //     await room.LeaveAsync();
-        //     await room.ForgetAsync();
-        //     return room;
-        // }).ToList();
-        // await Task.WhenAll(disbandRoomTasks);
-
-        // foreach (var room in rooms) {
-        //     // await room.DisbandRoomAsync();
-        //     await room.LeaveAsync();
-        //     await room.ForgetAsync();
-        // }
+        var hs = await _hsProvider.GetAuthenticatedWithToken(reg.Homeserver, reg.AccessToken);
+        ConfiguredHomeserver = hs;
+        _lock.Release();
 
         return hs;
     }
 
-    public static async Task<AuthenticatedHomeserverGeneric> GetRandomHomeserver() {
-        var rhs = await RemoteHomeserver.Create("https://matrixunittests.rory.gay");
-        var reg = await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!");
-        var hs = await reg.GetAuthenticatedHomeserver("https://matrixunittests.rory.gay");
-
-        // var rooms = await hs.GetJoinedRooms();
-        //
-        // var disbandRoomTasks = rooms.Select(async room => {
-        //     // await room.DisbandRoomAsync();
-        //     await room.LeaveAsync();
-        //     await room.ForgetAsync();
-        //     return room;
-        // }).ToList();
-        // await Task.WhenAll(disbandRoomTasks);
-
+    public async Task<AuthenticatedHomeserverGeneric> GetNewHomeserver() {
+        Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver));
+        var username = Guid.NewGuid().ToString();
+        var password = Guid.NewGuid().ToString();
+        
+        _logger.LogDebug("Creating new homeserver '{0}' with login '{1}' '{2}'", _config.TestHomeserver, username, password);
+        
+        var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver);
+        var reg = await rhs.RegisterAsync(username, password, "Unit tests!");
+        var hs = await _hsProvider.GetAuthenticatedWithToken(reg.Homeserver, reg.AccessToken);
+        
         return hs;
     }
 
-    public static async IAsyncEnumerable<AuthenticatedHomeserverGeneric> GetRandomHomeservers(int count = 1) {
+    public async IAsyncEnumerable<AuthenticatedHomeserverGeneric> GetNewHomeservers(int count = 1) {
         var createRandomUserTasks = Enumerable
             .Range(0, count)
-            .Select(_ => GetRandomHomeserver()).ToAsyncEnumerable();
+            .Select(_ => GetNewHomeserver()).ToAsyncEnumerable();
         await foreach (var hs in createRandomUserTasks) yield return hs;
     }
+
+    public async Task<(string username, string password, string token)> GetKnownCredentials() {
+        Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver));
+        var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver);
+        
+        var username = _config.TestUsername;
+        var password = _config.TestPassword;
+        
+        LoginResponse reg;
+        try {
+            reg = await rhs.LoginAsync(username, password);
+        }
+        catch (MatrixException e) {
+            if (e.ErrorCode == "M_FORBIDDEN") {
+                await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!");
+                reg = await rhs.RegisterAsync(username, password, "Unit tests!");
+            }
+            else throw new Exception("Failed to log in", e);
+        }
+        
+        return (username, password, reg.AccessToken);
+    }
 }
\ No newline at end of file
diff --git a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
index 2a380fc..88b6758 100644
--- a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
+++ b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
@@ -1,3 +1,4 @@
+using System.Diagnostics;
 using ArcaneLibs.Extensions;
 using LibMatrix.EventTypes.Spec.State;
 using LibMatrix.EventTypes.Spec.State.RoomInfo;
@@ -16,28 +17,28 @@ public static class RoomAbstraction {
         };
         crq.InitialState ??= new List<StateEvent>();
         crq.InitialState.Add(new StateEvent() {
-            Type = "m.room.topic",
+            Type = RoomTopicEventContent.EventId,
             StateKey = "",
             TypedContent = new RoomTopicEventContent() {
                 Topic = "LibMatrix Test Room " + DateTime.Now.ToString("O")
             }
         });
         crq.InitialState.Add(new StateEvent() {
-            Type = "m.room.name",
+            Type = RoomNameEventContent.EventId,
             StateKey = "",
             TypedContent = new RoomNameEventContent() {
                 Name = "LibMatrix Test Room " + DateTime.Now.ToString("O")
             }
         });
         crq.InitialState.Add(new StateEvent() {
-            Type = "m.room.avatar",
+            Type = RoomAvatarEventContent.EventId,
             StateKey = "",
             TypedContent = new RoomAvatarEventContent() {
                 Url = "mxc://conduit.rory.gay/r9KiT0f9eQbv8pv4RxwBZFuzhfKjGWHx"
             }
         });
         crq.InitialState.Add(new StateEvent() {
-            Type = "m.room.aliases",
+            Type = RoomAliasEventContent.EventId,
             StateKey = "",
             TypedContent = new RoomAliasEventContent() {
                 Aliases = Enumerable