diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-19 00:16:36 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-19 00:16:36 +0200 |
commit | f5447484512d726f4403f0d7725777d0a95601fb (patch) | |
tree | 47fe88a4c021f62ff42663f6d8c5229e71d21813 /Tests | |
parent | Improve README (diff) | |
download | LibMatrix-bak-f5447484512d726f4403f0d7725777d0a95601fb.tar.xz |
Add more stuff, add unit tests
Diffstat (limited to 'Tests')
-rw-r--r-- | Tests/LibMatrix.Tests/Config.cs | 17 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/Fixtures/TestFixture.cs | 37 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/LibMatrix.Tests.csproj | 13 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/ResolverTest.cs | 10 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/Tests/AuthTests.cs | 52 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/Tests/ResolverTest.cs | 54 | ||||
-rw-r--r-- | Tests/LibMatrix.Tests/Tests/RoomTests.cs | 332 | ||||
-rw-r--r-- | Tests/TestDataGenerator/Bot/DataFetcher.cs | 69 | ||||
-rw-r--r-- | Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs | 9 | ||||
-rw-r--r-- | Tests/TestDataGenerator/Program.cs | 31 | ||||
-rw-r--r-- | Tests/TestDataGenerator/Properties/launchSettings.json | 26 | ||||
-rw-r--r-- | Tests/TestDataGenerator/TestDataGenerator.csproj | 32 | ||||
-rw-r--r-- | Tests/TestDataGenerator/appsettings.Development.json | 18 | ||||
-rw-r--r-- | Tests/TestDataGenerator/appsettings.json | 9 |
14 files changed, 696 insertions, 13 deletions
diff --git a/Tests/LibMatrix.Tests/Config.cs b/Tests/LibMatrix.Tests/Config.cs new file mode 100644 index 0000000..fb4ef02 --- /dev/null +++ b/Tests/LibMatrix.Tests/Config.cs @@ -0,0 +1,17 @@ +namespace LibMatrix.Tests; + +public class Config { + public string? TestHomeserver { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_HOMESERVER") ?? null; + public string? TestUsername { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_USERNAME") ?? null; + public string? TestPassword { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_PASSWORD") ?? null; + public string? TestRoomId { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ID") ?? null; + public string? TestRoomAlias { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ALIAS") ?? null; + + public Dictionary<string, string> ExpectedHomeserverMappings { get; set; } = new() { + {"matrix.org", "https://matrix-client.matrix.org"}, + {"rory.gay", "https://matrix.rory.gay"} + }; + public Dictionary<string, string> ExpectedAliasMappings { get; set; } = new() { + {"#libmatrix:rory.gay", "!tuiLEoMqNOQezxILzt:rory.gay"} + }; +} diff --git a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs new file mode 100644 index 0000000..ef49b3e --- /dev/null +++ b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs @@ -0,0 +1,37 @@ +using ArcaneLibs.Extensions; +using LibMatrix.Services; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit.Microsoft.DependencyInjection; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Fixtures; + +public class TestFixture : TestBedFixture { + protected override void AddServices(IServiceCollection services, IConfiguration? configuration) { + services.AddSingleton<TieredStorageService>(x => + new TieredStorageService( + cacheStorageProvider: null, + dataStorageProvider: null + ) + ); + + services.AddRoryLibMatrixServices(); + + services.AddSingleton<Config>(config => { + var conf = new Config(); + configuration?.GetSection("Configuration").Bind(conf); + + File.WriteAllText("configuration.json", conf.ToJson()); + + return conf; + }); + } + + protected override ValueTask DisposeAsyncCore() + => new(); + + protected override IEnumerable<TestAppSettings> GetTestAppSettings() { + yield return new TestAppSettings { Filename = "appsettings.json", IsOptional = true }; + } +} diff --git a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj index ad9b2fa..630273b 100644 --- a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj +++ b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj @@ -10,11 +10,11 @@ </PropertyGroup> <ItemGroup> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0"/> - <PackageReference Include="xunit" Version="2.4.2"/> + <PackageReference Include="xunit" Version="2.5.0" /> <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="7.0.6"/> - <PackageReference Include="Xunit.DependencyInjection" Version="8.8.2" /> - <PackageReference Include="Xunit.DependencyInjection.Logging" Version="8.1.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> @@ -23,10 +23,17 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> + <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> </ItemGroup> + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> + </Project> diff --git a/Tests/LibMatrix.Tests/ResolverTest.cs b/Tests/LibMatrix.Tests/ResolverTest.cs deleted file mode 100644 index b1191fe..0000000 --- a/Tests/LibMatrix.Tests/ResolverTest.cs +++ /dev/null @@ -1,10 +0,0 @@ -using LibMatrix.Services; - -namespace LibMatrix.Tests; - -public class ResolverTest { - [Fact] - public void ResolveServer() { - - } -} diff --git a/Tests/LibMatrix.Tests/Tests/AuthTests.cs b/Tests/LibMatrix.Tests/Tests/AuthTests.cs new file mode 100644 index 0000000..72a509d --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/AuthTests.cs @@ -0,0 +1,52 @@ +using LibMatrix.Services; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class AuthTests : TestBed<TestFixture> { + private readonly TestFixture _fixture; + private readonly HomeserverResolverService _resolver; + private readonly Config _config; + private readonly HomeserverProviderService _provider; + + public AuthTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _fixture = fixture; + _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); + _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); + _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + } + + [Fact] + public async Task LoginWithPassword() { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver), $"{nameof(_config.TestHomeserver)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername), $"{nameof(_config.TestUsername)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword), $"{nameof(_config.TestPassword)} must be set in appsettings!"); + + // var server = await _resolver.ResolveHomeserverFromWellKnown(_config.TestHomeserver!); + var login = await _provider.Login(_config.TestHomeserver!, _config.TestUsername!, _config.TestPassword!); + Assert.NotNull(login); + var hs = await _provider.GetAuthenticatedWithToken(_config.TestHomeserver!, login.AccessToken); + Assert.NotNull(hs); + await hs.Logout(); + } + + [Fact] + public async Task LoginWithToken() { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver), $"{nameof(_config.TestHomeserver)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername), $"{nameof(_config.TestUsername)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword), $"{nameof(_config.TestPassword)} must be set in appsettings!"); + + // var server = await _resolver.ResolveHomeserverFromWellKnown(_config.TestHomeserver!); + var login = await _provider.Login(_config.TestHomeserver!, _config.TestUsername!, _config.TestPassword!); + Assert.NotNull(login); + + var hs = await _provider.GetAuthenticatedWithToken(_config.TestHomeserver!, login.AccessToken); + Assert.NotNull(hs); + Assert.NotNull(hs.WhoAmI); + Assert.NotNull(hs.UserId); + Assert.NotNull(hs.AccessToken); + await hs.Logout(); + } +} diff --git a/Tests/LibMatrix.Tests/Tests/ResolverTest.cs b/Tests/LibMatrix.Tests/Tests/ResolverTest.cs new file mode 100644 index 0000000..345508a --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/ResolverTest.cs @@ -0,0 +1,54 @@ +using LibMatrix.Services; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class ResolverTest : TestBed<TestFixture> { + private readonly TestFixture _fixture; + private readonly HomeserverResolverService _resolver; + private readonly Config _config; + private readonly HomeserverProviderService _provider; + public ResolverTest(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _fixture = fixture; + _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); + _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); + _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + } + + [Fact] + public async Task ResolveServer() { + foreach (var (domain, expected) in _config.ExpectedHomeserverMappings) { + var server = await _resolver.ResolveHomeserverFromWellKnown(domain); + Assert.Equal(expected, server); + } + } + + [Fact] + public async Task ResolveMedia() { + var media = await _resolver.ResolveMediaUri("matrix.org", "mxc://matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo"); + Assert.Equal("https://matrix-client.matrix.org/_matrix/media/v3/download/matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo", media); + } + + [Fact] + public async Task ResolveRoomAliasAsync() { + var hs = await _provider.GetRemoteHomeserver("matrix.org"); + var alias = await hs.ResolveRoomAliasAsync("#matrix:matrix.org"); + Assert.Equal("!OGEhHVWSdvArJzumhm:matrix.org", alias.RoomId); + } + + [Fact] + public async Task GetClientVersionsAsync() { + var hs = await _provider.GetRemoteHomeserver("matrix.org"); + var versions = await hs.GetClientVersionsAsync(); + Assert.NotNull(versions); + } + + [Fact] + public async Task GetProfileAsync() { + var hs = await _provider.GetRemoteHomeserver("matrix.org"); + var profile = await hs.GetProfileAsync("@alice-is-:matrix.org"); + Assert.NotNull(profile); + } +} diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests.cs new file mode 100644 index 0000000..ef63ec9 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests.cs @@ -0,0 +1,332 @@ +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec.State; +using LibMatrix.Homeservers; +using LibMatrix.Services; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class RoomTests : TestBed<TestFixture> { + private readonly TestFixture _fixture; + private readonly HomeserverResolverService _resolver; + private readonly Config _config; + private readonly HomeserverProviderService _provider; + + public RoomTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _fixture = fixture; + _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); + _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); + _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + } + + private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver), $"{nameof(_config.TestHomeserver)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername), $"{nameof(_config.TestUsername)} must be set in appsettings!"); + Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword), $"{nameof(_config.TestPassword)} must be set in appsettings!"); + + // var server = await _resolver.ResolveHomeserverFromWellKnown(_config.TestHomeserver!); + var login = await _provider.Login(_config.TestHomeserver!, _config.TestUsername!, _config.TestPassword!); + Assert.NotNull(login); + + var hs = await _provider.GetAuthenticatedWithToken(_config.TestHomeserver!, login.AccessToken); + return hs; + } + + [Fact] + public async Task GetJoinedRoomsAsync() { + var hs = await GetHomeserver(); + + var rooms = await hs.GetJoinedRooms(); + Assert.NotNull(rooms); + Assert.NotEmpty(rooms); + Assert.All(rooms, Assert.NotNull); + + await hs.Logout(); + } + + [Fact] + public async Task GetNameAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var name = await room.GetNameAsync(); + Assert.NotNull(name); + Assert.NotEmpty(name); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetTopicAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var topic = await room.GetTopicAsync(); + Assert.NotNull(topic); + Assert.NotNull(topic.Topic); + Assert.NotEmpty(topic.Topic); + } + + [Fact] + public async Task GetMembersAsync() { + Assert.True(StateEvent.KnownStateEventTypes is { Count: > 0 }, "StateEvent.KnownStateEventTypes is empty!"); + Assert.True(StateEvent.KnownStateEventTypesByName is { Count: > 0 }, "StateEvent.KnownStateEventTypesByName is empty!"); + + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var members = room.GetMembersAsync(); + Assert.NotNull(members); + bool hitMembers = false; + await foreach (var member in members) { + Assert.NotNull(member); + Assert.NotNull(member.StateKey); + Assert.NotEmpty(member.StateKey); + Assert.NotNull(member.Sender); + Assert.NotEmpty(member.Sender); + Assert.NotNull(member.RawContent); + Assert.NotEmpty(member.RawContent); + Assert.NotNull(member.TypedContent); + Assert.IsType<RoomMemberEventContent>(member.TypedContent); + var content = (RoomMemberEventContent)member.TypedContent; + Assert.NotNull(content); + Assert.NotNull(content.Membership); + Assert.NotEmpty(content.Membership); + hitMembers = true; + } + + Assert.True(hitMembers, "No members were found in the room"); + } + + /* + tests remaining: + GetStateAsync(string,string) 0% 8/8 + GetMessagesAsync(string,int,string,string) 0% 7/7 + JoinAsync(string[],string) 0% 8/8 + SendMessageEventAsync(RoomMessageEventContent) 0% 1/1 + GetAliasesAsync() 0% 4/4 + GetCanonicalAliasAsync() 0% 1/1 + GetAvatarUrlAsync() 0% 1/1 + GetJoinRuleAsync() 0% 1/1 + GetHistoryVisibilityAsync() 0% 1/1 + GetGuestAccessAsync() 0% 1/1 + GetCreateEventAsync() 0% 1/1 + GetRoomType() 0% 4/4 + GetPowerLevelsAsync() 0% 1/1 + ForgetAsync() 0% 1/1 + LeaveAsync(string) 0% 1/1 + KickAsync(string,string) 0% 1/1 + BanAsync(string,string) 0% 1/1 + UnbanAsync(string) 0% 1/1 + SendStateEventAsync(string,object) 0% 1/1 + SendStateEventAsync(string,string,object) 0% 1/1 + SendTimelineEventAsync(string,EventContent) 0% 5/5 + SendFileAsync(string,string,Stream) 0% 6/6 + GetRoomAccountData<T>(string) 0% 8/8 + SetRoomAccountData(string,object) 0% 7/7 + GetEvent<T>(string) 0% 3/3 + RedactEventAsync(string,string) 0% 4/4 + InviteUser(string,string) 0% 3/3 + */ + + [Fact] + public async Task JoinAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var id = await room.JoinAsync(); + Assert.NotNull(id); + Assert.NotNull(id.RoomId); + Assert.NotEmpty(id.RoomId); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetAliasesAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var aliases = await room.GetAliasesAsync(); + Assert.NotNull(aliases); + Assert.NotEmpty(aliases); + Assert.All(aliases, Assert.NotNull); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetCanonicalAliasAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var alias = await room.GetCanonicalAliasAsync(); + Assert.NotNull(alias); + Assert.NotNull(alias.Alias); + Assert.NotEmpty(alias.Alias); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetAvatarUrlAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var url = await room.GetAvatarUrlAsync(); + Assert.NotNull(url); + Assert.NotNull(url.Url); + Assert.NotEmpty(url.Url); + } + + [Fact] + public async Task GetJoinRuleAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var rule = await room.GetJoinRuleAsync(); + Assert.NotNull(rule); + Assert.NotNull(rule.JoinRule); + Assert.NotEmpty(rule.JoinRule); + } + + [Fact] + public async Task GetHistoryVisibilityAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var visibility = await room.GetHistoryVisibilityAsync(); + Assert.NotNull(visibility); + Assert.NotNull(visibility.HistoryVisibility); + Assert.NotEmpty(visibility.HistoryVisibility); + } + + [Fact] + public async Task GetGuestAccessAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + try { + var access = await room.GetGuestAccessAsync(); + Assert.NotNull(access); + Assert.NotNull(access.GuestAccess); + Assert.NotEmpty(access.GuestAccess); + } + catch (Exception e) { + if(e is not MatrixException exception) throw; + Assert.Equal("M_NOT_FOUND", exception.ErrorCode); + } + } + + [Fact] + public async Task GetCreateEventAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var create = await room.GetCreateEventAsync(); + Assert.NotNull(create); + Assert.NotNull(create.Creator); + Assert.NotEmpty(create.RoomVersion!); + } + + [Fact] + public async Task GetRoomType() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + await room.GetRoomType(); + } + + [Fact] + public async Task GetPowerLevelsAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var power = await room.GetPowerLevelsAsync(); + Assert.NotNull(power); + Assert.NotNull(power.Ban); + Assert.NotNull(power.Kick); + Assert.NotNull(power.Invite); + Assert.NotNull(power.Redact); + Assert.NotNull(power.StateDefault); + Assert.NotNull(power.EventsDefault); + Assert.NotNull(power.UsersDefault); + Assert.NotNull(power.Users); + Assert.NotNull(power.Events); + } + + [Fact(Skip = "This test is destructive!")] + public async Task ForgetAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + await room.ForgetAsync(); + } + + [Fact(Skip = "This test is destructive!")] + public async Task LeaveAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + await room.LeaveAsync(); + } + + [Fact(Skip = "This test is destructive!")] + public async Task KickAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + // await room.KickAsync(_config.TestUserId, "test"); + } + + [Fact(Skip = "This test is destructive!")] + public async Task BanAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + // await room.BanAsync(_config.TestUserId, "test"); + } + + [Fact(Skip = "This test is destructive!")] + public async Task UnbanAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + // await room.UnbanAsync(_config.TestUserId); + } + + [SkippableFact(typeof(MatrixException))] + public async Task SendStateEventAsync() { + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", new ProfileResponseEventContent() { + DisplayName = "wee_woo", + AvatarUrl = "no" + }); + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", "state_key_maybe", new ProfileResponseEventContent() { + DisplayName = "wee_woo", + AvatarUrl = "yes" + }); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetStateEventAsync() { + await SendStateEventAsync(); + + var hs = await GetHomeserver(); + var room = hs.GetRoom(_config.TestRoomId); + Assert.NotNull(room); + var state1 = await room.GetStateAsync<ProfileResponseEventContent>("gay.rory.libmatrix.unit_tests"); + Assert.NotNull(state1); + Assert.NotNull(state1.DisplayName); + Assert.NotEmpty(state1.DisplayName); + Assert.NotNull(state1.AvatarUrl); + Assert.NotEmpty(state1.AvatarUrl); + Assert.Equal("wee_woo", state1.DisplayName); + Assert.Equal("no", state1.AvatarUrl); + + var state2 = await room.GetStateAsync<ProfileResponseEventContent>("gay.rory.libmatrix.unit_tests", "state_key_maybe"); + Assert.NotNull(state2); + Assert.NotNull(state2.DisplayName); + Assert.NotEmpty(state2.DisplayName); + Assert.NotNull(state2.AvatarUrl); + Assert.NotEmpty(state2.AvatarUrl); + Assert.Equal("wee_woo", state2.DisplayName); + Assert.Equal("yes", state2.AvatarUrl); + } +} diff --git a/Tests/TestDataGenerator/Bot/DataFetcher.cs b/Tests/TestDataGenerator/Bot/DataFetcher.cs new file mode 100644 index 0000000..b1f8402 --- /dev/null +++ b/Tests/TestDataGenerator/Bot/DataFetcher.cs @@ -0,0 +1,69 @@ +using System.Text; +using System.Threading.Channels; +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec; +using LibMatrix.EventTypes.Spec.State; +using LibMatrix.Helpers; +using LibMatrix.Homeservers; +using LibMatrix.Interfaces; +using LibMatrix.RoomTypes; +using LibMatrix.Services; +using LibMatrix.Tests; +using LibMatrix.Utilities.Bot; +using LibMatrix.Utilities.Bot.Interfaces; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace PluralContactBotPoC.Bot; + +public class DataFetcher(AuthenticatedHomeserverGeneric hs, ILogger<DataFetcher> logger, LibMatrixBotConfiguration botConfiguration, + // DataFetcherConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { + private Task _listenerTask; + + private GenericRoom? _logRoom; + + /// <summary>Triggered when the application host is ready to start the service.</summary> + /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> + public async Task StartAsync(CancellationToken cancellationToken) { + _listenerTask = Run(cancellationToken); + logger.LogInformation("Bot started!"); + } + + private async Task Run(CancellationToken cancellationToken) { + Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete); + _logRoom = hs.GetRoom(botConfiguration.LogRoom); + + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Test data collector started!")); + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Fetching rooms...")); + + var rooms = await hs.GetJoinedRooms(); + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched {rooms.Count} rooms!")); + + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Fetching room data...")); + + Config cfg = new Config(); + + var roomAliasTasks = rooms.Select(room => room.GetCanonicalAliasAsync()).ToAsyncEnumerable(); + List<Task<(string, string)>> aliasResolutionTasks = new(); + await foreach (var @event in roomAliasTasks) { + if (@event?.Alias != null) { + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched room alias {(@event).Alias}!")); + aliasResolutionTasks.Add(Task<(string, string)>.Run(async () => { + var alias = await hs.ResolveRoomAliasAsync(@event.Alias); + return (@event.Alias, @alias.RoomId); + }, cancellationToken)); + } + } + var aliasResolutionTaskEnumerator = aliasResolutionTasks.ToAsyncEnumerable(); + await foreach (var result in aliasResolutionTaskEnumerator) { + await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Resolved room alias {result.Item1} to {result.Item2}!")); + } + } + + /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> + /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> + public async Task StopAsync(CancellationToken cancellationToken) { + logger.LogInformation("Shutting down bot!"); + } +} diff --git a/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs b/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs new file mode 100644 index 0000000..06df0eb --- /dev/null +++ b/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Configuration; + +namespace PluralContactBotPoC.Bot; + +public class DataFetcherConfiguration { + public DataFetcherConfiguration(IConfiguration config) => config.GetRequiredSection("DataFetcher").Bind(this); + + // public string +} diff --git a/Tests/TestDataGenerator/Program.cs b/Tests/TestDataGenerator/Program.cs new file mode 100644 index 0000000..9bd091b --- /dev/null +++ b/Tests/TestDataGenerator/Program.cs @@ -0,0 +1,31 @@ +// See https://aka.ms/new-console-template for more information + +using System.Text.Json; +using System.Text.Json.Serialization; +using ArcaneLibs.Extensions; +using LibMatrix.Services; +using LibMatrix.Utilities.Bot; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using PluralContactBotPoC; +using PluralContactBotPoC.Bot; + +Console.WriteLine("Hello, World!"); + +var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { + services.AddScoped<TieredStorageService>(x => + new TieredStorageService( + cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + dataStorageProvider: new FileStorageProvider("bot_data/data/") + ) + ); + // services.AddSingleton<DataFetcherConfiguration>(); + services.AddSingleton<AppServiceConfiguration>(); + + services.AddRoryLibMatrixServices(); + services.AddBot(withCommands: false); + + services.AddHostedService<DataFetcher>(); +}).UseConsoleLifetime().Build(); + +await host.RunAsync(); diff --git a/Tests/TestDataGenerator/Properties/launchSettings.json b/Tests/TestDataGenerator/Properties/launchSettings.json new file mode 100644 index 0000000..997e294 --- /dev/null +++ b/Tests/TestDataGenerator/Properties/launchSettings.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "Default": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + + } + }, + "Development": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + }, + "Local config": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Local" + } + } + } +} diff --git a/Tests/TestDataGenerator/TestDataGenerator.csproj b/Tests/TestDataGenerator/TestDataGenerator.csproj new file mode 100644 index 0000000..1b5a4a9 --- /dev/null +++ b/Tests/TestDataGenerator/TestDataGenerator.csproj @@ -0,0 +1,32 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net7.0</TargetFramework> + <LangVersion>preview</LangVersion> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <PublishAot>false</PublishAot> + <InvariantGlobalization>true</InvariantGlobalization> + <!-- <PublishTrimmed>true</PublishTrimmed>--> + <!-- <PublishReadyToRun>true</PublishReadyToRun>--> + <!-- <PublishSingleFile>true</PublishSingleFile>--> + <!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> + <!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> + <!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> + </ItemGroup> + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" /> + <ProjectReference Include="..\LibMatrix.Tests\LibMatrix.Tests.csproj" /> + </ItemGroup> +</Project> diff --git a/Tests/TestDataGenerator/appsettings.Development.json b/Tests/TestDataGenerator/appsettings.Development.json new file mode 100644 index 0000000..38c45c4 --- /dev/null +++ b/Tests/TestDataGenerator/appsettings.Development.json @@ -0,0 +1,18 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + }, + "LibMatrixBot": { + // The homeserver to connect to + "Homeserver": "rory.gay", + // The access token to use + "AccessToken": "syt_xxxxxxxxxxxxxxxxx", + // The command prefix + "Prefix": "?", + "LogRoom": "!xxxxxxxxxxxxxxxxxxxxxx:example.com" + } +} diff --git a/Tests/TestDataGenerator/appsettings.json b/Tests/TestDataGenerator/appsettings.json new file mode 100644 index 0000000..6ba02f3 --- /dev/null +++ b/Tests/TestDataGenerator/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} |