예제 #1
0
func TestIPAM(t *testing.T) {
	reg := getNew(t)

	i, cap := reg.IPAM("default")
	assert.NotEqual(t, i, nil)
	assert.NotEqual(t, cap, nil)
}
예제 #2
0
파일: system_test.go 프로젝트: bunsanorg/pm
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)
			}
		}
	}
}
예제 #3
0
func TestValidClaimsContext(t *testing.T) {
	userClaims := ClaimsContext{"user-id": "123456", "custom-time": 1453066866, "custom-time-f": 1631.083, "custom-date": time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{})}
	ctx, err := NewClaimsContext("fosite/auth", "Peter", "*****@*****.**", "", time.Now().Add(time.Hour), time.Now(), time.Now(), userClaims)
	assert.Nil(t, err)

	assert.Equal(t, "fosite/auth", ctx.GetIssuer())
	assert.NotEqual(t, "fosite/token", ctx.GetIssuer())
	assert.Equal(t, "Peter", ctx.GetSubject())
	assert.NotEqual(t, "Alex", ctx.GetSubject())
	assert.Equal(t, "*****@*****.**", ctx.GetAudience())
	assert.NotEqual(t, "*****@*****.**", ctx.GetAudience())

	assert.Equal(t, time.Now().Day(), ctx.GetNotBefore().Day())
	assert.Equal(t, time.Now().Day(), ctx.GetIssuedAt().Day())
	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetExpiresAt().Day())

	assert.Equal(t, time.Now().Add(time.Hour).Day(), ctx.GetAsTime("exp").Day())
	assert.Equal(t, time.Date(2016, time.January, 17, 19, 00, 00, 00, &time.Location{}), ctx.GetAsTime("custom-date"))
	assert.NotNil(t, ctx.GetAsTime("custom-time"))
	assert.NotNil(t, ctx.GetAsTime("custom-time-f"))

	str, err := ctx.String()
	assert.NotNil(t, str)
	assert.Nil(t, err)

	assert.Empty(t, ctx.GetAsString("doesnotexist"))
	assert.Equal(t, time.Time{}, ctx.GetAsTime("doesnotexist"))
	stringRep, err := ctx.String()
	assert.Nil(t, err)
	assert.NotEmpty(t, stringRep)
}
예제 #4
0
func TestCreateGenesisBlock(t *testing.T) {
	defer cleanupVisor()
	// Test as master, successful
	vc := newMasterVisorConfig(t)
	v := NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb := v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))

	// Test as not master, successful
	vc = newGenesisConfig(t)
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	sb = v.CreateGenesisBlock()
	assert.NotEqual(t, sb.Block, coin.Block{})
	assert.NotEqual(t, sb.Sig, cipher.Sig{})
	assert.Equal(t, len(v.blockchain.Blocks), 1)
	assert.Equal(t, len(v.blockSigs.Sigs), 1)
	assert.Nil(t, v.blockSigs.Verify(vc.MasterKeys.Public, v.blockchain))
	assert.Equal(t, v.Config.GenesisSignature, sb.Sig)
	assert.Equal(t, v.blockchain.Blocks[0].Header.Time, v.Config.GenesisTimestamp)

	// Test as master, blockSigs invalid for pubkey
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as not master, blockSigs invalid for pubkey
	vc = newGenesisConfig(t)
	vc.MasterKeys.Public = cipher.PubKey{}
	v = NewMinimalVisor(vc)
	assert.False(t, v.Config.IsMaster)
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })

	// Test as master, signing failed
	vc = newMasterVisorConfig(t)
	vc.MasterKeys.Secret = cipher.SecKey{}
	assert.Equal(t, vc.MasterKeys.Secret, cipher.SecKey{})
	v = NewMinimalVisor(vc)
	assert.True(t, v.Config.IsMaster)
	assert.Equal(t, v.Config, vc)
	assert.Equal(t, v.Config.MasterKeys.Secret, cipher.SecKey{})
	assert.Equal(t, len(v.blockchain.Blocks), 0)
	assert.Equal(t, len(v.blockSigs.Sigs), 0)
	assert.Panics(t, func() { v.CreateGenesisBlock() })
}
예제 #5
0
func (suite *FsTestSuite) TestFileAttrOwnership() {
	assert := suite.assert

	cases := []string{
		".clear_cache",
		".json/secret/hmac.key",
		".json/secrets",
		".running",
		".version",
		"hmac.key",
	}

	for _, filename := range cases {
		attr, status := suite.fs.GetAttr(filename, fuseContext)
		assert.Equal(fuse.OK, status, "Expected %v attr status to be fuse.OK", filename)
		assert.Equal(_SomeUID, attr.Uid, "Expected %v uid to be default", filename)
		assert.Equal(_SomeUID, attr.Gid, "Expected %v gid to be default", filename)
	}

	filename := "Nobody_PgPass"
	attr, status := suite.fs.GetAttr(filename, fuseContext)
	assert.Equal(fuse.OK, status, "Expected %v attr status to be fuse.OK", filename)
	assert.NotEqual(_SomeUID, attr.Uid, "Expected %v uid to not be default", filename)
	assert.NotEqual(0, attr.Uid, "Expected %v uid to be set", filename)
	assert.NotEqual(_SomeUID, attr.Gid, "Expected %v gid to not be default", filename)
	assert.NotEqual(0, attr.Gid, "Expected %v gid to be set", filename)
}
예제 #6
0
func TestTransactionSignInput(t *testing.T) {
	tx := &Transaction{}
	// Panics if too many inputs exist
	tx.In = append(tx.In, make([]SHA256, math.MaxUint16+2)...)
	_, s := GenerateKeyPair()
	assert.Panics(t, func() { tx.signInput(0, s, SHA256{}) })

	// Panics if idx too large for number of inputs
	tx = &Transaction{}
	ux, s := makeUxOutWithSecret(t)
	tx.PushInput(ux.Hash())
	assert.Panics(t, func() { tx.signInput(1, s, SHA256{}) })

	// Sigs should be extended if needed
	assert.Equal(t, len(tx.Head.Sigs), 0)
	ux2, s2 := makeUxOutWithSecret(t)
	tx.PushInput(ux2.Hash())
	tx.signInput(1, s2, tx.hashInner())
	assert.Equal(t, len(tx.Head.Sigs), 2)
	assert.Equal(t, tx.Head.Sigs[0], Sig{})
	assert.NotEqual(t, tx.Head.Sigs[1], Sig{})
	// Signing the earlier sig should be ok
	tx.signInput(0, s, tx.hashInner())
	assert.Equal(t, len(tx.Head.Sigs), 2)
	assert.NotEqual(t, tx.Head.Sigs[0], Sig{})
	assert.NotEqual(t, tx.Head.Sigs[1], Sig{})
}
예제 #7
0
func TestTracingPropagates(t *testing.T) {
	WithVerifiedServer(t, nil, func(ch *Channel, hostPort string) {
		handler := &traceHandler{t: t, ch: ch}
		json.Register(ch, json.Handlers{
			"call": handler.call,
		}, handler.onError)

		ctx, cancel := json.NewContext(time.Second)
		defer cancel()

		peer := ch.Peers().GetOrAdd(ch.PeerInfo().HostPort)
		var response TracingResponse
		require.NoError(t, json.CallPeer(ctx, peer, ch.PeerInfo().ServiceName, "call", &TracingRequest{
			ForwardCount: 1,
		}, &response))

		clientSpan := CurrentSpan(ctx)
		require.NotNil(t, clientSpan)
		assert.Equal(t, uint64(0), clientSpan.ParentID())

		assert.Equal(t, uint64(0), clientSpan.ParentID())
		assert.NotEqual(t, uint64(0), clientSpan.TraceID())
		assert.Equal(t, clientSpan.TraceID(), response.TraceID)
		assert.Equal(t, clientSpan.SpanID(), response.ParentID)
		assert.Equal(t, response.TraceID, response.SpanID, "traceID = spanID for root span")

		nestedResponse := response.Child
		require.NotNil(t, nestedResponse)
		assert.Equal(t, clientSpan.TraceID(), nestedResponse.TraceID)
		assert.Equal(t, response.SpanID, nestedResponse.ParentID)
		assert.NotEqual(t, response.SpanID, nestedResponse.SpanID)
	})
}
예제 #8
0
func TestProfileCopy(t *testing.T) {
	profile := &Profile{
		Id:         "id",
		CloudId:    "cloudy.tmpl",
		IgnitionId: "ignition.tmpl",
		Boot: &NetBoot{
			Kernel:  "/image/kernel",
			Initrd:  []string{"/image/initrd_a"},
			Cmdline: map[string]string{"a": "b"},
		},
	}
	copy := profile.Copy()
	// assert that:
	// - Profile fields are copied
	// - mutation of the copy does not affect the original
	assert.Equal(t, profile.Id, copy.Id)
	assert.Equal(t, profile.Name, copy.Name)
	assert.Equal(t, profile.IgnitionId, copy.IgnitionId)
	assert.Equal(t, profile.CloudId, copy.CloudId)
	assert.Equal(t, profile.Boot, copy.Boot)

	copy.Id = "a-copy"
	copy.Boot.Initrd = []string{"/image/initrd_b"}
	copy.Boot.Cmdline["c"] = "d"
	assert.NotEqual(t, profile.Id, copy.Id)
	assert.NotEqual(t, profile.Boot.Initrd, copy.Boot.Initrd)
	assert.NotEqual(t, profile.Boot.Cmdline, copy.Boot.Cmdline)
}
예제 #9
0
func TestNewV5(t *testing.T) {
	u := NewV5(NamespaceURL, goLang)

	assert.Equal(t, 5, u.Version(), "Expected correct version")
	assert.Equal(t, ReservedRFC4122, u.Variant(), "Expected correct variant")
	assert.True(t, parseUUIDRegex.MatchString(u.String()), "Expected string representation to be valid")

	ur, _ := url.Parse(string(goLang))

	// Same NS same name MUST be equal
	u2 := NewV5(NamespaceURL, ur)
	assert.Equal(t, u, u2, "Expected UUIDs generated with same namespace and name to equal")

	// Different NS same name MUST NOT be equal
	u3 := NewV5(NamespaceDNS, ur)
	assert.NotEqual(t, u, u3, "Expected UUIDs generated with different namespace and same name to be different")

	// Same NS different name MUST NOT be equal
	u4 := NewV5(NamespaceURL, u)
	assert.NotEqual(t, u, u4, "Expected UUIDs generated with the same namespace and different names to be different")

	ids := []UUID{
		u, u2, u3, u4,
	}

	for j, id := range ids {
		i := NewV5(NamespaceURL, NewName(string(j), id))
		assert.NotEqual(t, i, id, "Expected UUIDs generated with the same namespace and different names to be different")

	}
}
예제 #10
0
func TestChecksumFlagSet_Differs(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	flagz.DynDuration(set, "some_duration_1", 5*time.Second, "Use it or lose it")
	flagz.DynInt64(set, "some_int_1", 13371337, "Use it or lose it")
	set.String("static_string_1", "foobar", "meh")

	preInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("pre init checksum:  %x", preInitChecksum)

	set.Parse([]string{"--some_duration_1", "3s", "--static_string_1", "goodbar"})
	postInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post init checksum: %x", postInitChecksum)
	assert.NotEqual(t, preInitChecksum, postInitChecksum, "checksum must be different init changed 2 flags")

	require.NoError(t, set.Set("some_int_1", "1337"))
	postSet1Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set1 checksum: %x", postSet1Checksum)
	assert.NotEqual(t, postInitChecksum, postSet1Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "4s"))
	postSet2Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set2 checksum: %x", postSet2Checksum)
	assert.NotEqual(t, postSet1Checksum, postSet2Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "3s"))
	postSet3Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set3 checksum: %x", postSet3Checksum)
	assert.EqualValues(t, postSet1Checksum, postSet3Checksum, "flipping back duration flag to state at set1 should make it equal")
}
예제 #11
0
func TestLoad(t *testing.T) {
	_, err := Load("../foo.bar")
	assert.NotNil(t, err, "should return an error when file does not exist")

	_, err = Load("../uchiwa.go")
	assert.NotNil(t, err, "should return an error when it cannot parse a file")

	conf, err := Load("../../fixtures/config_test.json")
	assert.Nil(t, err, "got unexpected error: %s", err)

	// private config
	assert.NotEqual(t, "*****", conf.Uchiwa.User, "Uchiwa user in private config shouldn't be masked")
	assert.NotEqual(t, "*****", conf.Uchiwa.Pass, "Uchiwa pass in private config shouldn't be masked")
	for i := range conf.Sensu {
		assert.NotEqual(t, "*****", conf.Sensu[i].User, "Sensu APIs user in private config shouldn't be masked")
		assert.NotEqual(t, "*****", conf.Sensu[i].Pass, "Sensu APIs pass in private config shouldn't be masked")
	}
	assert.Equal(t, 1, len(conf.Uchiwa.Users))

	// public config
	public := conf.GetPublic()
	assert.Equal(t, "*****", public.Uchiwa.User, "Uchiwa user in public config should be masked")
	assert.Equal(t, "*****", public.Uchiwa.Pass, "Uchiwa pass in public config should be masked")
	for i := range public.Sensu {
		assert.Equal(t, "*****", public.Sensu[i].User, "Sensu APIs user in public config should be masked")
		assert.Equal(t, "*****", public.Sensu[i].Pass, "Sensu APIs pass in public config should be masked")
	}
	assert.Equal(t, 0, len(public.Uchiwa.Users))

}
예제 #12
0
// This func tests the correctness of inSccStack() pushSccStack() and  popSccStack()
func TestSccStack(t *testing.T) {
	i := commonTestlibExampleCommittedInstance()
	iClone := commonTestlibCloneInstance(i)
	iClone.ballot = iClone.ballot.IncNumClone()
	r := i.replica

	// push two items
	r.pushSccStack(i)
	r.pushSccStack(iClone)

	// test if they are valid in the stack
	assert.True(t, r.inSccStack(i))
	assert.True(t, r.inSccStack(iClone))

	// pop out one item and test if it's valid
	iPop := r.popSccStack()
	assert.Equal(t, iClone, iPop)
	assert.NotEqual(t, i, iPop)

	// test the content in the stack
	assert.False(t, r.inSccStack(iClone))
	assert.True(t, r.inSccStack(i))

	// pop out another one and test if it's valid
	iPop = r.popSccStack()
	assert.Equal(t, i, iPop)
	assert.NotEqual(t, iClone, iPop)

	// test the content of the stack
	assert.False(t, r.inSccStack(i))
}
예제 #13
0
//---------------
// secure access
//---------------
func TestRequireHTTPS(t *testing.T) {
	url := serverURL + amalgam8.ServiceNamesURL()
	c := defaultServerConfig()
	handler, err := setupServer(c)
	assert.Nil(t, err)

	recorder := httptest.NewRecorder()
	req, err := http.NewRequest("GET", url, nil)
	assert.Nil(t, err)
	req.Header.Set("Content-Type", "application/json")
	handler.ServeHTTP(recorder, req)
	assert.NotEqual(t, recorder.Code, http.StatusMovedPermanently)

	// Now, set up a a new handler, which requires HTTPS
	c.RequireHTTPS = true
	secureHandler, err := setupServer(c)
	assert.Nil(t, err)

	recorder = httptest.NewRecorder()
	secureHandler.ServeHTTP(recorder, req)
	assert.Equal(t, recorder.Code, http.StatusMovedPermanently)

	req.Header.Set("X-Forwarded-Proto", "https")
	recorder = httptest.NewRecorder()
	secureHandler.ServeHTTP(recorder, req)
	assert.NotEqual(t, recorder.Code, http.StatusMovedPermanently)
}
예제 #14
0
func TestPropagateIdsToChildren(t *testing.T) {
	// Make a generic file with 6 events and 2 checksums
	gf := testutil.MakeGenericFile(6, 2, "test.edu/test_bag/file.txt")
	assert.Equal(t, 6, len(gf.PremisEvents))
	assert.Equal(t, 2, len(gf.Checksums))

	// Check pre-condition before actual test.
	for _, event := range gf.PremisEvents {
		assert.NotEqual(t, gf.Id, event.GenericFileId)
		assert.NotEqual(t, gf.Identifier, event.GenericFileIdentifier)
		assert.NotEqual(t, gf.IntellectualObjectId, event.IntellectualObjectId)
		assert.NotEqual(t, gf.IntellectualObjectIdentifier, event.IntellectualObjectIdentifier)
	}
	for _, checksum := range gf.Checksums {
		assert.NotEqual(t, gf.Id, checksum.GenericFileId)
	}

	gf.PropagateIdsToChildren()
	for _, event := range gf.PremisEvents {
		assert.Equal(t, gf.Id, event.GenericFileId)
		assert.Equal(t, gf.Identifier, event.GenericFileIdentifier)
		assert.Equal(t, gf.IntellectualObjectId, event.IntellectualObjectId)
		assert.Equal(t, gf.IntellectualObjectIdentifier, event.IntellectualObjectIdentifier)
	}
	for _, checksum := range gf.Checksums {
		assert.Equal(t, gf.Id, checksum.GenericFileId)
	}
}
예제 #15
0
func TestRemoveInternalNetwork(t *testing.T) {
	ts := newTestServer(t)
	defer ts.Stop()

	name := "testnet3"
	spec := createNetworkSpec(name)
	// add label denoting internal network
	spec.Annotations.Labels = map[string]string{"com.docker.swarm.internal": "true"}
	nr, err := ts.Server.createInternalNetwork(context.Background(), &api.CreateNetworkRequest{
		Spec: spec,
	})
	assert.NoError(t, err)
	assert.NotEqual(t, nr.Network, nil)
	assert.NotEqual(t, nr.Network.ID, "")

	_, err = ts.Client.RemoveNetwork(context.Background(), &api.RemoveNetworkRequest{NetworkID: nr.Network.ID})
	// this SHOULD fail, because the internal network cannot be removed
	assert.Error(t, err)
	assert.Equal(t, grpc.Code(err), codes.PermissionDenied)
	assert.Contains(t, err.Error(), fmt.Sprintf("%s (%s) is a pre-defined network and cannot be removed", name, nr.Network.ID))

	// then, check to make sure network is still there
	ng, err := ts.Client.GetNetwork(context.Background(), &api.GetNetworkRequest{NetworkID: nr.Network.ID})
	assert.NoError(t, err)
	assert.NotEqual(t, ng.Network, nil)
	assert.NotEqual(t, ng.Network.ID, "")
}
예제 #16
0
// TestContext runs
func TestContext(t *testing.T) {
	assert := assert.New(t)

	{
		var (
			ctx1    *gin.Context = SharedContext()
			ctx2    *gin.Context = SharedContext()
			ctx3    *gin.Context = SharedContext()
			ctxptr1 string       = fmt.Sprintf("%p", ctx1)
			ctxptr2 string       = fmt.Sprintf("%p", ctx2)
			ctxptr3 string       = fmt.Sprintf("%p", ctx3)
		)
		if assert.NotNil(ctx1) {
			assert.Nil(ctx1.Request)
		}
		if assert.NotNil(ctx2) {
			assert.Nil(ctx2.Request)
		}
		if assert.NotNil(ctx3) {
			assert.Nil(ctx3.Request)
		}

		assert.NotEqual(ctxptr1, ctxptr2)
		assert.NotEqual(ctxptr2, ctxptr3)
		assert.NotEqual(ctxptr3, ctxptr1)
	}

	Init()

	{
		var (
			ctx1    *gin.Context = SharedContext()
			ctx2    *gin.Context = SharedContext()
			ctx3    *gin.Context = SharedContext()
			ctxptr1 string       = fmt.Sprintf("%p", ctx1)
			ctxptr2 string       = fmt.Sprintf("%p", ctx2)
			ctxptr3 string       = fmt.Sprintf("%p", ctx3)
			ptr1    string       = fmt.Sprintf("%p", ctx1.Request)
			ptr2    string       = fmt.Sprintf("%p", ctx2.Request)
			ptr3    string       = fmt.Sprintf("%p", ctx3.Request)
		)
		if assert.NotNil(ctx1) {
			assert.NotNil(ctx1.Request)
		}
		if assert.NotNil(ctx2) {
			assert.NotNil(ctx2.Request)
		}
		if assert.NotNil(ctx3) {
			assert.NotNil(ctx3.Request)
		}

		assert.Equal(ctxptr1, ctxptr2)
		assert.Equal(ctxptr2, ctxptr3)
		assert.Equal(ctxptr3, ctxptr1)

		assert.Equal(ptr1, ptr2)
		assert.Equal(ptr2, ptr3)
		assert.Equal(ptr3, ptr1)
	}
}
예제 #17
0
파일: lax_test.go 프로젝트: enova/tokyo
func TestEnv(t *testing.T) {
	assert := assert.New(t)

	assert.NotEqual(Username(), "unknown_user")
	assert.NotEqual(Hostname(), "unknown_host")
	assert.NotEqual(ExecPath(), "unknown_exec")
}
예제 #18
0
func Test_PerMinute_Hash(t *testing.T) {
	mock := clock.NewMock()
	hasher := PerMinuteHasher{
		Clock: mock,
	}

	resultOne := hasher.Hash("127.0.0.1")

	mock.Add(time.Minute)

	resultTwo := hasher.Hash("127.0.0.1")

	assert.NotEqual(t, resultOne, resultTwo)

	resultThree := hasher.Hash("127.0.0.1")
	resultFour := hasher.Hash("127.0.0.1")
	resultFive := hasher.Hash("127.0.0.2")

	assert.Equal(t, resultThree, resultFour)
	assert.NotEqual(t, resultFour, resultFive)

	// Test that it can create a new clock
	hasher = PerMinuteHasher{}
	hasher.Hash("127.0.0.1")
}
예제 #19
0
func TestTransactionHashInner(t *testing.T) {
	tx := makeTransaction(t)

	h := tx.hashInner()
	assert.NotEqual(t, h, SHA256{})

	// If tx.In is changed, hash should change
	tx2 := copyTransaction(tx)
	ux := makeUxOut(t)
	tx2.In[0] = ux.Hash()
	assert.NotEqual(t, tx, tx2)
	assert.Equal(t, tx2.In[0], ux.Hash())
	assert.NotEqual(t, tx.hashInner(), tx2.hashInner())

	// If tx.Out is changed, hash should change
	tx2 = copyTransaction(tx)
	a := makeAddress()
	tx2.Out[0].Address = a
	assert.NotEqual(t, tx, tx2)
	assert.Equal(t, tx2.Out[0].Address, a)
	assert.NotEqual(t, tx.hashInner(), tx2.hashInner())

	// If tx.Head is changed, hash should not change
	tx2 = copyTransaction(tx)
	tx.Head.Sigs = append(tx.Head.Sigs, Sig{})
	assert.Equal(t, tx.hashInner(), tx2.hashInner())
}
예제 #20
0
func TestCopy(t *testing.T) {
	request := buildApiRequest("/_ah/api/foo?bar=baz", `{"test": "body"}`, nil)
	copied, err := request.copy()
	assert.NoError(t, err)
	assert.Equal(t, request.Header, copied.Header)
	body, err := ioutil.ReadAll(request.Body)
	assert.NoError(t, err)
	body_copy, err2 := ioutil.ReadAll(copied.Body)
	assert.NoError(t, err2)
	assert.Equal(t, string(body), string(body_copy))
	assert.Equal(t, request.bodyJson, copied.bodyJson)
	assert.Equal(t, request.URL.Path, copied.URL.Path)

	copied.Header.Set("Content-Type", "text/plain")
	copied.Body = ioutil.NopCloser(bytes.NewBufferString("Got a whole new body!"))
	copied.bodyJson = map[string]interface{}{"new": "body"}
	copied.URL.Path = "And/a/new/path/"

	assert.NotEqual(t, request.Header, copied.Header)
	body, err = ioutil.ReadAll(request.Body)
	assert.NoError(t, err)
	body_copy, err2 = ioutil.ReadAll(copied.Body)
	assert.NoError(t, err2)
	assert.NotEqual(t, string(body), string(body_copy))
	assert.NotEqual(t, request.bodyJson, copied.bodyJson)
	assert.NotEqual(t, request.URL.Path, copied.URL.Path)
}
// For the case when exist = false
// Tests that a new TemplateDTO_CommBoughtProviderProp struct is created
// with it Key variable = this.currentProvider
// Tests that the new TemplateDTO_CommBoughtProviderProp struct is appended
// to this.entityTemplate.CommodityBought
// Tests that the TemplateCommodity passed to the Buys() method is appended to the
// member array named Value in the newly created TemplateDTO_CommBoughtProviderProp
func TestBuys_exist_false(t *testing.T) {
	assert := assert.New(t)
	eTemplate := new(TemplateDTO)
	provider := new(Provider)
	scnbuilder := &SupplyChainNodeBuilder{
		entityTemplate:  eTemplate,
		currentProvider: provider,
	}
	templateCommodity := new(TemplateCommodity)
	scnb := scnbuilder.Buys(*templateCommodity)
	var providerProp *TemplateDTO_CommBoughtProviderProp
	var commoditiesBought []*TemplateDTO_CommBoughtProviderProp
	if assert.NotEqual(([]*TemplateDTO_CommBoughtProviderProp)(nil), scnb.entityTemplate.CommodityBought) {
		assert.Equal(1, len(scnb.entityTemplate.CommodityBought))
		commoditiesBought = scnb.entityTemplate.CommodityBought
		for _, pp := range commoditiesBought {
			if pp.GetKey() == provider {
				providerProp = pp
			}
		}
	}
	// provideProp is the  *TemplateDTO_CommBoughtProviderProp
	// containing the []*TemplateCommodity to which Buys appended templateCommodity
	if assert.NotEqual(([]*TemplateCommodity)(nil), commoditiesBought[0].Value) {
		assert.Equal(1, len(providerProp.Value))
		assert.Equal(templateCommodity, providerProp.Value[0])
	}
}
예제 #22
0
func TestNewCarbonDatapoint(t *testing.T) {
	identityParser, _ := metricdeconstructor.Load("", "")
	dp, err := NewCarbonDatapoint("hello 3 3", identityParser)
	assert.Equal(t, nil, err, "Should be a valid carbon line")
	assert.Equal(t, "hello", dp.Metric, "Should get metric back")

	_, err = NewCarbonDatapoint("INVALIDLINE", identityParser)
	assert.NotEqual(t, nil, err, "Line should be invalid")

	_, err = NewCarbonDatapoint("hello 3 bob", identityParser)
	assert.NotEqual(t, nil, err, "Line should be invalid")

	_, err = NewCarbonDatapoint("hello bob 3", identityParser)
	assert.NotEqual(t, nil, err, "Line should be invalid")

	dp, _ = NewCarbonDatapoint("hello 3.3 3", identityParser)
	f := dp.Value.(datapoint.FloatValue).Float()
	assert.Equal(t, 3.3, f, "Should get value back")

	carbonDp, _ := NativeCarbonLine(dp)
	assert.Equal(t, "hello 3.3 3", carbonDp, "Should get the carbon line back")

	dp, err = NewCarbonDatapoint("hello 3 3", &errorDeconstructor{})
	assert.NotEqual(t, nil, err, "Should NOT be a valid carbon line")
}
예제 #23
0
// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	master, _, assert := setUp(t)
	mux := http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)

	// Ensure swagger isn't installed without the call
	ws := master.handlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	master.InstallSwaggerAPI()
	ws = master.handlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	master.handlerContainer = NewHandlerContainer(mux)
	master.externalHost = ""
	master.clusterIP = net.IPv4(10, 10, 10, 10)
	master.publicReadWritePort = 1010
	master.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
예제 #24
0
func TestNewReservation(t *testing.T) {
	privateKey := generateKey(t)
	txn, rand := NewNameReservation("my-new-repository", &privateKey.PublicKey)
	txn1, rand1 := NewNameReservation("my-new-repository", &privateKey.PublicKey)
	assert.NotEqual(t, txn.Hashed, txn1.Hashed, "hashed value should not be equal")
	assert.NotEqual(t, rand, rand1, "random numbers should not be equal")
}
예제 #25
0
func TestPingMonitor(t *testing.T) {
	conn, _ := rados.NewConn()
	conn.ReadDefaultConfigFile()
	conn.Connect()

	// mon id that should work with vstart.sh
	reply, err := conn.PingMonitor("a")
	if err == nil {
		assert.NotEqual(t, reply, "")
		return
	}

	// mon id that should work with micro-osd.sh
	reply, err = conn.PingMonitor("0")
	if err == nil {
		assert.NotEqual(t, reply, "")
		return
	}

	// try to use a hostname as the monitor id
	mon_addr, _ := conn.GetConfigOption("mon_host")
	hosts, _ := net.LookupAddr(mon_addr)
	for _, host := range hosts {
		reply, err := conn.PingMonitor(host)
		if err == nil {
			assert.NotEqual(t, reply, "")
			return
		}
	}

	t.Error("Could not find a valid monitor id")

	conn.Shutdown()
}
예제 #26
0
// TestGetNamespaceStats tests all flows of GetNamespaceStats.
func TestGetNamespaceStats(t *testing.T) {
	var (
		model        = newRealModel(time.Minute)
		source_cache = cacheFactory()
		assert       = assert.New(t)
	)
	model.Update(source_cache)

	// Invocation with nonexistant namespace
	res, err := model.GetNamespaceStats(NamespaceRequest{
		NamespaceName: "nonexistant",
	})
	assert.Nil(res)
	assert.Error(err)

	// Invocation with normal namespace
	res, err = model.GetNamespaceStats(NamespaceRequest{
		NamespaceName: "test",
	})
	assert.True(len(res.ByName) >= 6)
	assert.Equal(res.ByName[memUsage].Minute.Average, res.ByName[memUsage].Minute.Max)
	assert.Equal(res.ByName[memUsage].Minute.Average, res.ByName[memUsage].Minute.NinetyFifth)
	assert.NotEqual(res.ByName[memUsage].Minute.Average, uint64(0))
	assert.NotEqual(res.ByName[memUsage].Hour.Average, uint64(0))
	assert.NoError(err)
}
예제 #27
0
파일: client_test.go 프로젝트: niiyz/pgweb
func test_HistoryError(t *testing.T) {
	_, err := testClient.Query("SELECT * FROM books123")
	query := testClient.History[len(testClient.History)-1].Query

	assert.NotEqual(t, nil, err)
	assert.NotEqual(t, "SELECT * FROM books123", query)
}
예제 #28
0
func Test_LoadPhrases(t *testing.T) {
	phrases := loadPhrasebook()
	assert.True(t, len(phrases) > 0)
	pair := phrases[0]
	assert.NotEqual(t, pair.English, "")
	assert.NotEqual(t, pair.Esperanto, "")
}
예제 #29
0
// TestInstallSwaggerAPI verifies that the swagger api is added
// at the proper endpoint.
func TestInstallSwaggerAPI(t *testing.T) {
	etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)

	mux := http.NewServeMux()
	server := &GenericAPIServer{}
	server.HandlerContainer = NewHandlerContainer(mux, nil)

	// Ensure swagger isn't installed without the call
	ws := server.HandlerContainer.RegisteredWebServices()
	if !assert.Equal(len(ws), 0) {
		for x := range ws {
			assert.NotEqual("/swaggerapi", ws[x].RootPath(), "SwaggerAPI was installed without a call to InstallSwaggerAPI()")
		}
	}

	// Install swagger and test
	server.InstallSwaggerAPI()
	ws = server.HandlerContainer.RegisteredWebServices()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}

	// Empty externalHost verification
	mux = http.NewServeMux()
	server.HandlerContainer = NewHandlerContainer(mux, nil)
	server.ExternalAddress = ""
	server.ClusterIP = net.IPv4(10, 10, 10, 10)
	server.PublicReadWritePort = 1010
	server.InstallSwaggerAPI()
	if assert.NotEqual(0, len(ws), "SwaggerAPI not installed.") {
		assert.Equal("/swaggerapi/", ws[0].RootPath(), "SwaggerAPI did not install to the proper path. %s != /swaggerapi", ws[0].RootPath())
	}
}
예제 #30
0
func TestLoad(t *testing.T) {
	_, err := LoadConfig("../foo.bar")
	assert.NotNil(t, err, "should return an error when file does not exist")

	_, err = LoadConfig("../uchiwa.go")
	assert.NotNil(t, err, "should return an error when it cannot parse a file")

	conf, err := LoadConfig("../test/gotest/config_test.json")
	assert.Nil(t, err, "got unexpected error: %s", err)

	New(conf)

	assert.NotEqual(t, conf.Uchiwa.User, "*****", "Uchiwa user in private config shouldn't be masked")
	assert.NotEqual(t, conf.Uchiwa.Pass, "*****", "Uchiwa pass in private config shouldn't be masked")
	for i := range conf.Sensu {
		assert.NotEqual(t, conf.Sensu[i].User, "*****", "Sensu APIs user in private config shouldn't be masked")
		assert.NotEqual(t, conf.Sensu[i].Pass, "*****", "Sensu APIs pass in private config shouldn't be masked")
	}

	assert.Equal(t, PublicConfig.Uchiwa.User, "*****", "Uchiwa user in public config should be masked")
	assert.Equal(t, PublicConfig.Uchiwa.Pass, "*****", "Uchiwa pass in public config should be masked")
	for i := range PublicConfig.Sensu {
		assert.Equal(t, PublicConfig.Sensu[i].User, "*****", "Sensu APIs user in public config should be masked")
		assert.Equal(t, PublicConfig.Sensu[i].Pass, "*****", "Sensu APIs pass in public config should be masked")
	}

}