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 same file access exception #3373

Merged
merged 7 commits into from
May 30, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
31 changes: 23 additions & 8 deletions src/Microsoft.TestPlatform.Extensions.HtmlLogger/HtmlLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public class HtmlLogger : ITestLoggerWithParameters
private readonly IFileHelper _fileHelper;
private readonly XmlObjectSerializer _xmlSerializer;
private readonly IHtmlTransformer _htmlTransformer;
private static readonly object FileCreateLockObject = new();
private Dictionary<string, string> _parametersDictionary;

public HtmlLogger()
Expand Down Expand Up @@ -301,25 +302,25 @@ private void PopulateHtmlFile()
Environment.GetEnvironmentVariable("UserName"), Environment.MachineName,
FormatDateTimeForRunName(DateTime.Now));

XmlFilePath = GetFilePath(HtmlLoggerConstants.XmlFileExtension, fileName);
XmlFilePath = GenerateUniqueFilePath(fileName, HtmlLoggerConstants.XmlFileExtension);

using (var xmlStream = _fileHelper.GetStream(XmlFilePath, FileMode.Create))
using (var xmlStream = _fileHelper.GetStream(XmlFilePath, FileMode.OpenOrCreate))
{
_xmlSerializer.WriteObject(xmlStream, TestRunDetails);
}

if (string.IsNullOrEmpty(HtmlFilePath))
{
HtmlFilePath = GetFilePath(HtmlLoggerConstants.HtmlFileExtension, fileName);
HtmlFilePath = GenerateUniqueFilePath(fileName, HtmlLoggerConstants.HtmlFileExtension);
}

_htmlTransformer.Transform(XmlFilePath, HtmlFilePath);
}
catch (Exception ex)
{
EqtTrace.Error("HtmlLogger : Failed to populate html file. Exception : {0}",
EqtTrace.Error("HtmlLogger: Failed to populate html file. Exception: {0}",
ex.ToString());
ConsoleOutput.Instance.Error(false, string.Concat(HtmlResource.HtmlLoggerError), ex.Message);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated change but there was no need for the string.Concat.

ConsoleOutput.Instance.Error(false, HtmlResource.HtmlLoggerError, ex.Message);
return;
}
finally
Expand All @@ -335,10 +336,24 @@ private void PopulateHtmlFile()
ConsoleOutput.Instance.Information(false, htmlFilePathMessage);
}

private string GetFilePath(string fileExtension, string fileName)
private string GenerateUniqueFilePath(string fileName, string fileExtension)
{
var fullFileFormat = $".{fileExtension}";
return Path.Combine(TestResultsDirPath, string.Concat("TestResult_", fileName, fullFileFormat));
string fullFilePath;
for (short i = 0; i < short.MaxValue; i++)
{
var fileNameWithIter = i == 0 ? fileName : Path.GetFileNameWithoutExtension(fileName) + $"[{i}]";
fullFilePath = Path.Combine(TestResultsDirPath, $"TestResult_{fileNameWithIter}.{fileExtension}");
lock (FileCreateLockObject)
{
if (!File.Exists(fullFilePath))
{
using var _ = File.Create(fullFilePath);
return fullFilePath;
}
}
}

throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, HtmlResource.CannotGenerateUniqueFilePath, fileName, TestResultsDirPath));
}

private string FormatDateTimeForRunName(DateTime timeStamp)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CannotGenerateUniqueFilePath" xml:space="preserve">
<value>Cannot generate a unique file name for name '{0}' on path '{1}'.</value>
</data>
<data name="HtmlFilePath" xml:space="preserve">
<value>Html test results file : {0}</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Parametry LogFileName a LogFilePrefix nelze uvést společně.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Die Parameter "LogFileName" und "LogFilePrefix" können nicht zusammen angegeben werden. </target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Los parámetros LogFileName y LogFilePrefix no se pueden proporcionar juntos.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Les paramètres LogFileName et LogFilePrefix ne peuvent pas être donnés ensemble. </target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Non è possibile specificare insieme i parametri LogFileName e LogFilePrefix.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">パラメーター LogFileName と LogFilePrefix を同時に指定することはできません。</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">LogFileName 및 LogFilePrefix 매개 변수는 함께 제공할 수 없습니다.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Parametry LogFileName i LogFilePrefix nie mogą być podawane razem. </target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Os parâmetros LogFileName e LogFilePrefix não podem ser usados juntos.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">Параметры LogFileName и LogFilePrefix не могут использоваться вместе.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">LogFileName ve LogFilePrefix parametreleri birlikte kullanılamaz. </target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="new">The parameters LogFileName and LogFilePrefix cannot be given together.</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">参数 LogFileName 和 LogFilePrefix 不能一起使用。</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
<target state="translated">不能同時指定參數 LogFileName 和 LogFilePrefix。</target>
<note></note>
</trans-unit>
<trans-unit id="CannotGenerateUniqueFilePath">
<source>Cannot generate a unique file name for name '{0}' on path '{1}'.</source>
<target state="new">Cannot generate a unique file name for name '{0}' on path '{1}'.</target>
<note></note>
</trans-unit>
</body>
</file>
</xliff>
2 changes: 1 addition & 1 deletion test/Microsoft.TestPlatform.AcceptanceTests/LoggerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public void HtmlLoggerWithExecutorUriShouldProperlyOverwriteFile(RunnerInfo runn

var arguments = PrepareArguments(GetSampleTestAssembly(), GetTestAdapterPath(), string.Empty, FrameworkArgValue, runnerInfo.InIsolationValue, TempDirectory.Path);
var htmlFileName = "TestResults.html";
arguments = string.Concat(arguments, $" /logger:\"logger://Microsoft/TestPlatform/htmlLogger/v1;LogFileName{htmlFileName}\"");
arguments = string.Concat(arguments, $" /logger:\"logger://Microsoft/TestPlatform/htmlLogger/v1;LogFileName={htmlFileName}\"");
InvokeVsTest(arguments);

arguments = PrepareArguments(GetSampleTestAssembly(), GetTestAdapterPath(), string.Empty, FrameworkArgValue, runnerInfo.InIsolationValue, TempDirectory.Path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ public void TestCompleteHandlerShouldKeepTackOfSummary()
}

[TestMethod]
public void TestCompleteHandlerShouldCreateCustumHtmlFileNamewithLogFileNameKey()
public void TestCompleteHandlerShouldCreateCustomHtmlFileNamewithLogFileNameKey()
{
var parameters = new Dictionary<string, string?>
{
Expand All @@ -415,7 +415,7 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNamewithLogFileNameKey(
}

[TestMethod]
public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefix()
public void TestCompleteHandlerShouldCreateCustomHtmlFileNameWithLogPrefix()
{
var parameters = new Dictionary<string, string>
{
Expand All @@ -435,7 +435,7 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefix()
}

[TestMethod]
public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixIfTargetFrameworkIsNull()
public void TestCompleteHandlerShouldCreateCustomHtmlFileNameWithLogPrefixIfTargetFrameworkIsNull()
{
var parameters = new Dictionary<string, string>
{
Expand All @@ -455,7 +455,7 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixIfTarg
}

[TestMethod]
public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixNull()
public void TestCompleteHandlerShouldCreateCustomHtmlFileNameWithLogPrefixNull()
{
var parameters = new Dictionary<string, string?>
{
Expand All @@ -468,14 +468,14 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixNull()
var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed };
var resultEventArg1 = new Mock<TestResultEventArgs>(result1);

_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
{
}).Returns(new Mock<Stream>().Object);

_htmlLogger.TestResultHandler(new object(), resultEventArg1.Object);
_htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero));

_mockFileHelper.Verify(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite), Times.Once);
_mockFileHelper.Verify(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite), Times.Once);
}

[TestMethod]
Expand Down Expand Up @@ -514,14 +514,14 @@ public void TestCompleteHandlerShouldCreateFileCorrectly()
var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed };
var resultEventArg1 = new Mock<TestResultEventArgs>(result1);

_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
{
}).Returns(new Mock<Stream>().Object);

_htmlLogger.TestResultHandler(new object(), resultEventArg1.Object);
_htmlLogger.TestRunCompleteHandler(new object(), new TestRunCompleteEventArgs(null, false, true, null, null, null, TimeSpan.Zero));

_mockFileHelper.Verify(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite), Times.Once);
_mockFileHelper.Verify(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite), Times.Once);
}

[TestMethod]
Expand All @@ -548,7 +548,7 @@ public void TestCompleteHandlerShouldCallHtmlTransformerCorrectly()
var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed };
var resultEventArg1 = new Mock<TestResultEventArgs>(result1);

_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
{
}).Returns(new Mock<Stream>().Object);

Expand All @@ -564,7 +564,7 @@ public void TestCompleteHandlerShouldWriteToXmlSerializerCorrectly()
var testCase1 = CreateTestCase("TestCase1") ?? throw new ArgumentNullException($"CreateTestCase(\"TestCase1\")");
var result1 = new ObjectModel.TestResult(testCase1) { Outcome = TestOutcome.Failed };
var resultEventArg1 = new Mock<TestResultEventArgs>(result1);
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
{
}).Returns(new Mock<Stream>().Object);

Expand All @@ -579,7 +579,7 @@ public void TestCompleteHandlerShouldWriteToXmlSerializerCorrectly()
[TestMethod]
public void TestCompleteHandlerShouldNotDivideByZeroWhenThereAre0TestResults()
{
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.Create, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
_mockFileHelper.Setup(x => x.GetStream(It.IsAny<string>(), FileMode.OpenOrCreate, FileAccess.ReadWrite)).Callback<string, FileMode, FileAccess>((x, y, z) =>
{
}).Returns(new Mock<Stream>().Object);

Expand Down