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.
 
 
 
 

64 lines
2.5 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. public TestContext TestContext { get; set; }
  14. [TestMethod]
  15. public async Task Set_Session_Item()
  16. {
  17. using (var testEnvironment = new TestEnvironment(TestContext))
  18. {
  19. var serverOptions = new MqttServerOptionsBuilder()
  20. .WithConnectionValidator(delegate (MqttConnectionValidatorContext context)
  21. {
  22. // Don't validate anything. Just set some session items.
  23. context.SessionItems["can_subscribe_x"] = true;
  24. context.SessionItems["default_payload"] = "Hello World";
  25. })
  26. .WithSubscriptionInterceptor(delegate (MqttSubscriptionInterceptorContext context)
  27. {
  28. if (context.TopicFilter.Topic == "x")
  29. {
  30. context.AcceptSubscription = context.SessionItems["can_subscribe_x"] as bool? == true;
  31. }
  32. })
  33. .WithApplicationMessageInterceptor(delegate (MqttApplicationMessageInterceptorContext context)
  34. {
  35. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(context.SessionItems["default_payload"] as string);
  36. });
  37. await testEnvironment.StartServerAsync(serverOptions);
  38. string receivedPayload = null;
  39. var client = await testEnvironment.ConnectClientAsync();
  40. client.UseApplicationMessageReceivedHandler(delegate(MqttApplicationMessageReceivedEventArgs args)
  41. {
  42. receivedPayload = args.ApplicationMessage.ConvertPayloadToString();
  43. });
  44. var subscribeResult = await client.SubscribeAsync("x");
  45. Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS0, subscribeResult.Items[0].ResultCode);
  46. var client2 = await testEnvironment.ConnectClientAsync();
  47. await client2.PublishAsync("x");
  48. await Task.Delay(1000);
  49. Assert.AreEqual("Hello World", receivedPayload);
  50. }
  51. }
  52. }
  53. }