Exemple #1
0
func TestCompoundSetFilter(t *testing.T) {
	assert := assert.New(t)

	doTest := func(ts testSet) {
		set := ts.toCompoundSet()
		sort.Sort(ts)
		pivotPoint := 10
		pivot := ts.values[pivotPoint]
		actual := set.Filter(func(v Value) bool {
			return ts.less(v, pivot)
		})
		assert.True(newTypedSet(ts.tr, ts.values[:pivotPoint+1]...).Equals(actual))

		idx := 0
		actual.IterAll(func(v Value) {
			assert.True(ts.values[idx].Equals(v), "%v != %v", v, ts.values[idx])
			idx++
		})
	}

	doTest(getTestNativeOrderSet(16))
	doTest(getTestRefValueOrderSet(2))
	doTest(getTestRefToNativeOrderSet(2))
	doTest(getTestRefToValueOrderSet(2))
}
Exemple #2
0
// TestFormIsValid tests data that come from request (url.Values)
func TestFormIsValid(t *testing.T) {
	postData := url.Values{
		"field1": []string{"Foo"},
		"field2": []string{"Bar"},
		"fieldX": []string{"Ham"},
	}

	f := Form{
		Fields: map[string]*Field{
			"field1": &Field{
				Type: &Input{},
			},
			"field2": &Field{
				Type: &Input{},
			},
		},
	}

	assert.Equal(
		t, f.CleanedData, *new(Data),
		"CleanedData should be empty at beggining")

	assert.True(t, f.IsValid(postData), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Foo", "field2": "Bar"},
		"Forms CleanedData field should contain cleaned data")

	assert.True(t, f.IsValid(url.Values{}), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "", "field2": ""},
		"Form should pass")
}
Exemple #3
0
func testAtomicPutCreate(t *testing.T, kv store.Store) {
	// Use a key in a new directory to ensure Stores will create directories
	// that don't yet exist.
	key := "testAtomicPutCreate/create"
	value := []byte("putcreate")

	// AtomicPut the key, previous = nil indicates create.
	success, _, err := kv.AtomicPut(key, value, nil, nil)
	assert.NoError(t, err)
	assert.True(t, success)

	// Get should return the value and an incremented index
	pair, err := kv.Get(key)
	assert.NoError(t, err)
	if assert.NotNil(t, pair) {
		assert.NotNil(t, pair.Value)
	}
	assert.Equal(t, pair.Value, value)

	// Attempting to create again should fail.
	success, _, err = kv.AtomicPut(key, value, nil, nil)
	assert.Error(t, err)
	assert.False(t, success)

	// This CAS should succeed, since it has the value from Get()
	success, _, err = kv.AtomicPut(key, []byte("PUTCREATE"), pair, nil)
	assert.NoError(t, err)
	assert.True(t, success)
}
func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
	server := initTestServer("2014-12-16T01:51:37Z", false)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client:       ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
		ExpiryWindow: time.Hour * 1,
	}
	p.CurrentTime = func() time.Time {
		return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC)
	}

	assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")

	_, err := p.Retrieve()
	assert.Nil(t, err, "Expect no error")

	assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")

	p.CurrentTime = func() time.Time {
		return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC)
	}

	assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
func TestTypeResolver_AdditionalItems(t *testing.T) {
	_, resolver, err := basicTaskListResolver(t)
	tpe := spec.StringProperty()
	if assert.NoError(t, err) {
		// arrays of primitives and string formats with additional formats
		for _, val := range schTypeVals {
			var sch spec.Schema
			sch.Typed(val.Type, val.Format)
			var coll spec.Schema
			coll.Type = []string{"array"}
			coll.Items = new(spec.SchemaOrArray)
			coll.Items.Schema = tpe
			coll.AdditionalItems = new(spec.SchemaOrBool)
			coll.AdditionalItems.Schema = &sch

			rt, err := resolver.ResolveSchema(&coll, true)
			if assert.NoError(t, err) && assert.True(t, rt.IsArray) {
				assert.True(t, rt.HasAdditionalItems)
				assert.False(t, rt.IsNullable)
				//if assert.NotNil(t, rt.ElementType) {
				//assertPrimitiveResolve(t, "string", "", "string", *rt.ElementType)
				//}
			}
		}
	}
}
Exemple #6
0
func TestIsSameFile(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	fileInfo1, err := os.Stat(absPath + "/logs/test.log")
	fileInfo2, err := os.Stat(absPath + "/logs/system.log")

	assert.Nil(t, err)
	assert.NotNil(t, fileInfo1)
	assert.NotNil(t, fileInfo2)

	file1 := &File{
		FileInfo: fileInfo1,
	}

	file2 := &File{
		FileInfo: fileInfo2,
	}

	file3 := &File{
		FileInfo: fileInfo2,
	}

	assert.False(t, file1.IsSameFile(file2))
	assert.False(t, file2.IsSameFile(file1))

	assert.True(t, file1.IsSameFile(file1))
	assert.True(t, file2.IsSameFile(file2))

	assert.True(t, file3.IsSameFile(file2))
	assert.True(t, file2.IsSameFile(file3))
}
func TestLoadBagValidationConfig(t *testing.T) {
	configFilePath := path.Join("testdata", "json_objects", "bag_validation_config.json")
	conf, errors := validation.LoadBagValidationConfig(configFilePath)
	if errors != nil && len(errors) > 0 {
		assert.Fail(t, errors[0].Error())
	}
	assert.True(t, conf.AllowMiscTopLevelFiles)
	assert.True(t, conf.AllowMiscDirectories)
	assert.True(t, conf.TopLevelDirMustMatchBagName)
	assert.Equal(t, 7, len(conf.FileSpecs))
	assert.Equal(t, 3, len(conf.TagSpecs))
	assert.Equal(t, 2, len(conf.FixityAlgorithms))

	// Spot checks
	if _, ok := conf.FileSpecs["manifest-md5.txt"]; !ok {
		assert.Fail(t, "FileSpec for manifest-md5.txt is missing")
	}
	if _, ok := conf.FileSpecs["manifest-sha256.txt"]; !ok {
		assert.Fail(t, "FileSpec for manifest-sha256.txt is missing")
	}
	if _, ok := conf.TagSpecs["Title"]; !ok {
		assert.Fail(t, "TagSpec for Title is missing")
	}
	if len(conf.FixityAlgorithms) > 1 {
		assert.Equal(t, "md5", conf.FixityAlgorithms[0])
		assert.Equal(t, "sha256", conf.FixityAlgorithms[1])
	}
	assert.Equal(t, validation.REQUIRED, conf.FileSpecs["manifest-md5.txt"].Presence)
	assert.Equal(t, validation.OPTIONAL, conf.FileSpecs["manifest-sha256.txt"].Presence)
	assert.Equal(t, "aptrust-info.txt", conf.TagSpecs["Title"].FilePath)
	assert.Equal(t, validation.REQUIRED, conf.TagSpecs["Title"].Presence)
	assert.False(t, conf.TagSpecs["Title"].EmptyOK)
	assert.Equal(t, 3, len(conf.TagSpecs["Access"].AllowedValues))
}
Exemple #8
0
func TestHttpParser_301_response(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"http"})
	}

	data := "HTTP/1.1 301 Moved Permanently\r\n" +
		"Date: Sun, 29 Sep 2013 16:53:59 GMT\r\n" +
		"Server: Apache\r\n" +
		"Location: http://www.hotnews.ro/\r\n" +
		"Vary: Accept-Encoding\r\n" +
		"Content-Length: 290\r\n" +
		"Connection: close\r\n" +
		"Content-Type: text/html; charset=iso-8859-1\r\n" +
		"\r\n" +
		"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n" +
		"<html><head>\r\n" +
		"<title>301 Moved Permanently</title>\r\n" +
		"</head><body>\r\n" +
		"<h1>Moved Permanently</h1>\r\n" +
		"<p>The document has moved <a href=\"http://www.hotnews.ro/\">here</a>.</p>\r\n" +
		"<hr>\r\n" +
		"<address>Apache Server at hotnews.ro Port 80</address>\r\n" +
		"</body></html>"

	msg, ok, complete := testParse(nil, data)
	assert.True(t, ok)
	assert.True(t, complete)
	assert.Equal(t, 290, msg.contentLength)
}
Exemple #9
0
func TestHttpParser_censorPasswordPOST(t *testing.T) {

	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"http", "httpdetailed"})
	}

	http := httpModForTests()
	http.hideKeywords = []string{"password"}
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data1 :=
		"POST /users/login HTTP/1.1\r\n" +
			"HOST: www.example.com\r\n" +
			"Content-Type: application/x-www-form-urlencoded\r\n" +
			"Content-Length: 28\r\n" +
			"\r\n" +
			"username=ME&password=secret\r\n"
	tp := newTestParser(http, data1)

	msg, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.True(t, complete)

	rawMsg := tp.stream.data[tp.stream.message.start:tp.stream.message.end]
	path, params, err := http.extractParameters(msg, rawMsg)
	assert.Nil(t, err)
	assert.Equal(t, "/users/login", path)
	assert.False(t, strings.Contains(params, "secret"))
}
Exemple #10
0
func TestHttpParser_splitResponse_midHeaderName(t *testing.T) {
	http := httpModForTests()
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data1 := "HTTP/1.1 200 OK\r\n" +
		"Date: Tue, 14 Aug 2012 22:31:45 GMT\r\n" +
		"Expires: -1\r\n" +
		"Cache-Control: private, max-age=0\r\n" +
		"Content-Type: text/html; charset=UTF-8\r\n" +
		"Content-En"
	data2 := "coding: gzip\r\n" +
		"Server: gws\r\n" +
		"Content-Length: 0\r\n" +
		"X-XSS-Protection: 1; mode=block\r\n" +
		"X-Frame-Options: SAMEORIGIN\r\n" +
		"\r\n"
	tp := newTestParser(http, data1, data2)

	_, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	message, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.True(t, complete)
	assert.False(t, message.isRequest)
	assert.Equal(t, 200, int(message.statusCode))
	assert.Equal(t, "OK", string(message.statusPhrase))
	assert.True(t, isVersion(message.version, 1, 1))
	assert.Equal(t, 262, int(message.size))
	assert.Equal(t, 0, message.contentLength)
}
Exemple #11
0
func TestHttpParser_splitResponse_midBody(t *testing.T) {
	data1 := "HTTP/1.1 200 OK\r\n" +
		"Date: Tue, 14 Aug 2012 22:31:45 GMT\r\n" +
		"Expires: -1\r\n" +
		"Cache-Control: private, max-age=0\r\n" +
		"Content-Type: text/html; charset=UTF-8\r\n" +
		"Content-Encoding: gzip\r\n" +
		"Server: gws\r\n" +
		"Content-Length: 3"
	data2 := "0\r\n" +
		"X-XSS-Protection: 1; mode=block\r\n" +
		"X-Frame-Options: SAMEORIGIN\r\n" +
		"\r\n" +
		"xxxxxxxxxx"
	data3 := "xxxxxxxxxxxxxxxxxxxx"
	tp := newTestParser(nil, data1, data2, data3)

	_, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	_, ok, complete = tp.parse()
	assert.True(t, ok)
	assert.False(t, complete)

	message, ok, complete := tp.parse()
	assert.True(t, ok)
	assert.True(t, complete)
	assert.Equal(t, 30, message.contentLength)
	assert.Equal(t, []byte(""), tp.stream.data[tp.stream.parseOffset:])
}
Exemple #12
0
func TestHttpParser_eatBody_connclose(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"http", "httpdetailed"})
	}

	http := httpModForTests()
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data := []byte("HTTP/1.1 200 ok\r\n" +
		"user-agent: curl/7.35.0\r\n" +
		"host: localhost:9000\r\n" +
		"accept: */*\r\n" +
		"authorization: Company 1\r\n" +
		"connection: close\r\n" +
		"\r\n" +
		"0123456789")

	st := &stream{data: data, message: new(message)}
	ok, complete := testParseStream(http, st, 0)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 10)

	ok, complete = testParseStream(http, st, 5)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 15)

	ok, complete = testParseStream(http, st, 5)
	assert.True(t, ok)
	assert.False(t, complete)
	assert.Equal(t, st.bodyReceived, 20)
}
Exemple #13
0
func TestHttpParser_simpleRequest(t *testing.T) {
	http := httpModForTests()
	http.parserConfig.sendHeaders = true
	http.parserConfig.sendAllHeaders = true

	data := "GET / HTTP/1.1\r\n" +
		"Host: www.google.ro\r\n" +
		"Connection: keep-alive\r\n" +
		"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1\r\n" +
		"Accept: */*\r\n" +
		"X-Chrome-Variations: CLa1yQEIj7bJAQiftskBCKS2yQEIp7bJAQiptskBCLSDygE=\r\n" +
		"Referer: http://www.google.ro/\r\n" +
		"Accept-Encoding: gzip,deflate,sdch\r\n" +
		"Accept-Language: en-US,en;q=0.8\r\n" +
		"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n" +
		"Cookie: PREF=ID=6b67d166417efec4:U=69097d4080ae0e15:FF=0:TM=1340891937:LM=1340891938:S=8t97UBiUwKbESvVX; NID=61=sf10OV-t02wu5PXrc09AhGagFrhSAB2C_98ZaI53-uH4jGiVG_yz9WmE3vjEBcmJyWUogB1ZF5puyDIIiB-UIdLd4OEgPR3x1LHNyuGmEDaNbQ_XaxWQqqQ59mX1qgLQ\r\n" +
		"\r\n" +
		"garbage"

	message, ok, complete := testParse(http, data)

	assert.True(t, ok)
	assert.True(t, complete)
	assert.True(t, message.isRequest)
	assert.True(t, isVersion(message.version, 1, 1))
	assert.Equal(t, 669, int(message.size))
	assert.Equal(t, "GET", string(message.method))
	assert.Equal(t, "/", string(message.requestURI))
	assert.Equal(t, "www.google.ro", string(message.headers["host"]))
}
Exemple #14
0
func TestHttp_configsSettingAll(t *testing.T) {

	http := httpModForTests()
	config := defaultConfig

	// Assign config vars
	config.Ports = []int{80, 8080}

	config.SendRequest = true
	config.SendResponse = true
	config.HideKeywords = []string{"a", "b"}
	config.RedactAuthorization = true
	config.SendAllHeaders = true
	config.SplitCookie = true
	config.RealIPHeader = "X-Forwarded-For"

	// Set config
	http.setFromConfig(&config)

	// Check if http config is set correctly
	assert.Equal(t, config.Ports, http.ports)
	assert.Equal(t, config.Ports, http.GetPorts())
	assert.Equal(t, config.SendRequest, http.sendRequest)
	assert.Equal(t, config.SendResponse, http.sendResponse)
	assert.Equal(t, config.HideKeywords, http.hideKeywords)
	assert.Equal(t, config.RedactAuthorization, http.redactAuthorization)
	assert.True(t, http.parserConfig.sendHeaders)
	assert.True(t, http.parserConfig.sendAllHeaders)
	assert.Equal(t, config.SplitCookie, http.splitCookie)
	assert.Equal(t, strings.ToLower(config.RealIPHeader), http.parserConfig.realIPHeader)
}
func TestDoNotDeleteMirrorPods(t *testing.T) {
	staticPod := getTestPod()
	staticPod.Annotations = map[string]string{kubetypes.ConfigSourceAnnotationKey: "file"}
	mirrorPod := getTestPod()
	mirrorPod.UID = "mirror-12345678"
	mirrorPod.Annotations = map[string]string{
		kubetypes.ConfigSourceAnnotationKey: "api",
		kubetypes.ConfigMirrorAnnotationKey: "mirror",
	}
	// Set the deletion timestamp.
	mirrorPod.DeletionTimestamp = new(unversioned.Time)
	client := fake.NewSimpleClientset(mirrorPod)
	m := newTestManager(client)
	m.podManager.AddPod(staticPod)
	m.podManager.AddPod(mirrorPod)
	// Verify setup.
	assert.True(t, kubepod.IsStaticPod(staticPod), "SetUp error: staticPod")
	assert.True(t, kubepod.IsMirrorPod(mirrorPod), "SetUp error: mirrorPod")
	assert.Equal(t, m.podManager.TranslatePodUID(mirrorPod.UID), staticPod.UID)

	status := getRandomPodStatus()
	now := unversioned.Now()
	status.StartTime = &now
	m.SetPodStatus(staticPod, status)

	m.testSyncBatch()
	// Expect not to see an delete action.
	verifyActions(t, m.kubeClient, []core.Action{
		core.GetActionImpl{ActionImpl: core.ActionImpl{Verb: "get", Resource: "pods"}},
		core.UpdateActionImpl{ActionImpl: core.ActionImpl{Verb: "update", Resource: "pods", Subresource: "status"}},
	})
}
func TestPriorityQueue_order_Time(t *testing.T) {
	pq := NewPriorityQueue(Less(func(x, y interface{}) bool {
		return x.(time.Time).Before(y.(time.Time))
	}), 10)

	//Populate the priority queue with random times
	var src rand.Source = rand.NewSource(0)
	var r *rand.Rand = rand.New(src)
	for i := 0; i < 10; i++ {
		assert.True(
			t,
			pq.Length() == i,
			"pq.Length() = %d; want %d", pq.Length(), i,
		)
		pq.Insert(time.Now().Add(time.Hour * time.Duration(r.Int())))
	}
	var prev time.Time = pq.PopTop().(time.Time)
	var next time.Time
	for pq.Length() > 0 {
		next = pq.PopTop().(time.Time)
		assert.True(
			t,
			prev.Before(next),
			"%s sorted before %s; want %s sorted after %s", prev, next, prev, next,
		)
	}
}
Exemple #17
0
func TestGetRemoteSignedCertificate(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Create a new CSR to be signed
	csr, _, err := ca.GenerateAndWriteNewKey(tc.Paths.Node)
	assert.NoError(t, err)

	certs, err := ca.GetRemoteSignedCertificate(context.Background(), csr, tc.ManagerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)

	// Test the expiration for a manager certificate
	parsedCerts, err := helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.ManagerRole)

	// Test the expiration for an agent certificate
	certs, err = ca.GetRemoteSignedCertificate(tc.Context, csr, tc.WorkerToken, tc.RootCA.Pool, tc.Remotes, nil, nil)
	assert.NoError(t, err)
	assert.NotNil(t, certs)
	parsedCerts, err = helpers.ParseCertificatesPEM(certs)
	assert.NoError(t, err)
	assert.Len(t, parsedCerts, 2)
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, -1).Before(parsedCerts[0].NotAfter))
	assert.True(t, time.Now().Add(ca.DefaultNodeCertExpiration).AddDate(0, 0, 1).After(parsedCerts[0].NotAfter))
	assert.Equal(t, parsedCerts[0].Subject.OrganizationalUnit[0], ca.AgentRole)
}
Exemple #18
0
func TestSystem(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "")
	require.NoError(t, err)
	defer os.RemoveAll(tmpdir)

	sys := NewSystem(SystemConfig{BuildTempDir: tmpdir})
	{
		tmpFile1, err := sys.SmallTempFile()
		if assert.NoError(t, err) {
			defer os.Remove(tmpFile1.Name())
			defer tmpFile1.Close()
			tmpFile2, err := sys.SmallTempFile()
			if assert.NoError(t, err) {
				defer os.Remove(tmpFile2.Name())
				defer tmpFile2.Close()
				assert.NotEqual(t, tmpFile1.Name(), tmpFile2.Name())
			}
		}
	}
	{
		tmpDir1, err := sys.TempDirForBuild()
		if assert.NoError(t, err) {
			assert.True(t, strings.HasPrefix(tmpDir1, tmpdir))
			tmpDir2, err := sys.TempDirForBuild()
			if assert.NoError(t, err) {
				assert.True(t, strings.HasPrefix(tmpDir2, tmpdir))
				assert.NotEqual(t, tmpDir1, tmpDir2)
			}
		}
	}
}
Exemple #19
0
func TestMemoryDirTreeExists(t *testing.T) {
	m := NewMemoryDirTree(":")
	m.Mkdir("aaa:bbb:ccc")
	assert.True(t, m.Exists("aaa"))
	assert.True(t, m.Exists("aaa:bbb"))
	assert.True(t, m.Exists("aaa:bbb:ccc"))
}
func TestArrayItemsValidation(t *testing.T) {
	items := spec.NewItems().CollectionOf(stringItems, "").WithMinItems(1).WithMaxItems(5).UniqueValues()
	items.WithEnum("aaa", "bbb", "ccc")
	parent := spec.QueryParam("tags").CollectionOf(items, "")
	path := parent.Name + ".1"
	validator := newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default)

	// MinItems
	err := validator.Validate(1, []string{})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, minItemsErrorItems(path, validator.in, items), err.Errors[0].Error())
	// MaxItems
	err = validator.Validate(1, []string{"a", "b", "c", "d", "e", "f"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, maxItemsErrorItems(path, validator.in, items), err.Errors[0].Error())
	// UniqueItems
	err = validator.Validate(1, []string{"a", "a"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, duplicatesErrorItems(path, validator.in), err.Errors[0].Error())

	// Enum
	err = validator.Validate(1, []string{"a", "b", "c"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, enumFailItems(path, validator.in, items, []string{"a", "b", "c"}), err.Errors[0].Error())

	// Items
	strItems := spec.NewItems().WithMinLength(3).WithMaxLength(5).WithPattern(`^[a-z]+$`).Typed("string", "")
	items = spec.NewItems().CollectionOf(strItems, "").WithMinItems(1).WithMaxItems(5).UniqueValues()
	validator = newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default)

	err = validator.Validate(1, []string{"aa", "bbb", "ccc"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, minLengthErrorItems(path+".0", parent.In, strItems), err.Errors[0].Error())
}
Exemple #21
0
func TestEngineSpecs(t *testing.T) {
	engine := NewEngine("test", 0)
	assert.False(t, engine.isConnected())

	client := mockclient.NewMockClient()
	client.On("Info").Return(mockInfo, nil)
	client.On("Version").Return(mockVersion, nil)
	client.On("ListContainers", true, false, "").Return([]dockerclient.Container{}, nil)
	client.On("ListImages").Return([]*dockerclient.Image{}, nil)
	client.On("StartMonitorEvents", mock.Anything, mock.Anything, mock.Anything).Return()

	assert.NoError(t, engine.ConnectWithClient(client))
	assert.True(t, engine.isConnected())
	assert.True(t, engine.IsHealthy())

	assert.Equal(t, engine.Cpus, mockInfo.NCPU)
	assert.Equal(t, engine.Memory, mockInfo.MemTotal)
	assert.Equal(t, engine.Labels["storagedriver"], mockInfo.Driver)
	assert.Equal(t, engine.Labels["executiondriver"], mockInfo.ExecutionDriver)
	assert.Equal(t, engine.Labels["kernelversion"], mockInfo.KernelVersion)
	assert.Equal(t, engine.Labels["operatingsystem"], mockInfo.OperatingSystem)
	assert.Equal(t, engine.Labels["foo"], "bar")

	client.Mock.AssertExpectations(t)
}
Exemple #22
0
func TestSelectLoadStructs(t *testing.T) {
	s := createRealSessionWithFixtures()

	var people []*dbrPerson
	count, err := s.Select("id", "name", "email").From("dbr_people").OrderBy("id ASC").LoadStructs(&people)

	assert.NoError(t, err)
	assert.Equal(t, count, 2)

	assert.Equal(t, len(people), 2)
	if len(people) == 2 {
		// Make sure that the Ids are set. It's possible (maybe?) that different DBs set ids differently so
		// don't assume they're 1 and 2.
		assert.True(t, people[0].Id > 0)
		assert.True(t, people[1].Id > people[0].Id)

		assert.Equal(t, people[0].Name, "Jonathan")
		assert.True(t, people[0].Email.Valid)
		assert.Equal(t, people[0].Email.String, "*****@*****.**")
		assert.Equal(t, people[1].Name, "Dmitri")
		assert.True(t, people[1].Email.Valid)
		assert.Equal(t, people[1].Email.String, "*****@*****.**")
	}

	// TODO: test map
}
func TestTypeResolver_AnonymousStructs(t *testing.T) {

	_, resolver, err := basicTaskListResolver(t)
	if assert.NoError(t, err) {
		// anonymous structs should be accounted for
		parent := new(spec.Schema)
		parent.Typed("object", "")
		parent.Properties = make(map[string]spec.Schema)
		parent.Properties["name"] = *spec.StringProperty()
		parent.Properties["age"] = *spec.Int32Property()

		rt, err := resolver.ResolveSchema(parent, true)
		if assert.NoError(t, err) {
			assert.False(t, rt.IsNullable)
			assert.True(t, rt.IsAnonymous)
			assert.True(t, rt.IsComplexObject)
		}

		parent.Extensions = make(spec.Extensions)
		parent.Extensions["x-isnullable"] = true

		rt, err = resolver.ResolveSchema(parent, true)
		if assert.NoError(t, err) {
			assert.True(t, rt.IsNullable)
			assert.True(t, rt.IsAnonymous)
			assert.True(t, rt.IsComplexObject)
		}
	}
}
func TestIndexRecordEncodeDecodeExpired(t *testing.T) {
	now := time.Now()

	unix := now.UnixNano()
	index, offset := uint64(0), int64(24)
	ir := BasicIndexRecord{unix, index, offset, 1}

	encoder := NewIndexRecordEncoder()
	decoder := NewIndexRecordDecoder()
	buffer := encoder.Encode(ir)

	record, err := decoder.Decode(buffer)
	assert.Nil(t, err)

	// time
	assert.Equal(t, ir.Time(), record.Time())

	// index
	assert.Equal(t, ir.Index(), record.Index())

	// offset
	assert.Equal(t, ir.Offset(), record.Offset())

	// ttl
	assert.Equal(t, ir.TimeToLive(), record.TimeToLive())
	assert.True(t, ir.IsExpired())
	assert.True(t, record.IsExpired())
}
Exemple #25
0
func TestServiceSummaryGetSummariesInCurrentSpace(t *testing.T) {
	req := testapi.NewCloudControllerTestRequest(testnet.TestRequest{
		Method:   "GET",
		Path:     "/v2/spaces/my-space-guid/summary",
		Response: serviceInstanceSummariesResponse,
	})

	ts, handler, repo := createServiceSummaryRepo(t, req)
	defer ts.Close()

	serviceInstances, apiResponse := repo.GetSummariesInCurrentSpace()
	assert.True(t, handler.AllRequestsCalled())

	assert.True(t, apiResponse.IsSuccessful())
	assert.Equal(t, 1, len(serviceInstances))

	instance1 := serviceInstances[0]
	assert.Equal(t, instance1.Name, "my-service-instance")
	assert.Equal(t, instance1.ServicePlan.Name, "spark")
	assert.Equal(t, instance1.ServiceOffering.Label, "cleardb")
	assert.Equal(t, instance1.ServiceOffering.Label, "cleardb")
	assert.Equal(t, instance1.ServiceOffering.Provider, "cleardb-provider")
	assert.Equal(t, instance1.ServiceOffering.Version, "n/a")
	assert.Equal(t, len(instance1.ApplicationNames), 2)
	assert.Equal(t, instance1.ApplicationNames[0], "app1")
	assert.Equal(t, instance1.ApplicationNames[1], "app2")
}
Exemple #26
0
func TestDiskMailboxNackPutsAMessageAtTheFront(t *testing.T) {
	dir, err := ioutil.TempDir("", "mailbox")
	if err != nil {
		panic(err)
	}

	defer os.RemoveAll(dir)

	r, err := NewDiskStorage(dir)
	if err != nil {
		panic(err)
	}

	defer r.Close()

	m := r.Mailbox("a")

	msg := vega.Msg("hello")
	msg2 := vega.Msg("2nd message")

	m.Push(msg)
	m.Push(msg2)

	out, _ := m.Poll()
	assert.True(t, msg.Equal(out), "wrong value")

	err = m.Nack(out.MessageId)
	if err != nil {
		panic(err)
	}

	out3, _ := m.Poll()
	assert.True(t, out.Equal(out3), "nack'd message did not come back")
}
Exemple #27
0
// TestFromIsValidMap tests data that come from map
func TestFromIsValidMap(t *testing.T) {
	f := Form{
		Fields: map[string]*Field{
			"field1": &Field{
				Type: &Input{},
			},
			"field2": &Field{
				Type: &Input{},
			},
		},
	}

	values := map[string]interface{}{
		"field1": "Spam",
		"field2": []string{"Ham"},
	}

	assert.True(t, f.IsValidMap(values), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Spam", "field2": "Ham"},
		"Form should pass")

	values = map[string]interface{}{
		"field1": "Spam",
	}

	assert.True(t, f.IsValidMap(values), "Form should pass")
	assert.Equal(
		t, f.CleanedData, Data{"field1": "Spam", "field2": ""},
		"Form should pass")
}
Exemple #28
0
func TestAmqp_ConnectionCloseNoError(t *testing.T) {
	if testing.Verbose() {
		logp.LogInit(logp.LOG_DEBUG, "", false, true, []string{"amqp", "amqpdetailed"})
	}

	amqp := amqpModForTests()
	amqp.hideConnectionInformation = false

	data, err := hex.DecodeString("01000000000012000a003200c8076b74687862616900000000ce")
	assert.Nil(t, err)
	data2, err := hex.DecodeString("01000000000004000a0033ce")
	assert.Nil(t, err)

	tcptuple := testTCPTuple()

	req := protos.Packet{Payload: data}
	private := protos.ProtocolData(new(amqpPrivateData))
	private = amqp.Parse(&req, tcptuple, 0, private)
	req = protos.Packet{Payload: data2}
	amqp.Parse(&req, tcptuple, 1, private)

	trans := expectTransaction(t, amqp)
	assert.Equal(t, "connection.close", trans["method"])
	assert.Equal(t, "amqp", trans["type"])
	assert.Equal(t, common.OK_STATUS, trans["status"])
	assert.Nil(t, trans["notes"])

	fields, ok := trans["amqp"].(common.MapStr)
	assert.True(t, ok)
	code, ok := fields["reply-code"].(uint16)
	assert.True(t, ok)
	assert.Equal(t, uint16(200), code)
}
Exemple #29
0
func TestDimMakers(t *testing.T) {
	_, exists := ListenerDims("a", "b")["name"]
	assert.True(t, exists)

	_, exists = ForwarderDims("a", "b")["name"]
	assert.True(t, exists)
}
Exemple #30
0
func TestGroupHasAccess(t *testing.T) {
	f := FeatureFlag{
		Key:        "foo",
		Enabled:    false,
		Users:      []uint32{42},
		Groups:     []string{"bar"},
		Percentage: 20,
	}
	// Make sure the feature is not enabled
	assert.False(t, f.IsEnabled())

	assert.True(t, f.GroupHasAccess("bar"))
	assert.False(t, f.GroupHasAccess("baz"))

	f.Groups = []string{"bar", "baz"}
	assert.True(t, f.GroupHasAccess("baz"))

	f.Enabled = true
	assert.True(t, f.GroupHasAccess("klm"))

	f.Groups = []string{}
	f.Percentage = 100
	f.Enabled = false
	assert.True(t, f.GroupHasAccess("test"))
}