You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

62 lines
2.4 KiB

  1. using System.Text;
  2. using System.Threading.Tasks;
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;
  4. using MQTTnet.Client;
  5. using MQTTnet.Client.Subscribing;
  6. using MQTTnet.Server;
  7. using MQTTnet.Tests.Mockups;
  8. namespace MQTTnet.Tests
  9. {
  10. [TestClass]
  11. public class Session_Tests
  12. {
  13. [TestMethod]
  14. public async Task Set_Session_Item()
  15. {
  16. using (var testEnvironment = new TestEnvironment())
  17. {
  18. var serverOptions = new MqttServerOptionsBuilder()
  19. .WithConnectionValidator(delegate (MqttConnectionValidatorContext context)
  20. {
  21. // Don't validate anything. Just set some session items.
  22. context.SessionItems["can_subscribe_x"] = true;
  23. context.SessionItems["default_payload"] = "Hello World";
  24. })
  25. .WithSubscriptionInterceptor(delegate (MqttSubscriptionInterceptorContext context)
  26. {
  27. if (context.TopicFilter.Topic == "x")
  28. {
  29. context.AcceptSubscription = context.SessionItems["can_subscribe_x"] as bool? == true;
  30. }
  31. })
  32. .WithApplicationMessageInterceptor(delegate (MqttApplicationMessageInterceptorContext context)
  33. {
  34. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(context.SessionItems["default_payload"] as string);
  35. });
  36. await testEnvironment.StartServerAsync(serverOptions);
  37. string receivedPayload = null;
  38. var client = await testEnvironment.ConnectClientAsync();
  39. client.UseApplicationMessageReceivedHandler(delegate(MqttApplicationMessageReceivedEventArgs args)
  40. {
  41. receivedPayload = args.ApplicationMessage.ConvertPayloadToString();
  42. });
  43. var subscribeResult = await client.SubscribeAsync("x");
  44. Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS0, subscribeResult.Items[0].ResultCode);
  45. var client2 = await testEnvironment.ConnectClientAsync();
  46. await client2.PublishAsync("x");
  47. await Task.Delay(1000);
  48. Assert.AreEqual("Hello World", receivedPayload);
  49. }
  50. }
  51. }
  52. }