-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerTestsBase.cs
More file actions
159 lines (127 loc) · 5.96 KB
/
ControllerTestsBase.cs
File metadata and controls
159 lines (127 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SimpleResults;
using TransactionProcessor.Database.Contexts;
using TransactionProcessor.Database.Entities;
namespace EstateReportingAPI.IntegrationTests;
using System.Net.Http.Headers;
using System.Text;
using Azure;
using Client;
using Common;
using Ductus.FluentDocker.Services;
using Ductus.FluentDocker.Services.Extensions;
using NLog;
using Shared.IntegrationTesting;
using Shared.Logger;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
public abstract class ControllerTestsBase : IAsyncLifetime
{
protected List<Merchant> merchantsList;
protected List<(Guid contractId, String contractName, Guid operatorId, String operatorName)> contractList;
protected Dictionary<Guid, List<(Guid productId, String productName, Decimal? productValue)>> contractProducts;
protected DatabaseHelper helper;
protected ITestOutputHelper TestOutputHelper;
public virtual async Task InitializeAsync()
{
this.TestId = Guid.NewGuid();
await this.StartSqlContainer();
String dbConnString = GetLocalConnectionString($"EstateReportingReadModel{this.TestId}");
this.factory = new CustomWebApplicationFactory<Startup>(dbConnString);
this.Client = this.factory.CreateClient();
this.ApiClient = new EstateReportingApiClient((s) => "http://localhost", this.Client);
this.context = new EstateManagementContext(GetLocalConnectionString($"EstateReportingReadModel{this.TestId.ToString()}"));
this.helper = new DatabaseHelper(context);
await this.helper.CreateStoredProcedures(CancellationToken.None);
await this.SetupStandingData();
}
public virtual async Task DisposeAsync()
{
}
protected EstateManagementContext context;
protected abstract Task ClearStandingData();
protected abstract Task SetupStandingData();
protected HttpClient Client;
protected CustomWebApplicationFactory<Startup> factory;
protected EstateReportingApiClient ApiClient;
protected Guid TestId;
internal async Task<Result<T?>> CreateAndSendHttpRequestMessage<T>(String url, CancellationToken cancellationToken)
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
requestMessage.Headers.Add("estateId", this.TestId.ToString());
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Test");
HttpResponseMessage result = await this.Client.SendAsync(requestMessage, cancellationToken);
result.IsSuccessStatusCode.ShouldBeTrue(result.StatusCode.ToString());
String content = await result.Content.ReadAsStringAsync(cancellationToken);
content.ShouldNotBeNull();
return null;
}
internal async Task<Result<T?>> CreateAndSendHttpRequestMessage<T>(String url, String payload, CancellationToken cancellationToken)
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
requestMessage.Headers.Add("estateId", this.TestId.ToString());
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Test");
if (String.IsNullOrEmpty(payload) == false){
requestMessage.Content = new StringContent(payload, Encoding.UTF8, "application/json");
}
HttpResponseMessage result = await this.Client.SendAsync(requestMessage, cancellationToken);
result.IsSuccessStatusCode.ShouldBeTrue(result.StatusCode.ToString());
String content = await result.Content.ReadAsStringAsync(cancellationToken);
content.ShouldNotBeNull();
return null;
}
public static IContainerService DatabaseServerContainer;
public static INetworkService DatabaseServerNetwork;
public static (String usename, String password) SqlCredentials = ("sa", "thisisalongpassword123!");
public static String GetLocalConnectionString(String databaseName)
{
Int32 databaseHostPort = DatabaseServerContainer.ToHostExposedEndpoint("1433/tcp").Port;
return $"server=localhost,{databaseHostPort};database={databaseName};user id={SqlCredentials.usename};password={SqlCredentials.password};Encrypt=false";
}
internal async Task StartSqlContainer(){
DockerHelper dockerHelper = new TestDockerHelper();
NlogLogger logger = new NlogLogger();
logger.Initialise(LogManager.GetLogger("Specflow"), "Specflow");
LogManager.AddHiddenAssembly(typeof(NlogLogger).Assembly);
dockerHelper.Logger = logger;
dockerHelper.SqlCredentials = SqlCredentials;
dockerHelper.SqlServerContainerName = "sharedsqlserver";
dockerHelper.RequiredDockerServices = DockerServices.SqlServer;
DatabaseServerNetwork = dockerHelper.SetupTestNetwork("sharednetwork", true);
await Retry.For(async () => {
DatabaseServerContainer = await dockerHelper.SetupSqlServerContainer(DatabaseServerNetwork);
});
}
public void Dispose()
{
EstateManagementContext context = new EstateManagementContext(ControllerTestsBase.GetLocalConnectionString($"EstateReportingReadModel{this.TestId.ToString()}"));
Console.WriteLine($"About to delete database EstateReportingReadModel{this.TestId.ToString()}");
Boolean result = context.Database.EnsureDeleted();
Console.WriteLine($"Delete result is {result}");
result.ShouldBeTrue();
}
internal async Task<T> ExecuteAsyncFunction<T>(Func<Task<T>> asyncFunction)
{
try
{
// Execute the provided asynchronous function
return await asyncFunction();
}
catch (Exception ex)
{
// Handle exceptions here
Console.WriteLine($"An error occurred: {ex.Message}");
return default(T);
}
}
}
public class TestDockerHelper : DockerHelper{
public override async Task CreateSubscriptions(){
// Nothing here
}
}