github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/system/bus/common_test.go (about)

     1  // This file is part of the Smart Home
     2  // Program complex distribution https://github.com/e154/smart-home
     3  // Copyright (C) 2023, Filippov Alex
     4  //
     5  // This library is free software: you can redistribute it and/or
     6  // modify it under the terms of the GNU Lesser General Public
     7  // License as published by the Free Software Foundation; either
     8  // version 3 of the License, or (at your option) any later version.
     9  //
    10  // This library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13  // Library General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public
    16  // License along with this library.  If not, see
    17  // <https://www.gnu.org/licenses/>.
    18  
    19  package bus
    20  
    21  import (
    22  	"testing"
    23  )
    24  
    25  func TestTopicMatch(t *testing.T) {
    26  
    27  	const topic = "myhome/groundfloor/livingroom/temperature"
    28  	const topic2 = "myhome/groundfloor/kitchen/temperature"
    29  
    30  	// Test cases with exact matches
    31  	assertMatch(t, []byte(topic), []byte("myhome/groundfloor/livingroom/temperature"))
    32  
    33  	// Test cases with wildcard matches
    34  
    35  	assertMatch(t, []byte(topic), []byte("myhome/groundfloor/#"))
    36  	assertMatch(t, []byte(topic2), []byte("myhome/groundfloor/#"))
    37  	assertMatch(t, []byte(topic), []byte("myhome/groundfloor/+/#"))
    38  	assertMatch(t, []byte(topic2), []byte("myhome/groundfloor/+/#"))
    39  
    40  	// Test cases with no matches
    41  	assertNoMatch(t, []byte(topic), []byte("myhome/groundfloor/livingroom/temperature/"))
    42  	assertNoMatch(t, []byte(topic), []byte("myhome/groundfloor/livingroom/"))
    43  	assertNoMatch(t, []byte(topic), []byte("myhome/groundfloor/+/temperature/"))
    44  	assertNoMatch(t, []byte("myhome/groundfloor/livingroom"), []byte("myhome/groundfloor/+/temperature"))
    45  }
    46  
    47  func assertMatch(t *testing.T, topic []byte, topicFilter []byte) {
    48  	if !TopicMatch(topic, topicFilter) {
    49  		t.Errorf("Expected topic %s to match filter %s", topic, topicFilter)
    50  	}
    51  }
    52  
    53  func assertNoMatch(t *testing.T, topic []byte, topicFilter []byte) {
    54  	if TopicMatch(topic, topicFilter) {
    55  		t.Errorf("Expected topic %s to not match filter %s", topic, topicFilter)
    56  	}
    57  }