Skip to content

Commit

Permalink
replace TestFramework package usage (#6690)
Browse files Browse the repository at this point in the history
Co-authored-by: JhontSouth <[email protected]>
  • Loading branch information
ceciliaavila and JhontSouth authored Sep 18, 2023
1 parent 2d09ba8 commit 946f9d4
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 3 deletions.
1 change: 0 additions & 1 deletion tests/Microsoft.Bot.Connector.Tests/BaseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Bot.Schema;
using Microsoft.Rest;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Moq;

namespace Microsoft.Bot.Connector.Tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.7.0" />
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.4" />
<PackageReference Include="Microsoft.Azure.Test.HttpRecorder" Version="1.13.3" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.1" />
<PackageReference Include="Microsoft.Rest.ClientRuntime.Azure.TestFramework" Version="1.7.7" />
<PackageReference Include="Moq" Version="4.13.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RichardSzalay.MockHttp" Version="6.0.0" />
Expand Down
103 changes: 103 additions & 0 deletions tests/Microsoft.Bot.Connector.Tests/MockContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Azure.Test.HttpRecorder.ProcessRecordings;

namespace Microsoft.Bot.Connector.Tests
{
/// <summary>
/// A coordinator for tracking and undoing WAML operations. Usage pattern is
/// using(MockContext.Create())
/// {
/// maml stuff
/// }
/// You can also manually call the Dispose() or UndoAll() methods to undo all 'undoable' operations since the
/// UndoContext was created.
/// Call: MockContext.Commit() to remove all undo information.
/// </summary>
public class MockContext : IDisposable
{
//prevent multiple dispose events
private bool disposed = false;
private List<ResourceGroupCleaner> undoHandlers = new List<ResourceGroupCleaner>();

internal bool OptimizeTestRecordingFile { get; set; } = false;

/// <summary>
/// Initialize a new MockContext.
/// </summary>
/// <param name="className">The class name to identify the mock server.</param>
/// <returns>Returns a new MockContext.</returns>
/// <param name="methodName">The name method used for the test.</param>
public static MockContext Start(
string className,
[System.Runtime.CompilerServices.CallerMemberName]
string methodName = "testframework_failed")
{
var context = new MockContext();
if (HttpMockServer.FileSystemUtilsObject == null)
{
HttpMockServer.FileSystemUtilsObject = new FileSystemUtils();
}

HttpMockServer.Initialize(className, methodName);
if (HttpMockServer.Mode != HttpRecorderMode.Playback)
{
context.disposed = false;
}

return context;
}

/// <summary>
/// Dispose the object.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}

/// <summary>
/// Stop recording and Discard all undo information.
/// </summary>
public void Stop()
{
if (HttpMockServer.Mode != HttpRecorderMode.Playback)
{
foreach (var undoHandler in undoHandlers)
{
undoHandler.DeleteResourceGroups().ConfigureAwait(false).GetAwaiter().GetResult();
}
}

string recordedFilePath = HttpMockServer.Flush();

if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
// this check should be removed once we make the optimizatoin default
if (OptimizeTestRecordingFile)
{
ProcessRecordedFiles procRecFile = new ProcessRecordedFiles(recordedFilePath);
procRecFile.CompactLroPolling();
procRecFile.SerializeCompactData();
}
}
}

/// <summary>
/// Dispose only if we have not previously been disposed.
/// </summary>
/// <param name="disposing">true if we should dispose, otherwise false.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing && !this.disposed)
{
this.Stop();
this.disposed = true;
}
}
}
}
61 changes: 61 additions & 0 deletions tests/Microsoft.Bot.Connector.Tests/ResourceGroupCleaner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;

namespace Microsoft.Bot.Connector.Tests
{
public class ResourceGroupCleaner : DelegatingHandler
{
private Regex _resourceGroupPattern = new Regex(@"/subscriptions/[^/]+/resourcegroups/([^?]+)\?api-version");
private HashSet<string> _resourceGroupsCreated = new HashSet<string>();
private TokenCredentials _tokenCredentials;

public ResourceGroupCleaner(TokenCredentials tokenCredentials)
{
_tokenCredentials = tokenCredentials;
}

public async Task DeleteResourceGroups()
{
HttpClient httpClient = new HttpClient();
foreach (var resourceGroupUri in _resourceGroupsCreated)
{
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(resourceGroupUri);

_tokenCredentials.ProcessHttpRequestAsync(httpRequest, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();

HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest).ConfigureAwait(false);
string groupName = _resourceGroupPattern.Match(resourceGroupUri).Groups[1].Value;
string message = string.Format(
CultureInfo.InvariantCulture,
"Started deletion of resource group '{0}'. Server responded with status code {1}.",
groupName,
httpResponse.StatusCode);
Console.WriteLine(message);
Debug.WriteLine(message);
}
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_resourceGroupPattern.IsMatch(request.RequestUri.AbsoluteUri) &&
request.Method == HttpMethod.Put)
{
_resourceGroupsCreated.Add(request.RequestUri.AbsoluteUri);
}

return base.SendAsync(request, cancellationToken);
}
}
}

0 comments on commit 946f9d4

Please sign in to comment.