Skip to content

Commit

Permalink
Removed Moq dependency from OpenTelemetry.Tests (#5128)
Browse files Browse the repository at this point in the history
  • Loading branch information
ngruson authored Dec 6, 2023
1 parent f11801d commit 3619a6f
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
using System.Diagnostics.Tracing;
using System.IO.MemoryMappedFiles;
using System.Text;
using Moq;
using OpenTelemetry.Tests;
using Xunit;

namespace OpenTelemetry.Internal.Tests;
Expand All @@ -41,47 +41,40 @@ public void SelfDiagnosticsEventListener_constructor_Invalid_Input()
[Fact]
public void SelfDiagnosticsEventListener_EventSourceSetup_LowerSeverity()
{
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
var configRefresher = new TestSelfDiagnosticsConfigRefresher();
_ = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Emitting a Verbose event. Or any EventSource event with lower severity than Error.
OpenTelemetrySdkEventSource.Log.ActivityStarted("Activity started", "1");
configRefresherMock.Verify(refresher => refresher.TryGetLogStream(It.IsAny<int>(), out It.Ref<Stream>.IsAny, out It.Ref<int>.IsAny), Times.Never());
Assert.False(configRefresher.TryGetLogStreamCalled);
}

[Fact]
public void SelfDiagnosticsEventListener_EventSourceSetup_HigherSeverity()
{
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
configRefresherMock.Setup(configRefresher => configRefresher.TryGetLogStream(It.IsAny<int>(), out It.Ref<Stream>.IsAny, out It.Ref<int>.IsAny))
.Returns(true);
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
var configRefresher = new TestSelfDiagnosticsConfigRefresher();
_ = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Emitting an Error event. Or any EventSource event with higher than or equal to to Error severity.
OpenTelemetrySdkEventSource.Log.TracerProviderException("TestEvent", "Exception Details");
configRefresherMock.Verify(refresher => refresher.TryGetLogStream(It.IsAny<int>(), out It.Ref<Stream>.IsAny, out It.Ref<int>.IsAny));
Assert.True(configRefresher.TryGetLogStreamCalled);
}

[Fact]
public void SelfDiagnosticsEventListener_WriteEvent()
{
// Arrange
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
var memoryMappedFile = MemoryMappedFile.CreateFromFile(LOGFILEPATH, FileMode.Create, null, 1024);
Stream stream = memoryMappedFile.CreateViewStream();
var configRefresher = new TestSelfDiagnosticsConfigRefresher(stream);
string eventMessage = "Event Message";
int timestampPrefixLength = "2020-08-14T20:33:24.4788109Z:".Length;
byte[] bytes = Encoding.UTF8.GetBytes(eventMessage);
int availableByteCount = 100;
configRefresherMock.Setup(configRefresher => configRefresher.TryGetLogStream(timestampPrefixLength + bytes.Length + 1, out stream, out availableByteCount))
.Returns(true);
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Act: call WriteEvent method directly
listener.WriteEvent(eventMessage, null);

// Assert
configRefresherMock.Verify(refresher => refresher.TryGetLogStream(timestampPrefixLength + bytes.Length + 1, out stream, out availableByteCount));
Assert.True(configRefresher.TryGetLogStreamCalled);
stream.Dispose();
memoryMappedFile.Dispose();
AssertFileOutput(LOGFILEPATH, eventMessage);
Expand All @@ -90,18 +83,18 @@ public void SelfDiagnosticsEventListener_WriteEvent()
[Fact]
public void SelfDiagnosticsEventListener_DateTimeGetBytes()
{
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
var configRefresher = new TestSelfDiagnosticsConfigRefresher();
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Check DateTimeKind of Utc, Local, and Unspecified
DateTime[] datetimes = new DateTime[]
{
DateTime[] datetimes =
[
DateTime.SpecifyKind(DateTime.Parse("1996-12-01T14:02:31.1234567-08:00"), DateTimeKind.Utc),
DateTime.SpecifyKind(DateTime.Parse("1996-12-01T14:02:31.1234567-08:00"), DateTimeKind.Local),
DateTime.SpecifyKind(DateTime.Parse("1996-12-01T14:02:31.1234567-08:00"), DateTimeKind.Unspecified),
DateTime.UtcNow,
DateTime.Now,
};
];

// Expect to match output string from DateTime.ToString("O")
string[] expected = new string[datetimes.Length];
Expand Down Expand Up @@ -129,18 +122,16 @@ public void SelfDiagnosticsEventListener_DateTimeGetBytes()
public void SelfDiagnosticsEventListener_EmitEvent_OmitAsConfigured()
{
// Arrange
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
var configRefresher = new TestSelfDiagnosticsConfigRefresher();
var memoryMappedFile = MemoryMappedFile.CreateFromFile(LOGFILEPATH, FileMode.Create, null, 1024);
Stream stream = memoryMappedFile.CreateViewStream();
configRefresherMock.Setup(configRefresher => configRefresher.TryGetLogStream(It.IsAny<int>(), out stream, out It.Ref<int>.IsAny))
.Returns(true);
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
_ = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Act: emit an event with severity lower than configured
OpenTelemetrySdkEventSource.Log.ActivityStarted("ActivityStart", "123");

// Assert
configRefresherMock.Verify(refresher => refresher.TryGetLogStream(It.IsAny<int>(), out stream, out It.Ref<int>.IsAny), Times.Never());
Assert.False(configRefresher.TryGetLogStreamCalled);
stream.Dispose();
memoryMappedFile.Dispose();

Expand All @@ -154,18 +145,16 @@ public void SelfDiagnosticsEventListener_EmitEvent_OmitAsConfigured()
public void SelfDiagnosticsEventListener_EmitEvent_CaptureAsConfigured()
{
// Arrange
var configRefresherMock = new Mock<SelfDiagnosticsConfigRefresher>();
var memoryMappedFile = MemoryMappedFile.CreateFromFile(LOGFILEPATH, FileMode.Create, null, 1024);
Stream stream = memoryMappedFile.CreateViewStream();
configRefresherMock.Setup(configRefresher => configRefresher.TryGetLogStream(It.IsAny<int>(), out stream, out It.Ref<int>.IsAny))
.Returns(true);
var listener = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresherMock.Object);
var configRefresher = new TestSelfDiagnosticsConfigRefresher(stream);
_ = new SelfDiagnosticsEventListener(EventLevel.Error, configRefresher);

// Act: emit an event with severity equal to configured
OpenTelemetrySdkEventSource.Log.TracerProviderException("TestEvent", "Exception Details");

// Assert
configRefresherMock.Verify(refresher => refresher.TryGetLogStream(It.IsAny<int>(), out stream, out It.Ref<int>.IsAny));
Assert.True(configRefresher.TryGetLogStreamCalled);
stream.Dispose();
memoryMappedFile.Dispose();

Expand Down
1 change: 0 additions & 1 deletion test/OpenTelemetry.Tests/OpenTelemetry.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" PrivateAssets="All">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
Expand Down
35 changes: 35 additions & 0 deletions test/OpenTelemetry.Tests/TestSelfDiagnosticsConfigRefresher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// <copyright file="TestSelfDiagnosticsConfigRefresher.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System.Diagnostics.CodeAnalysis;
using OpenTelemetry.Internal;

namespace OpenTelemetry.Tests;

internal class TestSelfDiagnosticsConfigRefresher(Stream stream = null) : SelfDiagnosticsConfigRefresher
{
private readonly Stream stream = stream;

public bool TryGetLogStreamCalled { get; private set; }

public override bool TryGetLogStream(int byteCount, [NotNullWhen(true)] out Stream stream, out int availableByteCount)
{
this.TryGetLogStreamCalled = true;
stream = this.stream;
availableByteCount = 0;
return true;
}
}
47 changes: 14 additions & 33 deletions test/OpenTelemetry.Tests/Trace/ParentBasedSamplerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// </copyright>

using System.Diagnostics;
using Moq;
using OpenTelemetry.Tests;
using Xunit;

namespace OpenTelemetry.Trace.Tests;
Expand Down Expand Up @@ -105,47 +105,28 @@ public void DoNotExamineLinks()
[InlineData(false, false)]
public void CustomSamplers(bool parentIsRemote, bool parentIsSampled)
{
var mockRepository = new MockRepository(MockBehavior.Strict);
var remoteParentSampled = mockRepository.Create<Sampler>();
var remoteParentNotSampled = mockRepository.Create<Sampler>();
var localParentSampled = mockRepository.Create<Sampler>();
var localParentNotSampled = mockRepository.Create<Sampler>();
var remoteParentSampled = new TestSampler();
var remoteParentNotSampled = new TestSampler();
var localParentSampled = new TestSampler();
var localParentNotSampled = new TestSampler();

var samplerUnderTest = new ParentBasedSampler(
new AlwaysOnSampler(), // root
remoteParentSampled.Object,
remoteParentNotSampled.Object,
localParentSampled.Object,
localParentNotSampled.Object);
remoteParentSampled,
remoteParentNotSampled,
localParentSampled,
localParentNotSampled);

var samplingParams = MakeTestParameters(parentIsRemote, parentIsSampled);

Mock<Sampler> invokedSampler;
if (parentIsRemote && parentIsSampled)
{
invokedSampler = remoteParentSampled;
}
else if (parentIsRemote && !parentIsSampled)
{
invokedSampler = remoteParentNotSampled;
}
else if (!parentIsRemote && parentIsSampled)
{
invokedSampler = localParentSampled;
}
else
{
invokedSampler = localParentNotSampled;
}

var expectedResult = new SamplingResult(SamplingDecision.RecordAndSample);
invokedSampler.Setup(sampler => sampler.ShouldSample(samplingParams)).Returns(expectedResult);

var actualResult = samplerUnderTest.ShouldSample(samplingParams);

mockRepository.VerifyAll();
Assert.Equal(parentIsRemote && parentIsSampled, remoteParentSampled.LatestSamplingParameters.Equals(samplingParams));
Assert.Equal(parentIsRemote && !parentIsSampled, remoteParentNotSampled.LatestSamplingParameters.Equals(samplingParams));
Assert.Equal(!parentIsRemote && parentIsSampled, localParentSampled.LatestSamplingParameters.Equals(samplingParams));
Assert.Equal(!parentIsRemote && !parentIsSampled, localParentNotSampled.LatestSamplingParameters.Equals(samplingParams));

Assert.Equal(expectedResult, actualResult);
mockRepository.VerifyNoOtherCalls();
}

[Fact]
Expand Down

0 comments on commit 3619a6f

Please sign in to comment.