本文整理汇总了Golang中github.com/qingyuancloud/QingYuan/pkg/util.NewStringSet函数的典型用法代码示例。如果您正苦于以下问题:Golang NewStringSet函数的具体用法?Golang NewStringSet怎么用?Golang NewStringSet使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewStringSet函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: limitSecretReferences
func (s *serviceAccount) limitSecretReferences(serviceAccount *api.ServiceAccount, pod *api.Pod) error {
// Ensure all secrets the pod references are allowed by the service account
mountableSecrets := util.NewStringSet()
for _, s := range serviceAccount.Secrets {
mountableSecrets.Insert(s.Name)
}
for _, volume := range pod.Spec.Volumes {
source := volume.VolumeSource
if source.Secret == nil {
continue
}
secretName := source.Secret.SecretName
if !mountableSecrets.Has(secretName) {
return fmt.Errorf("Volume with secret.secretName=\"%s\" is not allowed because service account %s does not reference that secret", secretName, serviceAccount.Name)
}
}
// limit pull secret references as well
pullSecrets := util.NewStringSet()
for _, s := range serviceAccount.ImagePullSecrets {
pullSecrets.Insert(s.Name)
}
for i, pullSecretRef := range pod.Spec.ImagePullSecrets {
if !pullSecrets.Has(pullSecretRef.Name) {
return fmt.Errorf(`imagePullSecrets[%d].name="%s" is not allowed because service account %s does not reference that imagePullSecret`, i, pullSecretRef.Name, serviceAccount.Name)
}
}
return nil
}
示例2: TestAdd
func TestAdd(t *testing.T) {
testCases := []struct {
sel Selector
key string
operator Operator
values []string
refSelector Selector
}{
{
LabelSelector{},
"key",
InOperator,
[]string{"value"},
LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
},
{
LabelSelector{Requirement{"key", InOperator, util.NewStringSet("value")}},
"key2",
EqualsOperator,
[]string{"value2"},
LabelSelector{
Requirement{"key", InOperator, util.NewStringSet("value")},
Requirement{"key2", EqualsOperator, util.NewStringSet("value2")},
},
},
}
for _, ts := range testCases {
ts.sel = ts.sel.Add(ts.key, ts.operator, ts.values)
if !reflect.DeepEqual(ts.sel, ts.refSelector) {
t.Errorf("Expected %t found %t", ts.refSelector, ts.sel)
}
}
}
示例3: doTestIndex
// Test public interface
func doTestIndex(t *testing.T, indexer Indexer) {
mkObj := func(id string, val string) testStoreObject {
return testStoreObject{id: id, val: val}
}
// Test Index
expected := map[string]util.StringSet{}
expected["b"] = util.NewStringSet("a", "c")
expected["f"] = util.NewStringSet("e")
expected["h"] = util.NewStringSet("g")
indexer.Add(mkObj("a", "b"))
indexer.Add(mkObj("c", "b"))
indexer.Add(mkObj("e", "f"))
indexer.Add(mkObj("g", "h"))
{
for k, v := range expected {
found := util.StringSet{}
indexResults, err := indexer.Index("by_val", mkObj("", k))
if err != nil {
t.Errorf("Unexpected error %v", err)
}
for _, item := range indexResults {
found.Insert(item.(testStoreObject).id)
}
items := v.List()
if !found.HasAll(items...) {
t.Errorf("missing items, index %s, expected %v but found %v", k, items, found.List())
}
}
}
}
示例4: TestToString
func TestToString(t *testing.T) {
var req Requirement
toStringTests := []struct {
In *LabelSelector
Out string
Valid bool
}{
{&LabelSelector{
getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
getRequirement("y", NotInOperator, util.NewStringSet("jkl"), t),
getRequirement("z", ExistsOperator, nil, t)},
"x in (abc,def),y notin (jkl),z", true},
{&LabelSelector{
getRequirement("x", InOperator, util.NewStringSet("abc", "def"), t),
req}, // adding empty req for the trailing ','
"x in (abc,def),", false},
{&LabelSelector{
getRequirement("x", NotInOperator, util.NewStringSet("abc"), t),
getRequirement("y", InOperator, util.NewStringSet("jkl", "mno"), t),
getRequirement("z", NotInOperator, util.NewStringSet(""), t)},
"x notin (abc),y in (jkl,mno),z notin ()", true},
{&LabelSelector{
getRequirement("x", EqualsOperator, util.NewStringSet("abc"), t),
getRequirement("y", DoubleEqualsOperator, util.NewStringSet("jkl"), t),
getRequirement("z", NotEqualsOperator, util.NewStringSet("a"), t)},
"x=abc,y==jkl,z!=a", true},
}
for _, ts := range toStringTests {
if out := ts.In.String(); out == "" && ts.Valid {
t.Errorf("%+v.String() => '%v' expected no error", ts.In, out)
} else if out != ts.Out {
t.Errorf("%+v.String() => '%v' want '%v'", ts.In, out, ts.Out)
}
}
}
示例5: detectImages
func (im *realImageManager) detectImages(detected time.Time) error {
images, err := im.dockerClient.ListImages(docker.ListImagesOptions{})
if err != nil {
return err
}
containers, err := im.dockerClient.ListContainers(docker.ListContainersOptions{
All: true,
})
if err != nil {
return err
}
// Make a set of images in use by containers.
imagesInUse := util.NewStringSet()
for _, container := range containers {
imagesInUse.Insert(container.Image)
}
// Add new images and record those being used.
now := time.Now()
currentImages := util.NewStringSet()
im.imageRecordsLock.Lock()
defer im.imageRecordsLock.Unlock()
for _, image := range images {
currentImages.Insert(image.ID)
// New image, set it as detected now.
if _, ok := im.imageRecords[image.ID]; !ok {
im.imageRecords[image.ID] = &imageRecord{
detected: detected,
}
}
// Set last used time to now if the image is being used.
if isImageUsed(&image, imagesInUse) {
im.imageRecords[image.ID].lastUsed = now
}
im.imageRecords[image.ID].size = image.VirtualSize
}
// Remove old images from our records.
for image := range im.imageRecords {
if !currentImages.Has(image) {
delete(im.imageRecords, image)
}
}
return nil
}
示例6: TestEtcdWatch
func TestEtcdWatch(t *testing.T) {
table := map[string]generic.Matcher{
"single": setMatcher{util.NewStringSet("foo")},
"multi": setMatcher{util.NewStringSet("foo", "bar")},
}
for name, m := range table {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: "foo",
Namespace: api.NamespaceDefault,
ResourceVersion: "1",
},
Spec: api.PodSpec{NodeName: "machine"},
}
respWithPodA := &etcd.Response{
Node: &etcd.Node{
Key: "/registry/pods/default/foo",
Value: runtime.EncodeOrDie(testapi.Codec(), podA),
ModifiedIndex: 1,
CreatedIndex: 1,
},
Action: "create",
}
fakeClient, registry := NewTestGenericEtcdRegistry(t)
wi, err := registry.WatchPredicate(api.NewContext(), m, "1")
if err != nil {
t.Errorf("%v: unexpected error: %v", name, err)
continue
}
fakeClient.WaitForWatchCompletion()
go func() {
fakeClient.WatchResponse <- respWithPodA
}()
got, open := <-wi.ResultChan()
if !open {
t.Errorf("%v: unexpected channel close", name)
continue
}
if e, a := podA, got.Object; !api.Semantic.DeepDerivative(e, a) {
t.Errorf("%v: difference: %s", name, util.ObjectDiff(e, a))
}
}
}
示例7: newFakeMirrorClient
func newFakeMirrorClient() *fakeMirrorClient {
m := fakeMirrorClient{}
m.mirrorPods = util.NewStringSet()
m.createCounts = make(map[string]int)
m.deleteCounts = make(map[string]int)
return &m
}
示例8: TestFlushChain
func TestFlushChain(t *testing.T) {
fcmd := exec.FakeCmd{
CombinedOutputScript: []exec.FakeCombinedOutputAction{
// Success.
func() ([]byte, error) { return []byte{}, nil },
// Failure.
func() ([]byte, error) { return nil, &exec.FakeExitError{1} },
},
}
fexec := exec.FakeExec{
CommandScript: []exec.FakeCommandAction{
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
},
}
runner := New(&fexec, ProtocolIpv4)
// Success.
err := runner.FlushChain(TableNAT, Chain("FOOBAR"))
if err != nil {
t.Errorf("expected success, got %v", err)
}
if fcmd.CombinedOutputCalls != 1 {
t.Errorf("expected 1 CombinedOutput() call, got %d", fcmd.CombinedOutputCalls)
}
if !util.NewStringSet(fcmd.CombinedOutputLog[0]...).HasAll("iptables", "-t", "nat", "-F", "FOOBAR") {
t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[0])
}
// Failure.
err = runner.FlushChain(TableNAT, Chain("FOOBAR"))
if err == nil {
t.Errorf("expected failure")
}
}
示例9: TestDeleteRuleNew
func TestDeleteRuleNew(t *testing.T) {
fcmd := exec.FakeCmd{
CombinedOutputScript: []exec.FakeCombinedOutputAction{
// iptables version check
func() ([]byte, error) { return []byte("iptables v1.9.22"), nil },
// Success on the first call.
func() ([]byte, error) { return []byte{}, nil },
// Success on the second call.
func() ([]byte, error) { return []byte{}, nil },
},
}
fexec := exec.FakeExec{
CommandScript: []exec.FakeCommandAction{
// iptables version check
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
// The second Command() call is checking the rule. Success of that means delete it.
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
},
}
runner := New(&fexec, ProtocolIpv4)
err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123")
if err != nil {
t.Errorf("expected success, got %v", err)
}
if fcmd.CombinedOutputCalls != 3 {
t.Errorf("expected 3 CombinedOutput() calls, got %d", fcmd.CombinedOutputCalls)
}
if !util.NewStringSet(fcmd.CombinedOutputLog[2]...).HasAll("iptables", "-t", "nat", "-D", "OUTPUT", "abc", "123") {
t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[1])
}
}
示例10: TestDeleteRuleAlreadyExists
func TestDeleteRuleAlreadyExists(t *testing.T) {
fcmd := exec.FakeCmd{
CombinedOutputScript: []exec.FakeCombinedOutputAction{
// iptables version check
func() ([]byte, error) { return []byte("iptables v1.9.22"), nil },
// Status 1 on the first call.
func() ([]byte, error) { return nil, &exec.FakeExitError{1} },
},
}
fexec := exec.FakeExec{
CommandScript: []exec.FakeCommandAction{
// iptables version check
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
// The second Command() call is checking the rule. Failure of that exec means "does not exist".
func(cmd string, args ...string) exec.Cmd { return exec.InitFakeCmd(&fcmd, cmd, args...) },
},
}
runner := New(&fexec, ProtocolIpv4)
err := runner.DeleteRule(TableNAT, ChainOutput, "abc", "123")
if err != nil {
t.Errorf("expected success, got %v", err)
}
if fcmd.CombinedOutputCalls != 2 {
t.Errorf("expected 2 CombinedOutput() call, got %d", fcmd.CombinedOutputCalls)
}
if !util.NewStringSet(fcmd.CombinedOutputLog[1]...).HasAll("iptables", "-t", "nat", "-C", "OUTPUT", "abc", "123") {
t.Errorf("wrong CombinedOutput() log, got %s", fcmd.CombinedOutputLog[0])
}
}
示例11: describeService
func describeService(service *api.Service, endpoints *api.Endpoints, events *api.EventList) (string, error) {
if endpoints == nil {
endpoints = &api.Endpoints{}
}
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", service.Name)
fmt.Fprintf(out, "Labels:\t%s\n", formatLabels(service.Labels))
fmt.Fprintf(out, "Selector:\t%s\n", formatLabels(service.Spec.Selector))
fmt.Fprintf(out, "Type:\t%s\n", service.Spec.Type)
fmt.Fprintf(out, "IP:\t%s\n", service.Spec.ClusterIP)
if len(service.Status.LoadBalancer.Ingress) > 0 {
list := buildIngressString(service.Status.LoadBalancer.Ingress)
fmt.Fprintf(out, "LoadBalancer Ingress:\t%s\n", list)
}
for i := range service.Spec.Ports {
sp := &service.Spec.Ports[i]
name := sp.Name
if name == "" {
name = "<unnamed>"
}
fmt.Fprintf(out, "Port:\t%s\t%d/%s\n", name, sp.Port, sp.Protocol)
if sp.NodePort != 0 {
fmt.Fprintf(out, "NodePort:\t%s\t%d/%s\n", name, sp.NodePort, sp.Protocol)
}
fmt.Fprintf(out, "Endpoints:\t%s\n", formatEndpoints(endpoints, util.NewStringSet(sp.Name)))
}
fmt.Fprintf(out, "Session Affinity:\t%s\n", service.Spec.SessionAffinity)
if events != nil {
DescribeEvents(events, out)
}
return nil
})
}
示例12: TestSyncNamespaceThatIsActive
func TestSyncNamespaceThatIsActive(t *testing.T) {
mockClient := &testclient.Fake{}
testNamespace := api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: "test",
ResourceVersion: "1",
},
Spec: api.NamespaceSpec{
Finalizers: []api.FinalizerName{"qingyuan"},
},
Status: api.NamespaceStatus{
Phase: api.NamespaceActive,
},
}
err := syncNamespace(mockClient, testNamespace)
if err != nil {
t.Errorf("Unexpected error when synching namespace %v", err)
}
actionSet := util.NewStringSet()
for i := range mockClient.Actions {
actionSet.Insert(mockClient.Actions[i].Action)
}
if len(actionSet) != 0 {
t.Errorf("Expected no action from controller, but got: %v", actionSet)
}
}
示例13: getSecretReferences
func getSecretReferences(serviceAccount *api.ServiceAccount) util.StringSet {
references := util.NewStringSet()
for _, secret := range serviceAccount.Secrets {
references.Insert(secret.Name)
}
return references
}
示例14: TestTTLExpirationBasic
func TestTTLExpirationBasic(t *testing.T) {
testObj := testStoreObject{id: "foo", val: "bar"}
deleteChan := make(chan string)
ttlStore := NewFakeExpirationStore(
testStoreKeyFunc, deleteChan,
&FakeExpirationPolicy{
NeverExpire: util.NewStringSet(),
RetrieveKeyFunc: func(obj interface{}) (string, error) {
return obj.(*timestampedEntry).obj.(testStoreObject).id, nil
},
},
util.RealClock{},
)
err := ttlStore.Add(testObj)
if err != nil {
t.Errorf("Unable to add obj %#v", testObj)
}
item, exists, err := ttlStore.Get(testObj)
if err != nil {
t.Errorf("Failed to get from store, %v", err)
}
if exists || item != nil {
t.Errorf("Got unexpected item %#v", item)
}
key, _ := testStoreKeyFunc(testObj)
select {
case delKey := <-deleteChan:
if delKey != key {
t.Errorf("Unexpected delete for key %s", key)
}
case <-time.After(time.Millisecond * 100):
t.Errorf("Unexpected timeout waiting on delete")
}
close(deleteChan)
}
示例15: parseIdentifiersList
// parseIdentifiersList parses a (possibly empty) list of
// of comma separated (possibly empty) identifiers
func (p *Parser) parseIdentifiersList() (util.StringSet, error) {
s := util.NewStringSet()
for {
tok, lit := p.consume(Values)
switch tok {
case IdentifierToken:
s.Insert(lit)
tok2, lit2 := p.lookahead(Values)
switch tok2 {
case CommaToken:
continue
case ClosedParToken:
return s, nil
default:
return nil, fmt.Errorf("found '%s', expected: ',' or ')'", lit2)
}
case CommaToken: // handled here since we can have "(,"
if s.Len() == 0 {
s.Insert("") // to handle (,
}
tok2, _ := p.lookahead(Values)
if tok2 == ClosedParToken {
s.Insert("") // to handle ,) Double "" removed by StringSet
return s, nil
}
if tok2 == CommaToken {
p.consume(Values)
s.Insert("") // to handle ,, Double "" removed by StringSet
}
default: // it can be operator
return s, fmt.Errorf("found '%s', expected: ',', or identifier", lit)
}
}
}