// todo unify with accesscontrol NotificationMessageHolderType[] MyReceiveMessagesNotify( Action action, int timeout, TestTool.Proxies.Event.FilterType filter, XmlDocument doc ) { NotificationMessageHolderType[] NotificationMessage; System.DateTime subscribeStarted = System.DateTime.MaxValue; EndpointReferenceType subscriptionReference = null; Notify notify = null; try { subscriptionReference = ReceiveMessages(filter, timeout, action, doc, out notify, out subscribeStarted); NotificationMessage = notify.NotificationMessage; } finally { Operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); } return(NotificationMessage); }
void CommonDoorPropertyEventStateChangeTest(Func <DoorInfo, bool> doorCapabilitiesTest, TopicInfo topicInfo, ValidateMessageFunction validateMessageFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of doors from the DUT (see Annex A.1). List <DoorInfo> fullDoorInfosList = GetDoorInfoList(); //4. Check that there is at least one Door with Capabilities.[CAPABILITIES FOR THE TEST]= “true”. // Otherwise skip other steps and go to the next test. List <DoorInfo> doorsList = null; if (doorCapabilitiesTest != null) { doorsList = fullDoorInfosList.Where(A => doorCapabilitiesTest(A)).ToList(); if (doorsList.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test" + Environment.NewLine); return; } } else { doorsList = fullDoorInfosList; } //5. ONVIF Client will select one random Door (token = Token1) with // Capabilities.DoorMonitor= “true”. // ToDo: may be change it to really random selection DoorInfo selectedDoor = doorsList[0]; // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); //6. ONVIF Client will invoke SubscribeRequest message with tns1:DoorControl/DoorPhysicalState Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager is deleted after one minute. //7. Verify that the DUT sends a SubscribeResponse message. //8. Test Operator will invoke change of DoorPhysicalState property for Door with token = Token1. //9. Verify that DUT sends Notify message. string message = string.Format("{0} event is expected \r\n for the Door with token={{0}}", topicInfo.GetDescription()); DoorSelectionData data = new DoorSelectionData(); data.SelectedToken = selectedDoor.token; data.MessageTemplate = message; data.Doors = doorsList.Select( D => new DoorSelectionData.DoorShortInfo() { Token = D.token, Name = D.Name }).ToList(); Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>(); try { subscriptionReference = ReceiveMessages(filter, timeout, new Action(() => { _operator.ShowDoorSelectionMessage(data); }), 1, (n) => CheckMessagePropertyOperation(n, OnvifMessage.CHANGED), notifications, out subscribeStarted); } finally { _operator.HideDoorSelectionMessage(); } Assert(notifications.Count > 0, string.Format("Message with PropertyOperation='Changed' for the door with token='{0}' has not been received", data.SelectedToken), "Check that the message for selected door has been received"); //10. Verify received Notify messages (correct value for UTC time, TopicExpression and // wsnt:Message). //11. Verify that TopicExpression is equal to [TOPIC] for // received Notify message. //12. Verify that notification contains Source.SimpleItem item with Name="DoorToken" // and Value= “Token1”. //13. Verify that notification contains Data.SimpleItem item with Name=[ITEMNAME] and // Value with type is equal to [TYPE]. BeginStep("Validate messages"); XmlNamespaceManager manager = CreateNamespaceManager(notifications.First().Value.OwnerDocument); StringBuilder logger = new StringBuilder(); bool ok = true; MessageCheckSettings settings = new MessageCheckSettings(); settings.Data = data.SelectedToken; settings.ExpectedTopic = topicInfo; settings.RawMessageElements = notifications; settings.NamespaceManager = manager; foreach (NotificationMessageHolderType m in notifications.Keys) { bool local = validateMessageFunction(m, settings, logger); ok = ok && local; } if (!ok) { throw new AssertException(logger.ToStringTrimNewLine()); } StepPassed(); }, () => { _operator.HideDoorSelectionMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
void CommonDoorOperationEventTest( Func<DoorInfo, bool> doorCapabilitiesTest, string operationName, TopicInfo topic, ValidateMessageFunction validateMessage, Action<string> doorOperation, string stateItemName, string expectedState, bool equal) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = _eventSubscriptionTimeout; RunTest( () => { // Get full list List<DoorInfo> fullDoorsList = GetDoorInfoList(); // Check if there are Doors with required properties List<DoorInfo> doorInfos = fullDoorsList.Where(doorCapabilitiesTest).ToList(); // if there are no Doors with required capabilities, skip other steps. if (doorInfos.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test."); return; } // Select one Door. DoorInfo selectedDoor = doorInfos[0]; string selectedToken = selectedDoor.token; List<DoorSelectionData.DoorShortInfo> tokens = doorInfos.Select( D => new DoorSelectionData.DoorShortInfo(){ Token = D.token, Name=D.Name}).ToList(); string message = string.Format("Put the Door with token '{{0}}' into state which allows '{0}' operation", operationName); DoorSelectionData data = new DoorSelectionData(); data.Doors = tokens; data.SelectedToken = selectedToken; data.MessageTemplate = message; WaitHandle formHandle = _operator.ShowCountdownMessage(_messageTimeout, data); try { Sleep(_messageTimeout, new WaitHandle[] { formHandle }); } finally { _operator.HideCountdownMessage(); } selectedToken = data.SelectedToken; LogTestEvent(string.Format("Door with token '{0}' will be used for test{1}", selectedToken, Environment.NewLine)); EnsureEventPortTypeClientCreated(); TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topic); // Subscribe Utils.NotifyCollectingServer eventServer = new TestTool.Tests.TestCases.Utils.NotifyCollectingServer(_nic); SetupNotifyServer2(eventServer); string notificationsUri = eventServer.GetNotificationUri(); System.DateTime localSubscribeStarted = System.DateTime.MaxValue; Func<NotificationMessageHolderType, bool> messageCheck = (n) => CheckDoorEventSource(n, selectedToken); { AutoResetEvent subscribedEvent = new AutoResetEvent(false); // collect "Initialized" messaged Action setSynchronizationPointAction = new Action( () => { StepPassed(); subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out localSubscribeStarted); subscribedEvent.Set(); }); BeginStep("Start listening"); // collect messages for all door infos Dictionary<Notify, byte[]> notifications = eventServer.CollectNotifications(setSynchronizationPointAction, _operationDelay, 1, messageCheck, subscribedEvent, _semaphore.StopEvent); subscribeStarted = localSubscribeStarted; Assert(notifications.Count > 0, string.Format("No notifications were received for Door with token='{0}'", selectedToken), "Check that the DUT sent expected notification(s)"); // Create raw elements list Dictionary<NotificationMessageHolderType, XmlElement> messages = GetRawElements(notifications); Dictionary<NotificationMessageHolderType, XmlElement> filtered = GetFilteredList(messages, messageCheck); // Validate messages ValidateMessages(filtered, topic, OnvifMessage.INITIALIZED, doorInfos, validateMessage); } { // Perform operation AutoResetEvent initializedEvent = new AutoResetEvent(false); Action initiationAction = new Action(() => { doorOperation(selectedToken); initializedEvent.Set(); }); // Check state change message Dictionary<Notify, byte[]> notifications = eventServer.CollectNotifications(initiationAction, _operationDelay, 1, messageCheck, initializedEvent, _semaphore.StopEvent); Assert(notifications.Count > 0, string.Format("No notifications were received for Door with token='{0}'", selectedToken), "Check that the DUT sent notification(s)"); // Create raw elements list Dictionary<NotificationMessageHolderType, XmlElement> messages = GetRawElements(notifications); Dictionary<NotificationMessageHolderType, XmlElement> filtered = GetFilteredList(messages, messageCheck); // validate state changed message ValidateMessages(filtered, topic, OnvifMessage.CHANGED, selectedToken, validateMessage); BeginStep("Validate current State"); Dictionary<string, string> dataSimpleItems = messages.Keys.First().Message.GetMessageDataSimpleItems(); if (equal) { if (dataSimpleItems[stateItemName] != expectedState) { throw new AssertException(string.Format("{0} is incorrect: expected {1}, actual {2}", stateItemName, expectedState, dataSimpleItems[stateItemName])); } } else { if (dataSimpleItems[stateItemName] == expectedState) { throw new AssertException(string.Format("{0} is incorrect: must be different from {1}", stateItemName, dataSimpleItems[stateItemName])); } } StepPassed(); } RemoveHandlers2(eventServer); }, () => { _operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
public void AccessDoorTest() { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = _eventSubscriptionTimeout; Utils.NotifyAsyncServer eventServer = null; RunTest( () => { // 3. Get complete list of doors from the DUT (see Annex A.1). List<DoorInfo> fullDoorsList = GetDoorInfoList(); //4. ONVIF Client selects one door from the complete list of doors at step // 3 with DoorInfo.Capabilities.Access equal to true. If there is no such Door, // skip other steps and go to the next test. List<DoorInfo> doorInfos = fullDoorsList.Where( D => D.Capabilities != null && D.Capabilities.AccessSpecified && D.Capabilities.Access).ToList(); if (doorInfos.Count == 0) { LogTestEvent("No Doors with required Capabilities found, exit the test."); return; } //5. Test Operator puts Door in state when AccessDoor command will be accepted // with state change. // ToDo : discuss with customer if there are better methods to select Door // which will be convenient for operator List<DoorSelectionData.DoorShortInfo> tokens = doorInfos.Select( D => new DoorSelectionData.DoorShortInfo() { Token = D.token, Name = D.Name }).ToList(); string selectedToken = tokens.First().Token; string message ="Put the Door with token '{0}' into state which allows 'Access' operation"; Definitions.Data.DoorSelectionData data = new TestTool.Tests.Definitions.Data.DoorSelectionData(); data.Doors = tokens; data.SelectedToken = selectedToken; data.MessageTemplate = message; WaitHandle formHandle = _operator.ShowCountdownMessage(_messageTimeout, data); try { Sleep(_messageTimeout, new WaitHandle[] { formHandle }); } finally { _operator.HideCountdownMessage(); } selectedToken = data.SelectedToken; LogTestEvent(string.Format("Door with token '{0}' will be used for test{1}", selectedToken, Environment.NewLine)); TopicInfo topic = ConstructTopic(new string[] { "Door", "State", "DoorMode" }); TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topic); Func<NotificationMessageHolderType, bool> messageCheck = (n) => CheckDoorEventSource(n, selectedToken); // Subscribe eventServer = new TestTool.Tests.TestCases.Utils.NotifyAsyncServer(_nic); //SetupNotifyServer2(eventServer); string notificationsUri = eventServer.GetNotificationUri(); BeginStep("Begin listening"); eventServer.StartCollecting(_semaphore.StopEvent); StepPassed(); //6. ONVIF Client will invoke SubscribeRequest message with tns1:DoorControl/DoorMode // Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager // is deleted after one minute. //7. Verify that the DUT sends a SubscribeResponse message. subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out subscribeStarted); LogTestEvent(string.Format("Wait until message for Door with token='{0}' is received", selectedToken)+Environment.NewLine); System.DateTime messageTimeLimit = System.DateTime.Now.AddMilliseconds(_operationDelay); string initialMode = string.Empty; //8. Verify that DUT sends Notify message for selected Door with current state // (Notifications for other Doors will be ignored for this test case). //9. Verify received Notify message (correct value for UTC time, TopicExpression and // wsnt:Message). //10. Verify that PropertyOperation="Initialized". //11. Verify that TopicExpression is equal to tns1:DoorControl/DoorMode. //12. Verify that notification contains Source.SimpleItem item with Name="DoorToken" // and Value is equal to selected Door Token. //13. Verify that notification contains Data.SimpleItem item with Name="DoorMode" // and Value with type is equal to tdc:DoorMode. { System.Diagnostics.Debug.WriteLine("Wait for messages with PropertyOperation=INITIALIZED"); Dictionary<NotificationMessageHolderType, XmlElement> initialMessages = PeekMessages(eventServer, _messageTimeout, messageTimeLimit, fullDoorsList.Count, messageCheck); Assert(initialMessages.Count > 0, string.Format("Message for the door with token='{0}' has not been received", selectedToken ), "Check that the message for selected door has been received"); // validate ValidateMessages(initialMessages, topic, OnvifMessage.INITIALIZED, selectedToken, ValidateDoorModeMessage); NotificationMessageHolderType receivedMessage = initialMessages.Keys.First(); XmlElement dataElement = receivedMessage.Message.GetMessageData(); Dictionary<string, string> dataSimpleItems = dataElement.GetMessageElementSimpleItems(); initialMode = dataSimpleItems["State"]; } //14. ONVIF Client will invoke AccessDoorRequest message (Token = [selected Door token]) // to change door state. //15. Verify the AccessDoorResponse message from the DUT. AccessDoor(selectedToken, null, null, null, null, null); messageTimeLimit = System.DateTime.Now.AddSeconds(_operationDelay/1000); LogTestEvent("Wait until message with PropertyOperation=\"Changed\" is received" + Environment.NewLine); //16. Verify that DUT sends Notify message for selected Door with current state // (Notifications for other Doors will be ignored for this test case). //17. Verify received Notify message (correct value for UTC time, TopicExpression and // wsnt:Message). //18. Verify that PropertyOperation="Changed". //19. Verify that TopicExpression is equal to tns1:DoorControl/DoorMode. //20. Verify that notification contains Source.SimpleItem item with Name="DoorToken" // and Value is equal to selected Door Token. //21. Verify that notification contains Data.SimpleItem item with Name="DoorMode" // and Value equal to “Accessed”. { System.Diagnostics.Debug.WriteLine("Wait for first 'CHANGED' message"); Dictionary<NotificationMessageHolderType, XmlElement> doorModeChangedMessages = PeekMessages(eventServer, _messageTimeout, messageTimeLimit, 1, messageCheck); Assert(doorModeChangedMessages.Count > 0, string.Format("Message for the door with token='{0}' has not been received", selectedToken), "Check that the message for selected door has been received"); // validate ValidateMessages(doorModeChangedMessages, topic, selectedToken, ValidateDoorModeMessage); NotificationMessageHolderType receivedMessage = doorModeChangedMessages.Keys.First(); ValidateDoorModeSimpleItem(receivedMessage, DoorMode.Accessed); } LogTestEvent("Wait until message with PropertyOperation=\"Changed\" is received" + Environment.NewLine); //22. ONVIF Client will wait for next Notification for selected Door. //23. Verify that DUT sends Notify message for selected Door with current state // (Notifications for other Doors will be ignored for this test case). //24. Verify received Notify message (correct value for UTC time, TopicExpression // and wsnt:Message). //25. Verify that PropertyOperation="Changed". //26. Verify that TopicExpression is equal to tns1:DoorControl/DoorMode. //27. Verify that notification contains Source.SimpleItem item with Name="DoorToken" // and Value is equal to selected Door Token. //28. Verify that notification contains Data.SimpleItem item with Name="DoorMode" and // Value equal to previous state (previous state was received with Notification from step 8). { System.Diagnostics.Debug.WriteLine("Wait for second 'CHANGED' message"); messageTimeLimit = System.DateTime.Now.AddSeconds(_messageTimeout / 1000); // ToDo: should we wait for "_operationDelay" ? Dictionary<NotificationMessageHolderType, XmlElement> doorModeChangedMessages = PeekMessages(eventServer, _messageTimeout, messageTimeLimit, 1, messageCheck); Assert(doorModeChangedMessages.Count > 0, string.Format("Message for the door with token='{0}' has not been received", selectedToken), "Check that the message for selected door has been received"); // validate ValidateMessages(doorModeChangedMessages, topic, selectedToken, ValidateDoorModeMessage); NotificationMessageHolderType receivedMessage = doorModeChangedMessages.Keys.First(); ValidateDoorModeSimpleItem(receivedMessage, initialMode); } eventServer.StopCollecting(); }, () => { _operator.HideCountdownMessage(); if (eventServer != null) { eventServer.StopCollecting(); } ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
public static EndpointReferenceType CreatePullPointSubscription(this IEventService s, FilterType Filter, string InitialTerminationTime, CreatePullPointSubscriptionSubscriptionPolicy SubscriptionPolicy, ref System.Xml.XmlElement[] Any, out System.DateTime CurrentTime, out DateTime?TerminationTime) { s.InitializeGuard(); EndpointReferenceType r = null; XmlElement[] localAny = Any; System.DateTime localCurrentTime = System.DateTime.MinValue; System.DateTime?localTerminationTime = null; s.Test.RunStep(() => r = s.ServiceClient.Port.CreatePullPointSubscription(Filter, InitialTerminationTime, SubscriptionPolicy, ref localAny, out localCurrentTime, out localTerminationTime), "Get Service Capabilities(Event)"); CurrentTime = localCurrentTime; TerminationTime = localTerminationTime; return(r); }
void ConfigurationEventTest( TopicInfo topicInfo, Action <XmlElement, TopicInfo> validateTopic, ValidateConfigurationMessageFunction validateMessageFunction, string sourceTokenSimpleItem, Action <string> validateConfigurationFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { // Get topic description from the DUT. XmlElement topicElement = GetTopicElement(topicInfo); BeginStep("Check if the event topic is supported"); if (topicElement == null) { LogStepEvent(string.Format("Topic {0} not supported", topicInfo.GetDescription())); } StepPassed(); if (topicElement == null) { return; } XmlElement messageDescription = topicElement.GetMessageDescription(); validateTopic(messageDescription, topicInfo); // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); string message = string.Format("{0} event is expected!", topicInfo.GetDescription()); Notify notify = null; XmlDocument doc = new XmlDocument(); try { subscriptionReference = ReceiveMessages(filter, timeout, () => Operator.ShowMessage(message), doc, out notify, out subscribeStarted); } finally { Operator.HideMessage(); } Assert(notify.NotificationMessage.Length == 1, string.Format("{0} messages received - unable to check actual configuration", notify.NotificationMessage.Length), "Check that exactly one notification is received"); BeginStep("Validate message"); XmlNamespaceManager manager = CreateNamespaceManager(doc); Dictionary <NotificationMessageHolderType, XmlElement> notifications = GetRawElements(notify.NotificationMessage, doc, manager, true); StringBuilder logger = new StringBuilder(); bool ok = true; MessageCheckSettings settings = new MessageCheckSettings(); settings.ExpectedTopic = topicInfo; settings.RawMessageElements = notifications; settings.NamespaceManager = manager; NotificationMessageHolderType m = notify.NotificationMessage[0]; ok = validateMessageFunction(m, notifications[m], manager, logger); if (!ok) { throw new AssertException(logger.ToStringTrimNewLine()); } StepPassed(); // validateMessageFunction should return false, if this simple item is missing string token = m.Message.GetMessageSourceSimpleItems()[sourceTokenSimpleItem]; validateConfigurationFunction(token); }, () => { Operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
void ConfigurationEventTestBis( TopicInfo topicInfo, Action <XmlElement, TopicInfo> validateTopic, ValidateConfigurationMessageFunction validateMessageFunction, string sourceTokenSimpleItem, Action <string> validateConfigurationFunction) { int actualTerminationTime = 60; if (_eventSubscriptionTimeout != 0) { actualTerminationTime = _eventSubscriptionTimeout; } int timeout = _operationDelay / 1000; RunTest( () => { // Get topic description from the DUT. XmlElement topicElement = GetTopicElement(topicInfo); Assert(null != topicElement, string.Format("Topic {0} not supported", topicInfo.GetDescription()), "Check if the event topic is supported"); XmlElement messageDescription = topicElement.GetMessageDescription(); validateTopic(messageDescription, topicInfo); // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); string message = string.Format("{0} event is expected!", topicInfo.GetDescription()); bool UseNotify = UseNotifyToGetEvents; Dictionary <NotificationMessageHolderType, XmlElement> notifications = null; SubscriptionHandler Handler = null; try { Handler = new SubscriptionHandler(this, UseNotify, GetEventServiceAddress()); Handler.Subscribe(filter, actualTerminationTime); Operator.ShowMessage(message); var pullingCondition = new SubscriptionHandler.WaitFirstNotificationPollingCondition(timeout); Handler.WaitMessages(1, pullingCondition, out notifications); } finally { Operator.HideMessage(); SubscriptionHandler.Unsubscribe(Handler); } Assert(null != notifications && notifications.Any(), string.Format("No notification messages are received.{0}WARNING: may be Operation delay is too low", Environment.NewLine), "Check that DUT sent any notification messages"); Assert(notifications.Count == 1, string.Format("{0} messages received - unable to check actual configuration", notifications.Count), "Check that exactly one notification is received"); BeginStep("Validate message"); XmlNamespaceManager manager = CreateNamespaceManager(notifications.First().Value.OwnerDocument); StringBuilder logger = new StringBuilder(); bool ok = true; MessageCheckSettings settings = new MessageCheckSettings(); settings.ExpectedTopic = topicInfo; settings.RawMessageElements = notifications; settings.NamespaceManager = manager; NotificationMessageHolderType m = notifications.Keys.First(); ok = validateMessageFunction(m, notifications[m], manager, logger); if (!ok) { throw new AssertException(logger.ToStringTrimNewLine()); } StepPassed(); // validateMessageFunction should return false, if this simple item is missing string token = m.Message.GetMessageSourceSimpleItems()[sourceTokenSimpleItem]; validateConfigurationFunction(token); }, () => { }); }
//[04.03.2013] AKS: added parameter message limit and functionality to check if number of notifications in response to PullMessages command //exceeds messageLimit protected NotificationMessageHolderType[] ReceiveMessagesPullPointFirstMessage( Action action, TestTool.Proxies.Event.FilterType filter, int messageLimit, XmlDocument doc) { EndpointReferenceType subscriptionReference = null; int timeout = _eventSubscriptionTimeout; int actualTerminationTime = timeout; System.DateTime subscribeStarted = System.DateTime.Now; NotificationMessageHolderType[] NotificationMessage = null; System.DateTime pullingDeadline = System.DateTime.Now.AddSeconds(_operationDelay / 1000.0); System.DateTime TerminationExpectedTime = System.DateTime.Now.AddSeconds(timeout); try { actualTerminationTime = timeout; subscriptionReference = CreateStandardSubscription(filter, ref actualTerminationTime); Assert(null != subscriptionReference, "Can't create pullpoint subscription", "Check subscription result"); /*if (subscriptionReference == null) * { * goto ready; * }*/ CreatePullPointSubscriptionClient(subscriptionReference); string dump; //Operator.ShowMessage(message); action(); int terminationTimeSeconds = 60; do { DoRenewBeforePull(ref terminationTimeSeconds, ref TerminationExpectedTime); NotificationMessage = GetMessages(subscriptionReference, false, true, false, 1, out dump); if (System.DateTime.Now > pullingDeadline) { break; } if (NotificationMessage == null) { break; } }while ((NotificationMessage != null) && (NotificationMessage.Length == 0)); if ((NotificationMessage != null) && (NotificationMessage.Length == 0)) { NotificationMessage = null; } if (NotificationMessage != null) { doc.LoadXml(dump); } } catch (Exception exc) { StepFailed(exc); } finally { Operator.HideMessage(); } ready: try { Assert(null != NotificationMessage && 0 != NotificationMessage.Length, "No valid notification messages received", "Check that DUT sent valid notification messages"); //[04.03.2013] AKS: check if number of notifications in response to PullMessages command exceeds messageLimit Assert(null != NotificationMessage && messageLimit >= NotificationMessage.Length, "Maximum number of messages exceeded", string.Format("Check that DUT sent not more than {0} message(s)", messageLimit)); } finally { ReleaseSubscription(subscribeStarted, subscriptionReference, TerminationExpectedTime); } return(NotificationMessage); }
void ExternalAuthorizationTest( Func <AccessPointInfo, bool> accessPointCapabilitiesTest, TopicInfo accessRequestTopic, Action <XmlElement, TopicInfo> validateAccessRequestTopic, ValidateMessageFunction validateRequestMessageFunction, TopicInfo resultTopic, Action <XmlElement, TopicInfo> validateResultTopic, ValidateMessageFunction validateResultMessageFunction, Action <string, string> reactToRequest) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of access points from the DUT (see Annex A.1). List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList(); //4. Check that there is at least one Access Point with required Capabilities List <AccessPointInfo> accessPointsList = null; if (accessPointCapabilitiesTest != null) { accessPointsList = fullAccessPointsList.Where(A => accessPointCapabilitiesTest(A)).ToList(); if (accessPointsList.Count == 0) { LogTestEvent("No AccessPoints with required Capabilities found, exit the test." + Environment.NewLine); return; } } else { accessPointsList = fullAccessPointsList; } // Get topic description from the DUT and check topics support ValidateTopicsSupport(accessRequestTopic, validateAccessRequestTopic, resultTopic, validateResultTopic); // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(new TopicInfo[] { accessRequestTopic, resultTopic }); // create notification listener and subscription Utils.NotifyServer server = new NotifyServer(_nic); SetupNotifyServer(server); string notificationsUri = server.GetNotificationUri(); subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out subscribeStarted); string credentialsToken = string.Empty; string credentialsHolderName = string.Empty; string accessPointToken = GetAccessRequestMessage(server, timeout, accessRequestTopic, validateRequestMessageFunction, fullAccessPointsList, accessPointsList, ref credentialsToken, ref credentialsHolderName); // receive events - after calling ExternalAuthorization { BeginStep("Start listening"); Notify notify = server.WaitForNotify(() => { StepPassed(); reactToRequest(accessPointToken, credentialsToken); }, timeout * 1000, _semaphore.StopEvent); RemoveHandlers(server); ValidateNotificationsPacket(server.RawData); ValidateNotifyNotEmpty(notify); if (notify.NotificationMessage.Length > 1) { LogTestEvent("DUT sent more than one notification. Test will be performed for token from the first notification"); } NotificationMessageHolderType theMessage = notify.NotificationMessage[0]; ValidateResultMessage(notify, theMessage, server.RawData, resultTopic, validateResultMessageFunction, accessPointToken, credentialsToken, credentialsHolderName); } }, () => { _operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
void ExternalAuthorizationTimeoutTest( Func <AccessPointInfo, bool> accessPointCapabilitiesTest, TopicInfo accessRequestTopic, Action <XmlElement, TopicInfo> validateAccessRequestTopic, ValidateMessageFunction validateRequestMessageFunction, TopicInfo resultTopic, Action <XmlElement, TopicInfo> validateResultTopic, ValidateMessageFunction validateResultMessageFunction) { EndpointReferenceType subscriptionReference = null; System.DateTime subscribeStarted = System.DateTime.MaxValue; int timeout = 60; RunTest( () => { //3. Get complete list of access points from the DUT (see Annex A.1). List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList(); //4. Check that there is at least one Access Point with required Capabilities List <AccessPointInfo> accessPointsList = null; if (accessPointCapabilitiesTest != null) { accessPointsList = fullAccessPointsList.Where(A => accessPointCapabilitiesTest(A)).ToList(); if (accessPointsList.Count == 0) { LogTestEvent("No AccessPoints with required Capabilities found, exit the test." + Environment.NewLine); return; } } else { accessPointsList = fullAccessPointsList; } // Get topic description from the DUT and check topics support ValidateTopicsSupport(accessRequestTopic, validateAccessRequestTopic, resultTopic, validateResultTopic); // filter for current test TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(new TopicInfo[] { accessRequestTopic, resultTopic }); // create notification listener and subscription Utils.NotifyServer server = new NotifyServer(_nic); SetupNotifyServer(server); string notificationsUri = server.GetNotificationUri(); subscriptionReference = CreateSubscription(filter, timeout, notificationsUri, out subscribeStarted); // get access request message string credentialsToken = string.Empty; string credentialsHolderName = string.Empty; string accessPointToken = GetAccessRequestMessage(server, timeout, accessRequestTopic, validateRequestMessageFunction, fullAccessPointsList, accessPointsList, ref credentialsToken, ref credentialsHolderName); RemoveHandlers(server); // receive events { EnsureNotificationProducerClientCreated(); LogTestEvent(string.Format("Wait for {0} event{1}", resultTopic.GetDescription(), Environment.NewLine)); Utils.NotifyAsyncServer asyncServer = new NotifyAsyncServer(_nic); SetupNotifyServer2(asyncServer); asyncServer.StartCollecting(_semaphore.StopEvent); AutoResetEvent received = new AutoResetEvent(false); asyncServer.NotificationReceived += new Action <byte[]>((data) => { received.Set(); }); Renew request = new Renew(); request.TerminationTime = "PT60S"; // use 50 second instead of 60 int subscriptionGuaranteedTimeLeft = (int)(subscribeStarted.AddSeconds(50) - System.DateTime.Now).TotalMilliseconds; if (subscriptionGuaranteedTimeLeft < 0) { subscriptionGuaranteedTimeLeft = 0; } System.DateTime exitTime = System.DateTime.Now.AddMilliseconds(_messageTimeout); try { while (true) { // check if we are still waiting the message int waitTimeLeft = (int)(exitTime - System.DateTime.Now).TotalMilliseconds; if (waitTimeLeft <= 0) { break; } // compute time for next wait int waitTime = Math.Min(subscriptionGuaranteedTimeLeft, waitTimeLeft); int res = WaitHandle.WaitAny(new WaitHandle[] { received, _semaphore.StopEvent }, waitTime); if (res == WaitHandle.WaitTimeout) { // no notification received if (System.DateTime.Now < exitTime) { Renew(request); subscriptionGuaranteedTimeLeft = 50000; subscribeStarted = System.DateTime.Now; } else { break; } } else if (res == 1) { asyncServer.StopCollecting(); // Stop event received throw new StopEventException(); } else { // Notification received break; } } } catch (Exception exc) { throw; } finally { asyncServer.StopCollecting(); RemoveHandlers2(asyncServer); } Dictionary <Notify, byte[]> messages = asyncServer.Get(); Assert(messages.Count > 0, "No notifications received", "Check if the DUT sent notifications"); Notify notify = messages.Keys.First(); byte[] rawData = messages[notify]; ValidateNotificationsPacket(rawData); ValidateNotifyNotEmpty(notify); NotificationMessageHolderType theMessage = notify.NotificationMessage[0]; ValidateResultMessage(notify, theMessage, rawData, resultTopic, validateResultMessageFunction, accessPointToken, credentialsToken, credentialsHolderName); } }, () => { _operator.HideMessage(); ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); }); }
public void AccessPointTamperingStateChangeTest() { List <EndpointReferenceType> subscriptionReferences = new List <EndpointReferenceType>(); List <System.DateTime> allSubscribeStarted = new List <System.DateTime>(); int timeout = 60; RunTest( () => { //3. Get complete list of access points from the DUT (see Annex A.1). List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList(); //4. Check that there is at least one Access Point with Capabilities.Tamper = “true”. // Otherwise skip other steps and go to the next test. List <AccessPointInfo> accessPointsList = fullAccessPointsList.Where(A => A.Capabilities != null && A.Capabilities.TamperSpecified && A.Capabilities.Tamper).ToList(); if (accessPointsList.Count == 0) { LogTestEvent("No AccessPoints with required Capabilities found, exit the test." + Environment.NewLine); return; } // Topic for current test // tns1:AccessPoint/State/Tampering TopicInfo topicInfo = ConstructTopic(new string[] { "AccessPoint", "State", "Tampering" }); TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); foreach (AccessPointInfo info in accessPointsList) { string accessPointToken = info.token; //5. If Access Point with Token1 (Token1 is the first AccessPointInfo.token from the // complete list of access points at step 3) has AccessPointInfo.Capabilities.Tamper equal // to false, then skip steps 6-13 and go to the step 14. //6. ONVIF Client will invoke SubscribeRequest message with // tns1:AccessControl/AccessPoint/Tampering Topic as Filter and an InitialTerminationTime // of 60s to ensure that the SubscriptionManager is deleted after one minute. //7. Verify that the DUT sends a SubscribeResponse message. //8. Test Operator will invoke change of Tampering property. //9. Verify that DUT sends Notify message. //10. Verify received Notify messages (correct value for UTC time, TopicExpression and // wsnt:Message). Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>(); System.DateTime subscribeStarted = System.DateTime.MaxValue; int cnt = subscriptionReferences.Count; subscriptionReferences.Add(null); allSubscribeStarted.Add(subscribeStarted); EndpointReferenceType subscriptionReference = null; try { subscriptionReference = ReceiveMessages(filter, timeout, new Action(() => { _operator.ShowMessage("tns1:AccessPoint/State/Tampering event is expected!"); }), 1, (n) => CheckMessagePropertyOperation(n, OnvifMessage.CHANGED), notifications, out subscribeStarted); } finally { _operator.HideMessage(); } subscriptionReferences[cnt] = subscriptionReference; allSubscribeStarted[cnt] = subscribeStarted; //11. Verify that TopicExpression is equal to tns1:AccessControl/AccessPoint/Tampering // for all received Notify messages. //12. Verify that notification contains Source.SimpleItem item with Name="AccessPointToken" // and Value= “Token1” (e.g. complete list of access points contains Access Point with the // same token). //13. Verify that notification contains Data.SimpleItem item with Name="Active" and Value // with type is equal to xs:boolean. ValidateMessages(notifications, topicInfo, OnvifMessage.CHANGED, accessPointsList, ValidateAccessPointTamperingMessage); Dictionary <string, NotificationMessageHolderType> accessPointsMessages = new Dictionary <string, NotificationMessageHolderType>(); ValidateMessagesSet(notifications.Keys, accessPointsList, accessPointsMessages); //14. Repeat steps 5-13 for all other tokens from complete list of access points at step 3. } }, () => { _operator.HideMessage(); for (int i = 0; i < subscriptionReferences.Count; i++) { System.DateTime subscribeStarted = allSubscribeStarted[i]; EndpointReferenceType subscriptionReference = subscriptionReferences[i]; ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); } }); }
public void AccessPointEnabledStateChangeEventTest() { List <EndpointReferenceType> subscriptionReferences = new List <EndpointReferenceType>(); List <System.DateTime> allSubscribeStarted = new List <System.DateTime>(); int timeout = 60; RunTest( () => { // Topic for current test // tns1:AccessPoint/State/Enabled TopicInfo topicInfo = ConstructTopic(new string[] { "AccessPoint", "State", "Enabled" }); TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo); //3. Get complete list of access points from the DUT (see Annex A.1). //4. If Access Point with Token1 (Token1 is the first AccessPointInfo.token from the // complete list of access points at step 3) has AccessPointInfo.Capabilities.DisableAccessPoint // equal to false, then skip steps 7-18 and go to the step 19. List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList(); List <AccessPointInfo> accessPoints = fullAccessPointsList.Where(AP => AP.Capabilities.DisableAccessPoint).ToList(); foreach (AccessPointInfo info in accessPoints) { string accessPointToken = info.token; //5. ONVIF Client will invoke GetAccessPointStateRequest message (TokenList.Token = Token1, // where Token1 is the first token from the complete list of access points at step 3) to // retrieve Access Point state for specified token from the DUT. //6. Verify the GetAccessPointStateResponse message from the DUT. AccessPointState state = GetAccessPointState(accessPointToken); //7. ONVIF Client will invoke SubscribeRequest message with tns1:AccessControl/AccessPoint/Enabled // Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager is // deleted after one minute. //8. Verify that the DUT sends a SubscribeResponse message. //9. If Access Point with Token1 (Token1 is the first AccessPointInfo.token from the complete // list of access points at step 3) has AccessPointState.Enabled equal to true, then skip steps // 10-11 and go to the step 12. //10. ONVIF Client will invoke EnableAccessPointRequest message (Token = “Token1”, where Token1 // is the first AccessPointInfo.token from the complete list of access points at step 3) to try // enabling access point. //11. Verify the EnableAccessPointResponse message from the DUT. Go to the step 13. //12. ONVIF Client will invoke DisableAccessPointRequest message (Token = “Token1”, where Token1 // is the first AccessPointInfo.token from the complete list of access points at step 3) to try // disabling access point. //13. Verify the DisableAccessPointResponse message from the DUT. Action eventInitiationAction = null; if (state.Enabled) { eventInitiationAction = new Action(() => { DisableAccessPoint(accessPointToken); }); } else { eventInitiationAction = new Action(() => { EnableAccessPoint(accessPointToken); }); } //14. Verify that DUT sends Notify message. //15. Verify received Notify messages (correct value for UTC time, TopicExpression and // wsnt:Message). //16. Verify that TopicExpression is equal to tns1:AccessControl/AccessPoint/Enabled for all // received Notify messages. //17. Verify that notification contains Source.SimpleItem item with Name="AccessPointToken" and // Value= “Token1” (e.g. complete list of access points contains Access Point with the same token). Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>(); System.DateTime subscribeStarted = System.DateTime.MaxValue; int cnt = subscriptionReferences.Count; subscriptionReferences.Add(null); allSubscribeStarted.Add(subscribeStarted); EndpointReferenceType subscriptionReference = ReceiveMessages(filter, timeout, eventInitiationAction, 1, (n) => CheckMessagePropertyOperation(n, OnvifMessage.CHANGED), notifications, out subscribeStarted); subscriptionReferences[cnt] = subscriptionReference; allSubscribeStarted[cnt] = subscribeStarted; ValidateMessages(notifications, topicInfo, info.token, ValidateAccessPointEnabledMessage); //18. Verify that notification contains Data.SimpleItem item with Name="Enabled" and Value with // type is equal to xs:boolean and with value equal to current state of Access Point. // We ignore messages with property operation different from "Changed" // And the only message expected in this case should be message for "our" AccessPoint foreach (NotificationMessageHolderType message in notifications.Keys) { XmlElement messageElement = message.Message; string expectedState = (!state.Enabled).ToString().ToLower(); XmlElement dataElement = messageElement.GetMessageData(); // SimpleItems must be OK by that moment Dictionary <string, string> dataSimpleItems = dataElement.GetMessageDataSimpleItems(); string notificationState = dataSimpleItems["State"]; Assert(expectedState == notificationState, string.Format("State is different ({0} in GetAccessPointStateResponse, {1} in Notification)", expectedState, notificationState), "Check that state is the same in Notification and in GetAccessPointStateResponse"); } } //19. Repeat steps 4-18 for all other tokens from complete list of access points at step 3. }, () => { for (int i = 0; i < subscriptionReferences.Count; i++) { System.DateTime subscribeStarted = allSubscribeStarted[i]; EndpointReferenceType subscriptionReference = subscriptionReferences[i]; ReleaseSubscription(subscribeStarted, subscriptionReference, timeout); } }); }