mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-25 23:53:07 +08:00
Add Directory.Build.props. (#2120)
* Add Directory.Build.props. * Adjust Analysis related properties and add conditional enablement for ContinuousIntegrationBuild. * Adopt new changes in master --------- Co-authored-by: christian <6939810+chkr1011@users.noreply.github.com>
This commit is contained in:
@@ -119,9 +119,11 @@ public class MqttConnectionContextTest
|
||||
await Assert.ThrowsExactlyAsync<MqttCommunicationException>(() => ctx.ReceivePacketAsync(CancellationToken.None)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
class Startup
|
||||
sealed class Startup
|
||||
{
|
||||
#pragma warning disable CA1822
|
||||
public void Configure(IApplicationBuilder app)
|
||||
#pragma warning restore CA1822
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,12 @@ public abstract class BaseTestClass
|
||||
return new TestEnvironment(TestContext, protocolVersion, trackUnobservedTaskException);
|
||||
}
|
||||
|
||||
protected Task LongTestDelay()
|
||||
public static Task LongTestDelay()
|
||||
{
|
||||
return Task.Delay(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
protected Task MediumTestDelay()
|
||||
public static Task MediumTestDelay()
|
||||
{
|
||||
return Task.Delay(TimeSpan.FromSeconds(0.5));
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ public sealed class LowLevelMqttClient_Tests : BaseTestClass
|
||||
return await client.ReceiveAsync(CancellationToken.None) as MqttConnAckPacket;
|
||||
}
|
||||
|
||||
async Task<MqttSubAckPacket> Subscribe(ILowLevelMqttClient client, string topic)
|
||||
static async Task<MqttSubAckPacket> Subscribe(ILowLevelMqttClient client, string topic)
|
||||
{
|
||||
await client.SendAsync(
|
||||
new MqttSubscribePacket
|
||||
|
||||
@@ -73,7 +73,7 @@ public sealed class MqttClient_Connection_Tests : BaseTestClass
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsNotNull(exception);
|
||||
Assert.IsInstanceOfType(exception, typeof(MqttCommunicationException));
|
||||
Assert.IsInstanceOfType<MqttCommunicationException>(exception);
|
||||
}
|
||||
|
||||
await LongTestDelay(); // disconnected handler is called async
|
||||
@@ -161,7 +161,7 @@ public sealed class MqttClient_Connection_Tests : BaseTestClass
|
||||
Assert.AreEqual("test_value", eventArgs.UserProperties[0].Value);
|
||||
}
|
||||
|
||||
class TestClientKerberosAuthenticationHandler : IMqttEnhancedAuthenticationHandler
|
||||
sealed class TestClientKerberosAuthenticationHandler : IMqttEnhancedAuthenticationHandler
|
||||
{
|
||||
public async Task HandleEnhancedAuthenticationAsync(MqttEnhancedAuthenticationEventArgs eventArgs)
|
||||
{
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
@@ -122,8 +123,8 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
await Task.Delay(500);
|
||||
|
||||
Assert.IsNotNull(ex);
|
||||
Assert.IsInstanceOfType(ex, typeof(MqttCommunicationException));
|
||||
Assert.IsInstanceOfType(ex.InnerException, typeof(SocketException));
|
||||
Assert.IsInstanceOfType<MqttCommunicationException>(ex);
|
||||
Assert.IsInstanceOfType<SocketException>(ex.InnerException);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -245,8 +246,8 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsNotNull(exception);
|
||||
Assert.IsInstanceOfType(exception, typeof(MqttCommunicationException));
|
||||
Assert.IsInstanceOfType(exception.InnerException, typeof(SocketException));
|
||||
Assert.IsInstanceOfType<MqttCommunicationException>(exception);
|
||||
Assert.IsInstanceOfType<SocketException>(exception.InnerException);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +356,7 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
|
||||
async Task Handler1(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString());
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString(), CultureInfo.InvariantCulture);
|
||||
await Task.Delay(value);
|
||||
|
||||
lock (receivedValues)
|
||||
@@ -369,7 +370,7 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
await client2.PublishStringAsync("x", i.ToString());
|
||||
await client2.PublishStringAsync("x", i.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
@@ -401,7 +402,7 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
var client2 = await testEnvironment.ConnectClient();
|
||||
for (var i = MessagesCount; i > 0; i--)
|
||||
{
|
||||
await client2.PublishStringAsync("x", i.ToString(), MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
await client2.PublishStringAsync("x", i.ToString(CultureInfo.InvariantCulture), MqttQualityOfServiceLevel.ExactlyOnce);
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
@@ -415,7 +416,7 @@ public sealed class MqttClient_Tests : BaseTestClass
|
||||
|
||||
Task Handler1(MqttApplicationMessageReceivedEventArgs eventArgs)
|
||||
{
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString());
|
||||
var value = int.Parse(eventArgs.ApplicationMessage.ConvertPayloadToString(), CultureInfo.InvariantCulture);
|
||||
eventArgs.AutoAcknowledge = false;
|
||||
Task.Delay(value).ContinueWith(_ => eventArgs.AcknowledgeAsync(CancellationToken.None));
|
||||
|
||||
|
||||
@@ -220,7 +220,7 @@ public sealed class Rpc_Tests : BaseTestClass
|
||||
Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
|
||||
}
|
||||
|
||||
class TestTopicStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
sealed class TestTopicStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
{
|
||||
public MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context)
|
||||
{
|
||||
@@ -232,7 +232,7 @@ public sealed class Rpc_Tests : BaseTestClass
|
||||
}
|
||||
}
|
||||
|
||||
class TestParametersTopicGenerationStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
sealed class TestParametersTopicGenerationStrategy : IMqttRpcClientTopicGenerationStrategy
|
||||
{
|
||||
internal const string ExpectedParamName = "test_param_name";
|
||||
|
||||
|
||||
@@ -287,7 +287,7 @@ public sealed class MqttBufferReader_Tests
|
||||
|
||||
|
||||
// Helper class to build up a reference to elements of various types in a buffer
|
||||
class ElementReference
|
||||
sealed class ElementReference
|
||||
{
|
||||
public enum BufferElementType
|
||||
{
|
||||
|
||||
@@ -551,7 +551,7 @@ public sealed class MqttPacketSerialization_V3_Binary_Tests
|
||||
}
|
||||
|
||||
|
||||
void DeserializeAndCompare(MqttPacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
static void DeserializeAndCompare(MqttPacket packet, string expectedBase64Value, MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311)
|
||||
{
|
||||
var writer = WriterFactory();
|
||||
|
||||
|
||||
@@ -35,15 +35,15 @@ public sealed class MqttPacketBus_Tests
|
||||
|
||||
Assert.AreEqual(9, bus.TotalItemsCount);
|
||||
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPublishPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttSubAckPacket));
|
||||
Assert.IsInstanceOfType(bus.DequeueItemAsync(CancellationToken.None).Result.Packet, typeof(MqttPingRespPacket));
|
||||
Assert.IsInstanceOfType<MqttPublishPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttSubAckPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttPingRespPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttPublishPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttSubAckPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttPingRespPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttPublishPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttSubAckPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
Assert.IsInstanceOfType<MqttPingRespPacket>(bus.DequeueItemAsync(CancellationToken.None).Result.Packet);
|
||||
|
||||
Assert.AreEqual(0, bus.TotalItemsCount);
|
||||
}
|
||||
|
||||
@@ -3,19 +3,10 @@
|
||||
<PropertyGroup>
|
||||
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
<EnableNETAnalyzers>false</EnableNETAnalyzers>
|
||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||
<DisableImplicitAspNetCoreAnalyzers>true</DisableImplicitAspNetCoreAnalyzers>
|
||||
<NoWarn>1591;NETSDK1138;NU1803;NU1901;NU1902</NoWarn>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<NuGetAuditMode>all</NuGetAuditMode>
|
||||
<NuGetAudit>true</NuGetAudit>
|
||||
<NuGetAuditLevel>low</NuGetAuditLevel>
|
||||
<AnalysisLevel>latest-Recommended</AnalysisLevel>
|
||||
<LangVersion>default</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<NoWarn>$(NoWarn);CA1707</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -23,7 +14,6 @@
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.0" />
|
||||
<PackageReference Include="MSTest" Version="4.0.1" />
|
||||
|
||||
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ public sealed class MemoryMqttChannel : IMqttChannel
|
||||
|
||||
public EndPoint LocalEndPoint { get; set; }
|
||||
|
||||
public bool IsSecureConnection { get; } = false;
|
||||
public bool IsSecureConnection { get; }
|
||||
|
||||
public X509Certificate2 ClientCertificate { get; set; }
|
||||
|
||||
@@ -60,5 +60,6 @@ public sealed class MemoryMqttChannel : IMqttChannel
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stream.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
@@ -182,7 +181,9 @@ public sealed class TestEnvironment : IDisposable
|
||||
return new MqttRpcClient(await ConnectClient(), options);
|
||||
}
|
||||
|
||||
#pragma warning disable CA1822
|
||||
public TestApplicationMessageReceivedHandler CreateApplicationMessageHandler(IMqttClient mqttClient)
|
||||
#pragma warning restore CA1822
|
||||
{
|
||||
return new TestApplicationMessageReceivedHandler(mqttClient);
|
||||
}
|
||||
@@ -199,7 +200,7 @@ public sealed class TestEnvironment : IDisposable
|
||||
{
|
||||
var clientOptions = e.ClientOptions;
|
||||
var existingClientId = clientOptions.ClientId;
|
||||
if (existingClientId != null && !existingClientId.StartsWith(TestContext.TestName))
|
||||
if (existingClientId != null && !existingClientId.StartsWith(TestContext.TestName, StringComparison.InvariantCulture))
|
||||
{
|
||||
clientOptions.ClientId = TestContext.TestName + "_" + existingClientId;
|
||||
}
|
||||
@@ -257,7 +258,7 @@ public sealed class TestEnvironment : IDisposable
|
||||
if (TestContext != null)
|
||||
{
|
||||
// Null is used when the client id is assigned from the server!
|
||||
if (!string.IsNullOrEmpty(e.ClientId) && !e.ClientId.StartsWith(TestContext.TestName))
|
||||
if (!string.IsNullOrEmpty(e.ClientId) && !e.ClientId.StartsWith(TestContext.TestName, StringComparison.InvariantCulture))
|
||||
{
|
||||
TrackException(new InvalidOperationException($"Invalid client ID used ({e.ClientId}). It must start with UnitTest name."));
|
||||
e.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
|
||||
@@ -326,10 +327,10 @@ public sealed class TestEnvironment : IDisposable
|
||||
GC.WaitForFullGCComplete();
|
||||
GC.WaitForPendingFinalizers();
|
||||
|
||||
if (_exceptions.Any())
|
||||
if (_exceptions.Count > 0)
|
||||
{
|
||||
// ReSharper disable once ThrowExceptionInUnexpectedLocation
|
||||
throw new Exception($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
|
||||
throw new InvalidOperationException($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -387,7 +388,7 @@ public sealed class TestEnvironment : IDisposable
|
||||
{
|
||||
var message = $"Server had {_serverErrors.Count} errors (${string.Join(Environment.NewLine, _serverErrors)}).";
|
||||
Console.WriteLine(message);
|
||||
throw new Exception(message);
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,7 +401,7 @@ public sealed class TestEnvironment : IDisposable
|
||||
{
|
||||
var message = $"Client(s) had {_clientErrors.Count} errors (${string.Join(Environment.NewLine, _clientErrors)})";
|
||||
Console.WriteLine(message);
|
||||
throw new Exception(message);
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using MQTTnet.Diagnostics.Logger;
|
||||
|
||||
namespace MQTTnet.Tests.Mockups;
|
||||
@@ -13,12 +14,12 @@ public sealed class TestLogger : IMqttNetLogger
|
||||
|
||||
public bool IsEnabled { get; } = true;
|
||||
|
||||
public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
|
||||
public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception)
|
||||
{
|
||||
LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(new MqttNetLogMessage
|
||||
{
|
||||
Level = logLevel,
|
||||
Message = string.Format(message, parameters),
|
||||
Level = level,
|
||||
Message = string.Format(CultureInfo.InvariantCulture, message, parameters),
|
||||
Exception = exception
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class MqttTcpChannel_Tests
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Assert.IsInstanceOfType(exception, typeof(SocketException));
|
||||
Assert.IsInstanceOfType<SocketException>(exception);
|
||||
Assert.AreEqual(SocketError.OperationAborted, ((SocketException)exception).SocketErrorCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using MQTTnet.Internal;
|
||||
@@ -45,7 +46,7 @@ public class RoundtripTime_Tests
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
response = new TaskCompletionSource<string>();
|
||||
await senderClient.PublishStringAsync("test", DateTime.UtcNow.Ticks.ToString());
|
||||
await senderClient.PublishStringAsync("test", DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture));
|
||||
if (!response.Task.Wait(TimeSpan.FromSeconds(5)))
|
||||
{
|
||||
throw new TimeoutException();
|
||||
|
||||
@@ -350,7 +350,7 @@ public class General_Tests : BaseTestClass
|
||||
var isIntercepted = false;
|
||||
c2.ApplicationMessageReceivedAsync += e =>
|
||||
{
|
||||
isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(e.ApplicationMessage.Payload), StringComparison.Ordinal) == 0;
|
||||
isIntercepted = string.Equals("extended", Encoding.UTF8.GetString(e.ApplicationMessage.Payload), StringComparison.Ordinal);
|
||||
return CompletedTask.Instance;
|
||||
};
|
||||
|
||||
|
||||
@@ -295,10 +295,10 @@ public sealed class HotSwapCerts_Tests
|
||||
}
|
||||
}
|
||||
|
||||
class HotSwappableClientCertProvider : IMqttClientCertificatesProvider, IDisposable
|
||||
sealed class HotSwappableClientCertProvider : IMqttClientCertificatesProvider, IDisposable
|
||||
{
|
||||
X509Certificate2Collection _certificates;
|
||||
ConcurrentBag<X509Certificate2> _serverCerts = new ConcurrentBag<X509Certificate2>();
|
||||
ConcurrentBag<X509Certificate2> _serverCerts = new();
|
||||
|
||||
public HotSwappableClientCertProvider()
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// The .NET Foundation licenses this file to you under the MIT license.
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -16,10 +17,15 @@ namespace MQTTnet.Tests.Server;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
[TestClass]
|
||||
public sealed class MqttSubscriptionsManager_Tests : BaseTestClass
|
||||
public sealed class MqttSubscriptionsManager_Tests : BaseTestClass, IDisposable
|
||||
{
|
||||
MqttClientSubscriptionsManager _subscriptionsManager;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_subscriptionsManager?.Dispose();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MqttSubscriptionsManager_SubscribeAndUnsubscribeSingle()
|
||||
{
|
||||
@@ -46,7 +52,7 @@ public sealed class MqttSubscriptionsManager_Tests : BaseTestClass
|
||||
{
|
||||
TopicFilters =
|
||||
[
|
||||
new() { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }
|
||||
new MqttTopicFilter { Topic = "A/B/C", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce }
|
||||
]
|
||||
};
|
||||
|
||||
@@ -178,6 +184,48 @@ public sealed class MqttSubscriptionsManager_Tests : BaseTestClass
|
||||
CheckIsNotSubscribed("house/2/room/bed");
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void TestInitialize()
|
||||
{
|
||||
var logger = new TestLogger();
|
||||
var options = new MqttServerOptions();
|
||||
var retainedMessagesManager = new MqttRetainedMessagesManager(new MqttServerEventContainer(), logger);
|
||||
var eventContainer = new MqttServerEventContainer();
|
||||
var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger);
|
||||
|
||||
var session = new MqttSession(
|
||||
new MqttConnectPacket
|
||||
{
|
||||
ClientId = ""
|
||||
},
|
||||
new ConcurrentDictionary<object, object>(),
|
||||
options,
|
||||
eventContainer,
|
||||
retainedMessagesManager,
|
||||
clientSessionManager);
|
||||
|
||||
_subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager);
|
||||
}
|
||||
|
||||
void CheckIsNotSubscribed(string topic)
|
||||
{
|
||||
var result = CheckSubscriptions(topic, MqttQualityOfServiceLevel.AtMostOnce, "");
|
||||
Assert.IsFalse(result.IsSubscribed);
|
||||
}
|
||||
|
||||
void CheckIsSubscribed(string topic)
|
||||
{
|
||||
var result = CheckSubscriptions(topic, MqttQualityOfServiceLevel.AtMostOnce, "");
|
||||
Assert.IsTrue(result.IsSubscribed);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, result.QualityOfServiceLevel);
|
||||
}
|
||||
|
||||
CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel applicationMessageQoSLevel, string senderClientId)
|
||||
{
|
||||
MqttTopicHash.Calculate(topic, out var topicHash, out _, out _);
|
||||
return _subscriptionsManager.CheckSubscriptions(topic, topicHash, applicationMessageQoSLevel, senderClientId);
|
||||
}
|
||||
|
||||
async Task SubscribeToTopic(string topic)
|
||||
{
|
||||
var sp = new MqttSubscribePacket
|
||||
@@ -190,40 +238,4 @@ public sealed class MqttSubscriptionsManager_Tests : BaseTestClass
|
||||
|
||||
await _subscriptionsManager.Subscribe(sp, CancellationToken.None);
|
||||
}
|
||||
|
||||
void CheckIsSubscribed(string topic)
|
||||
{
|
||||
var result = CheckSubscriptions(topic, MqttQualityOfServiceLevel.AtMostOnce, "");
|
||||
Assert.IsTrue(result.IsSubscribed);
|
||||
Assert.AreEqual(MqttQualityOfServiceLevel.AtMostOnce, result.QualityOfServiceLevel);
|
||||
}
|
||||
|
||||
void CheckIsNotSubscribed(string topic)
|
||||
{
|
||||
var result = CheckSubscriptions(topic, MqttQualityOfServiceLevel.AtMostOnce, "");
|
||||
Assert.IsFalse(result.IsSubscribed);
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void TestInitialize()
|
||||
{
|
||||
var logger = new TestLogger();
|
||||
var options = new MqttServerOptions();
|
||||
var retainedMessagesManager = new MqttRetainedMessagesManager(new MqttServerEventContainer(), logger);
|
||||
var eventContainer = new MqttServerEventContainer();
|
||||
var clientSessionManager = new MqttClientSessionsManager(options, retainedMessagesManager, eventContainer, logger);
|
||||
|
||||
var session = new MqttSession(new MqttConnectPacket
|
||||
{
|
||||
ClientId = ""
|
||||
}, new ConcurrentDictionary<object, object>(), options, eventContainer, retainedMessagesManager, clientSessionManager);
|
||||
|
||||
_subscriptionsManager = new MqttClientSubscriptionsManager(session, new MqttServerEventContainer(), retainedMessagesManager, clientSessionManager);
|
||||
}
|
||||
|
||||
CheckSubscriptionsResult CheckSubscriptions(string topic, MqttQualityOfServiceLevel applicationMessageQoSLevel, string senderClientId)
|
||||
{
|
||||
MqttTopicHash.Calculate(topic, out var topicHash, out _, out _);
|
||||
return _subscriptionsManager.CheckSubscriptions(topic, topicHash, applicationMessageQoSLevel, senderClientId);
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public class Retained_Messages_Tests : BaseTestClass
|
||||
var c1 = await testEnvironment.ConnectClient();
|
||||
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[0]).WithRetainFlag().Build());
|
||||
await c1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload([]).WithRetainFlag().Build());
|
||||
|
||||
await c1.DisconnectAsync();
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ public class Security_Tests : BaseTestClass
|
||||
var clientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", testEnvironment.ServerPort).WithCredentials(username, password).Build();
|
||||
|
||||
var ex = await Assert.ThrowsExactlyAsync<MqttConnectingFailedException>(async () => await client.ConnectAsync(clientOptions));
|
||||
Assert.IsInstanceOfType(ex.InnerException, typeof(MqttProtocolViolationException));
|
||||
Assert.IsInstanceOfType<MqttProtocolViolationException>(ex.InnerException);
|
||||
Assert.AreEqual("Error while authenticating. If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2-22].", ex.Message, false);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// See the LICENSE file in the project root for more information.
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -222,7 +223,7 @@ public sealed class Subscribe_Tests : BaseTestClass
|
||||
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var so = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(i.ToString()).Build();
|
||||
var so = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(i.ToString(CultureInfo.InvariantCulture)).Build();
|
||||
|
||||
await c1.SubscribeAsync(so);
|
||||
|
||||
@@ -234,7 +235,7 @@ public sealed class Subscribe_Tests : BaseTestClass
|
||||
var messageBuilder = new MqttApplicationMessageBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
messageBuilder.WithTopic(i.ToString());
|
||||
messageBuilder.WithTopic(i.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
await c2.PublishAsync(messageBuilder.Build());
|
||||
|
||||
@@ -264,7 +265,7 @@ public sealed class Subscribe_Tests : BaseTestClass
|
||||
var optionsBuilder = new MqttClientSubscribeOptionsBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
optionsBuilder.WithTopicFilter(i.ToString());
|
||||
optionsBuilder.WithTopicFilter(i.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
await c1.SubscribeAsync(optionsBuilder.Build());
|
||||
@@ -274,7 +275,7 @@ public sealed class Subscribe_Tests : BaseTestClass
|
||||
var messageBuilder = new MqttApplicationMessageBuilder();
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
messageBuilder.WithTopic(i.ToString());
|
||||
messageBuilder.WithTopic(i.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
await c2.PublishAsync(messageBuilder.Build());
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ using MQTTnet.Tests.Mockups;
|
||||
namespace MQTTnet.Tests.Server;
|
||||
|
||||
[TestClass]
|
||||
public sealed class SubscriptionTopicHashTests
|
||||
public sealed class SubscriptionTopicHashTests : IDisposable
|
||||
{
|
||||
MqttSession _clientSession;
|
||||
|
||||
@@ -84,6 +84,11 @@ public sealed class SubscriptionTopicHashTests
|
||||
CheckTopicHash("client1/+/level1/#", 0x65004A0000000000, 0xFF00FF0000000000);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_clientSession?.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test long topic name with last level being #
|
||||
/// </summary>
|
||||
@@ -414,7 +419,7 @@ public sealed class SubscriptionTopicHashTests
|
||||
foreach (var t in topics)
|
||||
{
|
||||
// replace last letter with x
|
||||
topicsToFind.Add(t.Substring(0, t.Length - 1) + "x");
|
||||
topicsToFind.Add(string.Concat(t.AsSpan(0, t.Length - 1), "x"));
|
||||
}
|
||||
|
||||
matchCount = CheckTopicSubscriptions(_clientSession, topicsToFind, "No Wildcard No Match (Replace X)");
|
||||
@@ -468,7 +473,7 @@ public sealed class SubscriptionTopicHashTests
|
||||
Assert.AreEqual(0xff, hashMaskBytes[7], "mask 7 mismatch");
|
||||
}
|
||||
|
||||
void CheckTopicHash(string topic, ulong expectedHash, ulong expectedHashMask)
|
||||
static void CheckTopicHash(string topic, ulong expectedHash, ulong expectedHashMask)
|
||||
{
|
||||
MqttTopicHash.Calculate(topic, out var topicHash, out var hashMask, out _);
|
||||
|
||||
@@ -481,7 +486,7 @@ public sealed class SubscriptionTopicHashTests
|
||||
Assert.AreEqual(expectedHashMask, hashMask, "Topic hash mask not as expected");
|
||||
}
|
||||
|
||||
int CheckTopicSubscriptions(MqttSession clientSession, List<string> topicsToFind, string subject)
|
||||
static int CheckTopicSubscriptions(MqttSession clientSession, List<string> topicsToFind, string subject)
|
||||
{
|
||||
var matchCount = 0;
|
||||
|
||||
@@ -517,7 +522,7 @@ public sealed class SubscriptionTopicHashTests
|
||||
return matchCount;
|
||||
}
|
||||
|
||||
byte[] GetBytes(ulong value)
|
||||
static byte[] GetBytes(ulong value)
|
||||
{
|
||||
var bytes = BitConverter.GetBytes(value);
|
||||
// Ensure that highest byte comes first for comparison left to right
|
||||
|
||||
@@ -71,6 +71,6 @@ public sealed class Topic_Alias_Tests : BaseTestClass
|
||||
|
||||
Assert.HasCount(3, receivedTopics);
|
||||
CollectionAssert.AllItemsAreNotNull(receivedTopics);
|
||||
Assert.IsTrue(receivedTopics.All(t => t.Equals("this_is_the_topic")));
|
||||
Assert.IsTrue(receivedTopics.All(t => t.Equals("this_is_the_topic", System.StringComparison.Ordinal)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user