Esempio n. 1
1
func TestHandlerAdd(t *testing.T) {
	tests := []struct {
		description string
		params      *articles.HandlerAddParams
		code        int
	}{
		{"No Title", &articles.HandlerAddParams{}, http.StatusBadRequest},
		{"Title filled with spaces", &articles.HandlerAddParams{Title: "       "}, http.StatusBadRequest},
		{"As few params as possible", &articles.HandlerAddParams{Title: "My Super Article"}, http.StatusCreated},
		{"Duplicate title", &articles.HandlerAddParams{Title: "My Super Article"}, http.StatusCreated},
	}

	for _, tc := range tests {
		t.Run(tc.description, func(t *testing.T) {
			rec := callHandlerAdd(t, tc.params)
			assert.Equal(t, tc.code, rec.Code)

			if rec.Code == http.StatusCreated {
				var a articles.Article
				if err := json.NewDecoder(rec.Body).Decode(&a); err != nil {
					t.Fatal(err)
				}

				assert.NotEmpty(t, a.ID)
				assert.NotEmpty(t, a.Slug)
				assert.Equal(t, tc.params.Title, a.Title)
				if err := a.FullyDelete(); err != nil {
					t.Fatal(err)
				}
			}
		})
	}
}
Esempio n. 2
0
func TestTemplate(t *testing.T) {
	files := make(map[string]*file.File)
	files["test_file.txt"] = &file.File{
		Name: "test_file.txt",
		Path: "static/test_file.txt",
		Data: `[]byte("\x12\x34\x56\x78\x10")`,
	}

	dirs := new(dir.Dir)
	dirs.Insert("static/")

	tp := new(Template)
	tp.Set("files")
	tp.Variables = struct {
		Pkg     string
		Files   map[string]*file.File
		Spread  bool
		DirList []string
	}{
		Pkg:     "main",
		Files:   files,
		Spread:  false,
		DirList: dirs.Clean(),
	}

	tmpl, err := tp.Exec()
	assert.NoError(t, err)
	assert.NotEmpty(t, tmpl)

	s := string(tmpl)

	assert.True(t, strings.Contains(s, `var FileStaticTestFileTxt = []byte("\x12\x34\x56\x78\x10")`))
	assert.True(t, strings.Contains(s, `err = FS.Mkdir("static/", 0777)`))
	assert.True(t, strings.Contains(s, `f, err = FS.OpenFile("static/test_file.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)`))

	// now with spread
	tp.Set("file")
	tp.Variables = struct {
		Pkg  string
		Path string
		Name string
		Dir  [][]string
		Data string
	}{
		Pkg:  "main",
		Path: files["test_file.txt"].Path,
		Name: files["test_file.txt"].Name,
		Dir:  dirs.List,
		Data: files["test_file.txt"].Data,
	}

	tmpl, err = tp.Exec()
	assert.NoError(t, err)
	assert.NotEmpty(t, tmpl)

	s = string(tmpl)

	assert.True(t, strings.Contains(s, `var FileStaticTestFileTxt = []byte("\x12\x34\x56\x78\x10")`))
	assert.True(t, strings.Contains(s, `f, err := FS.OpenFile("static/test_file.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)`))
}
// TestItemsAreInLongTermStorage - make sure that each tar file is
// stored in our S3 test storage bucket, with correct metadata.
func TestItemsAreInLongTermStorage(t *testing.T) {
	if !apt_testutil.ShouldRunIntegrationTests() {
		t.Skip("Skipping integration test. Set ENV var RUN_EXCHANGE_INTEGRATION=true if you want to run them.")
	}
	_context, err := apt_testutil.GetContext("integration.json")
	require.Nil(t, err, "Could not create context")

	localClient, err := network.NewDPNRestClient(
		_context.Config.DPN.RestClient.LocalServiceURL,
		_context.Config.DPN.RestClient.LocalAPIRoot,
		_context.Config.DPN.RestClient.LocalAuthToken,
		_context.Config.DPN.LocalNode,
		_context.Config.DPN)
	require.Nil(t, err)

	// s3List lists bucket contents.
	s3List := apt_network.NewS3ObjectList(
		constants.AWSVirginia,
		_context.Config.DPN.DPNPreservationBucket,
		int64(100),
	)
	// s3Head gets metadata about specific objects in S3/Glacier.
	s3Head := apt_network.NewS3Head(_context.Config.APTrustS3Region,
		_context.Config.DPN.DPNPreservationBucket)

	for _, identifier := range dpn_testutil.BAG_IDS {
		resp := localClient.DPNBagGet(identifier)
		dpnBag := resp.Bag()
		require.NotNil(t, dpnBag)
		if dpnBag.IngestNode == _context.Config.DPN.LocalNode {
			continue // we would not have replicated our own bag
		}
		tarFileName := fmt.Sprintf("%s.tar", identifier)
		s3List.GetList(tarFileName)
		require.NotEmpty(t, s3List.Response.Contents, "%s not found in S3", tarFileName)
		object := s3List.Response.Contents[0]
		fiveMinutesAgo := time.Now().UTC().Add(-5 * time.Minute)
		require.NotNil(t, object.LastModified)
		assert.True(t, object.LastModified.After(fiveMinutesAgo))

		// Make sure each item has the expected metadata.
		// s3Head.Response.Metadata is map[string]*string.
		s3Head.Head(tarFileName)
		require.Empty(t, s3Head.ErrorMessage)
		metadata := s3Head.Response.Metadata
		require.NotNil(t, metadata)
		// Amazon library transforms first letters of keys to CAPS
		require.NotNil(t, metadata["From_node"])
		require.NotNil(t, metadata["Transfer_id"])
		require.NotNil(t, metadata["Member"])
		require.NotNil(t, metadata["Local_id"])
		require.NotNil(t, metadata["Version"])

		assert.NotEmpty(t, *metadata["From_node"])
		assert.NotEmpty(t, *metadata["Transfer_id"])
		assert.NotEmpty(t, *metadata["Member"])
		assert.NotEmpty(t, *metadata["Local_id"])
		assert.NotEmpty(t, *metadata["Version"])
	}
}
Esempio n. 4
0
func TestStorageReInit(t *testing.T) {

	// quick implement, use mock of dbr.SessionRunner and remove connection
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()

	nsg := store.MustNewStorage(nil, nil, nil)
	assert.NoError(t, nsg.ReInit(dbc.NewSession()))

	stores, err := nsg.Stores()
	assert.NoError(t, err)
	assert.True(t, stores.Len() > 0, "Expecting at least one store loaded from DB")
	for _, s := range stores {
		assert.NotEmpty(t, s.Data.Code.String, "Store: %#v", s.Data)
	}

	groups, err := nsg.Groups()
	assert.True(t, groups.Len() > 0, "Expecting at least one group loaded from DB")
	assert.NoError(t, err)
	for _, g := range groups {
		assert.NotEmpty(t, g.Data.Name, "Group: %#v", g.Data)
	}

	websites, err := nsg.Websites()
	assert.True(t, websites.Len() > 0, "Expecting at least one website loaded from DB")
	assert.NoError(t, err)
	for _, w := range websites {
		assert.NotEmpty(t, w.Data.Code.String, "Website: %#v", w.Data)
	}
}
Esempio n. 5
0
func TestDockbus(t *testing.T) {
	wea := weather.New()
	locations, e := weather.FindLocation("paris")
	assert.NoError(t, e, "weather.FindLocation")
	assert.NotEmpty(t, locations, "locations")

	wea.SetConfig(&weather.Config{
		LocationCode:       locations[0].ID,
		NbDays:             10,
		DisplayCurrentIcon: true,
		Time24H:            true,
		UseCelcius:         true,
	})
	for e := range wea.Get() {
		assert.NoError(t, e, "weather.Get")
	}
	cur := wea.Current()
	assert.NotNil(t, cur, "Current")

	fc := wea.Forecast()
	assert.True(t, len(fc.Days) > 10, "Forecast")

	assert.Equal(t, "Paris-Montsouris, 75, FR", cur.Observatory, "Observatory")
	assert.Equal(t, "Paris, 75, France", cur.LocName, "LocName")
	assert.Equal(t, "°C", cur.UnitTemp, "UnitTemp")
	assert.Equal(t, "km/h", cur.UnitSpeed, "UnitSpeed")
	assert.NotEmpty(t, cur.WeatherIcon, "WeatherIcon")
	assert.NotEmpty(t, cur.MoonIcon, "MoonIcon")
}
func TestCreateIDSiteURL(t *testing.T) {
	t.Parallel()

	application := createTestApplication(t)
	defer application.Purge()

	idSiteOptions := IDSiteOptions{
		CallbackURL: "http://localhost:8080",
	}

	idSiteURL, err := application.CreateIDSiteURL(idSiteOptions)

	u, _ := url.Parse(idSiteURL)

	assert.NoError(t, err)
	assert.Equal(t, "/sso", u.Path)
	assert.NotEmpty(t, u.Query)

	//Check Token
	jwtString := u.Query().Get("jwtRequest")

	claims := &SSOTokenClaims{}

	token := ParseJWT(jwtString, claims)

	assert.True(t, token.Valid)

	assert.Equal(t, "http://localhost:8080", claims.CallbackURI)
	assert.Equal(t, "", claims.State)
	assert.Equal(t, "/", claims.Path)
	assert.Equal(t, client.ClientConfiguration.APIKeyID, claims.Issuer)
	assert.Equal(t, application.Href, claims.Subject)
	assert.NotEmpty(t, claims.Id)
	assert.NotEmpty(t, claims.IssuedAt)
}
Esempio n. 7
0
func TestGC(t *testing.T) {
	var podEvictedCount int
	var containerEvictedCount int

	cache := NewCache(time.Millisecond, time.Second)
	cache.AddCacheListener(CacheListener{
		PodEvicted: func(namespace string, name string) {
			podEvictedCount += 1
		},
		FreeContainerEvicted: func(hostname string, name string) {
			containerEvictedCount += 1
		},
	})

	var (
		pods       []source_api.Pod
		containers []source_api.Container
	)
	f := fuzz.New().NumElements(2, 10).NilChance(0)
	f.Fuzz(&pods)
	f.Fuzz(&containers)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	zeroTime := time.Time{}
	assert.NotEmpty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.NotEmpty(cache.GetPods(zeroTime, zeroTime))
	// Expect all data to be deleted after 2 seconds.
	time.Sleep(10 * time.Second)
	assert.Empty(cache.GetFreeContainers(zeroTime, zeroTime))
	assert.Empty(cache.GetPods(zeroTime, zeroTime))

	assert.Equal(len(pods), podEvictedCount)
	assert.Equal(len(containers), containerEvictedCount)
}
func TestKMSGenerateCipherData(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, `{"CiphertextBlob":"AQEDAHhqBCCY1MSimw8gOGcUma79cn4ANvTtQyv9iuBdbcEF1QAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDJ6IcN5E4wVbk38MNAIBEIA7oF1E3lS7FY9DkoxPc/UmJsEwHzL82zMqoLwXIvi8LQHr8If4Lv6zKqY8u0+JRgSVoqCvZDx3p8Cn6nM=","KeyId":"arn:aws:kms:us-west-2:042062605278:key/c80a5cdb-8d09-4f9f-89ee-df01b2e3870a","Plaintext":"6tmyz9JLBE2yIuU7iXpArqpDVle172WSmxjcO6GNT7E="}`)
	}))

	sess := unit.Session.Copy(&aws.Config{
		MaxRetries:       aws.Int(0),
		Endpoint:         aws.String(ts.URL[7:]),
		DisableSSL:       aws.Bool(true),
		S3ForcePathStyle: aws.Bool(true),
		Region:           aws.String("us-west-2"),
	})

	svc := kms.New(sess)
	handler := NewKMSKeyGenerator(svc, "testid")

	keySize := 32
	ivSize := 16

	cd, err := handler.GenerateCipherData(keySize, ivSize)
	assert.NoError(t, err)
	assert.Equal(t, keySize, len(cd.Key))
	assert.Equal(t, ivSize, len(cd.IV))
	assert.NotEmpty(t, cd.Key)
	assert.NotEmpty(t, cd.IV)
}
Esempio n. 9
0
func TestTradableTradesIntegration(t *testing.T) {
	client, ts := setup(t, "GET", "/2/tradables/trades/11:101,13:101", defSessionKey, tradableTradesJSON)
	defer ts.Close()

	if resp, err := client.TradableTrades("11:101,13:101"); err != nil {
		t.Fatal(err)
	} else {
		assert := assert.New(t)
		assert.NotEmpty(resp)

		tradableTrade := resp[0]
		assert.EqualValues(123, tradableTrade.MarketId)
		assert.Equal("test", tradableTrade.Identifier)

		assert.NotEmpty(tradableTrade.Trades)

		trade := tradableTrade.Trades[0]
		assert.Equal("test", trade.BrokerBuying)
		assert.Equal("test", trade.BrokerSelling)
		assert.EqualValues(123, trade.Volume)
		assert.Equal(1.1, trade.Price)
		assert.Equal("test", trade.TradeId)
		assert.Equal("test", trade.TradeType)
		assert.EqualValues(123, trade.TradeTimestamp)
	}
}
Esempio n. 10
0
func TestTradableIntradayIntegration(t *testing.T) {
	client, ts := setup(t, "GET", "/2/tradables/intraday/11:101,13:101", defSessionKey, tradableIntradayJSON)
	defer ts.Close()

	if resp, err := client.TradableIntraday("11:101,13:101"); err != nil {
		t.Fatal(err)
	} else {
		assert := assert.New(t)
		assert.NotEmpty(resp)

		tradableIntraday := resp[0]
		assert.EqualValues(123, tradableIntraday.MarketId)
		assert.Equal("test", tradableIntraday.Identifier)

		assert.NotEmpty(tradableIntraday.Ticks)

		tick := tradableIntraday.Ticks[0]
		assert.EqualValues(123, tick.Timestamp)
		assert.Equal(1.1, tick.Last)
		assert.Equal(1.1, tick.Low)
		assert.Equal(1.1, tick.High)
		assert.Equal(1.1, tick.Volume)
		assert.EqualValues(123, tick.NoOfTrades)
	}
}
Esempio n. 11
0
func TestAccountPositionsIntegration(t *testing.T) {
	client, ts := setup(t, "GET", "/2/accounts/1000000/positions", defSessionKey, accountPositionsJSON)
	defer ts.Close()

	if resp, err := client.AccountPositions(1000000); err != nil {
		t.Fatal(err)
	} else {
		assert := assert.New(t)

		assert.NotEmpty(resp)

		position := resp[0]
		assert.EqualValues(123, position.Accno)

		assert.NotEmpty(position.Instrument)

		instrument := position.Instrument
		assertInstrument(assert, &instrument)

		assert.Equal(1.1, position.Qty)
		assert.Equal(1.1, position.PawnPercent)
		assert.Equal(Amount{1.1, "test"}, position.MarketValueAcc)
		assert.Equal(Amount{1.1, "test"}, position.MarketValue)
		assert.Equal(Amount{1.1, "test"}, position.AcqPriceAcc)
		assert.Equal(Amount{1.1, "test"}, position.AcqPrice)
		assert.Equal(Amount{1.1, "test"}, position.MorningPrice)
	}
}
Esempio n. 12
0
func TestHeartbeatTimeout(t *testing.T) {
	cfg := DefaultConfig()
	cfg.HeartbeatPeriod = 100 * time.Millisecond
	cfg.HeartbeatEpsilon = 0
	gd, err := startDispatcher(cfg)
	assert.NoError(t, err)
	defer gd.Close()

	var expectedSessionID string
	{
		stream, err := gd.Clients[0].Session(context.Background(), &api.SessionRequest{})
		assert.NoError(t, err)
		resp, err := stream.Recv()
		assert.NoError(t, err)
		assert.NotEmpty(t, resp.SessionID)
		expectedSessionID = resp.SessionID

	}
	time.Sleep(500 * time.Millisecond)

	gd.Store.View(func(readTx store.ReadTx) {
		storeNodes, err := store.FindNodes(readTx, store.All)
		assert.NoError(t, err)
		assert.NotEmpty(t, storeNodes)
		assert.Equal(t, api.NodeStatus_DOWN, storeNodes[0].Status.State)
	})

	// check that node is deregistered
	resp, err := gd.Clients[0].Heartbeat(context.Background(), &api.HeartbeatRequest{SessionID: expectedSessionID})
	assert.Nil(t, resp)
	assert.Error(t, err)
	assert.Equal(t, grpc.ErrorDesc(err), ErrNodeNotRegistered.Error())
}
Esempio n. 13
0
func TestDirInsert(t *testing.T) {
	folder := "public/assets/img/png/"
	d.Insert(folder)

	assert.NotEmpty(t, d.List)
	assert.NotEmpty(t, d.Blacklist)

	// exists
	assert.True(t, d.Exists("public/"))
	assert.True(t, d.Exists("public/assets/"))
	assert.True(t, d.Exists("public/assets/img/"))
	assert.True(t, d.Exists("public/assets/img/png/"))

	expecTed := [][]string{
		{"public/", "public/assets/", "public/assets/img/", "public/assets/img/png/"},
	}

	ebl := []string{
		"public/assets/img/png/", // it should be removed on d.Clean()
		"public/",
		"public/assets/",
		"public/assets/img/",
		"public/assets/img/png/", // duplicaTed
	}

	assert.EqualValues(t, expecTed, d.List)
	assert.EqualValues(t, ebl, d.Blacklist)
}
Esempio n. 14
0
func TestNewManagerDefaultStoreView(t *testing.T) {
	managerDefaultStore := getTestManager(func(ms *mockStorage) {
		ms.dsv = func() (*store.Store, error) {
			return store.NewStore(
				&store.TableStore{StoreID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "de", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
				&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}},
				&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
			), nil
		}
	})

	// call it twice to test internal caching
	s, err := managerDefaultStore.DefaultStoreView()
	assert.NotNil(t, s)
	assert.NoError(t, err)
	assert.NotEmpty(t, s.Data.Code.String)

	s, err = managerDefaultStore.DefaultStoreView()
	assert.NotNil(t, s)
	assert.NoError(t, err)
	assert.NotEmpty(t, s.Data.Code.String)
	assert.False(t, managerDefaultStore.IsCacheEmpty())
	managerDefaultStore.ClearCache()
	assert.True(t, managerDefaultStore.IsCacheEmpty())
}
Esempio n. 15
0
func TestCreateService(t *testing.T) {
	ts := newTestServer(t)
	defer ts.Stop()
	_, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{})
	assert.Error(t, err)
	assert.Equal(t, codes.InvalidArgument, grpc.Code(err))

	spec := createSpec("name", "image", 1)
	r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
	assert.NoError(t, err)
	assert.NotEmpty(t, r.Service.ID)

	// test port conflicts
	spec = createSpec("name2", "image", 1)
	spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
	}}
	r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
	assert.NoError(t, err)
	assert.NotEmpty(t, r.Service.ID)

	spec2 := createSpec("name3", "image", 1)
	spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
	}}
	_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
	assert.Error(t, err)
	assert.Equal(t, codes.InvalidArgument, grpc.Code(err))

	// test no port conflicts when no publish port is specified
	spec3 := createSpec("name4", "image", 1)
	spec3.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
	}}
	r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec3})
	assert.NoError(t, err)
	assert.NotEmpty(t, r.Service.ID)
	spec4 := createSpec("name5", "image", 1)
	spec4.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{TargetPort: uint32(9001), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
	}}
	_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec4})
	assert.NoError(t, err)

	// ensure no port conflict when different protocols are used
	spec = createSpec("name6", "image", 1)
	spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
	}}
	r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
	assert.NoError(t, err)
	assert.NotEmpty(t, r.Service.ID)

	spec2 = createSpec("name7", "image", 1)
	spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
		{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolUDP)},
	}}
	_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
	assert.NoError(t, err)
}
Esempio n. 16
0
func TestPasswordGrantType(t *testing.T) {
	router := mux.NewRouter()
	handler.SetRoutes(router, mockAuthorization("", new(jwt.Token)))
	ts := httptest.NewServer(router)
	defer ts.Close()

	for k, c := range []struct {
		config *oauth2.Config
		user   *userAuth
		pass   bool
	}{
		{configs["working"], logins["working"], true},
		{configs["working"], logins["voidEmail"], false},
		{configs["working"], logins["voidPassword"], false},
		{configs["working"], logins["working"], true},
		{configs["voidSecret"], logins["working"], false},
		{configs["voidID"], logins["working"], false},
		{configs["working"], logins["working"], true},
	} {
		config := *c.config
		config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth", TokenURL: ts.URL + "/oauth2/token"}
		token, err := config.PasswordCredentialsToken(oauth2.NoContext, c.user.Username, c.user.Password)
		if c.pass {
			require.Nil(t, err, "Case %d", k)
			assert.NotEmpty(t, token.AccessToken, "Case %d", k)
			assert.NotEmpty(t, token.RefreshToken, "Case %d", k)
			testTokenRefresh(t, ts.URL, config.ClientID, config.ClientSecret, token.RefreshToken, true)
		} else {
			assert.NotNil(t, err, "Case %d", k)
		}
	}
}
Esempio n. 17
0
func TestNewServiceDefaultStoreView(t *testing.T) {
	serviceDefaultStore := storemock.MustNewService(scope.Option{}, func(ms *storemock.Storage) {
		ms.MockStore = func() (*store.Store, error) {
			return store.NewStore(
				&store.TableStore{StoreID: 1, Code: dbr.NewNullString("de"), WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
				&store.TableWebsite{WebsiteID: 1, Code: dbr.NewNullString("euro"), Name: dbr.NewNullString("Europe"), SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NewNullBool(true)},
				&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
			)
		}
	})

	// call it twice to test internal caching
	s, err := serviceDefaultStore.DefaultStoreView()
	assert.NotNil(t, s)
	assert.NoError(t, err)
	assert.NotEmpty(t, s.Data.Code.String)

	s, err = serviceDefaultStore.DefaultStoreView()
	assert.NotNil(t, s)
	assert.NoError(t, err)
	assert.NotEmpty(t, s.Data.Code.String)
	assert.False(t, serviceDefaultStore.IsCacheEmpty())
	serviceDefaultStore.ClearCache()
	assert.True(t, serviceDefaultStore.IsCacheEmpty())
}
Esempio n. 18
0
func TestAccountLedgersIntegration(t *testing.T) {
	client, ts := setup(t, "GET", "/2/accounts/1000000/ledgers", defSessionKey, accountLedgersJSON)
	defer ts.Close()

	if resp, err := client.AccountLedgers(1000000); err != nil {
		t.Fatal(err)
	} else {
		assert := assert.New(t)

		assert.NotEmpty(resp)

		accLedger := resp[0]
		assert.Equal(Amount{1.1, "test"}, accLedger.TotalAccIntDeb)
		assert.Equal(Amount{1.1, "test"}, accLedger.TotalAccIntCred)
		assert.Equal(Amount{1.1, "test"}, accLedger.Total)

		assert.NotEmpty(accLedger.Ledgers)

		ledger := accLedger.Ledgers[0]
		assert.Equal("test", ledger.Currency)
		assert.Equal(Amount{1.1, "test"}, ledger.AccountSum)
		assert.Equal(Amount{1.1, "test"}, ledger.AccountSumAcc)
		assert.Equal(Amount{1.1, "test"}, ledger.AccIntDeb)
		assert.Equal(Amount{1.1, "test"}, ledger.AccIntCred)
		assert.Equal(Amount{1.1, "test"}, ledger.ExchangeRate)
	}
}
Esempio n. 19
0
func TestFeed(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	client := ConnectTestClient("")
	feed := client.Feed(TestFeedSlug.Slug, TestFeedSlug.ID)
	activity := NewTestActivity()

	t.Log("adding activity...")
	addedActivity, e := feed.AddActivity(activity)
	a.NoError(t, e)
	a.NotEqual(t, activity, addedActivity, "AddActivity should not modify existing instance.")
	a.NotNil(t, addedActivity)
	a.NotEmpty(t, addedActivity.ID)

	t.Log("listing added activities...")
	activities, e := feed.Activities(nil)
	a.NoError(t, e)
	a.NotEmpty(t, activities)
	a.Len(t, activities, 1) // otherwise we might be getting result from another test run.
	a.Equal(t, addedActivity.ID, activities[0].ID)

	t.Log("removing added activity...")
	e = feed.RemoveActivity(addedActivity.ID)
	a.NoError(t, e)

	t.Log("listing added activities again...")
	activities, e = feed.Activities(nil)
	a.NoError(t, e)
	a.Empty(t, activities)
}
Esempio n. 20
0
func TestValidateCircularAncestry(t *testing.T) {
	doc, err := spec.JSONSpec(filepath.Join("..", "..", "fixtures", "validation", "direct-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

	doc, err = spec.JSONSpec(filepath.Join("..", "..", "fixtures", "validation", "indirect-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

	doc, err = spec.JSONSpec(filepath.Join("..", "..", "fixtures", "validation", "recursive-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

}
Esempio n. 21
0
func TestMakeResponse_WithAllOfSchema(t *testing.T) {
	b, err := methodPathOpBuilder("get", "/media/search", "../fixtures/codegen/instagram.yml")
	if assert.NoError(t, err) {
		resolver := &typeResolver{ModelsPackage: b.ModelsPackage, Doc: b.Doc}
		resolver.KnownDefs = make(map[string]struct{})
		for k := range b.Doc.Spec().Definitions {
			resolver.KnownDefs[k] = struct{}{}
		}
		gO, err := b.MakeResponse("a", "get /media/search", true, resolver, 200, b.Operation.Responses.StatusCodeResponses[200])
		if assert.NoError(t, err) {
			if assert.NotNil(t, gO.Schema) {
				assert.Equal(t, "GetMediaSearchBodyBody", gO.Schema.GoType)
			}
			if assert.NotEmpty(t, b.ExtraSchemas) {
				body := b.ExtraSchemas["GetMediaSearchBodyBody"]
				if assert.NotEmpty(t, body.Properties) {
					prop := body.Properties[0]
					assert.Equal(t, "data", prop.Name)
					assert.Equal(t, "[]*DataItems0", prop.GoType)
				}
				items := b.ExtraSchemas["DataItems0"]
				if assert.NotEmpty(t, items.AllOf) {
					media := items.AllOf[0]
					assert.Equal(t, "models.Media", media.GoType)
				}
			}
		}
	}
}
Esempio n. 22
0
func TestIdleChildrenIdleSystem(t *testing.T) {
	var s Suite
	s.SetUpTest(t)
	s.Worker.Concurrency = 2
	s.BootstrapWorker(t)

	w1 := s.Worker.getIdleChild()
	assert.NotEmpty(t, w1)
	w2 := s.Worker.getIdleChild()
	assert.NotEmpty(t, w2)
	w3 := s.Worker.getIdleChild()
	assert.Empty(t, w3)
	assert.Len(t, s.Worker.idleWorkers, 0)
	assert.Len(t, s.Worker.childWorkers, 2)

	s.Worker.systemIdle = true

	s.Worker.returnIdleChild(w1)
	assert.Len(t, s.Worker.idleWorkers, 0)
	assert.Len(t, s.Worker.childWorkers, 1)

	s.Worker.returnIdleChild(w2)
	assert.Len(t, s.Worker.idleWorkers, 0)
	assert.Len(t, s.Worker.childWorkers, 0)
}
Esempio n. 23
0
func TestRefreshOAuthTokenValidAccount(t *testing.T) {
	t.Parallel()

	application := createTestApplication(t)
	defer application.Purge()

	account := createTestAccount(application, t)

	oauthResponse, err := application.GetOAuthToken(account.Username, "1234567z!A89")

	assert.NoError(t, err)
	assert.NotNil(t, oauthResponse)
	assert.NotEmpty(t, oauthResponse.AccessToken)
	assert.NotEmpty(t, oauthResponse.RefreshToken)
	assert.Equal(t, 3600, oauthResponse.ExpiresIn)

	refreshOauthResponse, err := application.RefreshOAuthToken(oauthResponse.RefreshToken)

	assert.NoError(t, err)
	assert.NotNil(t, refreshOauthResponse)
	assert.NotEmpty(t, refreshOauthResponse.AccessToken)
	assert.NotEmpty(t, refreshOauthResponse.RefreshToken)
	assert.Equal(t, 3600, refreshOauthResponse.ExpiresIn)

	assert.NotEqual(t, oauthResponse.AccessToken, refreshOauthResponse.AccessToken)
}
Esempio n. 24
0
func TestWebIDRSAAuth(t *testing.T) {
	request, err := http.NewRequest("GET", testServer.URL+aclDir+"abc", nil)
	assert.NoError(t, err)
	response, err := httpClient.Do(request)
	assert.NoError(t, err)
	assert.Equal(t, 401, response.StatusCode)
	wwwAuth := response.Header.Get("WWW-Authenticate")
	assert.NotEmpty(t, wwwAuth)

	p, _ := ParseDigestAuthenticateHeader(wwwAuth)

	// Load private key
	pKey := x509.MarshalPKCS1PrivateKey(user1k)
	keyBytes := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: pKey,
	})
	signer, err := ParseRSAPrivatePEMKey(keyBytes)
	assert.NoError(t, err)

	claim := sha1.Sum([]byte(p.Source + user1 + p.Nonce))
	signed, err := signer.Sign(claim[:])
	assert.NoError(t, err)
	b64Sig := base64.StdEncoding.EncodeToString(signed)
	assert.NotEmpty(t, b64Sig)

	authHeader := `WebID-RSA source="` + p.Source + `", username="******", nonce="` + p.Nonce + `", sig="` + b64Sig + `"`

	request, err = http.NewRequest("GET", testServer.URL+aclDir+"abc", nil)
	request.Header.Add("Authorization", authHeader)
	assert.NoError(t, err)
	response, err = httpClient.Do(request)
	assert.NoError(t, err)
	assert.Equal(t, 200, response.StatusCode)
}
Esempio n. 25
0
func TestPager(t *testing.T) {
	pages := createTestPages(21)
	groups, _ := pages.GroupBy("Weight", "desc")

	urlFactory := func(page int) string {
		return fmt.Sprintf("page/%d/", page)
	}

	_, err := newPaginatorFromPages(pages, -1, urlFactory)
	assert.NotNil(t, err)

	_, err = newPaginatorFromPageGroups(groups, -1, urlFactory)
	assert.NotNil(t, err)

	pag, err := newPaginatorFromPages(pages, 5, urlFactory)
	assert.Nil(t, err)
	doTestPages(t, pag)
	first := pag.Pagers()[0].First()
	assert.NotEmpty(t, first.Pages())
	assert.Empty(t, first.PageGroups())

	pag, err = newPaginatorFromPageGroups(groups, 5, urlFactory)
	assert.Nil(t, err)
	doTestPages(t, pag)
	first = pag.Pagers()[0].First()
	assert.NotEmpty(t, first.PageGroups())
	assert.Empty(t, first.Pages())

}
Esempio n. 26
0
// Test explore method by passing no arguments
func TestCategoriesContains(t *testing.T) {
	api := GetApi()
	resp, error := api.Categories()
	assert.Nil(t, error)
	assert.NotNil(t, resp)

	assert.NotEmpty(t, resp.Response.Categories)

	topLevelIds := []string{}
	for _, cat := range resp.Response.Categories {
		topLevelIds = append(topLevelIds, cat.Id)
	}

	assert.Contains(t, topLevelIds, "4d4b7104d754a06370d81259")

	// the first category is Arts and Entertainment. This is brittle in that if Foursquare adds one before the test will fail
	aaeCat := resp.Response.Categories[0]
	assert.Equal(t, aaeCat.Id, "4d4b7104d754a06370d81259")
	assert.Equal(t, aaeCat.Name, "Arts & Entertainment")
	assert.Equal(t, aaeCat.PluralName, "Arts & Entertainment")
	assert.Equal(t, aaeCat.ShortName, "Arts & Entertainment")
	assert.NotEmpty(t, aaeCat.Categories)

	// the first category in Arts and Entertainment is Aquarium
	aqCat := aaeCat.Categories[0]
	assert.Equal(t, aqCat.Id, "4fceea171983d5d06c3e9823")
	assert.Equal(t, aqCat.Name, "Aquarium")
	assert.Equal(t, aqCat.PluralName, "Aquariums")
	assert.Equal(t, aqCat.ShortName, "Aquarium")
	assert.Empty(t, aqCat.Categories, "Acquarium has no sub-categories")
}
Esempio n. 27
0
// verifyCacheFactoryCluster performs assertions over a ClusterInfo structure,
// based on the values and structure generated by cacheFactory.
func verifyCacheFactoryCluster(clinfo *ClusterInfo, t *testing.T) {
	assert := assert.New(t)
	assert.NotNil(clinfo.Nodes["hostname2"])
	node2 := clinfo.Nodes["hostname2"]
	assert.NotEmpty(node2.Metrics)
	assert.Len(node2.FreeContainers, 1)
	assert.NotNil(node2.FreeContainers["free_container1"])

	assert.NotNil(clinfo.Nodes["hostname3"])
	node3 := clinfo.Nodes["hostname3"]
	assert.NotEmpty(node3.Metrics)

	assert.NotNil(clinfo.Namespaces["test"])
	namespace := clinfo.Namespaces["test"]

	assert.NotNil(namespace.Pods)
	pod1_ptr := namespace.Pods["pod1"]
	require.NotNil(t, pod1_ptr)
	assert.Equal(pod1_ptr, node2.Pods["pod1"])
	assert.Len(pod1_ptr.Containers, 2)
	pod2_ptr := namespace.Pods["pod2"]
	require.NotNil(t, pod2_ptr)
	assert.Equal(pod2_ptr, node3.Pods["pod2"])
	assert.Len(pod2_ptr.Containers, 2)
}
Esempio n. 28
0
func TestVirtualBagRead_ChecksumOptions(t *testing.T) {
	tempDir, bagPath, err := testhelper.UntarTestBag("example.edu.tagsample_good.tar")
	if err != nil {
		assert.Fail(t, err.Error())
	}
	if tempDir != "" {
		defer os.RemoveAll(tempDir)
	}
	files := []string{"bagit.txt", "bag-info.txt", "aptrust-info.txt"}
	vbag := models.NewVirtualBag(bagPath, files, true, false)
	assert.NotNil(t, vbag)
	obj, _ := vbag.Read()

	// Should calculate md5 only
	for _, gf := range obj.GenericFiles {
		assert.NotEmpty(t, gf.IngestMd5)
		assert.Empty(t, gf.IngestSha256)
	}

	vbag = models.NewVirtualBag(bagPath, files, false, true)
	assert.NotNil(t, vbag)
	obj, _ = vbag.Read()

	// Should calculate sha256 only
	for _, gf := range obj.GenericFiles {
		assert.Empty(t, gf.IngestMd5)
		assert.NotEmpty(t, gf.IngestSha256)
	}

}
Esempio n. 29
0
func TestRPCCreationOfDiffInstanceDiffCatalog(t *testing.T) {
	rep := createMockupReplication()
	close(rep.(*mockupReplication).syncChan) //Make sure no deadlock occur

	r := newInMemoryRegistry(nil, rep)

	catalog, err := r.GetCatalog(auth.NamespaceFrom("ns1"))
	assert.NoError(t, err)
	assert.NotNil(t, catalog)
	assert.NotEmpty(t, catalog)

	instance1 := newServiceInstance("Calc", "192.168.0.1", 9080)
	var err2 error
	instance1, err2 = catalog.Register(instance1)
	assert.NoError(t, err2)
	assert.NotNil(t, instance1)

	otherCatalog, err1 := r.GetCatalog(auth.NamespaceFrom("ns1"))
	assert.NoError(t, err1)
	assert.NotNil(t, otherCatalog)
	assert.NotEmpty(t, otherCatalog)
	assert.Equal(t, otherCatalog, catalog)

	instance2 := newServiceInstance("Calc", "192.168.0.2", 9082)
	var err3 error
	instance2, err3 = otherCatalog.Register(instance2)
	assert.NoError(t, err3)
	assert.NotNil(t, instance2)

	instances, err4 := catalog.List("Calc", protocolPredicate)
	assert.NoError(t, err4)
	assert.Len(t, instances, 2)
	assertContainsInstance(t, instances, instance1)
	assertContainsInstance(t, instances, instance2)
}
Esempio n. 30
0
func Test_ForceBootstrap(t *testing.T) {
	// generate valid keys
	ms := NewMemStore()
	mender := newTestMender(nil,
		menderConfig{
			DeviceKey: "temp.key",
		},
		testMenderPieces{
			MenderPieces: MenderPieces{
				store: ms,
			},
		},
	)

	merr := mender.Bootstrap()
	assert.NoError(t, merr)

	kdataold, err := ms.ReadAll("temp.key")
	assert.NoError(t, err)
	assert.NotEmpty(t, kdataold)

	mender.ForceBootstrap()

	assert.True(t, mender.needsBootstrap())

	merr = mender.Bootstrap()
	assert.NoError(t, merr)

	// bootstrap should have generated a new key
	kdatanew, err := ms.ReadAll("temp.key")
	assert.NoError(t, err)
	assert.NotEmpty(t, kdatanew)
	// we should have a new key
	assert.NotEqual(t, kdatanew, kdataold)
}