github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/registry/consul/watcher_test.go (about)

     1  package consul
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/hashicorp/consul/api"
     7  	"github.com/volts-dev/volts/registry"
     8  )
     9  
    10  func TestHealthyServiceHandler(t *testing.T) {
    11  	watcher := newWatcher()
    12  	serviceEntry := newServiceEntry(
    13  		"node-name", "node-address", "service-name", "v1.0.0",
    14  		[]*api.HealthCheck{
    15  			newHealthCheck("node-name", "service-name", "passing"),
    16  		},
    17  	)
    18  
    19  	watcher.serviceHandler(1234, []*api.ServiceEntry{serviceEntry})
    20  
    21  	if len(watcher.services["service-name"][0].Nodes) != 1 {
    22  		t.Errorf("Expected length of the service nodes to be 1")
    23  	}
    24  }
    25  
    26  func TestUnhealthyServiceHandler(t *testing.T) {
    27  	watcher := newWatcher()
    28  	serviceEntry := newServiceEntry(
    29  		"node-name", "node-address", "service-name", "v1.0.0",
    30  		[]*api.HealthCheck{
    31  			newHealthCheck("node-name", "service-name", "critical"),
    32  		},
    33  	)
    34  
    35  	watcher.serviceHandler(1234, []*api.ServiceEntry{serviceEntry})
    36  
    37  	if len(watcher.services["service-name"][0].Nodes) != 0 {
    38  		t.Errorf("Expected length of the service nodes to be 0")
    39  	}
    40  }
    41  
    42  func TestUnhealthyNodeServiceHandler(t *testing.T) {
    43  	watcher := newWatcher()
    44  	serviceEntry := newServiceEntry(
    45  		"node-name", "node-address", "service-name", "v1.0.0",
    46  		[]*api.HealthCheck{
    47  			newHealthCheck("node-name", "service-name", "passing"),
    48  			newHealthCheck("node-name", "serfHealth", "critical"),
    49  		},
    50  	)
    51  
    52  	watcher.serviceHandler(1234, []*api.ServiceEntry{serviceEntry})
    53  
    54  	if len(watcher.services["service-name"][0].Nodes) != 0 {
    55  		t.Errorf("Expected length of the service nodes to be 0")
    56  	}
    57  }
    58  
    59  func newWatcher() *consulWatcher {
    60  	return &consulWatcher{
    61  		exit:     make(chan bool),
    62  		next:     make(chan *registry.Result, 10),
    63  		services: make(map[string][]*registry.Service),
    64  	}
    65  }
    66  
    67  func newHealthCheck(node, name, status string) *api.HealthCheck {
    68  	return &api.HealthCheck{
    69  		Node:        node,
    70  		Name:        name,
    71  		Status:      status,
    72  		ServiceName: name,
    73  	}
    74  }
    75  
    76  func newServiceEntry(node, address, name, version string, checks []*api.HealthCheck) *api.ServiceEntry {
    77  	return &api.ServiceEntry{
    78  		Node: &api.Node{Node: node, Address: name},
    79  		Service: &api.AgentService{
    80  			Service: name,
    81  			Address: address,
    82  			Tags:    encodeVersion(version),
    83  		},
    84  		Checks: checks,
    85  	}
    86  }