From b8e9416132a42082ee622a5fbe20706c2c9eb13f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Tue, 9 Dec 2025 10:23:20 +0100 Subject: [PATCH 1/6] fix: tests --- .../PopulationHappinessProcessorTests.cs | 39 ++++--- ...ulationResourceProductionProcessorTests.cs | 33 +++--- .../Procesors/ResourceChangeProcessorTests.cs | 12 ++- Tests/Tests.csproj | 2 +- .../Base/BaseCachedModifierProcessor.cs | 10 ++ .../PopulationConditions.cs | 1 - .../ModifierConditions/ResourceConditions.cs | 1 - .../Modifiers/ModifierConditionsMapper.cs | 100 ++++++++++++++++++ .../Processors/FactionPowerProcessor.cs | 4 - .../PopulationHappinessProcessor.cs | 3 - Wg-backend-api/Models/EventModels.cs | 1 - Wg-backend-api/Models/Modifiers.cs | 3 - 12 files changed, 158 insertions(+), 51 deletions(-) create mode 100644 Wg-backend-api/Logic/Modifiers/ModifierConditionsMapper.cs diff --git a/Tests/Procesors/PopulationHappinessProcessorTests.cs b/Tests/Procesors/PopulationHappinessProcessorTests.cs index 2696842..282e8bc 100644 --- a/Tests/Procesors/PopulationHappinessProcessorTests.cs +++ b/Tests/Procesors/PopulationHappinessProcessorTests.cs @@ -6,7 +6,9 @@ using System.Text; using System.Threading.Tasks; using Wg_backend_api.Data; +using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers.Processors; +using Wg_backend_api.Logic.Modifiers.ModifierConditions; using Wg_backend_api.Models; namespace Tests.Procesors @@ -25,7 +27,7 @@ public void Setup() .Options; _context = new GameDbContext(options, "Test"); - _processor = new PopulationHappinessProcessor(_context, NullLogger.Instance); + _processor = new PopulationHappinessProcessor(_context); SeedTestData(); } @@ -92,9 +94,9 @@ public async Task ProcessAsync_HappinessIncrease_UpdatesHappinessCorrectly() { new() { - Operation = "Add", + Operation = ModifierOperation.Add, Value = 10, - Conditions = new Dictionary { ["SocialGroupId"] = 1 } + Conditions = new PopulationConditions { SocialGroupId = 1 } } }; @@ -114,14 +116,14 @@ public async Task ProcessAsync_InvalidSocialGroup_ReturnsNoAffectedEntities() { // Arrange var effects = new List - { - new() { - Operation = "Add", - Value = 10, - Conditions = new Dictionary { ["SocialGroupId"] = 999 } - } - }; + new() + { + Operation = ModifierOperation.Add, + Value = 10, + Conditions = new PopulationConditions { SocialGroupId = 999 } + } + }; // Act var result = await _processor.ProcessAsync(1, effects, _context); @@ -145,9 +147,9 @@ public async Task ProcessAsync_VariousHappinessValues_UpdatesCorrectly(float cha { new() { - Operation = "Add", + Operation = ModifierOperation.Add, Value = change, - Conditions = new Dictionary { ["SocialGroupId"] = 1 } + Conditions = new PopulationConditions { SocialGroupId = 1 } } }; @@ -182,9 +184,9 @@ public async Task ProcessAsync_LargeDataset_CompletesInReasonableTime() { new() { - Operation = "Add", + Operation = ModifierOperation.Add, Value = 5, - Conditions = new Dictionary { ["SocialGroupId"] = 1 } + Conditions = new PopulationConditions { SocialGroupId = 1 } } }; @@ -193,7 +195,14 @@ public async Task ProcessAsync_LargeDataset_CompletesInReasonableTime() // Assert Assert.That(result.Success, Is.True); - Assert.That((int)result.AffectedEntities["affected_Population_count"], Is.EqualTo(100)); + + // The processor uses dynamic keys with timestamps, so we need to find the affected entities + var affectedEntitiesKey = result.AffectedEntities.Keys.FirstOrDefault(k => k.StartsWith("affected_Population_")); + Assert.That(affectedEntitiesKey, Is.Not.Null, "Expected to find an affected_Population key in results"); + + var changeRecord = result.AffectedEntities[affectedEntitiesKey] as ModifierChangeRecord; + Assert.That(changeRecord, Is.Not.Null); + Assert.That(changeRecord.Change, Is.EqualTo(100)); } } diff --git a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs index 6a1b142..c697d5e 100644 --- a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs +++ b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs @@ -6,7 +6,9 @@ using System.Text; using System.Threading.Tasks; using Wg_backend_api.Data; +using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers.Processors; +using Wg_backend_api.Logic.Modifiers.ModifierConditions; using Wg_backend_api.Models; namespace Tests.Procesors @@ -26,8 +28,7 @@ public void Setup() _context = new GameDbContext(options, "Test"); _processor = new PopulationResourceProductionProcessor( - _context, - NullLogger.Instance); + _context); SeedTestData(); } @@ -96,14 +97,12 @@ public async Task ProcessAsync_ProductionIncrease_UpdatesShare() { new() { - Operation = "Add", + Operation = ModifierOperation.Add, Value = 0.2f, - Conditions = new Dictionary + Conditions = new PopulationResourceConditions { - ["SocialGroupId"] = 1, - ["ResourceId"] = 1 - - + SocialGroupId = 1, + ResourceId = 1 } } }; @@ -133,12 +132,12 @@ public async Task ProcessAsync_VariousProductionChanges_UpdatesCorrectly( { new() { - Operation = "Add", + Operation = ModifierOperation.Add, Value = changeValue, - Conditions = new Dictionary + Conditions = new PopulationResourceConditions { - ["SocialGroupId"] = 1, // Lub SocialGroupId - ["ResourceId"] = 1 // Lub ResourceId + SocialGroupId = 1, + ResourceId = 1 } } }; @@ -161,12 +160,12 @@ public async Task RevertAsync_ProductionChange_RestoresOriginalValue() { new() { - Operation = "Add", - Value = 0.2f, - Conditions = new Dictionary + Operation = ModifierOperation.Add, + Value = 0.1f, + Conditions = new PopulationResourceConditions { - ["SocialGroupId"] = 1, - ["ResourceId"] = 1 + SocialGroupId = 1, + ResourceId = 1 } } }; diff --git a/Tests/Procesors/ResourceChangeProcessorTests.cs b/Tests/Procesors/ResourceChangeProcessorTests.cs index 1d18b42..d579dbd 100644 --- a/Tests/Procesors/ResourceChangeProcessorTests.cs +++ b/Tests/Procesors/ResourceChangeProcessorTests.cs @@ -4,9 +4,11 @@ using NUnit.Framework; using NUnit.Framework.Internal.Execution; using System; +using System.Collections.Generic; using Wg_backend_api.Data; using Wg_backend_api.DTO; using Wg_backend_api.Enums; +using Wg_backend_api.Logic.Modifiers.ModifierConditions; using Wg_backend_api.Logic.Modifiers.Processors; using Wg_backend_api.Models; @@ -24,7 +26,7 @@ public void Setup() .Options; _context = new GameDbContext(options, "test"); - _processor = new ResourceChangeProcessor(_context, NullLogger.Instance); + _processor = new ResourceChangeProcessor(_context); SeedTestData(); } @@ -53,8 +55,8 @@ private void SeedTestData() { Id = 1, EventId = 1, - modiferType = ModifierType.ResourceChange, - Effects = """[{"Operation": "Add", "Value": 50, "Conditions": {"ResourceId": 1}}]""" + ModifierType = ModifierType.ResourceChange, + Effects = new ModifierEffect() { Operation =ModifierOperation.Add, Value= 50, Conditions= new ResourceConditions() { ResourceId = 1 } } }; var relatedEvent = new RelatedEvents { EventId = 1, NationId = 1 }; @@ -96,8 +98,8 @@ public async Task CalculateChangeAsync_PercentageOperation_ReturnsCorrectValue() { Id = 2, EventId = 1, - modiferType = ModifierType.ResourceChange, - Effects = """[{"Operation": "Percentage", "Value": 20, "Conditions": {"ResourceId": 1}}]""" + ModifierType = ModifierType.ResourceChange, + Effects = new ModifierEffect() { Operation = ModifierOperation.Percentage, Value = 20, Conditions = new ResourceConditions() { ResourceId = 1 } } }; _context.Modifiers.Add(modifier); _context.SaveChanges(); diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 0f4dff1..2269b88 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 enable enable diff --git a/Wg-backend-api/Logic/Modifiers/Base/BaseCachedModifierProcessor.cs b/Wg-backend-api/Logic/Modifiers/Base/BaseCachedModifierProcessor.cs index d801d79..1864093 100644 --- a/Wg-backend-api/Logic/Modifiers/Base/BaseCachedModifierProcessor.cs +++ b/Wg-backend-api/Logic/Modifiers/Base/BaseCachedModifierProcessor.cs @@ -28,6 +28,7 @@ protected BaseCachedModifierProcessor(GameDbContext context) public async Task ProcessAsync(int nationId, List effects, GameDbContext context) { var result = new ModifierApplicationResult { Success = true }; + int totalAffectedEntities = 0; try { @@ -54,6 +55,8 @@ public async Task ProcessAsync(int nationId, List ProcessAsync(int nationId, List ToDictionary() return dict; } } - } diff --git a/Wg-backend-api/Logic/Modifiers/ModifierConditions/ResourceConditions.cs b/Wg-backend-api/Logic/Modifiers/ModifierConditions/ResourceConditions.cs index 86f290a..fc099b9 100644 --- a/Wg-backend-api/Logic/Modifiers/ModifierConditions/ResourceConditions.cs +++ b/Wg-backend-api/Logic/Modifiers/ModifierConditions/ResourceConditions.cs @@ -12,5 +12,4 @@ public override Dictionary ToDictionary() return dict; } } - } diff --git a/Wg-backend-api/Logic/Modifiers/ModifierConditionsMapper.cs b/Wg-backend-api/Logic/Modifiers/ModifierConditionsMapper.cs new file mode 100644 index 0000000..84d9f62 --- /dev/null +++ b/Wg-backend-api/Logic/Modifiers/ModifierConditionsMapper.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using Wg_backend_api.Enums; +using Wg_backend_api.Logic.Modifiers.Interfaces; +using Wg_backend_api.Logic.Modifiers.ModifierConditions; + +namespace Wg_backend_api.Logic.Modifiers +{ + /// + /// Maps ModifierTypes to their corresponding Conditions types + /// + public static class ModifierConditionsMapper + { + /// + /// Returns the Type of Conditions for a given ModifierType + /// + public static Type GetConditionsType(ModifierType modifierType) + { + return modifierType switch + { + ModifierType.PopulationHappiness => typeof(PopulationConditions), + ModifierType.VoluneerChange => typeof(PopulationConditions), + ModifierType.ResourceProduction => typeof(PopulationResourceConditions), + ModifierType.ResouerceUsage => typeof(PopulationResourceConditions), + ModifierType.ResourceChange => typeof(ResourceConditions), + ModifierType.FactionPower => typeof(FactionConditions), + ModifierType.FactionContenment => typeof(FactionConditions), + _ => throw new NotSupportedException($"ModifierType {modifierType} is not supported") + }; + } + + /// + /// Creates an instance of Conditions for a given ModifierType from a dictionary + /// + public static IBaseModifierConditions CreateConditions(ModifierType modifierType, Dictionary data) + { + return modifierType switch + { + ModifierType.PopulationHappiness => CreatePopulationConditions(data), + ModifierType.VoluneerChange => CreatePopulationConditions(data), + ModifierType.ResourceProduction => CreatePopulationResourceConditions(data), + ModifierType.ResouerceUsage => CreatePopulationResourceConditions(data), + ModifierType.ResourceChange => CreateResourceConditions(data), + ModifierType.FactionPower => CreateFactionConditions(data), + ModifierType.FactionContenment => CreateFactionConditions(data), + _ => throw new NotSupportedException($"ModifierType {modifierType} is not supported") + }; + } + + private static PopulationConditions CreatePopulationConditions(Dictionary data) + { + var conditions = new PopulationConditions(); + + if (data.TryGetValue("CultureId", out var cultureId)) + conditions.CultureId = Convert.ToInt32(cultureId); + if (data.TryGetValue("SocialGroupId", out var socialGroupId)) + conditions.SocialGroupId = Convert.ToInt32(socialGroupId); + if (data.TryGetValue("ReligionId", out var religionId)) + conditions.ReligionId = Convert.ToInt32(religionId); + + return conditions; + } + + private static PopulationResourceConditions CreatePopulationResourceConditions(Dictionary data) + { + var conditions = new PopulationResourceConditions(); + + if (data.TryGetValue("CultureId", out var cultureId)) + conditions.CultureId = Convert.ToInt32(cultureId); + if (data.TryGetValue("SocialGroupId", out var socialGroupId)) + conditions.SocialGroupId = Convert.ToInt32(socialGroupId); + if (data.TryGetValue("ReligionId", out var religionId)) + conditions.ReligionId = Convert.ToInt32(religionId); + if (data.TryGetValue("ResourceId", out var resourceId)) + conditions.ResourceId = Convert.ToInt32(resourceId); + + return conditions; + } + + private static ResourceConditions CreateResourceConditions(Dictionary data) + { + var conditions = new ResourceConditions(); + + if (data.TryGetValue("ResourceId", out var resourceId)) + conditions.ResourceId = Convert.ToInt32(resourceId); + + return conditions; + } + + private static FactionConditions CreateFactionConditions(Dictionary data) + { + var conditions = new FactionConditions(); + + if (data.TryGetValue("FactionId", out var factionId)) + conditions.FactionId = Convert.ToInt32(factionId); + + return conditions; + } + } +} diff --git a/Wg-backend-api/Logic/Modifiers/Processors/FactionPowerProcessor.cs b/Wg-backend-api/Logic/Modifiers/Processors/FactionPowerProcessor.cs index 25de55b..99f45d9 100644 --- a/Wg-backend-api/Logic/Modifiers/Processors/FactionPowerProcessor.cs +++ b/Wg-backend-api/Logic/Modifiers/Processors/FactionPowerProcessor.cs @@ -16,7 +16,6 @@ protected override void ApplyToEntity(Faction entity, ModifierOperation operatio { var oldValue = entity.Power; entity.Power = (int)OperationProcessor.ApplyOperation(entity.Power, value, operation); - } protected override void RevertFromEntity(Faction entity, ModifierOperation operation, float value) @@ -24,7 +23,6 @@ protected override void RevertFromEntity(Faction entity, ModifierOperation opera var oldValue = entity.Power; entity.Power = (int)OperationProcessor.ReverseOperation(entity.Power, (float)value, operation); entity.Power = Math.Max(0, Math.Min(100, entity.Power)); - } } @@ -39,7 +37,6 @@ protected override void ApplyToEntity(Faction entity, ModifierOperation operatio { var oldValue = entity.Contentment; entity.Contentment = (int)OperationProcessor.ApplyOperation(entity.Contentment, (float)value, operation); - } protected override void RevertFromEntity(Faction entity, ModifierOperation operation, float value) @@ -47,7 +44,6 @@ protected override void RevertFromEntity(Faction entity, ModifierOperation opera var oldValue = entity.Contentment; entity.Contentment = (int)OperationProcessor.ReverseOperation(entity.Contentment, value, operation); entity.Contentment = Math.Max(0, Math.Min(100, entity.Contentment)); - } } } diff --git a/Wg-backend-api/Logic/Modifiers/Processors/PopulationHappinessProcessor.cs b/Wg-backend-api/Logic/Modifiers/Processors/PopulationHappinessProcessor.cs index cc3d8de..6d607f3 100644 --- a/Wg-backend-api/Logic/Modifiers/Processors/PopulationHappinessProcessor.cs +++ b/Wg-backend-api/Logic/Modifiers/Processors/PopulationHappinessProcessor.cs @@ -17,7 +17,6 @@ protected override void ApplyToEntity(Population entity, ModifierOperation opera var oldValue = entity.Happiness; entity.Happiness = OperationProcessor.ApplyOperation(entity.Happiness, value, operation); entity.Happiness = Math.Max(0, Math.Min(100, entity.Happiness)); // Clamp 0-100 - } protected override void RevertFromEntity(Population entity, ModifierOperation operation, float value) @@ -25,8 +24,6 @@ protected override void RevertFromEntity(Population entity, ModifierOperation op var oldValue = entity.Happiness; entity.Happiness = OperationProcessor.ReverseOperation(entity.Happiness, value, operation); entity.Happiness = Math.Max(0, Math.Min(100, entity.Happiness)); - } } - } diff --git a/Wg-backend-api/Models/EventModels.cs b/Wg-backend-api/Models/EventModels.cs index f13ac9e..6914bd3 100644 --- a/Wg-backend-api/Models/EventModels.cs +++ b/Wg-backend-api/Models/EventModels.cs @@ -4,7 +4,6 @@ namespace Wg_backend_api.Models { - [Table("relatedEvents")] public class RelatedEvents { diff --git a/Wg-backend-api/Models/Modifiers.cs b/Wg-backend-api/Models/Modifiers.cs index 29cec2a..ef7d4b8 100644 --- a/Wg-backend-api/Models/Modifiers.cs +++ b/Wg-backend-api/Models/Modifiers.cs @@ -37,7 +37,6 @@ public class ModifierChangeRecord /// Różnica (NewValue - OldValue) /// public object Change { get; set; } - } /// @@ -80,7 +79,5 @@ public class ModifierEffect public ModifierOperation Operation { get; set; } public float Value { get; set; } public IBaseModifierConditions Conditions { get; set; } - } - } From b2fd2c3769e0c9b8ff6ee9e1e04a124965f77202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Wed, 10 Dec 2025 21:00:52 +0100 Subject: [PATCH 2/6] basic settings for api tests --- Tests/Api/CustomWebApplicationFactory.cs | 56 + Tests/Api/FakeAuthHandler.cs | 31 + Tests/Api/PopulationsTests.cs | 47 + Tests/Api/TestDatabaseManager.cs | 85 + Tests/Api/TestGameDbContextFactory.cs | 21 + Tests/Api/TestSessionDataService.cs | 40 + Tests/Api/wg-init-db-seeder.sql | 2841 +++++++++++++++++ Tests/ConditionBuilderTests.cs | 7 +- .../ModifierProcessorFactoryTests.cs | 5 - .../PopulationHappinessProcessorTests.cs | 6 - ...ulationResourceProductionProcessorTests.cs | 6 - .../Procesors/ResourceChangeProcessorTests.cs | 6 - Tests/Tests.csproj | 19 +- .../Migrations/global-schema-init.sql | 232 ++ Wg-backend-api/Program.cs | 315 +- Wg-backend-api/Wg-backend-api.csproj | 5 + 16 files changed, 3530 insertions(+), 192 deletions(-) create mode 100644 Tests/Api/CustomWebApplicationFactory.cs create mode 100644 Tests/Api/FakeAuthHandler.cs create mode 100644 Tests/Api/PopulationsTests.cs create mode 100644 Tests/Api/TestDatabaseManager.cs create mode 100644 Tests/Api/TestGameDbContextFactory.cs create mode 100644 Tests/Api/TestSessionDataService.cs create mode 100644 Tests/Api/wg-init-db-seeder.sql create mode 100644 Wg-backend-api/Migrations/global-schema-init.sql diff --git a/Tests/Api/CustomWebApplicationFactory.cs b/Tests/Api/CustomWebApplicationFactory.cs new file mode 100644 index 0000000..555e1cf --- /dev/null +++ b/Tests/Api/CustomWebApplicationFactory.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Moq; +using Wg_backend_api.Data; +using Wg_backend_api.Services; + +namespace Tests +{ +internal class TestingWebAppFactory : WebApplicationFactory +{ + private readonly string _connectionString; + private readonly string _schema = "game_1"; + private readonly string _nation = "1"; + private readonly Mock _sessionDataService; + + + public TestingWebAppFactory(string connectionString, string schema, string nation, Mock sessionDataService) + { + _connectionString = connectionString; + _schema = schema; + _nation = nation; + _sessionDataService = sessionDataService; + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + + builder.ConfigureServices(services => + { + services.AddSingleton(_sessionDataService); + services.RemoveAll(); + + services.AddSingleton(sp => + new TestGameDbContextFactory(_connectionString)); + + services.RemoveAll(); + services.AddSingleton( + new TestSessionDataService(_schema, _nation, "Player")); + + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = "Test"; + options.DefaultChallengeScheme = "Test"; + }) + .AddScheme("Test", _ => { }); + + }); + + builder.UseEnvironment("Development"); + } +} +} diff --git a/Tests/Api/FakeAuthHandler.cs b/Tests/Api/FakeAuthHandler.cs new file mode 100644 index 0000000..0887a08 --- /dev/null +++ b/Tests/Api/FakeAuthHandler.cs @@ -0,0 +1,31 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +public class FakeAuthHandler : AuthenticationHandler +{ + public FakeAuthHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : base(options, logger, encoder, clock) + { + } + + protected override Task HandleAuthenticateAsync() + { + var identity = new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.NameIdentifier, "1"), + new Claim(ClaimTypes.Name, "TestUser"), + new Claim(ClaimTypes.Role, "Player") + }, "Test"); + + var principal = new ClaimsPrincipal(identity); + var ticket = new AuthenticationTicket(principal, "Test"); + + return Task.FromResult(AuthenticateResult.Success(ticket)); + } +} diff --git a/Tests/Api/PopulationsTests.cs b/Tests/Api/PopulationsTests.cs new file mode 100644 index 0000000..d8585d2 --- /dev/null +++ b/Tests/Api/PopulationsTests.cs @@ -0,0 +1,47 @@ +using Tests; +using Xunit; +using Wg_backend_api.Services; +using Moq; + +public class PopulationsControllerTests : IDisposable +{ + private readonly HttpClient _client; + private readonly TestingWebAppFactory _factory; + + public PopulationsControllerTests() + { + string conn = TestDatabaseManager.RecreateDatabase(); + var mockSession = new Mock(); + mockSession.Setup(s => s.GetNation()).Returns("1"); + mockSession.Setup(s => s.GetSchema()).Returns("game_1"); + mockSession.Setup(s => s.GetRole()).Returns("Player"); + + _factory = new TestingWebAppFactory(conn, schema: "game_1", nation: "1",mockSession); + _client = _factory.CreateClient(); + + } + + [Fact] + public async Task GetAll_ReturnsOkAndData() + { + var response = await _client.GetAsync("/api/auth/status"); + response.EnsureSuccessStatusCode(); + + string json = await response.Content.ReadAsStringAsync(); + Console.WriteLine(json); + + var responsepop = await _client.GetAsync("/api/populations"); + responsepop.EnsureSuccessStatusCode(); + + string jsonpop = await responsepop.Content.ReadAsStringAsync(); + Console.WriteLine(jsonpop); + } + + public void Dispose() + { + _client?.Dispose(); + _factory?.Dispose(); + TestDatabaseManager.DropDatabase(); + } +} + diff --git a/Tests/Api/TestDatabaseManager.cs b/Tests/Api/TestDatabaseManager.cs new file mode 100644 index 0000000..7659ee0 --- /dev/null +++ b/Tests/Api/TestDatabaseManager.cs @@ -0,0 +1,85 @@ +using Npgsql; +using System.Text.RegularExpressions; + +public static class TestDatabaseManager +{ + private const string AdminConnection + = "Host=localhost;Username=postgres;Password=postgres"; + + private const string TestDbName = "wg_test"; + + private static string TestDbConnection => + $"Host=localhost;Database={TestDbName};Username=postgres;Password=postgres"; + + public static string GetConnectionString() => TestDbConnection; + + public static string RecreateDatabase() + { + using var admin = new NpgsqlConnection(AdminConnection); + admin.Open(); + + Console.WriteLine("Terminating existing connections..."); + using (var cmd = new NpgsqlCommand($@" + SELECT pg_terminate_backend(pid) + FROM pg_stat_activity + WHERE datname = '{TestDbName}' AND pid <> pg_backend_pid()", admin)) + { + cmd.ExecuteNonQuery(); + } + + Console.WriteLine($"Dropping database {TestDbName} if exists..."); + using (var cmd = new NpgsqlCommand($"DROP DATABASE IF EXISTS {TestDbName}", admin)) + { + cmd.ExecuteNonQuery(); + } + + Console.WriteLine($"Creating database {TestDbName}..."); + using (var cmd = new NpgsqlCommand($"CREATE DATABASE {TestDbName}", admin)) + { + cmd.ExecuteNonQuery(); + } + + var path = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "Api","wg-init-db-seeder.sql"); // hehe fuszera drut + string script = File.ReadAllText(path); + + script = Regex.Replace(script, @"^\\.*$", "", RegexOptions.Multiline); + + Console.WriteLine($"Executing migration script (size: {script.Length} bytes)..."); + using var connection = new NpgsqlConnection(TestDbConnection); + connection.Open(); + + using var command = new NpgsqlCommand(script, connection); + command.CommandTimeout = 600; + try + { + command.ExecuteNonQuery(); + Console.WriteLine($"✓ Database initialized successfully"); + } + catch (Exception ex) + { + Console.WriteLine($"✗ Error initializing database: {ex.Message}"); + throw; + } + + return TestDbConnection; + } + + public static void DropDatabase() + { + using var admin = new NpgsqlConnection(AdminConnection); + admin.Open(); + + using (var cmd = new NpgsqlCommand($@" + SELECT pg_terminate_backend(pid) + FROM pg_stat_activity + WHERE datname = '{TestDbName}' AND pid <> pg_backend_pid()", admin)) + { + cmd.ExecuteNonQuery(); + } + + using (var cmd = new NpgsqlCommand($"DROP DATABASE IF EXISTS {TestDbName}", admin)) + { + cmd.ExecuteNonQuery(); + } + } +} diff --git a/Tests/Api/TestGameDbContextFactory.cs b/Tests/Api/TestGameDbContextFactory.cs new file mode 100644 index 0000000..2dd28a5 --- /dev/null +++ b/Tests/Api/TestGameDbContextFactory.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Wg_backend_api.Data; + +public class TestGameDbContextFactory : IGameDbContextFactory +{ + private readonly string _connectionString; + + public TestGameDbContextFactory(string connectionString) + { + _connectionString = connectionString; + } + + public GameDbContext Create(string schema) + { + var options = new DbContextOptionsBuilder() + .UseNpgsql(_connectionString) + .Options; + + return new GameDbContext(options, schema); + } +} diff --git a/Tests/Api/TestSessionDataService.cs b/Tests/Api/TestSessionDataService.cs new file mode 100644 index 0000000..fd1e18a --- /dev/null +++ b/Tests/Api/TestSessionDataService.cs @@ -0,0 +1,40 @@ +using Wg_backend_api.Services; + +public class TestSessionDataService : ISessionDataService +{ + private string _schema; + private string _nation; + private string? _userId; + private string? _role; + + public TestSessionDataService(string schema, string nation, string role = "Player") + { + _schema = schema; + _nation = nation; + _role = role; + } + + public string GetSchema() => _schema; + public string GetNation() => _nation; + + public string? GetRole() => _role; + public void SetSchema(string schema) + { + this._schema = schema; + } + public void SetNation(string nation) + { + this._nation = nation; + } + public void SetRole(string role) + { + this._role = role; + } + + public string? GetUserIdItems() => _userId; + + public void SetUserIdItems(string id) + { + this._userId = id; + } +} diff --git a/Tests/Api/wg-init-db-seeder.sql b/Tests/Api/wg-init-db-seeder.sql new file mode 100644 index 0000000..5be4978 --- /dev/null +++ b/Tests/Api/wg-init-db-seeder.sql @@ -0,0 +1,2841 @@ +-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 17.4 +-- Dumped by pg_dump version 17.4 + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +-- +-- Name: Global; Type: SCHEMA; Schema: -; Owner: - +-- + +CREATE SCHEMA "Global"; + + +-- +-- Name: game_1; Type: SCHEMA; Schema: -; Owner: - +-- + +CREATE SCHEMA game_1; + + +-- +-- Name: add_nation_to_all_resources(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.add_nation_to_all_resources() RETURNS trigger + LANGUAGE plpgsql + AS $$ +DECLARE + nationId INT := NEW.id; +BEGIN + INSERT INTO game_1."ownedResources" (fk_nation, fk_resource, amount) + SELECT nationId, r.id, 0 + FROM game_1.resources r; + + RETURN NEW; +END; +$$; + + +-- +-- Name: add_population_relations(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.add_population_relations() RETURNS trigger + LANGUAGE plpgsql + AS $$ +DECLARE + socialGroupId INT := NEW.fk_socialgroups; + popId INT := NEW.id; +BEGIN + -- Tworzenie rekordów w populationproductionshares + INSERT INTO game_1.populationproductionshares (fk_population, fk_resources, coefficient) + SELECT popId, ps."fk_Resources", ps.coefficient + FROM game_1."productionShares" ps + WHERE ps."fk_SocialGroups" = socialGroupId; + + -- Tworzenie rekordów w populationusedresource + INSERT INTO game_1.populationusedresource (fk_population, fk_resources, amount) + SELECT popId, ur."fk_Resources", ur.amount + FROM game_1."usedResources" ur + WHERE ur."fk_SocialGroups" = socialGroupId; + + RETURN NEW; +END; +$$; + + +-- +-- Name: add_production_shares_to_populations(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.add_production_shares_to_populations() RETURNS trigger + LANGUAGE plpgsql + AS $$ +DECLARE + socialGroupId INT := NEW."fk_SocialGroups"; +BEGIN + INSERT INTO game_1.populationproductionshares (fk_population, fk_resources, coefficient) + SELECT p.id, NEW."fk_Resources", NEW.coefficient + FROM game_1.populations p + WHERE p.fk_socialgroups = socialGroupId; + + RETURN NEW; +END; +$$; + + +-- +-- Name: add_resource_to_all_nations(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.add_resource_to_all_nations() RETURNS trigger + LANGUAGE plpgsql + AS $$ +DECLARE + resourceId INT := NEW.id; +BEGIN + INSERT INTO game_1."ownedResources" (fk_nation, fk_resource, amount) + SELECT n.id, resourceId, 0 + FROM game_1.nations n; + + RETURN NEW; +END; +$$; + + +-- +-- Name: add_used_resources_to_populations(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.add_used_resources_to_populations() RETURNS trigger + LANGUAGE plpgsql + AS $$ +DECLARE + socialGroupId INT := NEW."fk_SocialGroups"; +BEGIN + INSERT INTO game_1.populationusedresource (fk_population, fk_resources, amount) + SELECT p.id, NEW."fk_Resources", NEW.amount + FROM game_1.populations p + WHERE p.fk_socialgroups = socialGroupId; + + RETURN NEW; +END; +$$; + + +-- +-- Name: create_default_armies(); Type: FUNCTION; Schema: game_1; Owner: - +-- + +CREATE FUNCTION game_1.create_default_armies() RETURNS trigger + LANGUAGE plpgsql + AS $$ +BEGIN + -- Create Barracks (Land army) + INSERT INTO game_1.armies (name, "fk_Nations", fk_localisations, is_naval) + VALUES ('Baraki', NEW.id, NULL, FALSE); + + -- Create Docks (Naval army) + INSERT INTO game_1.armies (name, "fk_Nations", fk_localisations, is_naval) + VALUES ('Doki', NEW.id, NULL, TRUE); + + RETURN NEW; +END; +$$; + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: gameaccess; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".gameaccess ( + id integer NOT NULL, + "fk_Users" integer NOT NULL, + "fk_Games" integer NOT NULL, + "accessType" integer NOT NULL, + "isArchived" boolean NOT NULL +); + + +-- +-- Name: gameaccess_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".gameaccess ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".gameaccess_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: games; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".games ( + id integer NOT NULL, + name text NOT NULL, + description text, + image text, + "ownerId" integer NOT NULL, + game_code text DEFAULT upper(substr(md5((random())::text), 1, 6)) +); + + +-- +-- Name: games_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".games ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".games_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: refresh_tokens; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".refresh_tokens ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id integer, + token text NOT NULL, + expires_at timestamp with time zone NOT NULL, + revoked_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() +); + + +-- +-- Name: users; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".users ( + id integer NOT NULL, + name text NOT NULL, + email text NOT NULL, + password text NOT NULL, + issso boolean NOT NULL, + isarchived boolean NOT NULL, + image text +); + + +-- +-- Name: users_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".users ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".users_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: accessToUnits; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."accessToUnits" ( + id integer NOT NULL, + "fk_Nation" integer NOT NULL, + "fk_UnitTypes" integer NOT NULL +); + + +-- +-- Name: accessToUnits_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."accessToUnits" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."accessToUnits_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: accessestonations; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.accessestonations ( + id integer NOT NULL, + fk_nations integer NOT NULL, + fk_users integer NOT NULL, + dateacquired timestamp with time zone NOT NULL, + isactive boolean NOT NULL +); + + +-- +-- Name: accessestonations_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.accessestonations ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.accessestonations_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: actions; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.actions ( + id integer NOT NULL, + "fk_Nations" integer NOT NULL, + name text, + description text NOT NULL, + result text, + "isSettled" boolean NOT NULL +); + + +-- +-- Name: actions_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.actions ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.actions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: armies; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.armies ( + id integer NOT NULL, + name text NOT NULL, + "fk_Nations" integer NOT NULL, + fk_localisations integer, + is_naval boolean NOT NULL +); + + +-- +-- Name: armies_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.armies ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.armies_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: cultures; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.cultures ( + id integer NOT NULL, + name text NOT NULL +); + + +-- +-- Name: cultures_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.cultures ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.cultures_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: events; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.events ( + id integer NOT NULL, + name text NOT NULL, + description text, + isactive boolean NOT NULL, + picture text +); + + +-- +-- Name: events_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.events ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.events_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: factions; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.factions ( + id integer NOT NULL, + name text NOT NULL, + "fk_Nations" integer NOT NULL, + power integer NOT NULL, + agenda text NOT NULL, + contentment integer NOT NULL, + color text NOT NULL, + description text +); + + +-- +-- Name: factions_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.factions ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.factions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: localisations; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.localisations ( + id integer NOT NULL, + name text NOT NULL, + size integer NOT NULL, + fortifications integer NOT NULL, + fk_nations integer NOT NULL +); + + +-- +-- Name: localisationsResources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."localisationsResources" ( + id integer NOT NULL, + fk_localisations integer NOT NULL, + "fk_Resources" integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: localisationsResources_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."localisationsResources" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."localisationsResources_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: localisations_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.localisations ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.localisations_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: maintenanceCosts; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."maintenanceCosts" ( + id integer NOT NULL, + "fk_UnitTypes" integer NOT NULL, + "fk_Resources" integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: maintenanceCosts_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."maintenanceCosts" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."maintenanceCosts_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: map; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.map ( + id integer NOT NULL, + name text NOT NULL, + "mapLocation" text NOT NULL, + "mapIconLocation" text NOT NULL +); + + +-- +-- Name: mapAccess; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."mapAccess" ( + "fk_Nations" integer NOT NULL, + "fk_Maps" integer NOT NULL +); + + +-- +-- Name: map_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.map ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.map_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: modifiers; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.modifiers ( + id integer NOT NULL, + event_id integer NOT NULL, + modifier_type integer NOT NULL, + effects jsonb NOT NULL +); + + +-- +-- Name: modifiers_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +CREATE SEQUENCE game_1.modifiers_id_seq + AS integer + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: modifiers_id_seq; Type: SEQUENCE OWNED BY; Schema: game_1; Owner: - +-- + +ALTER SEQUENCE game_1.modifiers_id_seq OWNED BY game_1.modifiers.id; + + +-- +-- Name: nations; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.nations ( + id integer NOT NULL, + name text NOT NULL, + fk_religions integer NOT NULL, + fk_cultures integer NOT NULL, + flag text, + color text +); + + +-- +-- Name: nations_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.nations ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.nations_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: offeredresources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.offeredresources ( + id integer NOT NULL, + fk_resource integer NOT NULL, + fk_tradeagreement integer NOT NULL, + quantity integer NOT NULL +); + + +-- +-- Name: offeredresources_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.offeredresources ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.offeredresources_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: ownedResources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."ownedResources" ( + id integer NOT NULL, + fk_nation integer NOT NULL, + fk_resource integer NOT NULL, + amount real DEFAULT 0 NOT NULL +); + + +-- +-- Name: ownedResources_Id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +CREATE SEQUENCE game_1."ownedResources_Id_seq" + AS integer + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: ownedResources_Id_seq; Type: SEQUENCE OWNED BY; Schema: game_1; Owner: - +-- + +ALTER SEQUENCE game_1."ownedResources_Id_seq" OWNED BY game_1."ownedResources".id; + + +-- +-- Name: players; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.players ( + id integer NOT NULL, + "fk_User" integer NOT NULL, + "playerType" integer NOT NULL, + name text NOT NULL +); + + +-- +-- Name: players_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.players ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.players_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: populationproductionshares; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.populationproductionshares ( + id integer NOT NULL, + fk_population integer NOT NULL, + fk_resources integer NOT NULL, + coefficient double precision NOT NULL +); + + +-- +-- Name: populationproductionshares_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.populationproductionshares ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( + SEQUENCE NAME game_1.populationproductionshares_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: populations; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.populations ( + id integer NOT NULL, + fk_religions integer NOT NULL, + fk_cultures integer NOT NULL, + fk_socialgroups integer NOT NULL, + fk_localisations integer NOT NULL, + happiness real NOT NULL, + volunteers integer +); + + +-- +-- Name: populations_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.populations ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.populations_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: populationusedresource; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.populationusedresource ( + id integer NOT NULL, + fk_population integer NOT NULL, + fk_resources integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: populationusedresource_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.populationusedresource ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( + SEQUENCE NAME game_1.populationusedresource_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: productionCost; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."productionCost" ( + id integer NOT NULL, + "fk_UnitTypes" integer NOT NULL, + "fk_Resources" integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: productionCost_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."productionCost" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."productionCost_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: productionShares; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."productionShares" ( + id integer NOT NULL, + "fk_SocialGroups" integer NOT NULL, + "fk_Resources" integer NOT NULL, + coefficient double precision NOT NULL +); + + +-- +-- Name: productionShares_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."productionShares" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."productionShares_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: relatedEvents; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."relatedEvents" ( + id integer NOT NULL, + "fk_Events" integer NOT NULL, + "fk_Nations" integer NOT NULL +); + + +-- +-- Name: relatedEvents_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."relatedEvents" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."relatedEvents_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: religions; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.religions ( + id integer NOT NULL, + name text NOT NULL, + icon text +); + + +-- +-- Name: religions_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.religions ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.religions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: resources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.resources ( + id integer NOT NULL, + name text NOT NULL, + ismain boolean NOT NULL, + icon text +); + + +-- +-- Name: resources_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.resources ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.resources_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: socialgroups; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.socialgroups ( + id integer NOT NULL, + name text NOT NULL, + basehappiness real NOT NULL, + volunteers integer NOT NULL, + icon text +); + + +-- +-- Name: socialgroups_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.socialgroups ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.socialgroups_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: tradeagreements; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.tradeagreements ( + id integer NOT NULL, + fk_nationoffering integer NOT NULL, + fk_nationreceiving integer NOT NULL, + status integer NOT NULL, + duration integer NOT NULL, + description text NOT NULL +); + + +-- +-- Name: tradeagreements_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.tradeagreements ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.tradeagreements_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: troops; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.troops ( + id integer NOT NULL, + "fk_UnitTypes" integer NOT NULL, + "fk_Armies" integer NOT NULL, + quantity integer NOT NULL +); + + +-- +-- Name: troops_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.troops ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.troops_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: unitOrders; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."unitOrders" ( + id integer NOT NULL, + "fk_UnitTypes" integer NOT NULL, + "fk_Nations" integer NOT NULL, + quantity integer NOT NULL +); + + +-- +-- Name: unitOrders_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."unitOrders" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."unitOrders_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: unitTypes; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."unitTypes" ( + id integer NOT NULL, + name text NOT NULL, + description text NOT NULL, + melee integer NOT NULL, + range integer NOT NULL, + defense integer NOT NULL, + speed integer NOT NULL, + morale integer NOT NULL, + "volunteersNeeded" integer NOT NULL, + "isNaval" boolean NOT NULL +); + + +-- +-- Name: unitTypes_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."unitTypes" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."unitTypes_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: usedResources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1."usedResources" ( + id integer NOT NULL, + "fk_SocialGroups" integer NOT NULL, + "fk_Resources" integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: usedResources_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1."usedResources" ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1."usedResources_id_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: wantedresources; Type: TABLE; Schema: game_1; Owner: - +-- + +CREATE TABLE game_1.wantedresources ( + id integer NOT NULL, + fk_resource integer NOT NULL, + fk_tradeagreement integer NOT NULL, + amount double precision NOT NULL +); + + +-- +-- Name: wantedresources_id_seq; Type: SEQUENCE; Schema: game_1; Owner: - +-- + +ALTER TABLE game_1.wantedresources ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME game_1.wantedresources_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: modifiers id; Type: DEFAULT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.modifiers ALTER COLUMN id SET DEFAULT nextval('game_1.modifiers_id_seq'::regclass); + + +-- +-- Name: ownedResources id; Type: DEFAULT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."ownedResources" ALTER COLUMN id SET DEFAULT nextval('game_1."ownedResources_Id_seq"'::regclass); + + +-- +-- Data for Name: gameaccess; Type: TABLE DATA; Schema: Global; Owner: - +-- + +INSERT INTO "Global".gameaccess VALUES (1, 1, 1, 1, false); +INSERT INTO "Global".gameaccess VALUES (2, 2, 1, 0, false); +INSERT INTO "Global".gameaccess VALUES (3, 3, 1, 1, false); +INSERT INTO "Global".gameaccess VALUES (4, 4, 1, 1, false); + + +-- +-- Data for Name: games; Type: TABLE DATA; Schema: Global; Owner: - +-- + +INSERT INTO "Global".games VALUES (1, 'default_schema', 'Demo testowe +', NULL, 2, 'XIWDFW'); + + +-- +-- Data for Name: refresh_tokens; Type: TABLE DATA; Schema: Global; Owner: - +-- + + + +-- +-- Data for Name: users; Type: TABLE DATA; Schema: Global; Owner: - +-- + +INSERT INTO "Global".users VALUES (1, 'Test', 'test@test', '$2a$11$s/J0zefb5amFzjdjllmuZ.AXuziyjVRcYTeEhxyemaxsJJyKnzxU2', false, false, NULL); +INSERT INTO "Global".users VALUES (2, 'admin', 'admin@admin', '$2a$11$t8DGLO5spPxXzpyRb5j0vuuk54ycsFEo9scO7xswpGCH9WvMcwive', false, false, NULL); +INSERT INTO "Global".users VALUES (3, 'tomek', 'tomek@tomek', '$2a$11$t8DGLO5spPxXzpyRb5j0vuuk54ycsFEo9scO7xswpGCH9WvMcwive', false, false, NULL); +INSERT INTO "Global".users VALUES (4, 'jakub', 'jakub@jakub', '$2a$11$t8DGLO5spPxXzpyRb5j0vuuk54ycsFEo9scO7xswpGCH9WvMcwive', false, false, NULL); + + +-- +-- Data for Name: accessToUnits; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."accessToUnits" VALUES (1, 1, 1); +INSERT INTO game_1."accessToUnits" VALUES (2, 1, 2); +INSERT INTO game_1."accessToUnits" VALUES (3, 1, 3); +INSERT INTO game_1."accessToUnits" VALUES (4, 2, 1); +INSERT INTO game_1."accessToUnits" VALUES (5, 2, 3); +INSERT INTO game_1."accessToUnits" VALUES (6, 2, 4); +INSERT INTO game_1."accessToUnits" VALUES (7, 3, 1); +INSERT INTO game_1."accessToUnits" VALUES (8, 3, 5); +INSERT INTO game_1."accessToUnits" VALUES (9, 4, 1); +INSERT INTO game_1."accessToUnits" VALUES (10, 4, 2); +INSERT INTO game_1."accessToUnits" VALUES (11, 5, 1); +INSERT INTO game_1."accessToUnits" VALUES (12, 5, 3); + + +-- +-- Data for Name: accessestonations; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.accessestonations VALUES (1, 1, 1, '2025-01-01 00:00:00+01', true); +INSERT INTO game_1.accessestonations VALUES (2, 2, 2, '2025-01-02 00:00:00+01', true); + + +-- +-- Data for Name: actions; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.actions VALUES (1, 1, 'Ekspedycja', 'Wysłanie ekspedycji na niezbadane tereny', NULL, false); +INSERT INTO game_1.actions VALUES (2, 2, 'Budowa Świątyni', 'Rozpoczęcie budowy wielkiej świątyni', NULL, false); +INSERT INTO game_1.actions VALUES (3, 3, 'Szlak Handlowy', 'Otwarcie nowego szlaku handlowego', 'Zwiększenie przychodów o 10%', true); +INSERT INTO game_1.actions VALUES (4, 4, 'Reformy', 'Wprowadzenie reform społecznych', NULL, false); +INSERT INTO game_1.actions VALUES (5, 5, 'Mobilizacja', 'Mobilizacja sił zbrojnych', 'Wzrost liczebności armii o 20%', true); + + +-- +-- Data for Name: armies; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.armies VALUES (1, 'Armia Północy', 1, 1, false); +INSERT INTO game_1.armies VALUES (2, 'Legiony Cesarskie', 2, 2, false); +INSERT INTO game_1.armies VALUES (3, 'Flota Republiki', 3, 3, true); +INSERT INTO game_1.armies VALUES (4, 'Drużyna Księcia', 4, 4, false); +INSERT INTO game_1.armies VALUES (5, 'Jeźdźcy Pustyni', 5, 5, false); +INSERT INTO game_1.armies VALUES (6, 'Baraki', 1, NULL, false); +INSERT INTO game_1.armies VALUES (7, 'Baraki', 2, NULL, false); +INSERT INTO game_1.armies VALUES (8, 'Baraki', 3, NULL, false); +INSERT INTO game_1.armies VALUES (9, 'Baraki', 4, NULL, false); +INSERT INTO game_1.armies VALUES (10, 'Baraki', 5, NULL, false); +INSERT INTO game_1.armies VALUES (11, 'Doki', 1, NULL, true); +INSERT INTO game_1.armies VALUES (12, 'Doki', 2, NULL, true); +INSERT INTO game_1.armies VALUES (13, 'Doki', 3, NULL, true); +INSERT INTO game_1.armies VALUES (14, 'Doki', 4, NULL, true); +INSERT INTO game_1.armies VALUES (15, 'Doki', 5, NULL, true); + + +-- +-- Data for Name: cultures; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.cultures VALUES (1, 'Nordycka'); +INSERT INTO game_1.cultures VALUES (2, 'Słowiańska'); +INSERT INTO game_1.cultures VALUES (3, 'Germańska'); +INSERT INTO game_1.cultures VALUES (4, 'Romańska'); +INSERT INTO game_1.cultures VALUES (5, 'Grecka'); + + +-- +-- Data for Name: events; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.events VALUES (1, 'Wielka Bitwa', 'Epiczna bitwa, która zmieniła losy świata', true, 'battle.jpg'); +INSERT INTO game_1.events VALUES (2, 'Plaga', 'Śmiertelna zaraza dziesiątkująca populację', true, 'plague.jpg'); +INSERT INTO game_1.events VALUES (3, 'Odkrycie', 'Odkrycie nowych terenów i technologii', true, 'discovery.jpg'); +INSERT INTO game_1.events VALUES (4, 'Rewolta', 'Rewolta społeczeństwa przeciwko władcy', true, 'revolt.jpg'); +INSERT INTO game_1.events VALUES (5, 'Sojusz', 'Zawarcie sojuszu między narodami', true, 'alliance.jpg'); + + +-- +-- Data for Name: factions; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.factions VALUES (1, 'Konserwatyści', 1, 70, 'Utrzymanie tradycji', 60, '#0000FF', NULL); +INSERT INTO game_1.factions VALUES (2, 'Reformatorzy', 1, 30, 'Wprowadzenie zmian', 40, '#00FF00', NULL); +INSERT INTO game_1.factions VALUES (3, 'Militaryści', 2, 60, 'Ekspansja militarna', 50, '#FF0000', NULL); +INSERT INTO game_1.factions VALUES (4, 'Handlarze', 2, 40, 'Rozwój handlu', 70, '#FFFF00', NULL); +INSERT INTO game_1.factions VALUES (5, 'Zjednoczeni', 3, 90, 'Jedność narodu', 80, '#800080', NULL); + + +-- +-- Data for Name: localisations; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.localisations VALUES (1, 'Stolica Północy', 5, 4, 1); +INSERT INTO game_1.localisations VALUES (2, 'Twierdza Cesarska', 6, 5, 2); +INSERT INTO game_1.localisations VALUES (3, 'Port Republiki', 4, 3, 3); +INSERT INTO game_1.localisations VALUES (4, 'Wschodni Gród', 3, 2, 4); +INSERT INTO game_1.localisations VALUES (5, 'Oaza Południowa', 4, 3, 5); +INSERT INTO game_1.localisations VALUES (6, 'Górska Osada', 2, 1, 1); +INSERT INTO game_1.localisations VALUES (7, 'Cesarskie Tereny', 3, 2, 2); +INSERT INTO game_1.localisations VALUES (8, 'Nadmorska Wioska', 2, 1, 3); + + +-- +-- Data for Name: localisationsResources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."localisationsResources" VALUES (1, 1, 1, 1000); +INSERT INTO game_1."localisationsResources" VALUES (2, 1, 3, 2000); +INSERT INTO game_1."localisationsResources" VALUES (3, 2, 2, 1500); +INSERT INTO game_1."localisationsResources" VALUES (4, 2, 5, 3000); +INSERT INTO game_1."localisationsResources" VALUES (5, 3, 1, 800); +INSERT INTO game_1."localisationsResources" VALUES (6, 3, 8, 500); +INSERT INTO game_1."localisationsResources" VALUES (7, 4, 3, 2500); +INSERT INTO game_1."localisationsResources" VALUES (8, 4, 4, 3500); +INSERT INTO game_1."localisationsResources" VALUES (9, 5, 7, 600); +INSERT INTO game_1."localisationsResources" VALUES (10, 5, 6, 400); + + +-- +-- Data for Name: maintenanceCosts; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."maintenanceCosts" VALUES (1, 1, 1, 0.5); +INSERT INTO game_1."maintenanceCosts" VALUES (2, 1, 4, 1); +INSERT INTO game_1."maintenanceCosts" VALUES (3, 2, 1, 0.3); +INSERT INTO game_1."maintenanceCosts" VALUES (4, 2, 3, 0.5); +INSERT INTO game_1."maintenanceCosts" VALUES (5, 3, 1, 1); +INSERT INTO game_1."maintenanceCosts" VALUES (6, 3, 4, 1.5); +INSERT INTO game_1."maintenanceCosts" VALUES (7, 4, 1, 2); +INSERT INTO game_1."maintenanceCosts" VALUES (8, 4, 3, 1); +INSERT INTO game_1."maintenanceCosts" VALUES (9, 5, 1, 3); +INSERT INTO game_1."maintenanceCosts" VALUES (10, 5, 3, 2); + + +-- +-- Data for Name: map; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.map VALUES (1, 'Europa Środkowa', 'maps/central_europe.jpg', 'maps/central_europe.jpg'); +INSERT INTO game_1.map VALUES (2, 'Wyspy Brytyjskie', 'maps/british_isles.jpg', 'maps/central_europe.jpg'); +INSERT INTO game_1.map VALUES (3, 'Półwysep Iberyjski', 'maps/iberia.jpg', 'maps/central_europe.jpg'); +INSERT INTO game_1.map VALUES (4, 'Skandynawia', 'maps/scandinavia.jpg', 'maps/central_europe.jpg'); +INSERT INTO game_1.map VALUES (5, 'Bałkany', 'maps/balkans.jpg', 'maps/central_europe.jpg'); + + +-- +-- Data for Name: mapAccess; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."mapAccess" VALUES (1, 1); +INSERT INTO game_1."mapAccess" VALUES (1, 4); +INSERT INTO game_1."mapAccess" VALUES (2, 2); +INSERT INTO game_1."mapAccess" VALUES (2, 5); +INSERT INTO game_1."mapAccess" VALUES (3, 3); +INSERT INTO game_1."mapAccess" VALUES (4, 1); +INSERT INTO game_1."mapAccess" VALUES (4, 5); +INSERT INTO game_1."mapAccess" VALUES (5, 3); + + +-- +-- Data for Name: modifiers; Type: TABLE DATA; Schema: game_1; Owner: - +-- + + + +-- +-- Data for Name: nations; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.nations VALUES (1, 'Królestwo Północy', 1, 1, NULL, 'red'); +INSERT INTO game_1.nations VALUES (2, 'Cesarstwo Centralne', 2, 3, NULL, 'yellow'); +INSERT INTO game_1.nations VALUES (3, 'Republika Nadmorska', 2, 4, NULL, 'red'); +INSERT INTO game_1.nations VALUES (4, 'Księstwo Wschodnie', 1, 2, NULL, 'green'); +INSERT INTO game_1.nations VALUES (5, 'Kalifat Południowy', 3, 5, NULL, 'blue'); + + +-- +-- Data for Name: offeredresources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.offeredresources VALUES (1, 2, 1, 100); +INSERT INTO game_1.offeredresources VALUES (2, 3, 1, 200); +INSERT INTO game_1.offeredresources VALUES (3, 1, 3, 50); +INSERT INTO game_1.offeredresources VALUES (4, 4, 3, 300); +INSERT INTO game_1.offeredresources VALUES (5, 3, 4, 150); + + +-- +-- Data for Name: ownedResources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."ownedResources" VALUES (1, 1, 1, 4201); +INSERT INTO game_1."ownedResources" VALUES (2, 1, 2, 4202); +INSERT INTO game_1."ownedResources" VALUES (3, 1, 3, 4203); +INSERT INTO game_1."ownedResources" VALUES (4, 1, 4, 4204); +INSERT INTO game_1."ownedResources" VALUES (5, 1, 5, 4205); +INSERT INTO game_1."ownedResources" VALUES (6, 1, 6, 4206); +INSERT INTO game_1."ownedResources" VALUES (7, 1, 7, 4207); +INSERT INTO game_1."ownedResources" VALUES (8, 1, 8, 4208); +INSERT INTO game_1."ownedResources" VALUES (9, 1, 9, 4209); +INSERT INTO game_1."ownedResources" VALUES (10, 2, 1, 2137); +INSERT INTO game_1."ownedResources" VALUES (11, 2, 2, 2173); +INSERT INTO game_1."ownedResources" VALUES (12, 2, 3, 1237); +INSERT INTO game_1."ownedResources" VALUES (13, 2, 4, 2137); +INSERT INTO game_1."ownedResources" VALUES (14, 2, 5, 1273); +INSERT INTO game_1."ownedResources" VALUES (15, 2, 6, 2137); +INSERT INTO game_1."ownedResources" VALUES (16, 2, 7, 1237); +INSERT INTO game_1."ownedResources" VALUES (17, 2, 8, 2173); +INSERT INTO game_1."ownedResources" VALUES (18, 2, 9, 1237); +INSERT INTO game_1."ownedResources" VALUES (19, 3, 1, 4201); +INSERT INTO game_1."ownedResources" VALUES (20, 3, 2, 4202); +INSERT INTO game_1."ownedResources" VALUES (21, 3, 3, 4203); +INSERT INTO game_1."ownedResources" VALUES (22, 3, 4, 4204); +INSERT INTO game_1."ownedResources" VALUES (23, 3, 5, 4205); +INSERT INTO game_1."ownedResources" VALUES (24, 3, 6, 4206); +INSERT INTO game_1."ownedResources" VALUES (25, 3, 7, 4207); +INSERT INTO game_1."ownedResources" VALUES (26, 3, 8, 4208); +INSERT INTO game_1."ownedResources" VALUES (27, 3, 9, 4209); +INSERT INTO game_1."ownedResources" VALUES (28, 4, 1, 2137); +INSERT INTO game_1."ownedResources" VALUES (29, 4, 2, 2173); +INSERT INTO game_1."ownedResources" VALUES (30, 4, 3, 1237); +INSERT INTO game_1."ownedResources" VALUES (31, 4, 4, 2137); +INSERT INTO game_1."ownedResources" VALUES (32, 4, 5, 1273); +INSERT INTO game_1."ownedResources" VALUES (33, 4, 6, 2137); +INSERT INTO game_1."ownedResources" VALUES (34, 4, 7, 1237); +INSERT INTO game_1."ownedResources" VALUES (35, 4, 8, 2173); +INSERT INTO game_1."ownedResources" VALUES (36, 4, 9, 1237); +INSERT INTO game_1."ownedResources" VALUES (37, 5, 1, 2137); +INSERT INTO game_1."ownedResources" VALUES (38, 5, 2, 2173); +INSERT INTO game_1."ownedResources" VALUES (39, 5, 3, 1237); +INSERT INTO game_1."ownedResources" VALUES (40, 5, 4, 2137); +INSERT INTO game_1."ownedResources" VALUES (41, 5, 5, 1273); +INSERT INTO game_1."ownedResources" VALUES (42, 5, 6, 2137); +INSERT INTO game_1."ownedResources" VALUES (43, 5, 7, 1237); +INSERT INTO game_1."ownedResources" VALUES (44, 5, 8, 2173); +INSERT INTO game_1."ownedResources" VALUES (45, 5, 9, 1237); + + +-- +-- Data for Name: players; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.players VALUES (1, 1, 1, 'Test'); +INSERT INTO game_1.players VALUES (2, 2, 0, 'admin'); +INSERT INTO game_1.players VALUES (3, 3, 1, 'tomek'); +INSERT INTO game_1.players VALUES (4, 4, 1, 'jakub'); + + +-- +-- Data for Name: populationproductionshares; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (1, 1, 1, 1.1); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (2, 1, 2, 2.1); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (3, 2, 1, 3.7); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (4, 3, 3, 6.9); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (5, 4, 4, 1.2); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (6, 5, 5, 1.2); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (7, 6, 6, 0.9); +INSERT INTO game_1.populationproductionshares OVERRIDING SYSTEM VALUE VALUES (8, 7, 7, 1.3); + + +-- +-- Data for Name: populations; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.populations VALUES (1, 1, 1, 1, 1, 5.5, 3); +INSERT INTO game_1.populations VALUES (2, 2, 3, 2, 2, 6, 3); +INSERT INTO game_1.populations VALUES (3, 2, 4, 3, 3, 7.2, 1); +INSERT INTO game_1.populations VALUES (4, 1, 2, 1, 4, 4.8, 2); +INSERT INTO game_1.populations VALUES (5, 3, 5, 5, 5, 5.7, 2); +INSERT INTO game_1.populations VALUES (6, 1, 1, 2, 6, 5.2, 1); +INSERT INTO game_1.populations VALUES (7, 2, 3, 4, 7, 6.8, 1); +INSERT INTO game_1.populations VALUES (8, 2, 4, 5, 8, 6.3, 1); + + +-- +-- Data for Name: populationusedresource; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (1, 1, 1, 0.1); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (2, 1, 2, 1.1); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (3, 1, 3, 2.7); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (4, 3, 3, 0.9); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (5, 4, 4, 1.2); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (6, 5, 5, 1.4); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (7, 6, 6, 0.7); +INSERT INTO game_1.populationusedresource OVERRIDING SYSTEM VALUE VALUES (8, 7, 7, 1.3); + + +-- +-- Data for Name: productionCost; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."productionCost" VALUES (1, 1, 1, 10); +INSERT INTO game_1."productionCost" VALUES (2, 1, 2, 5); +INSERT INTO game_1."productionCost" VALUES (3, 2, 1, 8); +INSERT INTO game_1."productionCost" VALUES (4, 2, 3, 10); +INSERT INTO game_1."productionCost" VALUES (5, 3, 1, 20); +INSERT INTO game_1."productionCost" VALUES (6, 3, 2, 15); +INSERT INTO game_1."productionCost" VALUES (7, 4, 1, 30); +INSERT INTO game_1."productionCost" VALUES (8, 4, 3, 25); +INSERT INTO game_1."productionCost" VALUES (9, 5, 1, 50); +INSERT INTO game_1."productionCost" VALUES (10, 5, 2, 30); + + +-- +-- Data for Name: productionShares; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."productionShares" VALUES (1, 1, 3, 2); +INSERT INTO game_1."productionShares" VALUES (2, 1, 4, 3); +INSERT INTO game_1."productionShares" VALUES (3, 2, 1, 1.5); +INSERT INTO game_1."productionShares" VALUES (4, 2, 6, 2); +INSERT INTO game_1."productionShares" VALUES (5, 3, 2, 1); +INSERT INTO game_1."productionShares" VALUES (6, 3, 5, 1.5); +INSERT INTO game_1."productionShares" VALUES (7, 4, 1, 1); +INSERT INTO game_1."productionShares" VALUES (8, 4, 7, 0.5); +INSERT INTO game_1."productionShares" VALUES (9, 5, 1, 2.5); +INSERT INTO game_1."productionShares" VALUES (10, 5, 8, 2); + + +-- +-- Data for Name: relatedEvents; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."relatedEvents" VALUES (1, 1, 1); +INSERT INTO game_1."relatedEvents" VALUES (2, 1, 2); +INSERT INTO game_1."relatedEvents" VALUES (3, 2, 3); +INSERT INTO game_1."relatedEvents" VALUES (4, 2, 4); +INSERT INTO game_1."relatedEvents" VALUES (5, 3, 1); +INSERT INTO game_1."relatedEvents" VALUES (6, 3, 5); +INSERT INTO game_1."relatedEvents" VALUES (7, 4, 2); +INSERT INTO game_1."relatedEvents" VALUES (8, 4, 4); +INSERT INTO game_1."relatedEvents" VALUES (9, 5, 1); +INSERT INTO game_1."relatedEvents" VALUES (10, 5, 3); + + +-- +-- Data for Name: religions; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.religions VALUES (1, 'Pogaństwo', NULL); +INSERT INTO game_1.religions VALUES (2, 'Chrześcijaństwo', NULL); +INSERT INTO game_1.religions VALUES (3, 'Islam', NULL); +INSERT INTO game_1.religions VALUES (4, 'Judaizm', NULL); +INSERT INTO game_1.religions VALUES (5, 'Zoroastrianizm', NULL); + + +-- +-- Data for Name: resources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.resources VALUES (1, 'Złoto', true, NULL); +INSERT INTO game_1.resources VALUES (2, 'Żelazo', true, NULL); +INSERT INTO game_1.resources VALUES (3, 'Drewno', true, NULL); +INSERT INTO game_1.resources VALUES (4, 'Żywność', true, NULL); +INSERT INTO game_1.resources VALUES (5, 'Kamień', true, NULL); +INSERT INTO game_1.resources VALUES (6, 'Tkaniny', false, NULL); +INSERT INTO game_1.resources VALUES (7, 'Przyprawy', false, NULL); +INSERT INTO game_1.resources VALUES (8, 'Wino', false, NULL); +INSERT INTO game_1.resources VALUES (9, 'Drewno', true, NULL); +INSERT INTO game_1.resources VALUES (11, 'Miód', true, NULL); + + +-- +-- Data for Name: socialgroups; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.socialgroups VALUES (1, 'Chłopi', 5, 10, NULL); +INSERT INTO game_1.socialgroups VALUES (2, 'Mieszczanie', 6, 20, NULL); +INSERT INTO game_1.socialgroups VALUES (3, 'Szlachta', 7, 30, NULL); +INSERT INTO game_1.socialgroups VALUES (4, 'Duchowieństwo', 8, 5, NULL); +INSERT INTO game_1.socialgroups VALUES (5, 'Kupcy', 6.5, 15, NULL); + + +-- +-- Data for Name: tradeagreements; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.tradeagreements VALUES (1, 1, 2, 0, 10, 'I am description'); +INSERT INTO game_1.tradeagreements VALUES (2, 1, 3, 0, 5, 'I am also description'); +INSERT INTO game_1.tradeagreements VALUES (3, 2, 4, 3, 8, 'But I m not description'); +INSERT INTO game_1.tradeagreements VALUES (4, 3, 5, 1, 12, 'What about me?'); +INSERT INTO game_1.tradeagreements VALUES (5, 4, 5, 2, 6, ''); + + +-- +-- Data for Name: troops; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.troops VALUES (1, 1, 1, 500); +INSERT INTO game_1.troops VALUES (2, 2, 1, 300); +INSERT INTO game_1.troops VALUES (3, 3, 2, 400); +INSERT INTO game_1.troops VALUES (4, 1, 2, 600); +INSERT INTO game_1.troops VALUES (5, 5, 3, 20); +INSERT INTO game_1.troops VALUES (6, 1, 4, 300); +INSERT INTO game_1.troops VALUES (7, 3, 4, 150); +INSERT INTO game_1.troops VALUES (8, 3, 5, 500); + + +-- +-- Data for Name: unitOrders; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."unitOrders" VALUES (1, 1, 1, 1); +INSERT INTO game_1."unitOrders" VALUES (2, 1, 2, 1); +INSERT INTO game_1."unitOrders" VALUES (3, 3, 2, 3); +INSERT INTO game_1."unitOrders" VALUES (4, 4, 2, 1); +INSERT INTO game_1."unitOrders" VALUES (5, 1, 3, 8); +INSERT INTO game_1."unitOrders" VALUES (6, 5, 3, 5); +INSERT INTO game_1."unitOrders" VALUES (7, 1, 4, 2); +INSERT INTO game_1."unitOrders" VALUES (8, 2, 4, 4); +INSERT INTO game_1."unitOrders" VALUES (9, 1, 5, 1); +INSERT INTO game_1."unitOrders" VALUES (10, 3, 5, 4); +INSERT INTO game_1."unitOrders" VALUES (12, 2, 1, 1); + + +-- +-- Data for Name: unitTypes; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."unitTypes" VALUES (1, 'Piechota', 'Podstawowa jednostka piechoty', 5, 0, 3, 3, 5, 100, false); +INSERT INTO game_1."unitTypes" VALUES (2, 'Łucznicy', 'Jednostka łuczników', 1, 6, 2, 3, 4, 80, false); +INSERT INTO game_1."unitTypes" VALUES (3, 'Kawaleria', 'Szybka jednostka kawalerii', 7, 0, 4, 6, 7, 120, false); +INSERT INTO game_1."unitTypes" VALUES (4, 'Oblężnicza', 'Machiny oblężnicze', 1, 8, 1, 2, 3, 150, false); +INSERT INTO game_1."unitTypes" VALUES (5, 'Okręty wojenne', 'Okręty bojowe', 6, 4, 5, 4, 6, 200, true); + + +-- +-- Data for Name: usedResources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1."usedResources" VALUES (1, 1, 4, 100); +INSERT INTO game_1."usedResources" VALUES (2, 1, 3, 50); +INSERT INTO game_1."usedResources" VALUES (3, 2, 4, 75); +INSERT INTO game_1."usedResources" VALUES (4, 2, 6, 25); +INSERT INTO game_1."usedResources" VALUES (5, 3, 4, 50); +INSERT INTO game_1."usedResources" VALUES (6, 3, 8, 30); +INSERT INTO game_1."usedResources" VALUES (7, 4, 4, 30); +INSERT INTO game_1."usedResources" VALUES (8, 4, 7, 10); +INSERT INTO game_1."usedResources" VALUES (9, 5, 4, 60); +INSERT INTO game_1."usedResources" VALUES (10, 5, 6, 40); + + +-- +-- Data for Name: wantedresources; Type: TABLE DATA; Schema: game_1; Owner: - +-- + +INSERT INTO game_1.wantedresources VALUES (1, 1, 1, 50); +INSERT INTO game_1.wantedresources VALUES (2, 4, 1, 100); +INSERT INTO game_1.wantedresources VALUES (3, 2, 3, 75); +INSERT INTO game_1.wantedresources VALUES (4, 5, 3, 200); +INSERT INTO game_1.wantedresources VALUES (5, 7, 4, 25); + + +-- +-- Name: gameaccess_id_seq; Type: SEQUENCE SET; Schema: Global; Owner: - +-- + +SELECT pg_catalog.setval('"Global".gameaccess_id_seq', 4, true); + + +-- +-- Name: games_id_seq; Type: SEQUENCE SET; Schema: Global; Owner: - +-- + +SELECT pg_catalog.setval('"Global".games_id_seq', 1, true); + + +-- +-- Name: users_id_seq; Type: SEQUENCE SET; Schema: Global; Owner: - +-- + +SELECT pg_catalog.setval('"Global".users_id_seq', 4, true); + + +-- +-- Name: accessToUnits_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."accessToUnits_id_seq"', 12, true); + + +-- +-- Name: accessestonations_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.accessestonations_id_seq', 5, true); + + +-- +-- Name: actions_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.actions_id_seq', 5, true); + + +-- +-- Name: armies_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.armies_id_seq', 15, true); + + +-- +-- Name: cultures_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.cultures_id_seq', 5, true); + + +-- +-- Name: events_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.events_id_seq', 5, true); + + +-- +-- Name: factions_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.factions_id_seq', 5, true); + + +-- +-- Name: localisationsResources_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."localisationsResources_id_seq"', 10, true); + + +-- +-- Name: localisations_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.localisations_id_seq', 8, true); + + +-- +-- Name: maintenanceCosts_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."maintenanceCosts_id_seq"', 10, true); + + +-- +-- Name: map_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.map_id_seq', 5, true); + + +-- +-- Name: modifiers_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.modifiers_id_seq', 1, false); + + +-- +-- Name: nations_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.nations_id_seq', 5, true); + + +-- +-- Name: offeredresources_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.offeredresources_id_seq', 5, true); + + +-- +-- Name: ownedResources_Id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."ownedResources_Id_seq"', 45, true); + + +-- +-- Name: players_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.players_id_seq', 4, true); + + +-- +-- Name: populationproductionshares_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.populationproductionshares_id_seq', 8, true); + + +-- +-- Name: populations_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.populations_id_seq', 8, true); + + +-- +-- Name: populationusedresource_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.populationusedresource_id_seq', 8, true); + + +-- +-- Name: productionCost_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."productionCost_id_seq"', 10, true); + + +-- +-- Name: productionShares_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."productionShares_id_seq"', 10, true); + + +-- +-- Name: relatedEvents_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."relatedEvents_id_seq"', 10, true); + + +-- +-- Name: religions_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.religions_id_seq', 5, true); + + +-- +-- Name: resources_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.resources_id_seq', 11, true); + + +-- +-- Name: socialgroups_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.socialgroups_id_seq', 5, true); + + +-- +-- Name: tradeagreements_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.tradeagreements_id_seq', 5, true); + + +-- +-- Name: troops_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.troops_id_seq', 8, true); + + +-- +-- Name: unitOrders_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."unitOrders_id_seq"', 12, true); + + +-- +-- Name: unitTypes_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."unitTypes_id_seq"', 5, true); + + +-- +-- Name: usedResources_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1."usedResources_id_seq"', 10, true); + + +-- +-- Name: wantedresources_id_seq; Type: SEQUENCE SET; Schema: game_1; Owner: - +-- + +SELECT pg_catalog.setval('game_1.wantedresources_id_seq', 5, true); + + +-- +-- Name: gameaccess PK_gameaccess; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "PK_gameaccess" PRIMARY KEY ("fk_Users", "fk_Games"); + + +-- +-- Name: games PK_games; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".games + ADD CONSTRAINT "PK_games" PRIMARY KEY (id); + + +-- +-- Name: users PK_users; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".users + ADD CONSTRAINT "PK_users" PRIMARY KEY (id); + + +-- +-- Name: refresh_tokens refresh_tokens_pkey; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".refresh_tokens + ADD CONSTRAINT refresh_tokens_pkey PRIMARY KEY (id); + + +-- +-- Name: accessToUnits PK_accessToUnits; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."accessToUnits" + ADD CONSTRAINT "PK_accessToUnits" PRIMARY KEY (id); + + +-- +-- Name: accessestonations PK_accessestonations; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.accessestonations + ADD CONSTRAINT "PK_accessestonations" PRIMARY KEY (id); + + +-- +-- Name: actions PK_actions; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.actions + ADD CONSTRAINT "PK_actions" PRIMARY KEY (id); + + +-- +-- Name: armies PK_armies; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.armies + ADD CONSTRAINT "PK_armies" PRIMARY KEY (id); + + +-- +-- Name: cultures PK_cultures; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.cultures + ADD CONSTRAINT "PK_cultures" PRIMARY KEY (id); + + +-- +-- Name: events PK_events; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.events + ADD CONSTRAINT "PK_events" PRIMARY KEY (id); + + +-- +-- Name: factions PK_factions; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.factions + ADD CONSTRAINT "PK_factions" PRIMARY KEY (id); + + +-- +-- Name: localisations PK_localisations; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.localisations + ADD CONSTRAINT "PK_localisations" PRIMARY KEY (id); + + +-- +-- Name: localisationsResources PK_localisationsResources; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."localisationsResources" + ADD CONSTRAINT "PK_localisationsResources" PRIMARY KEY (id); + + +-- +-- Name: maintenanceCosts PK_maintenanceCosts; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."maintenanceCosts" + ADD CONSTRAINT "PK_maintenanceCosts" PRIMARY KEY (id); + + +-- +-- Name: map PK_map; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.map + ADD CONSTRAINT "PK_map" PRIMARY KEY (id); + + +-- +-- Name: mapAccess PK_mapAccess; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."mapAccess" + ADD CONSTRAINT "PK_mapAccess" PRIMARY KEY ("fk_Nations", "fk_Maps"); + + +-- +-- Name: nations PK_nations; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.nations + ADD CONSTRAINT "PK_nations" PRIMARY KEY (id); + + +-- +-- Name: offeredresources PK_offeredresources; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.offeredresources + ADD CONSTRAINT "PK_offeredresources" PRIMARY KEY (id); + + +-- +-- Name: players PK_players; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.players + ADD CONSTRAINT "PK_players" PRIMARY KEY (id); + + +-- +-- Name: populations PK_populations; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populations + ADD CONSTRAINT "PK_populations" PRIMARY KEY (id); + + +-- +-- Name: productionCost PK_productionCost; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionCost" + ADD CONSTRAINT "PK_productionCost" PRIMARY KEY (id); + + +-- +-- Name: productionShares PK_productionShares; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionShares" + ADD CONSTRAINT "PK_productionShares" PRIMARY KEY (id); + + +-- +-- Name: relatedEvents PK_relatedEvents; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."relatedEvents" + ADD CONSTRAINT "PK_relatedEvents" PRIMARY KEY (id); + + +-- +-- Name: religions PK_religions; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.religions + ADD CONSTRAINT "PK_religions" PRIMARY KEY (id); + + +-- +-- Name: resources PK_resources; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.resources + ADD CONSTRAINT "PK_resources" PRIMARY KEY (id); + + +-- +-- Name: socialgroups PK_socialgroups; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.socialgroups + ADD CONSTRAINT "PK_socialgroups" PRIMARY KEY (id); + + +-- +-- Name: tradeagreements PK_tradeagreements; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.tradeagreements + ADD CONSTRAINT "PK_tradeagreements" PRIMARY KEY (id); + + +-- +-- Name: troops PK_troops; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.troops + ADD CONSTRAINT "PK_troops" PRIMARY KEY (id); + + +-- +-- Name: unitOrders PK_unitOrders; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."unitOrders" + ADD CONSTRAINT "PK_unitOrders" PRIMARY KEY (id); + + +-- +-- Name: unitTypes PK_unitTypes; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."unitTypes" + ADD CONSTRAINT "PK_unitTypes" PRIMARY KEY (id); + + +-- +-- Name: usedResources PK_usedResources; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."usedResources" + ADD CONSTRAINT "PK_usedResources" PRIMARY KEY (id); + + +-- +-- Name: wantedresources PK_wantedresources; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.wantedresources + ADD CONSTRAINT "PK_wantedresources" PRIMARY KEY (id); + + +-- +-- Name: modifiers modifiers_pkey; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.modifiers + ADD CONSTRAINT modifiers_pkey PRIMARY KEY (id); + + +-- +-- Name: ownedResources ownedResources_pkey; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."ownedResources" + ADD CONSTRAINT "ownedResources_pkey" PRIMARY KEY (id); + + +-- +-- Name: populationproductionshares populationproductionshares_pkey; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationproductionshares + ADD CONSTRAINT populationproductionshares_pkey PRIMARY KEY (id); + + +-- +-- Name: populationusedresource populationusedresource_pkey; Type: CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationusedresource + ADD CONSTRAINT populationusedresource_pkey PRIMARY KEY (id); + + +-- +-- Name: IX_gameaccess_fk_Games; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE INDEX "IX_gameaccess_fk_Games" ON "Global".gameaccess USING btree ("fk_Games"); + + +-- +-- Name: IX_games_name; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_games_name" ON "Global".games USING btree (name); + + +-- +-- Name: IX_games_ownerId; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE INDEX "IX_games_ownerId" ON "Global".games USING btree ("ownerId"); + + +-- +-- Name: IX_users_email; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_users_email" ON "Global".users USING btree (email); + + +-- +-- Name: IX_users_name; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_users_name" ON "Global".users USING btree (name); + + +-- +-- Name: IX_accessToUnits_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_accessToUnits_fk_Nations" ON game_1."accessToUnits" USING btree ("fk_Nation"); + + +-- +-- Name: IX_accessToUnits_fk_UnitTypes; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_accessToUnits_fk_UnitTypes" ON game_1."accessToUnits" USING btree ("fk_UnitTypes"); + + +-- +-- Name: IX_accessestonations_fk_nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_accessestonations_fk_nations" ON game_1.accessestonations USING btree (fk_nations); + + +-- +-- Name: IX_accessestonations_fk_users; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_accessestonations_fk_users" ON game_1.accessestonations USING btree (fk_users); + + +-- +-- Name: IX_actions_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_actions_fk_Nations" ON game_1.actions USING btree ("fk_Nations"); + + +-- +-- Name: IX_armies_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_armies_fk_Nations" ON game_1.armies USING btree ("fk_Nations"); + + +-- +-- Name: IX_armies_fk_localisations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_armies_fk_localisations" ON game_1.armies USING btree (fk_localisations); + + +-- +-- Name: IX_factions_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_factions_fk_Nations" ON game_1.factions USING btree ("fk_Nations"); + + +-- +-- Name: IX_localisations_fk_nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_localisations_fk_nations" ON game_1.localisations USING btree (fk_nations); + + +-- +-- Name: IX_maintenanceCosts_fk_Resources; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_maintenanceCosts_fk_Resources" ON game_1."maintenanceCosts" USING btree ("fk_Resources"); + + +-- +-- Name: IX_maintenanceCosts_fk_UnitTypes; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_maintenanceCosts_fk_UnitTypes" ON game_1."maintenanceCosts" USING btree ("fk_UnitTypes"); + + +-- +-- Name: IX_mapAccess_fk_Maps; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_mapAccess_fk_Maps" ON game_1."mapAccess" USING btree ("fk_Maps"); + + +-- +-- Name: IX_offeredresources_fk_resource; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_offeredresources_fk_resource" ON game_1.offeredresources USING btree (fk_resource); + + +-- +-- Name: IX_offeredresources_fk_tradeagreement; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_offeredresources_fk_tradeagreement" ON game_1.offeredresources USING btree (fk_tradeagreement); + + +-- +-- Name: IX_populations_fk_cultures; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_populations_fk_cultures" ON game_1.populations USING btree (fk_cultures); + + +-- +-- Name: IX_populations_fk_localisations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_populations_fk_localisations" ON game_1.populations USING btree (fk_localisations); + + +-- +-- Name: IX_populations_fk_religions; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_populations_fk_religions" ON game_1.populations USING btree (fk_religions); + + +-- +-- Name: IX_populations_fk_socialgroups; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_populations_fk_socialgroups" ON game_1.populations USING btree (fk_socialgroups); + + +-- +-- Name: IX_productionCost_fk_Resources; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_productionCost_fk_Resources" ON game_1."productionCost" USING btree ("fk_Resources"); + + +-- +-- Name: IX_productionCost_fk_UnitTypes; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_productionCost_fk_UnitTypes" ON game_1."productionCost" USING btree ("fk_UnitTypes"); + + +-- +-- Name: IX_relatedEvents_fk_Events; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_relatedEvents_fk_Events" ON game_1."relatedEvents" USING btree ("fk_Events"); + + +-- +-- Name: IX_relatedEvents_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_relatedEvents_fk_Nations" ON game_1."relatedEvents" USING btree ("fk_Nations"); + + +-- +-- Name: IX_tradeagreements_fk_nationoffering; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_tradeagreements_fk_nationoffering" ON game_1.tradeagreements USING btree (fk_nationoffering); + + +-- +-- Name: IX_tradeagreements_fk_nationreceiving; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_tradeagreements_fk_nationreceiving" ON game_1.tradeagreements USING btree (fk_nationreceiving); + + +-- +-- Name: IX_troops_fk_Armies; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_troops_fk_Armies" ON game_1.troops USING btree ("fk_Armies"); + + +-- +-- Name: IX_troops_fk_UnitTypes; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_troops_fk_UnitTypes" ON game_1.troops USING btree ("fk_UnitTypes"); + + +-- +-- Name: IX_unitOrders_fk_Nations; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_unitOrders_fk_Nations" ON game_1."unitOrders" USING btree ("fk_Nations"); + + +-- +-- Name: IX_unitOrders_fk_UnitTypes; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_unitOrders_fk_UnitTypes" ON game_1."unitOrders" USING btree ("fk_UnitTypes"); + + +-- +-- Name: IX_wantedresources_fk_resource; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_wantedresources_fk_resource" ON game_1.wantedresources USING btree (fk_resource); + + +-- +-- Name: IX_wantedresources_fk_tradeagreement; Type: INDEX; Schema: game_1; Owner: - +-- + +CREATE INDEX "IX_wantedresources_fk_tradeagreement" ON game_1.wantedresources USING btree (fk_tradeagreement); + + +-- +-- Name: nations trg_after_nations_insert; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_after_nations_insert AFTER INSERT ON game_1.nations FOR EACH ROW EXECUTE FUNCTION game_1.add_nation_to_all_resources(); + + +-- +-- Name: populations trg_after_populations_insert; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_after_populations_insert AFTER INSERT ON game_1.populations FOR EACH ROW EXECUTE FUNCTION game_1.add_population_relations(); + + +-- +-- Name: productionShares trg_after_productionshares_insert; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_after_productionshares_insert AFTER INSERT ON game_1."productionShares" FOR EACH ROW EXECUTE FUNCTION game_1.add_production_shares_to_populations(); + + +-- +-- Name: resources trg_after_resources_insert; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_after_resources_insert AFTER INSERT ON game_1.resources FOR EACH ROW EXECUTE FUNCTION game_1.add_resource_to_all_nations(); + + +-- +-- Name: usedResources trg_after_usedresources_insert; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_after_usedresources_insert AFTER INSERT ON game_1."usedResources" FOR EACH ROW EXECUTE FUNCTION game_1.add_used_resources_to_populations(); + + +-- +-- Name: nations trg_create_default_armies; Type: TRIGGER; Schema: game_1; Owner: - +-- + +CREATE TRIGGER trg_create_default_armies AFTER INSERT ON game_1.nations FOR EACH ROW EXECUTE FUNCTION game_1.create_default_armies(); + + +-- +-- Name: gameaccess FK_gameaccess_games_fk_Games; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "FK_gameaccess_games_fk_Games" FOREIGN KEY ("fk_Games") REFERENCES "Global".games(id) ON DELETE CASCADE; + + +-- +-- Name: gameaccess FK_gameaccess_users_fk_Users; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "FK_gameaccess_users_fk_Users" FOREIGN KEY ("fk_Users") REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: games FK_games_users_ownerId; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".games + ADD CONSTRAINT "FK_games_users_ownerId" FOREIGN KEY ("ownerId") REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: refresh_tokens refresh_tokens_user_id_fkey; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".refresh_tokens + ADD CONSTRAINT refresh_tokens_user_id_fkey FOREIGN KEY (user_id) REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: accessToUnits FK_accessToUnits_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."accessToUnits" + ADD CONSTRAINT "FK_accessToUnits_fk_Nations" FOREIGN KEY ("fk_Nation") REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: accessToUnits FK_accessToUnits_fk_UnitTypes; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."accessToUnits" + ADD CONSTRAINT "FK_accessToUnits_fk_UnitTypes" FOREIGN KEY ("fk_UnitTypes") REFERENCES game_1."unitTypes"(id) ON DELETE CASCADE; + + +-- +-- Name: accessestonations FK_accessestonations_fk_nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.accessestonations + ADD CONSTRAINT "FK_accessestonations_fk_nations" FOREIGN KEY (fk_nations) REFERENCES game_1.nations(id) ON DELETE CASCADE; + + +-- +-- Name: accessestonations FK_accessestonations_fk_users; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.accessestonations + ADD CONSTRAINT "FK_accessestonations_fk_users" FOREIGN KEY (fk_users) REFERENCES game_1.players(id) ON DELETE CASCADE; + + +-- +-- Name: actions FK_actions_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.actions + ADD CONSTRAINT "FK_actions_fk_Nations" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: armies FK_armies_localisations_fk_localisations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.armies + ADD CONSTRAINT "FK_armies_localisations_fk_localisations" FOREIGN KEY (fk_localisations) REFERENCES game_1.localisations(id) ON DELETE CASCADE; + + +-- +-- Name: armies FK_armies_nations_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.armies + ADD CONSTRAINT "FK_armies_nations_fk_Nations" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE CASCADE; + + +-- +-- Name: factions FK_factions_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.factions + ADD CONSTRAINT "FK_factions_fk_Nations" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: localisationsResources FK_localisationsResources_localisations_fk_localisations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."localisationsResources" + ADD CONSTRAINT "FK_localisationsResources_localisations_fk_localisations" FOREIGN KEY (fk_localisations) REFERENCES game_1.localisations(id) ON DELETE CASCADE; + + +-- +-- Name: localisationsResources FK_localisationsResources_resources_fk_Resources; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."localisationsResources" + ADD CONSTRAINT "FK_localisationsResources_resources_fk_Resources" FOREIGN KEY ("fk_Resources") REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: localisations FK_localisations_nations_fk_nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.localisations + ADD CONSTRAINT "FK_localisations_nations_fk_nations" FOREIGN KEY (fk_nations) REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: maintenanceCosts FK_maintenanceCosts_fk_Resources; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."maintenanceCosts" + ADD CONSTRAINT "FK_maintenanceCosts_fk_Resources" FOREIGN KEY ("fk_Resources") REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: maintenanceCosts FK_maintenanceCosts_fk_UnitTypes; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."maintenanceCosts" + ADD CONSTRAINT "FK_maintenanceCosts_fk_UnitTypes" FOREIGN KEY ("fk_UnitTypes") REFERENCES game_1."unitTypes"(id) ON DELETE CASCADE; + + +-- +-- Name: mapAccess FK_mapAccess_map_fk_Maps; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."mapAccess" + ADD CONSTRAINT "FK_mapAccess_map_fk_Maps" FOREIGN KEY ("fk_Maps") REFERENCES game_1.map(id) ON DELETE CASCADE; + + +-- +-- Name: mapAccess FK_mapAccess_map_fk_Nation; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."mapAccess" + ADD CONSTRAINT "FK_mapAccess_map_fk_Nation" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE CASCADE; + + +-- +-- Name: nations FK_nations_players_fk_cultures; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.nations + ADD CONSTRAINT "FK_nations_players_fk_cultures" FOREIGN KEY (fk_cultures) REFERENCES game_1.cultures(id) ON DELETE CASCADE; + + +-- +-- Name: nations FK_nations_players_fk_religions; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.nations + ADD CONSTRAINT "FK_nations_players_fk_religions" FOREIGN KEY (fk_religions) REFERENCES game_1.religions(id) ON DELETE RESTRICT; + + +-- +-- Name: offeredresources FK_offeredresources_resources_fk_resource; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.offeredresources + ADD CONSTRAINT "FK_offeredresources_resources_fk_resource" FOREIGN KEY (fk_resource) REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: offeredresources FK_offeredresources_tradeagreements_fk_tradeagreement; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.offeredresources + ADD CONSTRAINT "FK_offeredresources_tradeagreements_fk_tradeagreement" FOREIGN KEY (fk_tradeagreement) REFERENCES game_1.tradeagreements(id) ON DELETE CASCADE; + + +-- +-- Name: ownedResources FK_ownedresources_nation_fk_nation; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."ownedResources" + ADD CONSTRAINT "FK_ownedresources_nation_fk_nation" FOREIGN KEY (fk_nation) REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: ownedResources FK_ownedresources_resource_fk_resource; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."ownedResources" + ADD CONSTRAINT "FK_ownedresources_resource_fk_resource" FOREIGN KEY (fk_resource) REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: players FK_players_users_fk_users; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.players + ADD CONSTRAINT "FK_players_users_fk_users" FOREIGN KEY ("fk_User") REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: populations FK_populations_cultures_fk_cultures; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populations + ADD CONSTRAINT "FK_populations_cultures_fk_cultures" FOREIGN KEY (fk_cultures) REFERENCES game_1.cultures(id) ON DELETE CASCADE; + + +-- +-- Name: populations FK_populations_localisations_fk_localisations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populations + ADD CONSTRAINT "FK_populations_localisations_fk_localisations" FOREIGN KEY (fk_localisations) REFERENCES game_1.localisations(id) ON DELETE CASCADE; + + +-- +-- Name: populations FK_populations_religions_fk_religions; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populations + ADD CONSTRAINT "FK_populations_religions_fk_religions" FOREIGN KEY (fk_religions) REFERENCES game_1.religions(id) ON DELETE RESTRICT; + + +-- +-- Name: populations FK_populations_socialgroups_fk_socialgroups; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populations + ADD CONSTRAINT "FK_populations_socialgroups_fk_socialgroups" FOREIGN KEY (fk_socialgroups) REFERENCES game_1.socialgroups(id) ON DELETE CASCADE; + + +-- +-- Name: productionCost FK_productionCost_resources_fk_Resources; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionCost" + ADD CONSTRAINT "FK_productionCost_resources_fk_Resources" FOREIGN KEY ("fk_Resources") REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: productionCost FK_productionCost_unitTypes_fk_UnitTypes; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionCost" + ADD CONSTRAINT "FK_productionCost_unitTypes_fk_UnitTypes" FOREIGN KEY ("fk_UnitTypes") REFERENCES game_1."unitTypes"(id) ON DELETE CASCADE; + + +-- +-- Name: productionShares FK_productionShares_populations_fk_Resources; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionShares" + ADD CONSTRAINT "FK_productionShares_populations_fk_Resources" FOREIGN KEY ("fk_Resources") REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: productionShares FK_productionShares_populations_fk_SocialGroups; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."productionShares" + ADD CONSTRAINT "FK_productionShares_populations_fk_SocialGroups" FOREIGN KEY ("fk_SocialGroups") REFERENCES game_1.socialgroups(id) ON DELETE CASCADE; + + +-- +-- Name: relatedEvents FK_relatedEvents_events_fk_Events; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."relatedEvents" + ADD CONSTRAINT "FK_relatedEvents_events_fk_Events" FOREIGN KEY ("fk_Events") REFERENCES game_1.events(id) ON DELETE CASCADE; + + +-- +-- Name: relatedEvents FK_relatedEvents_nations_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."relatedEvents" + ADD CONSTRAINT "FK_relatedEvents_nations_fk_Nations" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: tradeagreements FK_tradeagreements_nations_fk_nationoffering; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.tradeagreements + ADD CONSTRAINT "FK_tradeagreements_nations_fk_nationoffering" FOREIGN KEY (fk_nationoffering) REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: tradeagreements FK_tradeagreements_nations_fk_nationreceiving; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.tradeagreements + ADD CONSTRAINT "FK_tradeagreements_nations_fk_nationreceiving" FOREIGN KEY (fk_nationreceiving) REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: troops FK_troops_armies_fk_Armies; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.troops + ADD CONSTRAINT "FK_troops_armies_fk_Armies" FOREIGN KEY ("fk_Armies") REFERENCES game_1.armies(id) ON DELETE CASCADE; + + +-- +-- Name: troops FK_troops_unitTypes_fk_UnitTypes; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.troops + ADD CONSTRAINT "FK_troops_unitTypes_fk_UnitTypes" FOREIGN KEY ("fk_UnitTypes") REFERENCES game_1."unitTypes"(id) ON DELETE CASCADE; + + +-- +-- Name: unitOrders FK_unitOrders_nations_fk_Nations; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."unitOrders" + ADD CONSTRAINT "FK_unitOrders_nations_fk_Nations" FOREIGN KEY ("fk_Nations") REFERENCES game_1.nations(id) ON DELETE RESTRICT; + + +-- +-- Name: unitOrders FK_unitOrders_unitTypes_fk_UnitTypes; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."unitOrders" + ADD CONSTRAINT "FK_unitOrders_unitTypes_fk_UnitTypes" FOREIGN KEY ("fk_UnitTypes") REFERENCES game_1."unitTypes"(id) ON DELETE CASCADE; + + +-- +-- Name: usedResources FK_usedResources_populations_fk_Resources; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."usedResources" + ADD CONSTRAINT "FK_usedResources_populations_fk_Resources" FOREIGN KEY ("fk_Resources") REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: usedResources FK_usedResources_populations_fk_SocialGroups; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1."usedResources" + ADD CONSTRAINT "FK_usedResources_populations_fk_SocialGroups" FOREIGN KEY ("fk_SocialGroups") REFERENCES game_1.socialgroups(id) ON DELETE CASCADE; + + +-- +-- Name: wantedresources FK_wantedresources_resources_fk_resource; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.wantedresources + ADD CONSTRAINT "FK_wantedresources_resources_fk_resource" FOREIGN KEY (fk_resource) REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: wantedresources FK_wantedresources_tradeagreements_fk_tradeagreement; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.wantedresources + ADD CONSTRAINT "FK_wantedresources_tradeagreements_fk_tradeagreement" FOREIGN KEY (fk_tradeagreement) REFERENCES game_1.tradeagreements(id) ON DELETE CASCADE; + + +-- +-- Name: modifiers modifiers_event_id_fkey; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.modifiers + ADD CONSTRAINT modifiers_event_id_fkey FOREIGN KEY (event_id) REFERENCES game_1.events(id) ON DELETE CASCADE; + + +-- +-- Name: populationproductionshares populationproductionshares_fkpopulation_fkey; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationproductionshares + ADD CONSTRAINT populationproductionshares_fkpopulation_fkey FOREIGN KEY (fk_population) REFERENCES game_1.populations(id) ON DELETE CASCADE; + + +-- +-- Name: populationproductionshares populationproductionshares_fkresources_fkey; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationproductionshares + ADD CONSTRAINT populationproductionshares_fkresources_fkey FOREIGN KEY (fk_resources) REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- Name: populationusedresource populationusedresource_fkpopulation_fkey; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationusedresource + ADD CONSTRAINT populationusedresource_fkpopulation_fkey FOREIGN KEY (fk_population) REFERENCES game_1.populations(id) ON DELETE CASCADE; + + +-- +-- Name: populationusedresource populationusedresource_fkresources_fkey; Type: FK CONSTRAINT; Schema: game_1; Owner: - +-- + +ALTER TABLE ONLY game_1.populationusedresource + ADD CONSTRAINT populationusedresource_fkresources_fkey FOREIGN KEY (fk_resources) REFERENCES game_1.resources(id) ON DELETE CASCADE; + + +-- +-- PostgreSQL database dump complete +-- + diff --git a/Tests/ConditionBuilderTests.cs b/Tests/ConditionBuilderTests.cs index 8d664ea..9686c9d 100644 --- a/Tests/ConditionBuilderTests.cs +++ b/Tests/ConditionBuilderTests.cs @@ -1,11 +1,6 @@ - -using NUnit.Framework; -using System; -using System.Collections.Generic; -using Wg_backend_api.Enums; +using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers; using Wg_backend_api.Logic.Modifiers.ModifierConditions; -using Wg_backend_api.Models; namespace Tests { diff --git a/Tests/Procesors/ModifierProcessorFactoryTests.cs b/Tests/Procesors/ModifierProcessorFactoryTests.cs index 1a071e1..32fe441 100644 --- a/Tests/Procesors/ModifierProcessorFactoryTests.cs +++ b/Tests/Procesors/ModifierProcessorFactoryTests.cs @@ -1,10 +1,5 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Wg_backend_api.Data; using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers; diff --git a/Tests/Procesors/PopulationHappinessProcessorTests.cs b/Tests/Procesors/PopulationHappinessProcessorTests.cs index 282e8bc..2db388e 100644 --- a/Tests/Procesors/PopulationHappinessProcessorTests.cs +++ b/Tests/Procesors/PopulationHappinessProcessorTests.cs @@ -1,10 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging.Abstractions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Wg_backend_api.Data; using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers.Processors; diff --git a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs index c697d5e..b0a068d 100644 --- a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs +++ b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs @@ -1,10 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging.Abstractions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Wg_backend_api.Data; using Wg_backend_api.Enums; using Wg_backend_api.Logic.Modifiers.Processors; diff --git a/Tests/Procesors/ResourceChangeProcessorTests.cs b/Tests/Procesors/ResourceChangeProcessorTests.cs index d579dbd..e8122ad 100644 --- a/Tests/Procesors/ResourceChangeProcessorTests.cs +++ b/Tests/Procesors/ResourceChangeProcessorTests.cs @@ -1,10 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Resources; -using NUnit.Framework; -using NUnit.Framework.Internal.Execution; -using System; -using System.Collections.Generic; using Wg_backend_api.Data; using Wg_backend_api.DTO; using Wg_backend_api.Enums; diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 2269b88..bf3f367 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -1,7 +1,8 @@ - + net9.0 + true enable enable @@ -11,11 +12,21 @@ + + + + + + - + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + @@ -27,4 +38,8 @@ + + + + diff --git a/Wg-backend-api/Migrations/global-schema-init.sql b/Wg-backend-api/Migrations/global-schema-init.sql new file mode 100644 index 0000000..4b6f0f9 --- /dev/null +++ b/Wg-backend-api/Migrations/global-schema-init.sql @@ -0,0 +1,232 @@ +-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 17.4 +-- Dumped by pg_dump version 17.4 + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +-- +-- Name: Global; Type: SCHEMA; Schema: -; Owner: - +-- + +CREATE SCHEMA "Global"; + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: gameaccess; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".gameaccess ( + id integer NOT NULL, + "fk_Users" integer NOT NULL, + "fk_Games" integer NOT NULL, + "accessType" integer NOT NULL, + "nationName" text, + "isArchived" boolean NOT NULL +); + + +-- +-- Name: gameaccess_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".gameaccess ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".gameaccess_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: games; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".games ( + id integer NOT NULL, + name text NOT NULL, + description text, + image text, + "ownerId" integer NOT NULL, + game_code text DEFAULT upper(substr(md5((random())::text), 1, 6)) +); + + +-- +-- Name: games_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".games ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".games_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: refresh_tokens; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".refresh_tokens ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id integer, + token text NOT NULL, + expires_at timestamp with time zone NOT NULL, + revoked_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() +); + + +-- +-- Name: users; Type: TABLE; Schema: Global; Owner: - +-- + +CREATE TABLE "Global".users ( + id integer NOT NULL, + name text NOT NULL, + email text NOT NULL, + password text NOT NULL, + issso boolean NOT NULL, + isarchived boolean NOT NULL, + image text +); + + +-- +-- Name: users_id_seq; Type: SEQUENCE; Schema: Global; Owner: - +-- + +ALTER TABLE "Global".users ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME "Global".users_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- Name: gameaccess PK_gameaccess; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "PK_gameaccess" PRIMARY KEY ("fk_Users", "fk_Games"); + + +-- +-- Name: games PK_games; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".games + ADD CONSTRAINT "PK_games" PRIMARY KEY (id); + + +-- +-- Name: users PK_users; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".users + ADD CONSTRAINT "PK_users" PRIMARY KEY (id); + + +-- +-- Name: refresh_tokens refresh_tokens_pkey; Type: CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".refresh_tokens + ADD CONSTRAINT refresh_tokens_pkey PRIMARY KEY (id); + + +-- +-- Name: IX_gameaccess_fk_Games; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE INDEX "IX_gameaccess_fk_Games" ON "Global".gameaccess USING btree ("fk_Games"); + + +-- +-- Name: IX_games_name; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_games_name" ON "Global".games USING btree (name); + + +-- +-- Name: IX_games_ownerId; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE INDEX "IX_games_ownerId" ON "Global".games USING btree ("ownerId"); + + +-- +-- Name: IX_users_email; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_users_email" ON "Global".users USING btree (email); + + +-- +-- Name: IX_users_name; Type: INDEX; Schema: Global; Owner: - +-- + +CREATE UNIQUE INDEX "IX_users_name" ON "Global".users USING btree (name); + + +-- +-- Name: gameaccess FK_gameaccess_games_fk_Games; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "FK_gameaccess_games_fk_Games" FOREIGN KEY ("fk_Games") REFERENCES "Global".games(id) ON DELETE CASCADE; + + +-- +-- Name: gameaccess FK_gameaccess_users_fk_Users; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".gameaccess + ADD CONSTRAINT "FK_gameaccess_users_fk_Users" FOREIGN KEY ("fk_Users") REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: games FK_games_users_ownerId; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".games + ADD CONSTRAINT "FK_games_users_ownerId" FOREIGN KEY ("ownerId") REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- Name: refresh_tokens refresh_tokens_user_id_fkey; Type: FK CONSTRAINT; Schema: Global; Owner: - +-- + +ALTER TABLE ONLY "Global".refresh_tokens + ADD CONSTRAINT refresh_tokens_user_id_fkey FOREIGN KEY (user_id) REFERENCES "Global".users(id) ON DELETE CASCADE; + + +-- +-- PostgreSQL database dump complete +-- + diff --git a/Wg-backend-api/Program.cs b/Wg-backend-api/Program.cs index 5b3325e..e71fb5d 100644 --- a/Wg-backend-api/Program.cs +++ b/Wg-backend-api/Program.cs @@ -9,197 +9,190 @@ using Microsoft.Extensions.FileProviders; using Microsoft.IdentityModel.Tokens; using Wg_backend_api.Auth; +using Wg_backend_api.Data; using Wg_backend_api.Logic.Modifiers; using Wg_backend_api.Logic.Modifiers.Processors; using Wg_backend_api.Services; -namespace Wg_backend_api.Data +var builder = WebApplication.CreateBuilder(args); +var connectionString = string.Empty; +if (builder.Environment.IsDevelopment()) { - class Program - { - static void Main(string[] args) - { - var builder = WebApplication.CreateBuilder(args); - var connectionString = string.Empty; - if (builder.Environment.IsDevelopment()) - { - connectionString = builder.Configuration.GetConnectionString("DevConection"); - } - else - { - connectionString = builder.Configuration.GetConnectionString("DeploymentConection"); - } + connectionString = builder.Configuration.GetConnectionString("DevConection"); +} +else +{ + connectionString = builder.Configuration.GetConnectionString("DeploymentConection"); +} - builder.Services.AddSingleton(new GameService(connectionString)); +builder.Services.AddSingleton(new GameService(connectionString)); - // Add DbContexts - builder.Services.AddDbContext(options => - options.UseNpgsql(connectionString)); +// Add DbContexts +builder.Services.AddDbContext(options => + options.UseNpgsql(connectionString)); - builder.Services.AddDbContext((serviceProvider, options) => options.UseNpgsql(connectionString)); +builder.Services.AddDbContext((serviceProvider, options) => options.UseNpgsql(connectionString)); - // Add Scoped GameDbContextFactory - builder.Services.AddScoped(); +// Add Scoped GameDbContextFactory +builder.Services.AddScoped(); - // Session setup - builder.Services.AddDistributedMemoryCache(); - builder.Services.AddSession(options => - { - options.IdleTimeout = TimeSpan.FromDays(365); - options.Cookie.SameSite = SameSiteMode.Lax; // Nie None dla HTTP - options.Cookie.SecurePolicy = CookieSecurePolicy.None; // Nie Always dla HTTP// TODO how many minutes we need? - options.Cookie.HttpOnly = true; - options.Cookie.IsEssential = true; - }); +// Session setup +builder.Services.AddDistributedMemoryCache(); +builder.Services.AddSession(options => +{ + options.IdleTimeout = TimeSpan.FromDays(365); + options.Cookie.SameSite = SameSiteMode.Lax; // Nie None dla HTTP + options.Cookie.SecurePolicy = CookieSecurePolicy.None; // Nie Always dla HTTP// TODO how many minutes we need? + options.Cookie.HttpOnly = true; + options.Cookie.IsEssential = true; +}); - // Authentication and Authorization setup +// Authentication and Authorization setup - builder.Services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultSignInScheme = "External"; - }) - .AddCookie("External") - .AddJwtBearer(options => - { - options.TokenValidationParameters = new TokenValidationParameters - { - ValidateIssuer = true, - ValidIssuer = builder.Configuration["Jwt:Issuer"], - ValidateAudience = true, - ValidAudience = builder.Configuration["Jwt:Audience"], - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])), - ValidateLifetime = true, - }; - options.Events = new JwtBearerEvents - { - OnMessageReceived = context => - - { - var accessToken = context.Request.Cookies["access_token"]; - if (!string.IsNullOrEmpty(accessToken)) - { - context.Token = accessToken; - } - - return Task.CompletedTask; - }, - }; - }) - .AddGoogle("Google", options => +builder.Services.AddAuthentication(options => +{ + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultSignInScheme = "External"; +}) +.AddCookie("External") +.AddJwtBearer(options => +{ + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuer = builder.Configuration["Jwt:Issuer"], + ValidateAudience = true, + ValidAudience = builder.Configuration["Jwt:Audience"], + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])), + ValidateLifetime = true, + }; + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + var accessToken = context.Request.Cookies["access_token"]; + if (!string.IsNullOrEmpty(accessToken)) { - options.ClientId = builder.Configuration["Authentication:Google:ClientId"]; - options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; + context.Token = accessToken; + } + + return Task.CompletedTask; + }, + }; +}) +.AddGoogle("Google", options => +{ + options.ClientId = builder.Configuration["Authentication:Google:ClientId"]; + options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]; - options.ClaimActions.MapJsonKey("picture", "picture"); - options.ClaimActions.MapJsonKey("locale", "locale"); - options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); + options.ClaimActions.MapJsonKey("picture", "picture"); + options.ClaimActions.MapJsonKey("locale", "locale"); + options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); - options.SaveTokens = true; - options.CallbackPath = "/signin-google"; + options.SaveTokens = true; + options.CallbackPath = "/signin-google"; - options.SignInScheme = "External"; - }); + options.SignInScheme = "External"; +}); - builder.Services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .RequireClaim(ClaimTypes.NameIdentifier) - .Build()); +builder.Services.AddAuthorization(options => options.DefaultPolicy = new AuthorizationPolicyBuilder() + .RequireAuthenticatedUser() + .RequireClaim(ClaimTypes.NameIdentifier) + .Build()); - // CORS setup to allow access from Angular frontend - builder.Services.AddCors(options => options.AddPolicy("AllowAngular", builder => builder.WithOrigins("https://localhost:4200", "http://localhost:4200", "https://localhost", "https://wargameshub.pl") - .AllowCredentials() - .AllowAnyHeader() - .AllowAnyMethod())); +// CORS setup to allow access from Angular frontend +builder.Services.AddCors(options => options.AddPolicy("AllowAngular", builder => builder.WithOrigins("https://localhost:4200", "http://localhost:4200", "https://localhost", "https://wargameshub.pl") + .AllowCredentials() + .AllowAnyHeader() + .AllowAnyMethod())); - builder.Services.AddHostedService(); +builder.Services.AddHostedService(); - builder.Services.AddScoped(); +builder.Services.AddScoped(); - // Add Controllers (API endpoints) - builder.Services.AddControllers(config => - { - config.Filters.Add(); - }) - .AddJsonOptions(options => - { - options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; - options.JsonSerializerOptions.WriteIndented = true; - options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver(); - options.JsonSerializerOptions.AllowOutOfOrderMetadataProperties = true; - }); - - // Add Swagger configuration - builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(); - builder.Services.AddHttpContextAccessor(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - - // rejestracja factory - builder.Services.AddScoped(); - - builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); - - var app = builder.Build(); - - // Configure the HTTP request pipeline - if (app.Environment.IsDevelopment()) - { - app.UseSwagger(); - app.UseSwaggerUI(); - } +// Add Controllers (API endpoints) +builder.Services.AddControllers(config => +{ + config.Filters.Add(); +}) +.AddJsonOptions(options => +{ + options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; + options.JsonSerializerOptions.WriteIndented = true; + options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver(); + options.JsonSerializerOptions.AllowOutOfOrderMetadataProperties = true; +}); + +// Add Swagger configuration +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddHttpContextAccessor(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// rejestracja factory +builder.Services.AddScoped(); + +builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); + +var app = builder.Build(); + +// Configure the HTTP request pipeline +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} - var corsService = app.Services.GetRequiredService(); - var corsPolicyProvider = app.Services.GetRequiredService(); +var corsService = app.Services.GetRequiredService(); +var corsPolicyProvider = app.Services.GetRequiredService(); - // Konfiguracja plik�w statycznych z CORS - app.UseStaticFiles(new StaticFileOptions - { - FileProvider = new PhysicalFileProvider( - Path.Combine(app.Environment.ContentRootPath, "Resources", "Images")), - RequestPath = "/images", - OnPrepareResponse = ctx => - { - var policy = corsPolicyProvider.GetPolicyAsync(ctx.Context, "AllowAngular") - .ConfigureAwait(false) - .GetAwaiter().GetResult(); +// Konfiguracja plik�w statycznych z CORS +app.UseStaticFiles(new StaticFileOptions +{ + FileProvider = new PhysicalFileProvider( + Path.Combine(app.Environment.ContentRootPath, "Resources", "Images")), + RequestPath = "/images", + OnPrepareResponse = ctx => + { + var policy = corsPolicyProvider.GetPolicyAsync(ctx.Context, "AllowAngular") + .ConfigureAwait(false) + .GetAwaiter().GetResult(); - var corsResult = corsService.EvaluatePolicy(ctx.Context, policy); - corsService.ApplyResult(corsResult, ctx.Context.Response); - } - }); + var corsResult = corsService.EvaluatePolicy(ctx.Context, policy); + corsService.ApplyResult(corsResult, ctx.Context.Response); + } +}); - // app.UseHttpsRedirection(); +// app.UseHttpsRedirection(); - //app.UseStaticFiles(); // Teraz z obs�ug� CORS +//app.UseStaticFiles(); // Teraz z obs�ug� CORS - app.UseRouting(); // Jawnie dodane - app.UseSession(); // Tutaj dodajemy middleware sesji +app.UseRouting(); // Jawnie dodane +app.UseSession(); // Tutaj dodajemy middleware sesji - app.UseCors("AllowAngular"); // Po routingu, przed autentykacj� +app.UseCors("AllowAngular"); // Po routingu, przed autentykacj� - app.UseAuthentication(); +app.UseAuthentication(); - if (!args.Contains("--no-login")) - { - // app.UseMiddleware(); - } +if (!args.Contains("--no-login")) +{ + // app.UseMiddleware(); +} - app.UseMiddleware(); - app.UseAuthorization(); +app.UseMiddleware(); +app.UseAuthorization(); - app.MapControllers(); // Map controller routes +app.MapControllers(); // Map controller routes - app.Run(); - } - } -} +app.Run(); + +public partial class Program { } \ No newline at end of file diff --git a/Wg-backend-api/Wg-backend-api.csproj b/Wg-backend-api/Wg-backend-api.csproj index d79358e..b6070b4 100644 --- a/Wg-backend-api/Wg-backend-api.csproj +++ b/Wg-backend-api/Wg-backend-api.csproj @@ -6,6 +6,8 @@ enable Wg_backend_api 3f09c764-3f01-45a2-95b0-e003043bc9ae + true + false @@ -38,5 +40,8 @@ + + + From 9f82a8cca25deb65faa621dea9ee994e4dfeb1bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Wed, 10 Dec 2025 22:14:37 +0100 Subject: [PATCH 3/6] get api tests for army, nations, trades and idk what else --- Tests/Api/ApiArmyTests.cs | 73 +++++++++++++++++++++++++ Tests/Api/ApiNationsTests.cs | 85 +++++++++++++++++++++++++++++ Tests/Api/ApiPopulationsTests.cs | 76 ++++++++++++++++++++++++++ Tests/Api/ApiTradeTests.cs | 91 ++++++++++++++++++++++++++++++++ Tests/Api/DatabaseFixture.cs | 21 ++++++++ Tests/Api/PopulationsTests.cs | 47 ----------------- Tests/Api/TestDatabaseManager.cs | 6 --- 7 files changed, 346 insertions(+), 53 deletions(-) create mode 100644 Tests/Api/ApiArmyTests.cs create mode 100644 Tests/Api/ApiNationsTests.cs create mode 100644 Tests/Api/ApiPopulationsTests.cs create mode 100644 Tests/Api/ApiTradeTests.cs create mode 100644 Tests/Api/DatabaseFixture.cs delete mode 100644 Tests/Api/PopulationsTests.cs diff --git a/Tests/Api/ApiArmyTests.cs b/Tests/Api/ApiArmyTests.cs new file mode 100644 index 0000000..967083d --- /dev/null +++ b/Tests/Api/ApiArmyTests.cs @@ -0,0 +1,73 @@ +using Tests; +using Xunit; +using Wg_backend_api.Services; +using Moq; +using System.Net; +using XAssert = Xunit.Assert; + +[Collection("Database collection")] +public class ApiArmyTests +{ + private readonly HttpClient _client; + + public ApiArmyTests(DatabaseFixture db) + { + var mockSession = new Mock(); + mockSession.Setup(s => s.GetNation()).Returns("1"); + mockSession.Setup(s => s.GetSchema()).Returns("game_1"); + mockSession.Setup(s => s.GetRole()).Returns("Player"); + + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + _client = _factory.CreateClient(); + } + + [Fact] + public async Task GetArmies_WithoutId_ReturnsOkWithList() + { + var response = await _client.GetAsync("/api/armies"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetArmies_WithValidId_ReturnsOk() + { + var response = await _client.GetAsync("/api/armies/1"); + + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task GetArmies_WithInvalidId_ReturnsNotFound() + { + var response = await _client.GetAsync("/api/armies/99999"); + + XAssert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetArmies_IsAuthenticated_ReturnsData() + { + var authResponse = await _client.GetAsync("/api/auth/status"); + authResponse.EnsureSuccessStatusCode(); + + var response = await _client.GetAsync("/api/armies"); + response.EnsureSuccessStatusCode(); + } + + [Fact] + public async Task GetArmies_ReturnsValidArmyStructure() + { + var response = await _client.GetAsync("/api/armies"); + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(); + + XAssert.Contains("armyId", json); + // XAssert.Contains("ArmyId", json); + } +} diff --git a/Tests/Api/ApiNationsTests.cs b/Tests/Api/ApiNationsTests.cs new file mode 100644 index 0000000..d889d4f --- /dev/null +++ b/Tests/Api/ApiNationsTests.cs @@ -0,0 +1,85 @@ +using Xunit; +using System.Net; +using Moq; +using Wg_backend_api.Services; +using Tests; +using XAssert = Xunit.Assert; + +[Collection("Database collection")] +public class ApiNationsTests +{ + private readonly HttpClient _client; + + public ApiNationsTests(DatabaseFixture db) + { + var mockSession = new Mock(); + mockSession.Setup(s => s.GetNation()).Returns("1"); + mockSession.Setup(s => s.GetSchema()).Returns("game_1"); + mockSession.Setup(s => s.GetRole()).Returns("Player"); + + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1", mockSession); + _client = _factory.CreateClient(); + } + + [Fact] + public async Task GetNations_WithoutId_ReturnsOkWithList() + { + var response = await _client.GetAsync("/api/nations"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetNations_WithValidId_ReturnsOk() + { + var response = await _client.GetAsync("/api/nations/1"); + + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task GetNations_WithInvalidId_ReturnsNotFound() + { + var response = await _client.GetAsync("/api/nations/99999"); + + XAssert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetNations_IsAuthenticated_ReturnsData() + { + var authResponse = await _client.GetAsync("/api/auth/status"); + authResponse.EnsureSuccessStatusCode(); + + var response = await _client.GetAsync("/api/nations"); + response.EnsureSuccessStatusCode(); + } + + [Fact] + public async Task GetNations_ReturnsValidNationStructure() + { + var response = await _client.GetAsync("/api/nations"); + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(); + + XAssert.Contains("id", json.ToLower()); + XAssert.Contains("name", json.ToLower()); + } + + [Fact] + public async Task GetNationById_ReturnsValidNationData() + { + var response = await _client.GetAsync("/api/nations/1"); + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(); + + XAssert.NotEmpty(json); + XAssert.Contains("id", json.ToLower()); + } +} diff --git a/Tests/Api/ApiPopulationsTests.cs b/Tests/Api/ApiPopulationsTests.cs new file mode 100644 index 0000000..facc84b --- /dev/null +++ b/Tests/Api/ApiPopulationsTests.cs @@ -0,0 +1,76 @@ +using Tests; +using Xunit; +using Wg_backend_api.Services; +using Moq; +using System.Net; +using XAssert = Xunit.Assert; + +[Collection("Database collection")] +public class ApiControllersTests +{ + private readonly HttpClient _client; + + public ApiControllersTests(DatabaseFixture db) + { + var mockSession = new Mock(); + mockSession.Setup(s => s.GetNation()).Returns("1"); + mockSession.Setup(s => s.GetSchema()).Returns("game_1"); + mockSession.Setup(s => s.GetRole()).Returns("Player"); + + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + _client = _factory.CreateClient(); + } + + [Fact] + public async Task GetAll_ReturnsOkAndData() + { + var response = await _client.GetAsync("/api/auth/status"); + response.EnsureSuccessStatusCode(); + + string json = await response.Content.ReadAsStringAsync(); + + var responsepop = await _client.GetAsync("/api/populations"); + responsepop.EnsureSuccessStatusCode(); + + string jsonpop = await responsepop.Content.ReadAsStringAsync(); + } + + [Fact] + public async Task GetPopulations_ReturnsOkWithList() + { + var response = await _client.GetAsync("/api/populations"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetPopulationById_WithValidId_ReturnsOk() + { + var response = await _client.GetAsync("/api/populations/1"); + + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task GetPopulationById_WithInvalidId_ReturnsNotFound() + { + var response = await _client.GetAsync("/api/populations/99999"); + + XAssert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetPopulations_IsAuthenticated_ReturnsData() + { + var authResponse = await _client.GetAsync("/api/auth/status"); + authResponse.EnsureSuccessStatusCode(); + + var response = await _client.GetAsync("/api/populations"); + response.EnsureSuccessStatusCode(); + } +} + diff --git a/Tests/Api/ApiTradeTests.cs b/Tests/Api/ApiTradeTests.cs new file mode 100644 index 0000000..65fe126 --- /dev/null +++ b/Tests/Api/ApiTradeTests.cs @@ -0,0 +1,91 @@ +using Xunit; +using System.Net; +using Moq; +using Wg_backend_api.Services; +using Tests; +using XAssert = Xunit.Assert; + +[Collection("Database collection")] +public class ApiTradeTests +{ + private readonly HttpClient _client; + + public ApiTradeTests(DatabaseFixture db) + { + var mockSession = new Mock(); + mockSession.Setup(s => s.GetNation()).Returns("1"); + mockSession.Setup(s => s.GetSchema()).Returns("game_1"); + mockSession.Setup(s => s.GetRole()).Returns("Player"); + + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + _client = _factory.CreateClient(); + } + + [Fact] + public async Task GetOfferedTradeAgreements_WithoutNationId_ReturnsOk() + { + var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetOfferedTradeAgreements_WithNationId_ReturnsOk() + { + var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements/1"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetReceivedTradeAgreements_WithoutNationId_ReturnsOk() + { + var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetReceivedTradeAgreements_WithNationId_ReturnsOk() + { + var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements/1"); + + response.EnsureSuccessStatusCode(); + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); + + var json = await response.Content.ReadAsStringAsync(); + XAssert.NotEmpty(json); + } + + [Fact] + public async Task GetOfferedTradeAgreements_IsAuthenticated_ReturnsData() + { + var authResponse = await _client.GetAsync("/api/auth/status"); + authResponse.EnsureSuccessStatusCode(); + + var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements"); + response.EnsureSuccessStatusCode(); + } + + [Fact] + public async Task GetReceivedTradeAgreements_IsAuthenticated_ReturnsData() + { + var authResponse = await _client.GetAsync("/api/auth/status"); + authResponse.EnsureSuccessStatusCode(); + + var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements"); + response.EnsureSuccessStatusCode(); + } +} \ No newline at end of file diff --git a/Tests/Api/DatabaseFixture.cs b/Tests/Api/DatabaseFixture.cs new file mode 100644 index 0000000..c56cc31 --- /dev/null +++ b/Tests/Api/DatabaseFixture.cs @@ -0,0 +1,21 @@ +using Xunit; + +public class DatabaseFixture : IDisposable +{ + public string ConnectionString { get; } + + public DatabaseFixture() + { + ConnectionString = TestDatabaseManager.RecreateDatabase(); + } + + public void Dispose() + { + TestDatabaseManager.DropDatabase(); + } +} + +[CollectionDefinition("Database collection")] +public class DatabaseCollection : ICollectionFixture +{ +} diff --git a/Tests/Api/PopulationsTests.cs b/Tests/Api/PopulationsTests.cs deleted file mode 100644 index d8585d2..0000000 --- a/Tests/Api/PopulationsTests.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Tests; -using Xunit; -using Wg_backend_api.Services; -using Moq; - -public class PopulationsControllerTests : IDisposable -{ - private readonly HttpClient _client; - private readonly TestingWebAppFactory _factory; - - public PopulationsControllerTests() - { - string conn = TestDatabaseManager.RecreateDatabase(); - var mockSession = new Mock(); - mockSession.Setup(s => s.GetNation()).Returns("1"); - mockSession.Setup(s => s.GetSchema()).Returns("game_1"); - mockSession.Setup(s => s.GetRole()).Returns("Player"); - - _factory = new TestingWebAppFactory(conn, schema: "game_1", nation: "1",mockSession); - _client = _factory.CreateClient(); - - } - - [Fact] - public async Task GetAll_ReturnsOkAndData() - { - var response = await _client.GetAsync("/api/auth/status"); - response.EnsureSuccessStatusCode(); - - string json = await response.Content.ReadAsStringAsync(); - Console.WriteLine(json); - - var responsepop = await _client.GetAsync("/api/populations"); - responsepop.EnsureSuccessStatusCode(); - - string jsonpop = await responsepop.Content.ReadAsStringAsync(); - Console.WriteLine(jsonpop); - } - - public void Dispose() - { - _client?.Dispose(); - _factory?.Dispose(); - TestDatabaseManager.DropDatabase(); - } -} - diff --git a/Tests/Api/TestDatabaseManager.cs b/Tests/Api/TestDatabaseManager.cs index 7659ee0..4933b41 100644 --- a/Tests/Api/TestDatabaseManager.cs +++ b/Tests/Api/TestDatabaseManager.cs @@ -18,7 +18,6 @@ public static string RecreateDatabase() using var admin = new NpgsqlConnection(AdminConnection); admin.Open(); - Console.WriteLine("Terminating existing connections..."); using (var cmd = new NpgsqlCommand($@" SELECT pg_terminate_backend(pid) FROM pg_stat_activity @@ -27,13 +26,11 @@ FROM pg_stat_activity cmd.ExecuteNonQuery(); } - Console.WriteLine($"Dropping database {TestDbName} if exists..."); using (var cmd = new NpgsqlCommand($"DROP DATABASE IF EXISTS {TestDbName}", admin)) { cmd.ExecuteNonQuery(); } - Console.WriteLine($"Creating database {TestDbName}..."); using (var cmd = new NpgsqlCommand($"CREATE DATABASE {TestDbName}", admin)) { cmd.ExecuteNonQuery(); @@ -44,7 +41,6 @@ FROM pg_stat_activity script = Regex.Replace(script, @"^\\.*$", "", RegexOptions.Multiline); - Console.WriteLine($"Executing migration script (size: {script.Length} bytes)..."); using var connection = new NpgsqlConnection(TestDbConnection); connection.Open(); @@ -53,11 +49,9 @@ FROM pg_stat_activity try { command.ExecuteNonQuery(); - Console.WriteLine($"✓ Database initialized successfully"); } catch (Exception ex) { - Console.WriteLine($"✗ Error initializing database: {ex.Message}"); throw; } From ad7de5e10f1e3c639b85788b458e08d9a2d9d09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Thu, 11 Dec 2025 17:37:18 +0100 Subject: [PATCH 4/6] post api tests --- Tests/Api/ApiArmyTests.cs | 73 +++++++++++++++---- Tests/Api/ApiNationsTests.cs | 71 +++++++++++++----- Tests/Api/ApiPopulationsTests.cs | 71 ++++++++++++------ Tests/Api/ApiTradeTests.cs | 66 +++++++++++++---- Tests/Api/CustomWebApplicationFactory.cs | 2 +- Tests/Api/DatabaseFixture.cs | 1 + Tests/Api/TestDatabaseManager.cs | 2 + Tests/Api/TestGameDbContextFactory.cs | 2 + Tests/Api/TestSessionDataService.cs | 1 + .../Procesors/ResourceChangeProcessorTests.cs | 7 +- .../GameControllers/TradeController.cs | 9 --- 11 files changed, 226 insertions(+), 79 deletions(-) diff --git a/Tests/Api/ApiArmyTests.cs b/Tests/Api/ApiArmyTests.cs index 967083d..12d62fd 100644 --- a/Tests/Api/ApiArmyTests.cs +++ b/Tests/Api/ApiArmyTests.cs @@ -4,6 +4,11 @@ using Moq; using System.Net; using XAssert = Xunit.Assert; +using Wg_backend_api.DTO; +using Newtonsoft.Json; +using System.Text; + +namespace Tests.Api; [Collection("Database collection")] public class ApiArmyTests @@ -22,7 +27,7 @@ public ApiArmyTests(DatabaseFixture db) } [Fact] - public async Task GetArmies_WithoutId_ReturnsOkWithList() + public async Task GetArmies() { var response = await _client.GetAsync("/api/armies"); @@ -34,7 +39,7 @@ public async Task GetArmies_WithoutId_ReturnsOkWithList() } [Fact] - public async Task GetArmies_WithValidId_ReturnsOk() + public async Task GetArmies_ValidId() { var response = await _client.GetAsync("/api/armies/1"); @@ -42,7 +47,7 @@ public async Task GetArmies_WithValidId_ReturnsOk() } [Fact] - public async Task GetArmies_WithInvalidId_ReturnsNotFound() + public async Task GetArmy_InvalidId() { var response = await _client.GetAsync("/api/armies/99999"); @@ -50,24 +55,64 @@ public async Task GetArmies_WithInvalidId_ReturnsNotFound() } [Fact] - public async Task GetArmies_IsAuthenticated_ReturnsData() + public async Task PostArmy_ValidData() { - var authResponse = await _client.GetAsync("/api/auth/status"); - authResponse.EnsureSuccessStatusCode(); + var dto = new CreateArmyDTO + { + Name = "303rd Squadron", + LocationId = 1, + NationId = null, + IsNaval = false + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/armies", content); - var response = await _client.GetAsync("/api/armies"); response.EnsureSuccessStatusCode(); + + XAssert.Equal(HttpStatusCode.Created, response.StatusCode); + + var responseBody = await response.Content.ReadAsStringAsync(); + XAssert.Contains("303rd Squadron", responseBody); } [Fact] - public async Task GetArmies_ReturnsValidArmyStructure() + public async Task PostArmy_InvalidLocationData() { - var response = await _client.GetAsync("/api/armies"); - response.EnsureSuccessStatusCode(); + var dto = new CreateArmyDTO + { + Name = "303rd Squadron", + LocationId = null, + NationId = null, + IsNaval = false + }; - var json = await response.Content.ReadAsStringAsync(); - - XAssert.Contains("armyId", json); - // XAssert.Contains("ArmyId", json); + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/armies", content); + + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } + + [Fact] + public async Task PostArmy_InvalidDataName() + { + var dto = new CreateArmyDTO + { + Name = "303rd Squadron", + LocationId = 1, + NationId = null, + IsNaval = false + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/armies", content); + + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } } diff --git a/Tests/Api/ApiNationsTests.cs b/Tests/Api/ApiNationsTests.cs index d889d4f..8971afb 100644 --- a/Tests/Api/ApiNationsTests.cs +++ b/Tests/Api/ApiNationsTests.cs @@ -2,9 +2,10 @@ using System.Net; using Moq; using Wg_backend_api.Services; -using Tests; using XAssert = Xunit.Assert; +namespace Tests.Api; + [Collection("Database collection")] public class ApiNationsTests { @@ -22,7 +23,7 @@ public ApiNationsTests(DatabaseFixture db) } [Fact] - public async Task GetNations_WithoutId_ReturnsOkWithList() + public async Task GetNation() { var response = await _client.GetAsync("/api/nations"); @@ -34,7 +35,7 @@ public async Task GetNations_WithoutId_ReturnsOkWithList() } [Fact] - public async Task GetNations_WithValidId_ReturnsOk() + public async Task GetNation_ValidId() { var response = await _client.GetAsync("/api/nations/1"); @@ -42,7 +43,7 @@ public async Task GetNations_WithValidId_ReturnsOk() } [Fact] - public async Task GetNations_WithInvalidId_ReturnsNotFound() + public async Task GetNation_InvalidId() { var response = await _client.GetAsync("/api/nations/99999"); @@ -50,17 +51,7 @@ public async Task GetNations_WithInvalidId_ReturnsNotFound() } [Fact] - public async Task GetNations_IsAuthenticated_ReturnsData() - { - var authResponse = await _client.GetAsync("/api/auth/status"); - authResponse.EnsureSuccessStatusCode(); - - var response = await _client.GetAsync("/api/nations"); - response.EnsureSuccessStatusCode(); - } - - [Fact] - public async Task GetNations_ReturnsValidNationStructure() + public async Task GetNation_ValidNationStructure() { var response = await _client.GetAsync("/api/nations"); response.EnsureSuccessStatusCode(); @@ -72,7 +63,7 @@ public async Task GetNations_ReturnsValidNationStructure() } [Fact] - public async Task GetNationById_ReturnsValidNationData() + public async Task GetNation_ValidNationData() { var response = await _client.GetAsync("/api/nations/1"); response.EnsureSuccessStatusCode(); @@ -81,5 +72,51 @@ public async Task GetNationById_ReturnsValidNationData() XAssert.NotEmpty(json); XAssert.Contains("id", json.ToLower()); - } + } + + [Fact] + public async Task PostNation_ValidData() + { + var content = new MultipartFormDataContent + { + { new StringContent("Isengard"), "Name" }, + { new StringContent("1"), "ReligionId" }, + { new StringContent("1"), "CultureId" }, + { new StringContent(""), "Flag" }, + { new StringContent("#FF0000"), "Color" }, + }; + + var response = await _client.PostAsync("/api/Nations", content); + + response.EnsureSuccessStatusCode(); + + XAssert.Equal(HttpStatusCode.Created, response.StatusCode); + + var responseBody = await response.Content.ReadAsStringAsync(); + XAssert.Contains("Isengard", responseBody); + + var nationResponse = await _client.GetAsync("/api/Nations"); + response.EnsureSuccessStatusCode(); + + var nationsJson = await response.Content.ReadAsStringAsync(); + + XAssert.Contains("Isengard", nationsJson); + } + + [Fact] + public async Task PostNation_InvalidData() + { + var content = new MultipartFormDataContent + { + { new StringContent("Isengard"), "Name" }, + { new StringContent(""), "ReligionId" }, + { new StringContent(""), "CultureId" }, + { new StringContent(""), "Flag" }, + { new StringContent("#FF0000"), "Color" }, + }; + + var response = await _client.PostAsync("/api/Nations", content); + + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } } diff --git a/Tests/Api/ApiPopulationsTests.cs b/Tests/Api/ApiPopulationsTests.cs index facc84b..f03181e 100644 --- a/Tests/Api/ApiPopulationsTests.cs +++ b/Tests/Api/ApiPopulationsTests.cs @@ -4,6 +4,11 @@ using Moq; using System.Net; using XAssert = Xunit.Assert; +using Newtonsoft.Json; +using System.Text; +using Wg_backend_api.DTO; + +namespace Tests.Api; [Collection("Database collection")] public class ApiControllersTests @@ -22,21 +27,7 @@ public ApiControllersTests(DatabaseFixture db) } [Fact] - public async Task GetAll_ReturnsOkAndData() - { - var response = await _client.GetAsync("/api/auth/status"); - response.EnsureSuccessStatusCode(); - - string json = await response.Content.ReadAsStringAsync(); - - var responsepop = await _client.GetAsync("/api/populations"); - responsepop.EnsureSuccessStatusCode(); - - string jsonpop = await responsepop.Content.ReadAsStringAsync(); - } - - [Fact] - public async Task GetPopulations_ReturnsOkWithList() + public async Task GetPopulations_OkList() { var response = await _client.GetAsync("/api/populations"); @@ -48,7 +39,7 @@ public async Task GetPopulations_ReturnsOkWithList() } [Fact] - public async Task GetPopulationById_WithValidId_ReturnsOk() + public async Task GetPopulation_ValidId() { var response = await _client.GetAsync("/api/populations/1"); @@ -56,21 +47,57 @@ public async Task GetPopulationById_WithValidId_ReturnsOk() } [Fact] - public async Task GetPopulationById_WithInvalidId_ReturnsNotFound() + public async Task GetPopulation_InvalidId() { - var response = await _client.GetAsync("/api/populations/99999"); + var response = await _client.GetAsync("/api/populations/2137"); XAssert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Fact] - public async Task GetPopulations_IsAuthenticated_ReturnsData() + public async Task PostPopulation_ValidData() { - var authResponse = await _client.GetAsync("/api/auth/status"); - authResponse.EnsureSuccessStatusCode(); + var dto = new List() + { new PopulationDTO{ + ReligionId = 1, + CultureId = 1, + SocialGroupId = 1, + LocationId = 1, + Happiness = 75.5f, + Volonteers = 1000 + } + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/populations", content); - var response = await _client.GetAsync("/api/populations"); response.EnsureSuccessStatusCode(); + + XAssert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact] + public async Task PostPopulation_InvalidData() + { + var dto = new List() + { new PopulationDTO { + ReligionId = 1, + CultureId = 1, + SocialGroupId = 2137, + LocationId = 1, + Happiness = 69f, + Volonteers = 2137 + } + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/populations", content); + + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } diff --git a/Tests/Api/ApiTradeTests.cs b/Tests/Api/ApiTradeTests.cs index 65fe126..3d0c67a 100644 --- a/Tests/Api/ApiTradeTests.cs +++ b/Tests/Api/ApiTradeTests.cs @@ -4,6 +4,12 @@ using Wg_backend_api.Services; using Tests; using XAssert = Xunit.Assert; +using Wg_backend_api.DTO; +using Newtonsoft.Json; +using System.Text; +using Wg_backend_api.Enums; + +namespace Tests.Api; [Collection("Database collection")] public class ApiTradeTests @@ -22,7 +28,7 @@ public ApiTradeTests(DatabaseFixture db) } [Fact] - public async Task GetOfferedTradeAgreements_WithoutNationId_ReturnsOk() + public async Task GetOfferedTradeAgreements() { var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements"); @@ -34,7 +40,7 @@ public async Task GetOfferedTradeAgreements_WithoutNationId_ReturnsOk() } [Fact] - public async Task GetOfferedTradeAgreements_WithNationId_ReturnsOk() + public async Task GetOfferedTradeAgreements_Id() { var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements/1"); @@ -46,7 +52,7 @@ public async Task GetOfferedTradeAgreements_WithNationId_ReturnsOk() } [Fact] - public async Task GetReceivedTradeAgreements_WithoutNationId_ReturnsOk() + public async Task GetReceivedTradeAgreements() { var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements"); @@ -58,7 +64,7 @@ public async Task GetReceivedTradeAgreements_WithoutNationId_ReturnsOk() } [Fact] - public async Task GetReceivedTradeAgreements_WithNationId_ReturnsOk() + public async Task GetReceivedTradeAgreements_Id() { var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements/1"); @@ -70,22 +76,54 @@ public async Task GetReceivedTradeAgreements_WithNationId_ReturnsOk() } [Fact] - public async Task GetOfferedTradeAgreements_IsAuthenticated_ReturnsData() + public async Task PostTrade_ValidData() { - var authResponse = await _client.GetAsync("/api/auth/status"); - authResponse.EnsureSuccessStatusCode(); + var dto = new OfferTradeAgreementDTO + { + ReceivingNationId = 5, + Duration = 2, + Description = "Im description", + TradeStatus = TradeStatus.Pending, + OfferedResources = new List + { + new ResourceAmountDto { ResourceId = 1, Amount = 100 }, + new ResourceAmountDto { ResourceId = 2, Amount = 200 } + }, + RequestedResources = new List + { + new ResourceAmountDto { ResourceId = 3, Amount = 150 }, + new ResourceAmountDto { ResourceId = 4, Amount = 250 } + } + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/Trade/CreateTradeAgreementWithResources", content); - var response = await _client.GetAsync("/api/trade/OfferedTradeAgreements"); response.EnsureSuccessStatusCode(); + + XAssert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] - public async Task GetReceivedTradeAgreements_IsAuthenticated_ReturnsData() + public async Task PostTrade_InvalidData() { - var authResponse = await _client.GetAsync("/api/auth/status"); - authResponse.EnsureSuccessStatusCode(); - - var response = await _client.GetAsync("/api/trade/ReceivedTradeAgreements"); - response.EnsureSuccessStatusCode(); + var dto = new OfferTradeAgreementDTO + { + ReceivingNationId = 5, + Duration = 2, + Description = "Im description", + TradeStatus = TradeStatus.Pending, + OfferedResources = new List{}, + RequestedResources = new List{} + }; + + var json = JsonConvert.SerializeObject(dto); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _client.PostAsync("/api/Trade/CreateTradeAgreementWithResources", content); + + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } \ No newline at end of file diff --git a/Tests/Api/CustomWebApplicationFactory.cs b/Tests/Api/CustomWebApplicationFactory.cs index 555e1cf..fcf7e74 100644 --- a/Tests/Api/CustomWebApplicationFactory.cs +++ b/Tests/Api/CustomWebApplicationFactory.cs @@ -8,7 +8,7 @@ using Wg_backend_api.Data; using Wg_backend_api.Services; -namespace Tests +namespace Tests.Api { internal class TestingWebAppFactory : WebApplicationFactory { diff --git a/Tests/Api/DatabaseFixture.cs b/Tests/Api/DatabaseFixture.cs index c56cc31..984e201 100644 --- a/Tests/Api/DatabaseFixture.cs +++ b/Tests/Api/DatabaseFixture.cs @@ -1,5 +1,6 @@ using Xunit; +namespace Tests.Api; public class DatabaseFixture : IDisposable { public string ConnectionString { get; } diff --git a/Tests/Api/TestDatabaseManager.cs b/Tests/Api/TestDatabaseManager.cs index 4933b41..1740b08 100644 --- a/Tests/Api/TestDatabaseManager.cs +++ b/Tests/Api/TestDatabaseManager.cs @@ -1,6 +1,8 @@ using Npgsql; using System.Text.RegularExpressions; +namespace Tests.Api; + public static class TestDatabaseManager { private const string AdminConnection diff --git a/Tests/Api/TestGameDbContextFactory.cs b/Tests/Api/TestGameDbContextFactory.cs index 2dd28a5..774e24f 100644 --- a/Tests/Api/TestGameDbContextFactory.cs +++ b/Tests/Api/TestGameDbContextFactory.cs @@ -1,6 +1,8 @@ using Microsoft.EntityFrameworkCore; using Wg_backend_api.Data; +namespace Tests.Api; + public class TestGameDbContextFactory : IGameDbContextFactory { private readonly string _connectionString; diff --git a/Tests/Api/TestSessionDataService.cs b/Tests/Api/TestSessionDataService.cs index fd1e18a..e84add2 100644 --- a/Tests/Api/TestSessionDataService.cs +++ b/Tests/Api/TestSessionDataService.cs @@ -1,5 +1,6 @@ using Wg_backend_api.Services; +namespace Tests.Api; public class TestSessionDataService : ISessionDataService { private string _schema; diff --git a/Tests/Procesors/ResourceChangeProcessorTests.cs b/Tests/Procesors/ResourceChangeProcessorTests.cs index e8122ad..8c8cbff 100644 --- a/Tests/Procesors/ResourceChangeProcessorTests.cs +++ b/Tests/Procesors/ResourceChangeProcessorTests.cs @@ -6,8 +6,9 @@ using Wg_backend_api.Logic.Modifiers.Processors; using Wg_backend_api.Models; - -public class ResourceChangeProcessorTests +namespace Tests.Procesors +{ + public class ResourceChangeProcessorTests { private GameDbContext _context; private ResourceChangeProcessor _processor; @@ -107,3 +108,5 @@ public async Task CalculateChangeAsync_PercentageOperation_ReturnsCorrectValue() Assert.AreEqual(70f, result); // 50 (Add) + 20% of 100 = 70 } } + +} \ No newline at end of file diff --git a/Wg-backend-api/Controllers/GameControllers/TradeController.cs b/Wg-backend-api/Controllers/GameControllers/TradeController.cs index 83e61cb..21b06ec 100644 --- a/Wg-backend-api/Controllers/GameControllers/TradeController.cs +++ b/Wg-backend-api/Controllers/GameControllers/TradeController.cs @@ -142,15 +142,6 @@ public async Task> CreateTradeAgreementWithResources(int? offe this._context.TradeAgreements.Add(tradeAgreement); await this._context.SaveChangesAsync(); - if (tradeAgreement.Id.HasValue) - { - Console.WriteLine($"Wygenerowane ID: {tradeAgreement.Id.Value}"); - } - else - { - Console.WriteLine("ID nie zostało przypisane."); - } - foreach (var resource in offerTradeAgreementDTO.OfferedResources) { tradeAgreement.OfferedResources.Add(new OfferedResource From 4ba4313f1772c2c0fc39e1c8094711c4138f85a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Thu, 11 Dec 2025 17:39:48 +0100 Subject: [PATCH 5/6] format --- Tests/Api/ApiArmyTests.cs | 10 +- Tests/Api/ApiNationsTests.cs | 8 +- Tests/Api/ApiPopulationsTests.cs | 6 +- Tests/Api/ApiTradeTests.cs | 6 +- Tests/Api/CustomWebApplicationFactory.cs | 66 +++---- Tests/Api/TestDatabaseManager.cs | 6 +- .../PopulationHappinessProcessorTests.cs | 4 +- .../Procesors/ResourceChangeProcessorTests.cs | 174 +++++++++--------- 8 files changed, 140 insertions(+), 140 deletions(-) diff --git a/Tests/Api/ApiArmyTests.cs b/Tests/Api/ApiArmyTests.cs index 12d62fd..d9ad782 100644 --- a/Tests/Api/ApiArmyTests.cs +++ b/Tests/Api/ApiArmyTests.cs @@ -22,7 +22,7 @@ public ApiArmyTests(DatabaseFixture db) mockSession.Setup(s => s.GetSchema()).Returns("game_1"); mockSession.Setup(s => s.GetRole()).Returns("Player"); - var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1", mockSession); _client = _factory.CreateClient(); } @@ -75,7 +75,7 @@ public async Task PostArmy_ValidData() XAssert.Equal(HttpStatusCode.Created, response.StatusCode); var responseBody = await response.Content.ReadAsStringAsync(); - XAssert.Contains("303rd Squadron", responseBody); + XAssert.Contains("303rd Squadron", responseBody); } [Fact] @@ -94,7 +94,7 @@ public async Task PostArmy_InvalidLocationData() var response = await _client.PostAsync("/api/armies", content); - XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } [Fact] @@ -113,6 +113,6 @@ public async Task PostArmy_InvalidDataName() var response = await _client.PostAsync("/api/armies", content); - XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } } diff --git a/Tests/Api/ApiNationsTests.cs b/Tests/Api/ApiNationsTests.cs index 8971afb..2a8b5b7 100644 --- a/Tests/Api/ApiNationsTests.cs +++ b/Tests/Api/ApiNationsTests.cs @@ -57,7 +57,7 @@ public async Task GetNation_ValidNationStructure() response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); - + XAssert.Contains("id", json.ToLower()); XAssert.Contains("name", json.ToLower()); } @@ -80,7 +80,7 @@ public async Task PostNation_ValidData() var content = new MultipartFormDataContent { { new StringContent("Isengard"), "Name" }, - { new StringContent("1"), "ReligionId" }, + { new StringContent("1"), "ReligionId" }, { new StringContent("1"), "CultureId" }, { new StringContent(""), "Flag" }, { new StringContent("#FF0000"), "Color" }, @@ -109,7 +109,7 @@ public async Task PostNation_InvalidData() var content = new MultipartFormDataContent { { new StringContent("Isengard"), "Name" }, - { new StringContent(""), "ReligionId" }, + { new StringContent(""), "ReligionId" }, { new StringContent(""), "CultureId" }, { new StringContent(""), "Flag" }, { new StringContent("#FF0000"), "Color" }, @@ -117,6 +117,6 @@ public async Task PostNation_InvalidData() var response = await _client.PostAsync("/api/Nations", content); - XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + XAssert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } } diff --git a/Tests/Api/ApiPopulationsTests.cs b/Tests/Api/ApiPopulationsTests.cs index f03181e..e4d3c14 100644 --- a/Tests/Api/ApiPopulationsTests.cs +++ b/Tests/Api/ApiPopulationsTests.cs @@ -22,7 +22,7 @@ public ApiControllersTests(DatabaseFixture db) mockSession.Setup(s => s.GetSchema()).Returns("game_1"); mockSession.Setup(s => s.GetRole()).Returns("Player"); - var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1", mockSession); _client = _factory.CreateClient(); } @@ -33,7 +33,7 @@ public async Task GetPopulations_OkList() response.EnsureSuccessStatusCode(); XAssert.Equal(HttpStatusCode.OK, response.StatusCode); - + var json = await response.Content.ReadAsStringAsync(); XAssert.NotEmpty(json); } @@ -58,7 +58,7 @@ public async Task GetPopulation_InvalidId() public async Task PostPopulation_ValidData() { var dto = new List() - { new PopulationDTO{ + { new PopulationDTO{ ReligionId = 1, CultureId = 1, SocialGroupId = 1, diff --git a/Tests/Api/ApiTradeTests.cs b/Tests/Api/ApiTradeTests.cs index 3d0c67a..65fe14e 100644 --- a/Tests/Api/ApiTradeTests.cs +++ b/Tests/Api/ApiTradeTests.cs @@ -23,7 +23,7 @@ public ApiTradeTests(DatabaseFixture db) mockSession.Setup(s => s.GetSchema()).Returns("game_1"); mockSession.Setup(s => s.GetRole()).Returns("Player"); - var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1",mockSession); + var _factory = new TestingWebAppFactory(db.ConnectionString, schema: "game_1", nation: "1", mockSession); _client = _factory.CreateClient(); } @@ -115,8 +115,8 @@ public async Task PostTrade_InvalidData() Duration = 2, Description = "Im description", TradeStatus = TradeStatus.Pending, - OfferedResources = new List{}, - RequestedResources = new List{} + OfferedResources = new List { }, + RequestedResources = new List { } }; var json = JsonConvert.SerializeObject(dto); diff --git a/Tests/Api/CustomWebApplicationFactory.cs b/Tests/Api/CustomWebApplicationFactory.cs index fcf7e74..438a6e1 100644 --- a/Tests/Api/CustomWebApplicationFactory.cs +++ b/Tests/Api/CustomWebApplicationFactory.cs @@ -10,47 +10,47 @@ namespace Tests.Api { -internal class TestingWebAppFactory : WebApplicationFactory -{ - private readonly string _connectionString; - private readonly string _schema = "game_1"; - private readonly string _nation = "1"; - private readonly Mock _sessionDataService; - - - public TestingWebAppFactory(string connectionString, string schema, string nation, Mock sessionDataService) + internal class TestingWebAppFactory : WebApplicationFactory { - _connectionString = connectionString; - _schema = schema; - _nation = nation; - _sessionDataService = sessionDataService; - } + private readonly string _connectionString; + private readonly string _schema = "game_1"; + private readonly string _nation = "1"; + private readonly Mock _sessionDataService; - protected override void ConfigureWebHost(IWebHostBuilder builder) - { - builder.ConfigureServices(services => + public TestingWebAppFactory(string connectionString, string schema, string nation, Mock sessionDataService) { - services.AddSingleton(_sessionDataService); - services.RemoveAll(); - - services.AddSingleton(sp => - new TestGameDbContextFactory(_connectionString)); + _connectionString = connectionString; + _schema = schema; + _nation = nation; + _sessionDataService = sessionDataService; + } - services.RemoveAll(); - services.AddSingleton( - new TestSessionDataService(_schema, _nation, "Player")); + protected override void ConfigureWebHost(IWebHostBuilder builder) + { - services.AddAuthentication(options => + builder.ConfigureServices(services => { - options.DefaultAuthenticateScheme = "Test"; - options.DefaultChallengeScheme = "Test"; - }) - .AddScheme("Test", _ => { }); + services.AddSingleton(_sessionDataService); + services.RemoveAll(); + + services.AddSingleton(sp => + new TestGameDbContextFactory(_connectionString)); + + services.RemoveAll(); + services.AddSingleton( + new TestSessionDataService(_schema, _nation, "Player")); - }); + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = "Test"; + options.DefaultChallengeScheme = "Test"; + }) + .AddScheme("Test", _ => { }); - builder.UseEnvironment("Development"); + }); + + builder.UseEnvironment("Development"); + } } } -} diff --git a/Tests/Api/TestDatabaseManager.cs b/Tests/Api/TestDatabaseManager.cs index 1740b08..7d60ae2 100644 --- a/Tests/Api/TestDatabaseManager.cs +++ b/Tests/Api/TestDatabaseManager.cs @@ -5,7 +5,7 @@ namespace Tests.Api; public static class TestDatabaseManager { - private const string AdminConnection + private const string AdminConnection = "Host=localhost;Username=postgres;Password=postgres"; private const string TestDbName = "wg_test"; @@ -38,9 +38,9 @@ FROM pg_stat_activity cmd.ExecuteNonQuery(); } - var path = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "Api","wg-init-db-seeder.sql"); // hehe fuszera drut + var path = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "Api", "wg-init-db-seeder.sql"); // hehe fuszera drut string script = File.ReadAllText(path); - + script = Regex.Replace(script, @"^\\.*$", "", RegexOptions.Multiline); using var connection = new NpgsqlConnection(TestDbConnection); diff --git a/Tests/Procesors/PopulationHappinessProcessorTests.cs b/Tests/Procesors/PopulationHappinessProcessorTests.cs index 2db388e..7571759 100644 --- a/Tests/Procesors/PopulationHappinessProcessorTests.cs +++ b/Tests/Procesors/PopulationHappinessProcessorTests.cs @@ -189,11 +189,11 @@ public async Task ProcessAsync_LargeDataset_CompletesInReasonableTime() // Assert Assert.That(result.Success, Is.True); - + // The processor uses dynamic keys with timestamps, so we need to find the affected entities var affectedEntitiesKey = result.AffectedEntities.Keys.FirstOrDefault(k => k.StartsWith("affected_Population_")); Assert.That(affectedEntitiesKey, Is.Not.Null, "Expected to find an affected_Population key in results"); - + var changeRecord = result.AffectedEntities[affectedEntitiesKey] as ModifierChangeRecord; Assert.That(changeRecord, Is.Not.Null); Assert.That(changeRecord.Change, Is.EqualTo(100)); diff --git a/Tests/Procesors/ResourceChangeProcessorTests.cs b/Tests/Procesors/ResourceChangeProcessorTests.cs index 8c8cbff..d21eb07 100644 --- a/Tests/Procesors/ResourceChangeProcessorTests.cs +++ b/Tests/Procesors/ResourceChangeProcessorTests.cs @@ -7,106 +7,106 @@ using Wg_backend_api.Models; namespace Tests.Procesors -{ - public class ResourceChangeProcessorTests { - private GameDbContext _context; - private ResourceChangeProcessor _processor; - - [SetUp] - public void Setup() + public class ResourceChangeProcessorTests { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) - .Options; + private GameDbContext _context; + private ResourceChangeProcessor _processor; - _context = new GameDbContext(options, "test"); - _processor = new ResourceChangeProcessor(_context); - - SeedTestData(); - } - [TearDown] - public void TearDown() - { - _context.Dispose(); - } - private void SeedTestData() - { - // Seed test data - var nation = new Nation { Id = 1, Name = "TestNation", Color = "XXX"}; - var location = new Localisation { Id = 1, NationId = 1, Name = "TestLocation" }; - var resource = new Resource { Id = 1, Name = "Food" }; - var locResource = new LocalisationResource - { - Id = 1, - LocationId = 1, - ResourceId = 1, - Amount = 100f, - Location = location - }; - - var eventEntity = new Wg_backend_api.Models.Event { Id = 1, Name = "TestEvent" }; - var modifier = new Modifiers + [SetUp] + public void Setup() { - Id = 1, - EventId = 1, - ModifierType = ModifierType.ResourceChange, - Effects = new ModifierEffect() { Operation =ModifierOperation.Add, Value= 50, Conditions= new ResourceConditions() { ResourceId = 1 } } - }; - var relatedEvent = new RelatedEvents { EventId = 1, NationId = 1 }; - - _context.AddRange(nation, location, resource, locResource, eventEntity, modifier, relatedEvent); - _context.SaveChanges(); - } + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; - [Test] - public async Task CalculateChangeAsync_AddOperation_ReturnsCorrectValue() - { - // Arrange - var balance = new ResourceBalanceDto { ResourceId = 1 }; + _context = new GameDbContext(options, "test"); + _processor = new ResourceChangeProcessor(_context); - // Act - var result = await _processor.CalculateChangeAsync(1, balance); - - // Assert - Assert.AreEqual(50f, result); - } - - [Test] - public async Task CalculateChangeAsync_NoModifiers_ReturnsZero() - { - // Arrange - var balance = new ResourceBalanceDto { ResourceId = 999 }; // Non-existing resource + SeedTestData(); + } + [TearDown] + public void TearDown() + { + _context.Dispose(); + } + private void SeedTestData() + { + // Seed test data + var nation = new Nation { Id = 1, Name = "TestNation", Color = "XXX" }; + var location = new Localisation { Id = 1, NationId = 1, Name = "TestLocation" }; + var resource = new Resource { Id = 1, Name = "Food" }; + var locResource = new LocalisationResource + { + Id = 1, + LocationId = 1, + ResourceId = 1, + Amount = 100f, + Location = location + }; + + var eventEntity = new Wg_backend_api.Models.Event { Id = 1, Name = "TestEvent" }; + var modifier = new Modifiers + { + Id = 1, + EventId = 1, + ModifierType = ModifierType.ResourceChange, + Effects = new ModifierEffect() { Operation = ModifierOperation.Add, Value = 50, Conditions = new ResourceConditions() { ResourceId = 1 } } + }; + var relatedEvent = new RelatedEvents { EventId = 1, NationId = 1 }; + + _context.AddRange(nation, location, resource, locResource, eventEntity, modifier, relatedEvent); + _context.SaveChanges(); + } + + [Test] + public async Task CalculateChangeAsync_AddOperation_ReturnsCorrectValue() + { + // Arrange + var balance = new ResourceBalanceDto { ResourceId = 1 }; - // Act - var result = await _processor.CalculateChangeAsync(1, balance); + // Act + var result = await _processor.CalculateChangeAsync(1, balance); - // Assert - Assert.AreEqual(0f, result); - } + // Assert + Assert.AreEqual(50f, result); + } - [Test] - public async Task CalculateChangeAsync_PercentageOperation_ReturnsCorrectValue() - { - // Arrange - var modifier = new Modifiers + [Test] + public async Task CalculateChangeAsync_NoModifiers_ReturnsZero() { - Id = 2, - EventId = 1, - ModifierType = ModifierType.ResourceChange, - Effects = new ModifierEffect() { Operation = ModifierOperation.Percentage, Value = 20, Conditions = new ResourceConditions() { ResourceId = 1 } } - }; - _context.Modifiers.Add(modifier); - _context.SaveChanges(); + // Arrange + var balance = new ResourceBalanceDto { ResourceId = 999 }; // Non-existing resource - var balance = new ResourceBalanceDto { ResourceId = 1 }; + // Act + var result = await _processor.CalculateChangeAsync(1, balance); - // Act - var result = await _processor.CalculateChangeAsync(1, balance); + // Assert + Assert.AreEqual(0f, result); + } - // Assert - Assert.AreEqual(70f, result); // 50 (Add) + 20% of 100 = 70 + [Test] + public async Task CalculateChangeAsync_PercentageOperation_ReturnsCorrectValue() + { + // Arrange + var modifier = new Modifiers + { + Id = 2, + EventId = 1, + ModifierType = ModifierType.ResourceChange, + Effects = new ModifierEffect() { Operation = ModifierOperation.Percentage, Value = 20, Conditions = new ResourceConditions() { ResourceId = 1 } } + }; + _context.Modifiers.Add(modifier); + _context.SaveChanges(); + + var balance = new ResourceBalanceDto { ResourceId = 1 }; + + // Act + var result = await _processor.CalculateChangeAsync(1, balance); + + // Assert + Assert.AreEqual(70f, result); // 50 (Add) + 20% of 100 = 70 + } } -} } \ No newline at end of file From 1606ae73f7806da0dde3ab7b98ca3a501eb31e05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C5=9Aliwka?= Date: Thu, 11 Dec 2025 19:36:10 +0100 Subject: [PATCH 6/6] Delete console writeline --- Tests/Procesors/PopulationResourceProductionProcessorTests.cs | 4 ---- Wg-backend-api/Auth/AuthorizeGameRoleAttribute.cs | 1 - .../Controllers/GameControllers/MapAccessController.cs | 2 +- Wg-backend-api/Data/GameServices.cs | 4 ---- 4 files changed, 1 insertion(+), 10 deletions(-) diff --git a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs index b0a068d..a184a62 100644 --- a/Tests/Procesors/PopulationResourceProductionProcessorTests.cs +++ b/Tests/Procesors/PopulationResourceProductionProcessorTests.cs @@ -104,10 +104,6 @@ public async Task ProcessAsync_ProductionIncrease_UpdatesShare() // Act var result = await _processor.ProcessAsync(1, effects, _context); - // Assert - dodaj debug - Console.WriteLine($"Success: {result.Success}"); - Console.WriteLine($"Message: {result.Message}"); - Assert.That(result.Success, Is.True); var share = await _context.PopulationProductionShares.FindAsync(1); diff --git a/Wg-backend-api/Auth/AuthorizeGameRoleAttribute.cs b/Wg-backend-api/Auth/AuthorizeGameRoleAttribute.cs index 669c5ec..054ca22 100644 --- a/Wg-backend-api/Auth/AuthorizeGameRoleAttribute.cs +++ b/Wg-backend-api/Auth/AuthorizeGameRoleAttribute.cs @@ -15,7 +15,6 @@ public AuthorizeGameRoleAttribute(params string[] roles) public void OnAuthorization(AuthorizationFilterContext context) { var role = context.HttpContext.Items["RoleInGame"]?.ToString(); - Console.WriteLine($"AuthorizeGameRoleAttribute: User role in game is '{role}'."); if (string.IsNullOrEmpty(role) || !this._roles.Contains(role, StringComparer.OrdinalIgnoreCase)) { diff --git a/Wg-backend-api/Controllers/GameControllers/MapAccessController.cs b/Wg-backend-api/Controllers/GameControllers/MapAccessController.cs index 9989dfe..c187508 100644 --- a/Wg-backend-api/Controllers/GameControllers/MapAccessController.cs +++ b/Wg-backend-api/Controllers/GameControllers/MapAccessController.cs @@ -103,7 +103,7 @@ public async Task PostMapAccesses([FromBody] List ma.NationId == nationId && ma.MapId == mapId); - Console.WriteLine(existingMapAccess); + if (existingMapAccess != null) { return this.BadRequest("Map access already exists"); diff --git a/Wg-backend-api/Data/GameServices.cs b/Wg-backend-api/Data/GameServices.cs index 401b9cf..8d78b05 100644 --- a/Wg-backend-api/Data/GameServices.cs +++ b/Wg-backend-api/Data/GameServices.cs @@ -27,11 +27,9 @@ public bool GenerateNewGame(string sqlScriptPath, string schema) try { command.ExecuteNonQuery(); - Console.WriteLine($"Migracje zostały zastosowane dla schematu: {schema}"); } catch (Exception ex) { - Console.WriteLine($"Błąd podczas stosowania migracji dla schematu {schema}: {ex.Message}"); return false; } @@ -54,11 +52,9 @@ public bool DeleteGameSchema(string schema) try { command.ExecuteNonQuery(); - Console.WriteLine($"Schema {schema} has been deleted."); } catch (Exception ex) { - Console.WriteLine($"Error deleting schema {schema}: {ex.Message}"); return false; }