github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/events_test.go (about)

     1  package daemon
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	containertypes "github.com/docker/docker/api/types/container"
     8  	eventtypes "github.com/docker/docker/api/types/events"
     9  	"github.com/docker/docker/container"
    10  	"github.com/docker/docker/daemon/events"
    11  )
    12  
    13  func TestLogContainerEventCopyLabels(t *testing.T) {
    14  	e := events.New()
    15  	_, l, _ := e.Subscribe()
    16  	defer e.Evict(l)
    17  
    18  	container := &container.Container{
    19  		ID:   "container_id",
    20  		Name: "container_name",
    21  		Config: &containertypes.Config{
    22  			Image: "image_name",
    23  			Labels: map[string]string{
    24  				"node": "1",
    25  				"os":   "alpine",
    26  			},
    27  		},
    28  	}
    29  	daemon := &Daemon{
    30  		EventsService: e,
    31  	}
    32  	daemon.LogContainerEvent(container, "create")
    33  
    34  	if _, mutated := container.Config.Labels["image"]; mutated {
    35  		t.Fatalf("Expected to not mutate the container labels, got %q", container.Config.Labels)
    36  	}
    37  
    38  	validateTestAttributes(t, l, map[string]string{
    39  		"node": "1",
    40  		"os":   "alpine",
    41  	})
    42  }
    43  
    44  func TestLogContainerEventWithAttributes(t *testing.T) {
    45  	e := events.New()
    46  	_, l, _ := e.Subscribe()
    47  	defer e.Evict(l)
    48  
    49  	container := &container.Container{
    50  		ID:   "container_id",
    51  		Name: "container_name",
    52  		Config: &containertypes.Config{
    53  			Labels: map[string]string{
    54  				"node": "1",
    55  				"os":   "alpine",
    56  			},
    57  		},
    58  	}
    59  	daemon := &Daemon{
    60  		EventsService: e,
    61  	}
    62  	attributes := map[string]string{
    63  		"node": "2",
    64  		"foo":  "bar",
    65  	}
    66  	daemon.LogContainerEventWithAttributes(container, "create", attributes)
    67  
    68  	validateTestAttributes(t, l, map[string]string{
    69  		"node": "1",
    70  		"foo":  "bar",
    71  	})
    72  }
    73  
    74  func validateTestAttributes(t *testing.T, l chan interface{}, expectedAttributesToTest map[string]string) {
    75  	select {
    76  	case ev := <-l:
    77  		event, ok := ev.(eventtypes.Message)
    78  		if !ok {
    79  			t.Fatalf("Unexpected event message: %q", ev)
    80  		}
    81  		for key, expected := range expectedAttributesToTest {
    82  			actual, ok := event.Actor.Attributes[key]
    83  			if !ok || actual != expected {
    84  				t.Fatalf("Expected value for key %s to be %s, but was %s (event:%v)", key, expected, actual, event)
    85  			}
    86  		}
    87  	case <-time.After(10 * time.Second):
    88  		t.Fatal("LogEvent test timed out")
    89  	}
    90  }