Example #1
1
func Test_String(t *testing.T) {
	t.Parallel()
	a := assert.New(t)
	s := &facebook.Session{}

	a.Equal(s.String(), s.Marshal())
}
Example #2
1
func Test_Implements_Session(t *testing.T) {
	t.Parallel()
	a := assert.New(t)
	s := &facebook.Session{}

	a.Implements((*goth.Session)(nil), s)
}
func TestMostSpecific(t *testing.T) {
	assert := assert.New(t)

	for _, t := range []struct {
		input    []string
		expected string
		err      error
	}{
		{
			[]string{"Organisation"},
			"Organisation",
			nil,
		}, {
			[]string{"Organisation", "PublicCompany", "Company"},
			"PublicCompany",
			nil,
		}, {
			[]string{"PublicCompany", "Organisation"},
			"PublicCompany",
			nil,
		}, {
			[]string{"Organisation", "PublicCompany", "PrivateCompany", "Company"},
			"",
			ErrNotHierarchy,
		}, {
			[]string{"zzzzzz", "yyyyyy"},
			"",
			ErrNotHierarchy,
		},
	} {
		ms, err := mostSpecific(t.input)
		assert.Equal(t.expected, ms)
		assert.Equal(t.err, err)
	}
}
func TestCollect(t *testing.T) {
	cm := &collectorManager{}

	firstTime := time.Now().Add(-time.Hour)
	secondTime := time.Now().Add(time.Hour)
	f1 := &fakeCollector{
		nextCollectionTime: firstTime,
	}
	f2 := &fakeCollector{
		nextCollectionTime: secondTime,
	}

	assert := assert.New(t)
	assert.NoError(cm.RegisterCollector(f1))
	assert.NoError(cm.RegisterCollector(f2))

	// First collection, everyone gets collected from.
	nextTime, _, err := cm.Collect()
	assert.Equal(firstTime, nextTime)
	assert.NoError(err)
	assert.Equal(1, f1.collectedFrom)
	assert.Equal(1, f2.collectedFrom)

	f1.nextCollectionTime = time.Now().Add(2 * time.Hour)

	// Second collection, only the one that is ready gets collected from.
	nextTime, _, err = cm.Collect()
	assert.Equal(secondTime, nextTime)
	assert.NoError(err)
	assert.Equal(2, f1.collectedFrom)
	assert.Equal(1, f2.collectedFrom)
}
Example #5
0
// TestGetNodeAddresses verifies that proper results are returned
// when requesting node addresses.
func TestGetNodeAddresses(t *testing.T) {
	assert := assert.New(t)

	fakeNodeClient := fake.NewSimpleClientset(registrytest.MakeNodeList([]string{"node1", "node2"}, api.NodeResources{})).Core().Nodes()
	addressProvider := nodeAddressProvider{fakeNodeClient}

	// Fail case (no addresses associated with nodes)
	nodes, _ := fakeNodeClient.List(api.ListOptions{})
	addrs, err := addressProvider.externalAddresses()

	assert.Error(err, "addresses should have caused an error as there are no addresses.")
	assert.Equal([]string(nil), addrs)

	// Pass case with External type IP
	nodes, _ = fakeNodeClient.List(api.ListOptions{})
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeExternalIP, Address: "127.0.0.1"}}
		fakeNodeClient.Update(&nodes.Items[index])
	}
	addrs, err = addressProvider.externalAddresses()
	assert.NoError(err, "addresses should not have returned an error.")
	assert.Equal([]string{"127.0.0.1", "127.0.0.1"}, addrs)

	// Pass case with LegacyHost type IP
	nodes, _ = fakeNodeClient.List(api.ListOptions{})
	for index := range nodes.Items {
		nodes.Items[index].Status.Addresses = []api.NodeAddress{{Type: api.NodeLegacyHostIP, Address: "127.0.0.2"}}
		fakeNodeClient.Update(&nodes.Items[index])
	}
	addrs, err = addressProvider.externalAddresses()
	assert.NoError(err, "addresses failback should not have returned an error.")
	assert.Equal([]string{"127.0.0.2", "127.0.0.2"}, addrs)
}
Example #6
0
func TestBlobLen(t *testing.T) {
	assert := assert.New(t)
	b := NewBlob(&bytes.Buffer{})
	assert.Equal(uint64(0), b.Len())
	b = NewBlob(bytes.NewBuffer([]byte{0x01}))
	assert.Equal(uint64(1), b.Len())
}
Example #7
0
func Test_DoInTxError(t *testing.T) {
	a := assert.New(t)
	mStore := New("/TestDir")

	err := mStore.DoInTx("p2", nil)
	a.NotNil(err)
}
Example #8
0
func Test_MaxMessageIdError(t *testing.T) {
	a := assert.New(t)
	store := New("/TestDir")

	_, err := store.MaxMessageID("p2")
	a.NotNil(err)
}
Example #9
0
func TestPoliciesList(t *testing.T) {
	var httpStatusCode int
	var err error
	var reslut []apilib.RepPolicy

	assert := assert.New(t)
	apiTest := newHarborAPI()

	fmt.Println("Testing Policies Get/List API")

	//-------------------case 1 : response code = 200------------------------//
	fmt.Println("case 1 : response code = 200")
	projectID := "1"
	httpStatusCode, reslut, err = apiTest.ListPolicies(*admin, addPolicyName, projectID)
	if err != nil {
		t.Error("Error while get policies", err.Error())
		t.Log(err)
	} else {
		assert.Equal(int(200), httpStatusCode, "httpStatusCode should be 200")
		addPolicyID = int(reslut[0].Id)
	}

	//-------------------case 2 : response code = 400------------------------//
	fmt.Println("case 2 : response code = 400:invalid projectID")
	projectID = "cc"
	httpStatusCode, reslut, err = apiTest.ListPolicies(*admin, addPolicyName, projectID)
	if err != nil {
		t.Error("Error while get policies", err.Error())
		t.Log(err)
	} else {
		assert.Equal(int(400), httpStatusCode, "httpStatusCode should be 400")
	}

}
Example #10
0
func TestFSMHandlerEstablish_HoldTimerExpired(t *testing.T) {
	assert := assert.New(t)
	m := NewMockConnection()

	p, h := makePeerAndHandler()

	// push mock connection
	p.fsm.conn = m

	// set keepalive ticker
	p.fsm.pConf.Timers.State.NegotiatedHoldTime = 3

	msg := keepalive()
	header, _ := msg.Header.Serialize()
	body, _ := msg.Body.Serialize()

	pushPackets := func() {
		// first keepalive from peer
		m.setData(header)
		m.setData(body)
	}

	// set holdtime
	p.fsm.pConf.Timers.Config.HoldTime = 2
	p.fsm.pConf.Timers.State.NegotiatedHoldTime = 2

	go pushPackets()
	state, _ := h.established()
	time.Sleep(time.Second * 1)
	assert.Equal(bgp.BGP_FSM_IDLE, state)
	lastMsg := m.sendBuf[len(m.sendBuf)-1]
	sent, _ := bgp.ParseBGPMessage(lastMsg)
	assert.Equal(uint8(bgp.BGP_MSG_NOTIFICATION), sent.Header.Type)
	assert.Equal(uint8(bgp.BGP_ERROR_HOLD_TIMER_EXPIRED), sent.Body.(*bgp.BGPNotification).ErrorCode)
}
Example #11
0
func TestReadAll(t *testing.T) {
	assert := assert.New(t)
	m := NewMockConnection()
	msg := open()
	expected1, _ := msg.Header.Serialize()
	expected2, _ := msg.Body.Serialize()

	pushBytes := func() {
		fmt.Println("push 5 bytes")
		m.setData(expected1[0:5])
		fmt.Println("push rest")
		m.setData(expected1[5:])
		fmt.Println("push bytes at once")
		m.setData(expected2)
	}

	go pushBytes()

	var actual1 []byte
	actual1, _ = readAll(m, bgp.BGP_HEADER_LENGTH)
	fmt.Println(actual1)
	assert.Equal(expected1, actual1)

	var actual2 []byte
	actual2, _ = readAll(m, len(expected2))
	fmt.Println(actual2)
	assert.Equal(expected2, actual2)
}
Example #12
0
func TestDateParseLayout(t *testing.T) {
	assert := assert.New(t)
	testCases := []struct {
		Text     string
		Layout   string
		Expected Date
		Error    bool
	}{
		{
			Text:     "11 Jan 1994",
			Layout:   "02 Jan 2006",
			Expected: DateFor(1994, 1, 11),
		},
		{
			Text:   "Jan 11 1994",
			Layout: "02 Jan 2006",
			Error:  true,
		},
	}

	for _, tc := range testCases {
		d, err := DateParseLayout(tc.Layout, tc.Text)
		if tc.Error {
			assert.Error(err)
		} else {
			assert.NoError(err)
			assert.Equal(tc.Expected, d, datesNotEqual(tc.Expected, d))
		}
	}
}
Example #13
0
func TestDateSub(t *testing.T) {
	assert := assert.New(t)
	testCases := []struct {
		Date1 Date
		Date2 Date
		Days  int
	}{
		{
			Date1: DateFor(1994, 11, 14),
			Date2: DateFor(1994, 11, 13),
			Days:  1,
		},
		{
			Date1: DateFor(1994, 11, 14),
			Date2: DateFor(1994, 11, 15),
			Days:  -1,
		},
		{
			Date1: DateFor(1994, 11, 14),
			Date2: DateFor(1992, 12, 16),
			Days:  698,
		},
	}
	for _, tc := range testCases {
		d := tc.Date1.Sub(tc.Date2)
		assert.Equal(time.Duration(tc.Days)*time.Hour*24, d)
	}
}
Example #14
0
// Test for case where attempt made to unmarshal invalid binary data
func TestDateUnmarshalBinaryError(t *testing.T) {
	assert := assert.New(t)
	data := []byte("xxxx")
	var d Date
	err := d.UnmarshalBinary(data)
	assert.Error(err)
}
Example #15
0
// Test to create the scheduler plugin with an empty plugin config
func TestPlugin_New(t *testing.T) {
	assert := assert.New(t)

	c := PluginConfig{}
	p := NewPlugin(&c)
	assert.NotNil(p)
}
Example #16
0
// TestGenerateSSHKey verifies that SSH key generation does indeed
// generate keys even with keys already exist.
func TestGenerateSSHKey(t *testing.T) {
	assert := assert.New(t)

	privateKey := generateTempFilePath("private")
	publicKey := generateTempFilePath("public")

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// Pass case: Sunny day case
	err := generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PrivateKey exists test case
	os.Remove(publicKey)
	err = generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PublicKey exists test case
	os.Remove(privateKey)
	err = generateSSHKey(privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// TODO: testing error cases where the file can not be removed?
}
Example #17
0
func TestUnCompressed(t *testing.T) {
	assert := assert.New(t)
	// SELECT repeat("a", 50)
	before := `
09 00 00 00 03 53 45 4c 45 43 54 20 31                ....SELECT 1
`
	after := `
0d 00 00 00 00 00 00 09    00 00 00 03 53 45 4c 45    ............SELE
43 54 20 31                                           CT 1
`
	_, _ = before, after

	buf := bytes.NewBufferString("")
	buf.Write(DecodeDump(after))

	r := NewCompressedReader(buf)
	b, err := ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)

	// write and read again
	w := NewCompressedWriter(buf)
	_, err = w.Write(DecodeDump(before))
	assert.NoError(err)
	b, err = ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)
}
Example #18
0
func TestPolicyUpdateEnablement(t *testing.T) {
	var httpStatusCode int
	var err error

	enablement := &apilib.RepPolicyEnablementReq{int32(0)}

	assert := assert.New(t)
	apiTest := newHarborAPI()

	fmt.Println("Testing Policy PUT API to update policy enablement")

	//-------------------case 1 : response code = 200------------------------//
	fmt.Println("case 1 : response code = 200")

	policyID := strconv.Itoa(addPolicyID)
	httpStatusCode, err = apiTest.PutPolicyEnableByID(*admin, policyID, *enablement)
	if err != nil {
		t.Error("Error while put policy enablement", err.Error())
		t.Log(err)
	} else {
		assert.Equal(int(200), httpStatusCode, "httpStatusCode should be 200")
	}
	//-------------------case 2 : response code = 404------------------------//
	fmt.Println("case 2 : response code = 404,Not Found")

	policyID = "111"
	httpStatusCode, err = apiTest.PutPolicyEnableByID(*admin, policyID, *enablement)
	if err != nil {
		t.Error("Error while put policy enablement", err.Error())
		t.Log(err)
	} else {
		assert.Equal(int(404), httpStatusCode, "httpStatusCode should be 404")
	}

}
Example #19
0
func Test_StoreWithError(t *testing.T) {
	a := assert.New(t)
	mStore := New("/TestDir")

	err := mStore.Store("p1", uint64(1), []byte("124151qfas"))
	a.NotNil(err)
}
Example #20
0
func Test07ABadServer(t *testing.T) {
	assert := assert.New(t)

	f := func(c *gin.Context) {}

	required := []ServiceName{}
	sys, err := NewSystemConfig(PzGoCommon, required)
	assert.NoError(err)

	genericServer := GenericServer{Sys: sys}

	service := &ThingService{
		assert:  assert,
		IDCount: 0,
		Data:    make(map[string]string),
	}

	server := &ThingServer{}

	server.Init(service)

	server.routes = []RouteData{
		{"GET", "/", f},
		{"YOW", "/", f},
	}

	err = genericServer.Configure(server.routes)
	assert.Error(err)
}
Example #21
0
func TestFindIPFake(t *testing.T) {
	is := assert.New(t)

	ip, er := FindIP("foo")
	is.Error(er)
	is.Empty(ip)
}
Example #22
0
func PostFile(t *testing.T) {
	assert := assert.New(t)

	fs := []files.File{
		{"file.txt", "Hello", "QmNULL"},
		{"file2.txt", "Hello2", "QmNULL"},
	}

	request := AddFiles(t, fs)

	// Perform the request
	resp, err := http.DefaultClient.Do(request)

	assert.NoError(err)
	assert.Equal(http.StatusOK, resp.StatusCode)

	// Verify our return values
	var file files.File
	dec := json.NewDecoder(resp.Body)

	// TODO: The API does not have to return files in order
	// go-ipfs just happens to do so as of right now
	for _, f := range fs {
		err = dec.Decode(&file)
		assert.NoError(err)

		// Verify the name
		assert.Equal(f.Name, file.Name)

		// Verify hash
		_, err = mh.FromB58String(file.Hash)
		assert.NoError(err)
	}
}
func TestUpdateUser(t *testing.T) {
	assert := assert.New(t)
	s := sw.NewUserApi()
	newUser := sw.User{
		Id:         1000,
		FirstName:  "gopher20",
		LastName:   "lang20",
		Username:   "******",
		Password:   "******",
		Email:      "*****@*****.**",
		Phone:      "5101112222",
		UserStatus: 1}

	apiResponse, err := s.UpdateUser("gopher", newUser)

	if err != nil {
		t.Errorf("Error while deleting user by id")
		t.Log(err)
	}
	if apiResponse.Response.StatusCode != 200 {
		t.Log(apiResponse.Response)
	}

	//verify changings are correct
	resp, apiResponse, err := s.GetUserByName("gopher")
	if err != nil {
		t.Errorf("Error while getting user by id")
		t.Log(err)
	} else {
		assert.Equal(resp.Id, int64(1000), "User id should be equal")
		assert.Equal(resp.FirstName, "gopher20", "User name should be gopher")
		assert.Equal(resp.Password, "lang", "User name should be the same")
	}
}
Example #24
0
func TestConvertWithNewLines(t *testing.T) {
	assert := assert.New(t)

	s := `<?xml version="1.0" encoding="UTF-8"?>
  <osm>
   <foo>
	 	foo

		bar
	</foo>
  </osm>`

	// Build SimpleJSON
	json, err := sj.NewJson([]byte(`{
	  "osm": {
	    "foo": "foo\n\n\t\tbar"
	  }
	}`))
	assert.NoError(err)

	expected, err := json.MarshalJSON()
	assert.NoError(err)

	// Then encode it in JSON
	res, err := Convert(strings.NewReader(s))
	assert.NoError(err)

	// Assertion
	assert.JSONEq(string(expected), res.String(), "Drumroll")
}
Example #25
0
func testStateTrace(t *testing.T, transitions []transition) *Registry {
	assert := assert.New(t)

	registry := NewInMemoryRegistry()
	a, _ := fakePodTask("a")
	a, _ = registry.Register(a, nil)

	// initial pending state
	assert.Equal(a.State, StatePending)

	for _, transition := range transitions {
		if transition.expectPanic {
			assert.Panics(func() {
				registry.UpdateStatus(fakeStatusUpdate(a.ID, transition.statusUpdate))
			})
		} else {
			a, _ = registry.UpdateStatus(fakeStatusUpdate(a.ID, transition.statusUpdate))
			if transition.expectedState == nil {
				a, _ = registry.Get(a.ID)
				assert.Nil(a, "expected task to be deleted from registry after status update to %v", transition.statusUpdate)
			} else {
				assert.Equal(a.State, *transition.expectedState)
			}
		}
	}

	return &registry
}
Example #26
0
func TestAccountBatchesWithPaging(t *testing.T) {
	h := newRecordingHandler(`<?xml version="1.0" encoding="utf-8"?>
<messagebatches startindex="4" count="10" totalcount="200" xmlns="http://api.esendex.com/ns/">
</messagebatches>`, 200, map[string]string{})
	s := httptest.NewServer(h)
	defer s.Close()

	client := New("user", "pass")
	client.BaseURL, _ = url.Parse(s.URL)

	account := client.Account("EXWHAT")

	_, err := account.Batches(Page(5, 10))

	assert := assert.New(t)

	assert.Nil(err)

	assert.Equal("GET", h.Request.Method)
	assert.Equal("/v1.1/messagebatches", h.Request.URL.Path)

	if user, pass, ok := h.Request.BasicAuth(); assert.True(ok) {
		assert.Equal("user", user)
		assert.Equal("pass", pass)
	}

	query := h.Request.URL.Query()
	assert.Equal("account", query.Get("filterBy"))
	assert.Equal("EXWHAT", query.Get("filterValue"))
	assert.Equal("5", query.Get("startindex"))
	assert.Equal("10", query.Get("count"))
}
Example #27
0
func TestRead(t *testing.T) {
	assert := assert.New(t)
	ds := datas.NewDataStore(chunks.NewMemoryStore())

	dataString := `a,1,true
b,2,false
`
	r := NewCSVReader(bytes.NewBufferString(dataString), ',')

	headers := []string{"A", "B", "C"}
	kinds := KindSlice{types.StringKind, types.Int8Kind, types.BoolKind}
	l, typeRef, typeDef := Read(r, "test", headers, kinds, ds)

	assert.Equal(uint64(2), l.Len())

	assert.True(typeRef.IsUnresolved())

	desc, ok := typeDef.Desc.(types.StructDesc)
	assert.True(ok)
	assert.Len(desc.Fields, 3)
	assert.Equal("A", desc.Fields[0].Name)
	assert.Equal("B", desc.Fields[1].Name)
	assert.Equal("C", desc.Fields[2].Name)

	assert.True(l.Get(0).(types.Struct).Get("A").Equals(types.NewString("a")))
	assert.True(l.Get(1).(types.Struct).Get("A").Equals(types.NewString("b")))

	assert.True(l.Get(0).(types.Struct).Get("B").Equals(types.Int8(1)))
	assert.True(l.Get(1).(types.Struct).Get("B").Equals(types.Int8(2)))

	assert.True(l.Get(0).(types.Struct).Get("C").Equals(types.Bool(true)))
	assert.True(l.Get(1).(types.Struct).Get("C").Equals(types.Bool(false)))
}
Example #28
0
func TestDefaultConfig(t *testing.T) {
	assert := assert.New(t)

	config := DefaultConfig()
	assert.False(config.SSL.Enabled)
	assert.False(config.Ldap.Enabled)
}
Example #29
0
// TestSecondsSinceSync verifies that proper results are returned
// when checking the time between syncs
func TestSecondsSinceSync(t *testing.T) {
	tunneler := &SSHTunneler{}
	assert := assert.New(t)

	tunneler.lastSync = time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC).Unix()

	// Nano Second. No difference.
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 1, 2, time.UTC))
	assert.Equal(int64(0), tunneler.SecondsSinceSync())

	// Second
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 2, 1, time.UTC))
	assert.Equal(int64(1), tunneler.SecondsSinceSync())

	// Minute
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 2, 1, 1, time.UTC))
	assert.Equal(int64(60), tunneler.SecondsSinceSync())

	// Hour
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 2, 1, 1, 1, time.UTC))
	assert.Equal(int64(3600), tunneler.SecondsSinceSync())

	// Day
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 2, 1, 1, 1, 1, time.UTC))
	assert.Equal(int64(86400), tunneler.SecondsSinceSync())

	// Month
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC))
	assert.Equal(int64(2678400), tunneler.SecondsSinceSync())

	// Future Month. Should be -Month.
	tunneler.lastSync = time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC).Unix()
	tunneler.clock = util.NewFakeClock(time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC))
	assert.Equal(int64(-2678400), tunneler.SecondsSinceSync())
}
Example #30
0
// Ensures that outbound rules are not applied if a nil resource is returned by
// handler.
func TestOutboundRulesDontApplyOnNilResource(t *testing.T) {
	assert := assert.New(t)
	handler := new(MockResourceHandler)
	api := NewAPI(&Configuration{})
	rule := &Rule{
		Field:      "Foo",
		FieldAlias: "f",
		OutputOnly: true,
	}

	handler.On("ResourceName").Return("foo")
	handler.On("Authenticate").Return(nil)
	handler.On("Rules").Return(NewRules((*TestResource)(nil), rule))
	handler.On("ReadResource").Return(nil, nil)

	api.RegisterResourceHandler(handler)
	readHandler, _ := api.(*muxAPI).getRouteHandler("foo:read")

	req, _ := http.NewRequest("GET", "http://foo.com/api/v0.1/foo/1", nil)
	resp := httptest.NewRecorder()

	readHandler.ServeHTTP(resp, req)

	handler.Mock.AssertExpectations(t)
	assert.Equal(
		`{"messages":[],"reason":"OK","result":null,"status":200}`,
		resp.Body.String(),
		"Incorrect response string",
	)
}