Lista de estratégias de teste usando o simmy #113
marcialwushu
started this conversation in
Ideas
Replies: 2 comments
-
|
Aqui está um exemplo de código que demonstra como usar o Simmy juntamente com o MSTest para aplicar as seis estratégias mencionadas anteriormente: using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Polly;
using Polly.Contrib.Simmy;
using Polly.Contrib.Simmy.Latency;
using Polly.Contrib.Simmy.Outcomes;
using Polly.Contrib.Simmy.Utilities;
using System;
using System.Net.Http;
using System.Threading.Tasks;
[TestClass]
public class ChaosTestingWithSimmyTests
{
private IServiceProvider _serviceProvider;
private IHttpClientFactory _httpClientFactory;
[TestInitialize]
public void Initialize()
{
// Configuração do serviço de injeção de dependência
var services = new ServiceCollection();
services.AddHttpClient();
// Configuração do Simmy
services.AddSingleton<IEngineInjection, PollyInjection>();
services.AddSingleton<IMonkeyPolicy, ChaosPolicy>();
// Configuração do Polly
services.AddPolicyHandler(GetChaosPolicy);
_serviceProvider = services.BuildServiceProvider();
_httpClientFactory = _serviceProvider.GetRequiredService<IHttpClientFactory>();
}
[TestMethod]
public async Task TestLatencyInjection()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
});
}
[TestMethod]
public async Task TestExceptionInjection()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
});
}
[TestMethod]
public async Task TestConfigurableInjectionRate()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
});
}
[TestMethod]
public async Task TestCompositionOfPolicies()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
});
}
[TestMethod]
public async Task TestSelectiveInjection()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
});
}
[TestMethod]
public async Task TestExternalServiceSimulation()
{
var httpClient = _httpClientFactory.CreateClient();
await Policy
.Handle<Exception>()
.RetryAsync(3)
.ExecuteAsync(async () =>
{
var response = await httpClient.GetAsync("https://api.example |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
MSTest que executa uma requisição HTTP POST com corpo (body) e autenticação básica: using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Polly;
using Polly.Contrib.Simmy;
using Polly.Contrib.Simmy.Latency;
using Polly.Contrib.Simmy.Outcomes;
using Polly.Contrib.Simmy.Utilities;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
[TestClass]
public class HttpClientTests
{
private IServiceProvider _serviceProvider;
private IHttpClientFactory _httpClientFactory;
[TestInitialize]
public void Initialize()
{
// Configuração do serviço de injeção de dependência
var services = new ServiceCollection();
services.AddHttpClient();
// Configuração do Simmy
services.AddSingleton<IEngineInjection, PollyInjection>();
services.AddSingleton<IMonkeyPolicy, ChaosPolicy>();
// Configuração do Polly
services.AddPolicyHandler(GetChaosPolicy);
_serviceProvider = services.BuildServiceProvider();
_httpClientFactory = _serviceProvider.GetRequiredService<IHttpClientFactory>();
}
[TestMethod]
public async Task TestHttpPostWithBasicAuthAndBody()
{
var httpClient = _httpClientFactory.CreateClient();
// Configurar a autenticação básica
var username = "seu_usuario";
var password = "sua_senha";
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")));
httpClient.DefaultRequestHeaders.Authorization = authValue;
// Configurar o corpo da requisição
var requestBody = new { Nome = "Exemplo", Idade = 30 };
var jsonBody = JsonConvert.SerializeObject(requestBody);
var httpContent = new StringContent(jsonBody, Encoding.UTF8, "application/json");
// Executar a chamada HTTP POST
var response = await httpClient.PostAsync("https://api.example.com/endpoint", httpContent);
// Verificar o status da resposta
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
// Ler a resposta
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
private IAsyncPolicy<HttpResponseMessage> GetChaosPolicy(IServiceProvider serviceProvider)
{
var chaosPolicy = serviceProvider.GetRequiredService<IMonkeyPolicy>();
var latencyMonkey = MonkeyPolicy.InjectLatencyAsync(
latencyDuration: TimeSpan.FromSeconds(2),
injectionRate: 0.5, // 50% de chance de injeção de latência
enabled: true
);
var outcomePolicy = chaosPolicy
.WrapAsync(latencyMonkey)
.WrapAsync(MonkeyPolicy.InjectExceptionAsync(
injectionRate: 0.2, // 20% de chance de injeção de exceção
enabled: true
));
return outcomePolicy;
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
A biblioteca Simmy, juntamente com o Polly, pode ser usada para implementar várias estratégias de teste relacionadas à engenharia do caos. Aqui estão algumas estratégias comuns que podem ser aplicadas usando o Simmy:
Essas são apenas algumas das estratégias possíveis usando o Simmy para testes relacionados à engenharia do caos. A biblioteca oferece flexibilidade para adaptar as injeções de caos às suas necessidades específicas de teste e avaliar como seu sistema se comporta em cenários adversos.
Beta Was this translation helpful? Give feedback.
All reactions