Esempio n. 1
0
func init() {
	Describe("Testing with Ginkgo", func() {
		It("get returns an aws infrastructure", func() {
			logger, platform, provider := getNewProvider()
			inf, err := provider.Get("aws")

			assert.NoError(GinkgoT(), err)
			assert.IsType(GinkgoT(), NewAwsInfrastructure("http://169.254.169.254", NewDigDnsResolver(logger), platform), inf)
		})
		It("get returns vsphere infrastructure", func() {

			_, platform, provider := getNewProvider()
			inf, err := provider.Get("vsphere")

			assert.NoError(GinkgoT(), err)
			assert.IsType(GinkgoT(), NewVsphereInfrastructure(platform), inf)
		})
		It("get returns an error on unknown infrastructure", func() {

			_, _, provider := getNewProvider()
			_, err := provider.Get("some unknown infrastructure name")

			assert.Error(GinkgoT(), err)
		})
	})
}
Esempio n. 2
0
func TestMarshalUnmarshal(t *testing.T) {
	css := &Conditions{
		"clientIP": &CIDRCondition{CIDR: "127.0.0.1/0"},
		"owner":    &EqualsSubjectCondition{},
	}
	out, err := json.Marshal(css)
	require.Nil(t, err)
	t.Logf("%s", out)

	cs := Conditions{}
	require.Nil(t, json.Unmarshal([]byte(`{
	"owner": {
		"type": "EqualsSubjectCondition"
	},
	"clientIP": {
		"type": "CIDRCondition",
		"options": {
			"cidr": "127.0.0.1/0"
		}
	}
}`), &cs))

	require.Len(t, cs, 2)
	assert.IsType(t, &EqualsSubjectCondition{}, cs["owner"])
	assert.IsType(t, &CIDRCondition{}, cs["clientIP"])
}
func TestDecodeDictDict(t *testing.T) {
	data := `<dict>
		<key>foo</key>
		<dict>
			<key>foo</key>
			<string>bar</string>
		</dict>
	</dict>`
	rootDecoder := baseDecoder{nil, xml.NewDecoder(bytes.NewReader([]byte(data)))}

	value, err := rootDecoder.NextValue()
	assert.NoError(t, err)
	assert.IsType(t, &dictDecoder{}, value)

	dictDecoder1 := value.(*dictDecoder)
	value, err = dictDecoder1.NextValue()
	assert.NoError(t, err)
	entry := value.(DictEntry)
	assert.IsType(t, &dictDecoder{}, entry.Value)

	dictDecoder2 := entry.Value.(*dictDecoder)
	value, err = dictDecoder2.NextValue()
	assert.NoError(t, err)
	assert.Equal(t, DictEntry{"foo", "bar"}, value)

	value, err = dictDecoder2.NextValue()
	assert.NoError(t, err)
	assert.Equal(t, EndDecodingContainer{}, value)

	value, err = dictDecoder1.NextValue()
	assert.NoError(t, err)
	assert.Equal(t, EndDecodingContainer{}, value)
}
func TestRandomColSoft(t *testing.T) {
	assert := assert.New(t)
	rands, _ := randomColSoft()
	assert.IsType(rands.Randkey, "string")
	assert.IsType(rands.Randconst, "string")
	assert.Contains(rands.Randbuiltin, "#")
}
Esempio n. 5
0
func TestStandardClusterSlave(t *testing.T) {
	assert := assert.New(t)

	var c *StandardCluster
	var node *Node

	c = NewCluster("master")
	node = c.Slave()
	assert.IsType(Node{}, *node)
	assert.Equal("master", node.db)
	assert.Equal(c.master, node, "Slave() shoud equal to StandardCluster.master when no slaves")
	assert.Len(c.slaves, 0)

	c.RegisterSlave("slave")
	node = c.Slave()
	assert.IsType(Node{}, *node)
	assert.Equal("slave", node.db)
	assert.Equal(c.slaves[0], node, "Slave() shoud equal to node in StandardCluster.slaves")
	assert.Len(c.slaves, 1)

	for i, max := 0, 100; i < max; i++ {
		c.RegisterSlave(i)
	}
	assert.Len(c.slaves, 101)

	node = c.Slave()
	db := node.db
	for i, max := 0, 10; i < max; i++ {
		node = c.Slave()
		if node.db != db {
			return
		}
	}
	t.Error("Slave() should return different nodes")
}
Esempio n. 6
0
func TestStateUpdateError(t *testing.T) {

	update := client.UpdateResponse{
		ID: "foobar",
	}
	fooerr := NewTransientError(errors.New("foo"))

	es := NewUpdateErrorState(fooerr, update)
	assert.Equal(t, MenderStateUpdateError, es.Id())
	assert.IsType(t, &UpdateErrorState{}, es)
	errstate, _ := es.(*UpdateErrorState)
	assert.NotNil(t, errstate)
	assert.Equal(t, fooerr, errstate.cause)

	ms := NewMemStore()
	ctx := StateContext{
		store: ms,
	}
	sc := &stateTestController{}
	es = NewUpdateErrorState(fooerr, update)
	s, _ := es.Handle(&ctx, sc)
	assert.IsType(t, &UpdateStatusReportState{}, s)
	// verify that update status report state data is correct
	usr, _ := s.(*UpdateStatusReportState)
	assert.Equal(t, client.StatusError, usr.status)
	assert.Equal(t, update, usr.update)
}
Esempio n. 7
0
// listWorkUnits calls GetWorkUnits (as the similarly-named Python
// function does) and validates that the response matches an expected
// set of work units.
func listWorkUnits(t *testing.T, j *jobserver.JobServer, workSpecName string, options map[string]interface{}, expected map[string]map[string]interface{}) {
	gwu, msg, err := j.GetWorkUnits(workSpecName, options)
	if !assert.NoError(t, err) {
		return
	}
	assert.Empty(t, msg)
	missing := make(map[string]struct{})
	for name := range expected {
		missing[name] = struct{}{}
	}
	for _, item := range gwu {
		if !assert.IsType(t, cborrpc.PythonTuple{}, item) {
			continue
		}
		tuple := item.(cborrpc.PythonTuple)
		if !assert.Len(t, tuple.Items, 2) {
			continue
		}
		if !assert.IsType(t, []byte{}, tuple.Items[0]) {
			continue
		}
		name := string(tuple.Items[0].([]byte))
		assert.IsType(t, map[string]interface{}{}, tuple.Items[1])
		if assert.Contains(t, expected, name, "unexpected work unit") {
			assert.Equal(t, expected[name], tuple.Items[1])
		}
		assert.Contains(t, missing, name, "duplicate work unit")
		delete(missing, name)
	}
}
Esempio n. 8
0
func getOneWork(t *testing.T, j *jobserver.JobServer) (ok bool, workSpecName, workUnitKey string, workUnitData map[string]interface{}) {
	anything, msg, err := j.GetWork("test", map[string]interface{}{"available_gb": 1})
	if !assert.NoError(t, err) {
		return
	}
	assert.Empty(t, msg)
	// Since we didn't request multiple work units we should always
	// get at most one, but maybe none
	if assert.NotNil(t, anything) &&
		assert.IsType(t, cborrpc.PythonTuple{}, anything) {
		tuple := anything.(cborrpc.PythonTuple)
		if assert.Len(t, tuple.Items, 3) {
			// "no work unit" gets returned as tuple (nil,
			// nil, nil)
			if tuple.Items[0] != nil &&
				assert.IsType(t, "", tuple.Items[0]) &&
				assert.IsType(t, []byte{}, tuple.Items[1]) &&
				assert.IsType(t, map[string]interface{}{}, tuple.Items[2]) {
				ok = true
				workSpecName = tuple.Items[0].(string)
				bWorkUnitKey := tuple.Items[1].([]byte)
				workUnitKey = string(bWorkUnitKey)
				workUnitData = tuple.Items[2].(map[string]interface{})
			}
		}
	}
	return
}
Esempio n. 9
0
func TestStateUpdateCheck(t *testing.T) {
	cs := UpdateCheckState{}

	var s State
	var c bool

	// no update
	s, c = cs.Handle(nil, &stateTestController{})
	assert.IsType(t, &InventoryUpdateState{}, s)
	assert.False(t, c)

	// pretend update check failed
	s, c = cs.Handle(nil, &stateTestController{
		updateRespErr: NewTransientError(errors.New("check failed")),
	})
	assert.IsType(t, &ErrorState{}, s)
	assert.False(t, c)

	// pretend we have an update
	update := &client.UpdateResponse{}

	s, c = cs.Handle(nil, &stateTestController{
		updateResp: update,
	})
	assert.IsType(t, &UpdateFetchState{}, s)
	assert.False(t, c)
	ufs, _ := s.(*UpdateFetchState)
	assert.Equal(t, *update, ufs.update)
}
func TestTrackerSave(t *testing.T) {
	doWithTrackerRepository(t, func(trackerRepo application.TrackerRepository) {
		tracker, err := trackerRepo.Save(context.Background(), app.Tracker{})
		assert.IsType(t, NotFoundError{}, err)
		assert.Nil(t, tracker)

		tracker, _ = trackerRepo.Create(context.Background(), "http://api.github.com", ProviderGithub)
		tracker.Type = "blabla"
		tracker2, err := trackerRepo.Save(context.Background(), *tracker)
		assert.IsType(t, BadParameterError{}, err)
		assert.Nil(t, tracker2)

		tracker.Type = ProviderJira
		tracker.URL = "blabla"
		tracker, err = trackerRepo.Save(context.Background(), *tracker)
		assert.Equal(t, ProviderJira, tracker.Type)
		assert.Equal(t, "blabla", tracker.URL)

		tracker.ID = "10000"
		tracker2, err = trackerRepo.Save(context.Background(), *tracker)
		assert.IsType(t, NotFoundError{}, err)
		assert.Nil(t, tracker2)

		tracker.ID = "asdf"
		tracker2, err = trackerRepo.Save(context.Background(), *tracker)
		assert.IsType(t, NotFoundError{}, err)
		assert.Nil(t, tracker2)

	})
}
Esempio n. 11
0
func TestHandlerGetListInvalidPage(t *testing.T) {
	index := resource.NewIndex()
	test := index.Bind("test", schema.Schema{}, nil, resource.DefaultConf)
	r, _ := http.NewRequest("GET", "/test", nil)
	rm := &RouteMatch{
		ResourcePath: []*ResourcePathComponent{
			&ResourcePathComponent{
				Name:     "test",
				Resource: test,
			},
		},
		Params: url.Values{
			"page": []string{"invalid"},
		},
	}
	status, headers, body := listGet(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Invalid `page` parameter", err.Message)
	}

	rm.Params.Set("page", "-1")

	status, headers, body = listGet(context.TODO(), r, rm)
	assert.Equal(t, 422, status)
	assert.Nil(t, headers)
	if assert.IsType(t, body, &Error{}) {
		err := body.(*Error)
		assert.Equal(t, 422, err.Code)
		assert.Equal(t, "Invalid `page` parameter", err.Message)
	}
}
Esempio n. 12
0
func init() {
	Describe("Testing with Ginkgo", func() {
		It("get returns an aws infrastructure", func() {
			logger, platform, provider := getNewProvider()
			inf, err := provider.Get("aws")

			devicePathResolver := boshdpresolv.NewAwsDevicePathResolver(500*time.Millisecond, platform.GetFs())

			Expect(err).ToNot(HaveOccurred())
			assert.IsType(GinkgoT(), NewAwsInfrastructure("http://169.254.169.254", NewDigDNSResolver(logger), platform, devicePathResolver), inf)
		})
		It("get returns vsphere infrastructure", func() {

			logger, platform, provider := getNewProvider()
			inf, err := provider.Get("vsphere")

			devicePathResolver := boshdpresolv.NewAwsDevicePathResolver(500*time.Millisecond, platform.GetFs())

			Expect(err).ToNot(HaveOccurred())
			assert.IsType(GinkgoT(), NewVsphereInfrastructure(platform, devicePathResolver, logger), inf)
		})
		It("get returns an error on unknown infrastructure", func() {

			_, _, provider := getNewProvider()
			_, err := provider.Get("some unknown infrastructure name")

			Expect(err).To(HaveOccurred())
		})
	})
}
Esempio n. 13
0
func init() {
	Describe("Testing with Ginkgo", func() {
		It("handler provider get returns nats handler", func() {
			deps, provider := buildProvider("nats://0.0.0.0")
			handler, err := provider.Get(deps.platform, deps.dirProvider)

			Expect(err).ToNot(HaveOccurred())
			assert.IsType(GinkgoT(), NewNatsHandler(deps.settings, deps.logger, yagnats.NewClient()), handler)
		})
		It("handler provider get returns https handler", func() {

			deps, provider := buildProvider("https://0.0.0.0")
			handler, err := provider.Get(deps.platform, deps.dirProvider)

			Expect(err).ToNot(HaveOccurred())
			assert.IsType(GinkgoT(), micro.HttpsHandler{}, handler)
		})
		It("handler provider get returns an error if not supported", func() {

			deps, provider := buildProvider("foo://0.0.0.0")
			_, err := provider.Get(deps.platform, deps.dirProvider)

			Expect(err).To(HaveOccurred())
		})
	})
}
Esempio n. 14
0
// Make sure Hash.Verify() fails properly.
func TestHashVerify(t *testing.T) {
	data := []byte{1, 2, 3, 4, 5}

	// Zero (invalid) hash.
	err := (Hash{}).Verify(data)
	assert.Equal(t, InvalidHashError{Hash{}}, err)

	validH, err := DefaultHash(data)
	require.Nil(t, err)

	corruptData := make([]byte, len(data))
	copy(corruptData, data)
	corruptData[0] ^= 1
	err = validH.Verify(corruptData)
	assert.IsType(t, HashMismatchError{}, err)

	invalidH := hashFromRawNoCheck(InvalidHash, validH.hashData())
	err = invalidH.Verify(data)
	assert.Equal(t, InvalidHashError{invalidH}, err)

	unknownType := validH.hashType() + 1
	unknownH := hashFromRawNoCheck(unknownType, validH.hashData())
	err = unknownH.Verify(data)
	assert.Equal(t, UnknownHashTypeError{unknownType}, err)

	hashData := validH.hashData()
	hashData[0] ^= 1
	corruptH := hashFromRawNoCheck(validH.hashType(), hashData)
	err = corruptH.Verify(data)
	assert.IsType(t, HashMismatchError{}, err)
}
Esempio n. 15
0
// TestMiddleware runs
func TestMiddleware(t *testing.T) {
	assert := assert.New(t)

	mw := Middleware{}

	mw.Func = func() {
	}
	assert.Panics(func() {
		mw.HandlerFunc()
	})

	ProdModeClosure(func() {
		assert.NotPanics(func() {
			mw.HandlerFunc()
		})
	})

	mw.Func = func(c *gin.Context) {
	}
	assert.IsType(*new(gin.HandlerFunc), mw.HandlerFunc())

	mw.Func = func(c Context) {
	}
	assert.IsType(*new(gin.HandlerFunc), mw.HandlerFunc())
	assert.NotPanics(func() {
		mw.HandlerFunc()(nil)
	})

	mw = LoggerMiddleware()
	assert.IsType(*new(gin.HandlerFunc), mw.HandlerFunc())
}
Esempio n. 16
0
func TestStateUpdateCheckWait(t *testing.T) {
	cws := NewUpdateCheckWaitState()

	// no update
	var tstart, tend time.Time

	tstart = time.Now()
	s, c := cws.Handle(nil, &stateTestController{
		pollIntvl: 100 * time.Millisecond,
	})
	tend = time.Now()
	assert.IsType(t, &UpdateCheckState{}, s)
	assert.False(t, c)
	assert.WithinDuration(t, tend, tstart, 105*time.Millisecond)

	// asynchronously cancel state operation
	go func() {
		c := cws.Cancel()
		assert.True(t, c)
	}()
	// should finish right away
	tstart = time.Now()
	s, c = cws.Handle(nil, &stateTestController{
		pollIntvl: 100 * time.Millisecond,
	})
	tend = time.Now()
	// canceled state should return itself
	assert.IsType(t, &UpdateCheckWaitState{}, s)
	assert.True(t, c)
	assert.WithinDuration(t, tend, tstart, 5*time.Millisecond)
}
func TestTrackerQuerySave(t *testing.T) {
	doWithTrackerRepositories(t, func(trackerRepo application.TrackerRepository, queryRepo application.TrackerQueryRepository) {

		query, err := queryRepo.Load(context.Background(), "abcd")
		assert.IsType(t, NotFoundError{}, err)
		assert.Nil(t, query)

		tracker, err := trackerRepo.Create(context.Background(), "http://issues.jboss.com", ProviderJira)
		tracker2, err := trackerRepo.Create(context.Background(), "http://api.github.com", ProviderGithub)
		query, err = queryRepo.Create(context.Background(), "abc", "xyz", tracker.ID)
		query2, err := queryRepo.Load(context.Background(), query.ID)
		assert.Nil(t, err)
		assert.Equal(t, query, query2)

		query.Query = "after"
		query.Schedule = "the"
		query.TrackerID = tracker2.ID
		if err != nil {
			t.Errorf("could not convert id: %s", tracker2.ID)
		}

		query2, err = queryRepo.Save(context.Background(), *query)
		assert.Nil(t, err)
		assert.Equal(t, query, query2)

		trackerRepo.Delete(context.Background(), "10000")

		query.TrackerID = "10000"
		query2, err = queryRepo.Save(context.Background(), *query)
		assert.IsType(t, NotFoundError{}, err)
		assert.Nil(t, query2)
	})
}
Esempio n. 18
0
// If there is no timestamp key in the store, validation fails.  This could
// happen if pushing an existing repository from one server to another that
// does not have the repo.
func TestValidateRootNoTimestampKey(t *testing.T) {
	_, oldRepo, cs := testutils.EmptyRepo()

	r, tg, sn, ts, err := testutils.Sign(oldRepo)
	assert.NoError(t, err)
	root, targets, snapshot, _, err := getUpdates(r, tg, sn, ts)
	assert.NoError(t, err)

	store := storage.NewMemStorage()
	updates := []storage.MetaUpdate{root, targets, snapshot}

	// sanity check - no timestamp keys for the GUN
	_, _, err = store.GetKey("testGUN", data.CanonicalTimestampRole)
	assert.Error(t, err)
	assert.IsType(t, &storage.ErrNoKey{}, err)

	// do not copy the targets key to the storage, and try to update the root
	_, err = validateUpdate(cs, "testGUN", updates, store)
	assert.Error(t, err)
	assert.IsType(t, validation.ErrBadRoot{}, err)

	// there should still be no timestamp keys - one should not have been
	// created
	_, _, err = store.GetKey("testGUN", data.CanonicalTimestampRole)
	assert.Error(t, err)
}
Esempio n. 19
0
func Test_LookupIP(t *testing.T) {
	var T []net.IP
	var host string
	var ip []net.IP

	host = "192.168.0.1"
	ip, _ = LookupIP(host)
	assert.IsType(t, T, ip, "should be a type of []net.IP")
	assert.Equal(t, 1, len(ip), "should be equal 1")
	assert.Equal(t, "192.168.0.1", ip[0].String(), "should be equal '192.168.0.1'")

	host = "192.168.0.102/32"
	ip, _ = LookupIP(host)
	assert.IsType(t, T, ip, "should be a type of []net.IP")
	assert.Equal(t, 1, len(ip), "should be equal 1")
	assert.Equal(t, "192.168.0.102", ip[0].String(), "should be equal '192.168.0.102'")

	host = "192.168.0.0/24"
	ip, _ = LookupIP(host)
	assert.IsType(t, T, ip, "should be a type of []net.IP")
	assert.Equal(t, 254, len(ip), "should be equal 1")
	assert.Equal(t, "192.168.0.1", ip[0].String(), "should be '192.168.0.1'")
	assert.Equal(t, "192.168.0.254", ip[len(ip)-1].String(), "should be '192.168.0.254'")

	host = "google.com"
	ip, _ = LookupIP(host)
	assert.IsType(t, T, ip, "should be a type of []net.IP")
	assert.True(t, len(ip) > 0, "should be true")

	host = "invalid-host(address|name)"
	ip, err := LookupIP(host)
	assert.IsType(t, T, ip, "should be a type of []net.IP")
	assert.True(t, len(ip) == 0, "should be true")
	assert.Error(t, err, "occurred with invalid host")
}
Esempio n. 20
0
func TestParserNoTime(t *testing.T) {
	a1 := func(t *testing.T, r *parseTestResult) {
		assert.False(t, r.tfnd)
		assert.IsType(t, &ErrRequiredArg{}, r.err)
		err := r.err.(*ErrRequiredArg)
		assert.EqualValues(t, 't', err.Opt)
		assert.NotEqual(t, "37", r.nsecs)
		assert.False(t, r.nfnd)
		assert.Equal(t, "", r.name)
	}
	a1(t, testParse(t, "tipnt01", "--t"))
	a1(t, testParse(t, "tipnt02", "--ti"))
	a1(t, testParse(t, "tipnt03", "--tim"))
	a1(t, testParse(t, "tipnt04", "--time"))

	a2 := func(t *testing.T, r *parseTestResult) {
		assert.False(t, r.tfnd)
		assert.IsType(t, &ErrRequiredArg{}, r.err)
		err := r.err.(*ErrRequiredArg)
		assert.EqualValues(t, 't', err.Opt)
		assert.NotEqual(t, "37", r.nsecs)
		assert.True(t, r.nfnd)
		assert.Equal(t, "", r.name)
	}
	a2(t, testParse(t, "tipnt05", "-n", "--t"))
	a2(t, testParse(t, "tipnt06", "-n", "--ti"))
	a2(t, testParse(t, "tipnt07", "-n", "--tim"))
	a2(t, testParse(t, "tipnt08", "-n", "--time"))
}
Esempio n. 21
0
func TestEndpointGetTransactions(t *testing.T) {
	c := initClient()
	data, err := c.GetTransactions(1)
	if err != nil {
		log.Fatal(err)
	}
	assert.IsType(t, int64(1), data.TotalCount)
	assert.IsType(t, "string", data.Transactions[0].Hsh)
}
Esempio n. 22
0
func TestDeleteRunner(t *testing.T) {
	ts, gitlab := Stub("stubs/runners/delete.json")
	resp, err := gitlab.DeleteRunner(6)

	assert.Equal(t, err, nil)
	assert.IsType(t, new(Runner), resp)
	assert.IsType(t, resp.Id, 6)
	defer ts.Close()
}
Esempio n. 23
0
func TestParserUnknownOpt(t *testing.T) {
	a1 := func(t *testing.T, r *parseTestResult, u string) {
		assert.True(t, r.tfnd)
		assert.Equal(t, "37", r.nsecs)
		assert.IsType(t, &ErrUnknownOpt{}, r.err)
		err := r.err.(*ErrUnknownOpt)
		if err.LongName == "" {
			assert.Equal(t, u, fmt.Sprintf("%c", err.Opt))
		} else {
			assert.Equal(t, u, err.LongName)
		}
		assert.False(t, r.nfnd)
		assert.Equal(t, "", r.name)
	}
	a1(t, testParse(t, "tipunkn01a", "--t=37", "-f", "-n", "effie"), "f")
	a1(t, testParse(t, "tipunkn02a", "--ti=37", "-fu", "-n", "effie"), "f")
	a1(t, testParse(t, "tipunkn03a", "--tim=37", "-fub", "-n", "effie"), "f")
	a1(t, testParse(t, "tipunkn04a", "--time=37", "-fubar", "-n", "effie"), "f")

	a1(t, testParse(t, "tipunkn01b", "--t=37", "-W", "f", "-n", "effie"), "f")
	a1(t, testParse(t, "tipunkn02b", "--ti=37", "-W", "fu", "-n", "effie"), "fu")
	a1(t, testParse(t, "tipunkn03b", "--tim=37", "-W", "fub", "-n", "effie"), "fub")
	a1(t, testParse(t, "tipunkn04b", "--time=37", "-W", "fubar", "-n", "effie"), "fubar")

	a2 := func(t *testing.T, r *parseTestResult, u string) {
		assert.True(t, r.tfnd)
		assert.Equal(t, "37", r.nsecs)
		assert.True(t, r.nfnd)
		assert.Equal(t, "", r.name)
		assert.IsType(t, &ErrUnknownOpt{}, r.err)
		err := r.err.(*ErrUnknownOpt)
		if err.LongName == "" {
			assert.Equal(t, u, fmt.Sprintf("%c", err.Opt))
		} else {
			assert.Equal(t, u, err.LongName)
		}
	}
	a2(t, testParse(t, "tipunkn05", "--t=37", "-n", "effie", "-f"), "f")
	a2(t, testParse(t, "tipunkn06", "--ti=37", "-n", "effie", "-W", "f"), "f")
	a2(t, testParse(t, "tipunkn07", "--tim=37", "-n", "effie", "-fu"), "f")
	a2(t, testParse(t, "tipunkn08", "--time=37", "-n", "effie", "-W", "fubar"), "fubar")

	a3 := func(t *testing.T, r *parseTestResult) {
		assert.True(t, r.tfnd)
		assert.Equal(t, "37", r.nsecs)
		assert.IsType(t, &ErrUnknownOpt{}, r.err)
		err := r.err.(*ErrUnknownOpt)
		assert.Equal(t, 0, err.Opt)
		assert.Equal(t, "hello", err.LongName)
		assert.False(t, r.nfnd)
		assert.Equal(t, "", r.name)
	}
	a3(t, testParse(t, "tipunkn09", "--t=37", "--hello", "-f", "-n", "effie"))
	a3(t, testParse(t, "tipunkn10", "--ti=37", "--hello", "-f", "-n", "effie"))
	a3(t, testParse(t, "tipunkn11", "--tim=37", "--hello", "-f", "-n", "effie"))
	a3(t, testParse(t, "tipunkn12", "--time=37", "--hello", "-f", "-n", "effie"))
}
Esempio n. 24
0
func TestNewRolePathsAndHashPrefixRejection(t *testing.T) {
	_, err := NewRole("targets/level1", 1, []string{"abc"}, nil, nil)
	assert.Error(t, err)
	assert.IsType(t, ErrInvalidRole{}, err)

	_, err = NewRole("targets/level1", 1, []string{"abc"}, []string{""}, []string{""})
	assert.Error(t, err)
	assert.IsType(t, ErrInvalidRole{}, err)
}
Esempio n. 25
0
func (suite *CacheTestSuite) TestGetAll() {
	suite.TestAddAll()

	cachedParent, cachedNodes := directoryCache.GetAll(suite.parent.c.Name, suite.parent.path)

	assert.Len(suite.T(), cachedNodes, 1)
	assert.IsType(suite.T(), &Object{}, cachedNodes[suite.item1.Name()])
	assert.IsType(suite.T(), &Directory{}, cachedParent)
}
Esempio n. 26
0
func TestEndpointGetSellPrice(t *testing.T) {
	c := initClient()
	data, err := c.GetSellPrice(1)
	if err != nil {
		log.Fatal(err)
	}
	assert.IsType(t, "string", data.Subtotal.Currency)
	assert.IsType(t, "string", data.Total.Amount)
}
func TestPriorityGetPutDisposed(t *testing.T) {
	q := NewPriorityQueue(1, false)
	q.Dispose()

	_, err := q.Get(1)
	assert.IsType(t, ErrDisposed, err)

	err = q.Put(mockItem(1))
	assert.IsType(t, ErrDisposed, err)
}
Esempio n. 28
0
func (s *LockServiceSuite) TestNewLock() {
	ls := &LockService{}
	m := ls.NewLock(LOCK_SERVICE_VALID_MUTEX_NAME, LOCK_SERVICE_VALID_MUTEX_TTL)

	assert.NotNil(s.T(), ls)
	assert.NotNil(s.T(), m)
	assert.IsType(s.T(), &LockService{}, ls)
	assert.IsType(s.T(), &Mutex{}, m)
	assert.Equal(s.T(), &Mutex{Name: LOCK_SERVICE_VALID_MUTEX_NAME, TTL: LOCK_SERVICE_VALID_MUTEX_TTL}, m)
}
Esempio n. 29
0
func TestApiClient_TestDecoder_returnsCorrectEncoder(t *testing.T) {
	client := ApiClient{"", api.JsonEncoding}
	assert.IsType(t, &json.Decoder{}, client.decoder(nil))

	client = ApiClient{"", api.GobEncoding}
	assert.IsType(t, &gob.Decoder{}, client.decoder(nil))

	client = ApiClient{"", api.XmlEncoding}
	assert.IsType(t, &xml.Decoder{}, client.decoder(nil))
}
Esempio n. 30
0
func TestHandlerFunc_Handle(t *testing.T) {
	called := false

	fn := func(e *apiai.Event, c *apex.Context) (interface{}, error) {
		called = true

		assert.Equal(t, "9b49f2fb-fdd4-46f1-aa0d-7c4ed2caccdc", e.ID)
		assert.Equal(t, "7501656c-b86e-496f-ae03-c2c800b851ff", e.SessionID)
		assert.Equal(t, "2016-09-08T05:34:23.167Z", e.Timestamp)

		r := e.Result
		assert.Equal(t, "agent", r.Source)
		assert.Equal(t, "my name is Sam and I live in Paris", r.ResolvedQuery)
		assert.Equal(t, "", r.Action)
		assert.IsType(t, true, r.ActionIncomplete)
		assert.Equal(t, false, r.ActionIncomplete)

		assert.Equal(t, "Paris", r.Parameters["city"])
		assert.Equal(t, "Sam", r.Parameters["user_name"])

		ctx := r.Contexts
		assert.NotEmpty(t, ctx)

		grCtx := ctx[0]
		assert.NotEmpty(t, ctx[0])
		assert.Equal(t, "greetings", grCtx.Name)
		assert.IsType(t, 1, grCtx.Lifespan)
		assert.Equal(t, 5, grCtx.Lifespan)

		assert.Equal(t, "Paris", grCtx.Parameters["city"])
		assert.Equal(t, "Sam", grCtx.Parameters["user_name"])
		assert.Equal(t, "Paris", grCtx.Parameters["city.original"])
		assert.Equal(t, "Sam", grCtx.Parameters["user_name.original"])

		m := r.Metadata
		assert.Equal(t, "373a354b-c15a-4a60-ac9d-a9f2aee76cb4", m.IntentID)
		assert.Equal(t, "false", m.WebHookUsed)
		assert.Equal(t, "greetings", m.IntentName)

		f := r.Fulfillment
		assert.Equal(t, "Nice to meet you, Sam!", f.Speech)

		s := e.Status
		assert.IsType(t, 1, s.Code)
		assert.Equal(t, 200, s.Code)
		assert.Equal(t, "success", s.ErrorType)

		return nil, nil
	}

	_, err := apiai.HandlerFunc(fn).Handle(event, nil)
	assert.NoError(t, err)

	assert.True(t, called, "function never called")
}