github.com/taylorchu/nomad@v0.5.3-rc1.0.20170407200202-db11e7dd7b55/client/util_test.go (about) 1 package client 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "reflect" 8 "testing" 9 10 "github.com/hashicorp/nomad/nomad/mock" 11 "github.com/hashicorp/nomad/nomad/structs" 12 ) 13 14 func TestDiffAllocs(t *testing.T) { 15 t.Parallel() 16 alloc1 := mock.Alloc() // Ignore 17 alloc2 := mock.Alloc() // Update 18 alloc2u := new(structs.Allocation) 19 *alloc2u = *alloc2 20 alloc2u.AllocModifyIndex += 1 21 alloc3 := mock.Alloc() // Remove 22 alloc4 := mock.Alloc() // Add 23 24 exist := []*structs.Allocation{ 25 alloc1, 26 alloc2, 27 alloc3, 28 } 29 update := &allocUpdates{ 30 pulled: map[string]*structs.Allocation{ 31 alloc2u.ID: alloc2u, 32 alloc4.ID: alloc4, 33 }, 34 filtered: map[string]struct{}{ 35 alloc1.ID: struct{}{}, 36 }, 37 } 38 39 result := diffAllocs(exist, update) 40 41 if len(result.ignore) != 1 || result.ignore[0] != alloc1 { 42 t.Fatalf("Bad: %#v", result.ignore) 43 } 44 if len(result.added) != 1 || result.added[0] != alloc4 { 45 t.Fatalf("Bad: %#v", result.added) 46 } 47 if len(result.removed) != 1 || result.removed[0] != alloc3 { 48 t.Fatalf("Bad: %#v", result.removed) 49 } 50 if len(result.updated) != 1 { 51 t.Fatalf("Bad: %#v", result.updated) 52 } 53 if result.updated[0].exist != alloc2 || result.updated[0].updated != alloc2u { 54 t.Fatalf("Bad: %#v", result.updated) 55 } 56 } 57 58 func TestShuffleStrings(t *testing.T) { 59 t.Parallel() 60 // Generate input 61 inp := make([]string, 10) 62 for idx := range inp { 63 inp[idx] = structs.GenerateUUID() 64 } 65 66 // Copy the input 67 orig := make([]string, len(inp)) 68 copy(orig, inp) 69 70 // Shuffle 71 shuffleStrings(inp) 72 73 // Ensure order is not the same 74 if reflect.DeepEqual(inp, orig) { 75 t.Fatalf("shuffle failed") 76 } 77 } 78 79 func TestPersistRestoreState(t *testing.T) { 80 t.Parallel() 81 dir, err := ioutil.TempDir("", "nomad") 82 if err != nil { 83 t.Fatalf("err: %s", err) 84 } 85 defer os.RemoveAll(dir) 86 87 // Use a state path inside a non-existent directory. This 88 // verifies that the directory is created properly. 89 statePath := filepath.Join(dir, "subdir", "test-persist") 90 91 type stateTest struct { 92 Foo int 93 Bar string 94 Baz bool 95 } 96 state := stateTest{ 97 Foo: 42, 98 Bar: "the quick brown fox", 99 Baz: true, 100 } 101 102 err = persistState(statePath, &state) 103 if err != nil { 104 t.Fatalf("err: %v", err) 105 } 106 107 var out stateTest 108 err = restoreState(statePath, &out) 109 if err != nil { 110 t.Fatalf("err: %v", err) 111 } 112 113 if !reflect.DeepEqual(state, out) { 114 t.Fatalf("bad: %#v %#v", state, out) 115 } 116 }