Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(playwrighttesting): Using dependency injection instead of BlobClient in TestProcessor #46807

Merged
merged 11 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Text;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Interface;
using Azure.Storage.Blobs;
using System.Threading.Tasks;

namespace Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Implementation
{
internal class BlobService:IBlobService
{
private readonly ILogger _logger;

public BlobService(ILogger? logger)
{
_logger = logger ?? new Logger();
}

public async Task UploadBufferAsync(string uri, string buffer, string fileRelativePath)
{
try
{
string cloudFilePath = GetCloudFilePath(uri, fileRelativePath);
BlobClient blobClient = new(new Uri(cloudFilePath));
byte[] bufferBytes = Encoding.UTF8.GetBytes(buffer);
await blobClient.UploadAsync(new BinaryData(bufferBytes), overwrite: true).ConfigureAwait(false);
_logger.Info($"Uploaded buffer to {fileRelativePath}");
}
catch (Exception ex)
{
_logger.Error($"Failed to upload buffer: {ex}");
}
}

public string GetCloudFilePath(string uri, string fileRelativePath)
{
string[] parts = uri.Split(new string[] { ReporterConstants.s_sASUriSeparator }, StringSplitOptions.None);
string containerUri = parts[0];
string sasToken = parts.Length > 1 ? parts[1] : string.Empty;

return $"{containerUri}/{fileRelativePath}?{sasToken}";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading.Tasks;
namespace Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Interface
{
internal interface IBlobService
{
/// <summary>
///
/// </summary>
/// <param name="uri"></param>
/// <param name="buffer"></param>
/// <param name="fileRelativePath"></param>
/// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
Task UploadBufferAsync(string uri, string buffer, string fileRelativePath);
string GetCloudFilePath(string uri, string fileRelativePath);
kashish2508 marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Implementation;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Interface;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Model;
Expand All @@ -28,6 +29,7 @@ internal class TestProcessor : ITestProcessor
private readonly IConsoleWriter _consoleWriter;
private readonly CIInfo _cIInfo;
private readonly CloudRunMetadata _cloudRunMetadata;
private readonly IBlobService _blobService;

// Test Metadata
internal int TotalTestCount { get; set; } = 0;
Expand All @@ -42,7 +44,7 @@ internal class TestProcessor : ITestProcessor
internal TestRunShardDto? _testRunShard;
internal TestResultsUri? _testResultsSasUri;

public TestProcessor(CloudRunMetadata cloudRunMetadata, CIInfo cIInfo, ILogger? logger = null, IDataProcessor? dataProcessor = null, ICloudRunErrorParser? cloudRunErrorParser = null, IServiceClient? serviceClient = null, IConsoleWriter? consoleWriter = null)
public TestProcessor(CloudRunMetadata cloudRunMetadata, CIInfo cIInfo, ILogger? logger = null, IDataProcessor? dataProcessor = null, ICloudRunErrorParser? cloudRunErrorParser = null, IServiceClient? serviceClient = null, IConsoleWriter? consoleWriter = null, IBlobService? blobService = null)
{
_cloudRunMetadata = cloudRunMetadata;
_cIInfo = cIInfo;
Expand All @@ -51,6 +53,7 @@ public TestProcessor(CloudRunMetadata cloudRunMetadata, CIInfo cIInfo, ILogger?
_cloudRunErrorParser = cloudRunErrorParser ?? new CloudRunErrorParser(_logger);
_serviceClient = serviceClient ?? new ServiceClient(_cloudRunMetadata, _cloudRunErrorParser);
_consoleWriter = consoleWriter ?? new ConsoleWriter();
_blobService = blobService ?? new BlobService(_logger);
}

public void TestRunStartHandler(object? sender, TestRunStartEventArgs e)
Expand Down Expand Up @@ -171,7 +174,7 @@ public void TestRunCompleteHandler(object? sender, TestRunCompleteEventArgs e)
// Upload rawResult to blob storage using sasUri
var rawTestResultJson = JsonSerializer.Serialize(rawResult);
var filePath = $"{testResult.TestExecutionId}/rawTestResult.json";
UploadBuffer(sasUri!.Uri!, rawTestResultJson, filePath);
UploadBuffer(sasUri!.Uri!, rawTestResultJson, filePath);
}
else
{
Expand Down Expand Up @@ -237,7 +240,7 @@ private void UploadAttachment(TestResultEventArgs e, string testExecutionId)
}
}

private TestResultsUri? CheckAndRenewSasUri()
public TestResultsUri? CheckAndRenewSasUri()
{
var reporterUtils = new ReporterUtils();
if (_testResultsSasUri == null || !reporterUtils.IsTimeGreaterThanCurrentPlus10Minutes(_testResultsSasUri.Uri))
Expand Down Expand Up @@ -270,26 +273,14 @@ private void EndTestRun(TestRunCompleteEventArgs e)
}
_cloudRunErrorParser.DisplayMessages();
}
private static string GetCloudFilePath(string uri, string fileRelativePath)
private void UploadBuffer(string uri, string buffer, string fileRelativePath)
kashish2508 marked this conversation as resolved.
Show resolved Hide resolved
{
string[] parts = uri.Split(new string[] { ReporterConstants.s_sASUriSeparator }, StringSplitOptions.None);
string containerUri = parts[0];
string sasToken = parts.Length > 1 ? parts[1] : string.Empty;

return $"{containerUri}/{fileRelativePath}?{sasToken}";
}
private void UploadBuffer(string uri, string buffer, string fileRelativePath)
{
string cloudFilePath = GetCloudFilePath(uri, fileRelativePath);
BlobClient blobClient = new(new Uri(cloudFilePath));
byte[] bufferBytes = Encoding.UTF8.GetBytes(buffer);
blobClient.Upload(new BinaryData(bufferBytes), overwrite: true);
_logger.Info($"Uploaded buffer to {fileRelativePath}");
_blobService.UploadBufferAsync(uri, buffer, fileRelativePath);
}

private void UploadBlobFile(string uri, string fileRelativePath, string filePath)
kashish2508 marked this conversation as resolved.
Show resolved Hide resolved
{
string cloudFilePath = GetCloudFilePath(uri, fileRelativePath);
string cloudFilePath = _blobService.GetCloudFilePath(uri, fileRelativePath);
BlobClient blobClient = new(new Uri(cloudFilePath));
// Upload filePath to Blob
blobClient.Upload(filePath, overwrite: true);
kashish2508 marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Text;
using System.Threading.Tasks;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Implementation;
using Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Interface;
using Moq;
using NUnit.Framework;

namespace Azure.Developer.MicrosoftPlaywrightTesting.TestLogger.Tests.Implementation
{
[TestFixture]
[Parallelizable(ParallelScope.Self)]
public class BlobServiceTests
{
private Mock<ILogger>? _loggerMock;
private BlobService? _blobService;

[SetUp]
public void Setup()
{
_loggerMock = new Mock<ILogger>();
_blobService = new BlobService(_loggerMock.Object);
}
[Test]
public async Task UploadBufferAsync_WithException_LogsError()
{
string uri = "invalid_uri";
string buffer = "Test buffer";
string fileRelativePath = "test/path";

await _blobService!.UploadBufferAsync(uri, buffer, fileRelativePath);

_loggerMock!.Verify(logger => logger.Error(It.IsAny<string>()), Times.Once);
}

[Test]
public void GetCloudFilePath_WithValidParameters_ReturnsCorrectPath()
{
string uri = "https://example.com/container";
string fileRelativePath = "test/path";
kashish2508 marked this conversation as resolved.
Show resolved Hide resolved
string expectedPath = "https://example.com/container/test/path?";

string? result = _blobService?.GetCloudFilePath(uri, fileRelativePath);

Assert.AreEqual(expectedPath, result);
}

[Test]
public void GetCloudFilePath_WithSasUri_ReturnsCorrectPath()
{
string uri = "https://example.com/container?sasToken";
string fileRelativePath = "test/path";
string expectedPath = "https://example.com/container/test/path?sasToken";

string? result = _blobService?.GetCloudFilePath(uri, fileRelativePath);

Assert.AreEqual(expectedPath, result);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -580,5 +580,38 @@ public void TestRunCompleteHandler_EnableResultPublishSetToFalse_DisplaysMessage
serviceClientMock.Verify(c => c.PostTestRunShardInfo(It.IsAny<TestRunShardDto>()), Times.Never);
cloudRunErrorParserMock.Verify(c => c.DisplayMessages(), Times.Exactly(1));
}
[Test]
public void CheckAndRenewSasUri_WhenUriExpired_FetchesNewSasUri()
{
var loggerMock = new Mock<ILogger>();
var dataProcessorMock = new Mock<IDataProcessor>();
var consoleWriterMock = new Mock<IConsoleWriter>();
var cloudRunErrorParserMock = new Mock<ICloudRunErrorParser>();
var serviceClientMock = new Mock<IServiceClient>();
var testProcessor = new TestProcessor(_cloudRunMetadata, _cIInfo, loggerMock.Object, dataProcessorMock.Object, cloudRunErrorParserMock.Object, serviceClientMock.Object, consoleWriterMock.Object);
var expiredTestResultsSasUri = new TestResultsUri { Uri = "http://example.com", ExpiresAt = DateTime.UtcNow.AddMinutes(-5).ToString(), AccessLevel = AccessLevel.Read };
var newTestResultsSasUri = new TestResultsUri { Uri = "http://newexample.com", ExpiresAt = DateTime.UtcNow.AddHours(1).ToString(), AccessLevel = AccessLevel.Read };
testProcessor._testResultsSasUri = expiredTestResultsSasUri;
serviceClientMock.Setup(sc => sc.GetTestRunResultsUri()).Returns(newTestResultsSasUri);
TestResultsUri? result = testProcessor.CheckAndRenewSasUri();
Assert.AreEqual(newTestResultsSasUri, result);
loggerMock.Verify(l => l.Info(It.IsAny<string>()), Times.AtLeastOnce);
}
[Test]
public void CheckAndRenewSasUri_WhenUriNotExpired_DoesNotFetchNewSasUri()
{
var loggerMock = new Mock<ILogger>();
var dataProcessorMock = new Mock<IDataProcessor>();
var consoleWriterMock = new Mock<IConsoleWriter>();
var cloudRunErrorParserMock = new Mock<ICloudRunErrorParser>();
var serviceClientMock = new Mock<IServiceClient>();
var testProcessor = new TestProcessor(_cloudRunMetadata, _cIInfo, loggerMock.Object, dataProcessorMock.Object, cloudRunErrorParserMock.Object, serviceClientMock.Object, consoleWriterMock.Object);
var validTestResultsSasUri = new TestResultsUri { Uri = "http://example.com?se=" + DateTime.UtcNow.AddMinutes(15).ToString("o"), ExpiresAt = DateTime.UtcNow.AddMinutes(15).ToString(), AccessLevel = AccessLevel.Read };
testProcessor._testResultsSasUri = validTestResultsSasUri;
TestResultsUri? result = testProcessor.CheckAndRenewSasUri();
Assert.AreEqual(validTestResultsSasUri, result);
serviceClientMock.Verify(sc => sc.GetTestRunResultsUri(), Times.Never);
loggerMock.Verify(l => l.Info(It.IsAny<string>()), Times.Never);
}
}
}