Example #1
0
func TestAuthCode(t *testing.T) {
	var callbackURL *url.URL
	router := mux.NewRouter()
	ts := httptest.NewUnstartedServer(router)
	callbackCalled := false

	handler.SetRoutes(router, mockAuthorization("", new(jwt.Token)))
	router.HandleFunc("/remote/oauth2/auth", authHandlerMock(t, ts))
	router.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
		callbackURL = r.URL
		callbackCalled = true
	})

	ts.Start()
	defer ts.Close()

	for _, c := range []struct{ config *oauth2.Config }{{configs["working"]}} {
		config := *c.config
		config.Endpoint = oauth2.Endpoint{AuthURL: ts.URL + "/oauth2/auth?provider=mockprovider", TokenURL: ts.URL + "/oauth2/token"}
		authURL := config.AuthCodeURL(uuid.New())
		t.Logf("Auth code URL: %s", authURL)

		resp, err := http.Get(authURL)
		require.Nil(t, err)
		defer resp.Body.Close()
		require.True(t, callbackCalled)
		callbackCalled = false

		token, err := config.Exchange(oauth2.NoContext, callbackURL.Query().Get("code"))
		require.Nil(t, err)
		require.NotEmpty(t, token.AccessToken)
		require.NotEmpty(t, token.RefreshToken)
		testTokenRefresh(t, ts.URL, config.ClientID, config.ClientSecret, token.RefreshToken, true)
	}
}
Example #2
0
func TestGenerate(t *testing.T) {
	cg := HMACSHAEnigma{
		GlobalSecret: []byte("12345678901234567890"),
	}

	token, signature, err := cg.Generate([]byte("09876543210987654321"))
	require.Nil(t, err, "%s", err)
	require.NotEmpty(t, token)
	require.NotEmpty(t, signature)
	t.Logf("Token: %s\n Signature: %s", token, signature)

	validateSignature, err := cg.Validate([]byte("09876543210987654321"), token)
	require.Nil(t, err, "%s", err)
	assert.Equal(t, signature, validateSignature)

	_, err = cg.Validate([]byte("bar"), token)
	require.NotNil(t, err, "%s", err)

	_, err = cg.Validate([]byte("baz"), token)
	require.NotNil(t, err, "%s", err)

	cg.GlobalSecret = []byte("baz")
	_, err = cg.Validate([]byte("bar"), token)
	require.NotNil(t, err, "%s", err)
}
Example #3
0
func TestCreateKeyHandlerCreatesKey(t *testing.T) {
	publicKey, err := kmClient.CreateKey(context.Background(), &pb.Algorithm{Algorithm: data.ED25519Key})
	require.NotNil(t, publicKey)
	require.NotEmpty(t, publicKey.PublicKey)
	require.NotEmpty(t, publicKey.KeyInfo)
	require.Nil(t, err)
	require.Equal(t, grpc.Code(err), codes.OK)
}
Example #4
0
// TestUpdate tests the normal flows of Update.
// TestUpdate performs consecutive calls to Update with both empty and non-empty caches
func TestUpdate(t *testing.T) {
	var (
		cluster      = newRealModel(time.Minute)
		source_cache = cacheFactory()
		empty_cache  = cache.NewCache(24*time.Hour, time.Hour)
		zeroTime     = time.Time{}
		assert       = assert.New(t)
		require      = require.New(t)
	)

	// Invocation with empty cache
	assert.NoError(cluster.Update(empty_cache))
	assert.Empty(cluster.Nodes)
	assert.Empty(cluster.Namespaces)
	assert.Empty(cluster.Metrics)

	// Invocation with regular parameters
	assert.NoError(cluster.Update(source_cache))
	verifyCacheFactoryCluster(&cluster.ClusterInfo, t)

	// Assert Node Metric aggregation
	require.NotEmpty(cluster.Nodes)
	require.NotEmpty(cluster.Metrics)
	require.NotNil(cluster.Metrics[memWorking])
	mem_work_ts := *(cluster.Metrics[memWorking])
	actual := mem_work_ts.Hour.Get(zeroTime, zeroTime)
	require.Len(actual, 6)
	// Datapoint present in both nodes,

	assert.Equal(actual[0].Value, uint64(602+602))
	assert.Equal(actual[1].Value, 2*memWorkingEpsilon)
	assert.Equal(actual[5].Value, 2*memWorkingEpsilon)

	require.NotNil(cluster.Metrics[memUsage])
	mem_usage_ts := *(cluster.Metrics[memUsage])
	actual = mem_usage_ts.Hour.Get(zeroTime, zeroTime)
	require.Len(actual, 6)
	// Datapoint present in only one node, second node's metric is extended
	assert.Equal(actual[0].Value, uint64(10000))
	// Datapoint present in both nodes, added up to 10000
	assert.Equal(actual[1].Value, 2*memWorkingEpsilon)

	// Assert Kubernetes Metric aggregation up to namespaces
	ns := cluster.Namespaces["test"]
	mem_work_ts = *(ns.Metrics[memWorking])
	actual = mem_work_ts.Hour.Get(zeroTime, zeroTime)
	require.Len(actual, 8)
	assert.Equal(actual[0].Value, uint64(2408))

	// Invocation with no fresh data - expect no change in cluster
	assert.NoError(cluster.Update(source_cache))
	verifyCacheFactoryCluster(&cluster.ClusterInfo, t)

	// Invocation with empty cache - expect no change in cluster
	assert.NoError(cluster.Update(empty_cache))
	verifyCacheFactoryCluster(&cluster.ClusterInfo, t)
}
Example #5
0
func TestClonePluginSrc(t *testing.T) {
	t.Log("example plugin - latest version")
	{
		pluginSource := examplePluginGitURL
		versionTag := ""
		destinationDir, err := pathutil.NormalizedOSTempDirPath("TestClonePluginSrc")
		require.NoError(t, err)

		exist, err := pathutil.IsPathExists(destinationDir)
		require.NoError(t, err)
		if exist {
			err := os.RemoveAll(destinationDir)
			require.NoError(t, err)
		}

		version, hash, err := clonePluginSrc(pluginSource, versionTag, destinationDir)
		require.NoError(t, err)
		require.NotNil(t, version)
		require.NotEmpty(t, hash)

		exist, err = pathutil.IsPathExists(destinationDir)
		require.NoError(t, err)
		require.Equal(t, true, exist)
	}

	t.Log("example plugin - 0.9.0 version")
	{
		pluginSource := examplePluginGitURL
		versionTag := "0.9.0"
		destinationDir, err := pathutil.NormalizedOSTempDirPath("TestClonePluginSrc")
		require.NoError(t, err)

		exist, err := pathutil.IsPathExists(destinationDir)
		require.NoError(t, err)
		if exist {
			err := os.RemoveAll(destinationDir)
			require.NoError(t, err)
		}

		version, hash, err := clonePluginSrc(pluginSource, versionTag, destinationDir)
		require.NoError(t, err)
		require.NotNil(t, version)
		require.Equal(t, "0.9.0", version.String())
		require.NotEmpty(t, hash)

		exist, err = pathutil.IsPathExists(destinationDir)
		require.NoError(t, err)
		require.Equal(t, true, exist)
	}
}
Example #6
0
func TestKubePodMetricsFull(t *testing.T) {
	nodeList := nodes.NodeList{
		Items: map[nodes.Host]nodes.Info{
			nodes.Host("test-machine-b"): {InternalIP: "10.10.10.1"},
			nodes.Host("test-machine-1"): {InternalIP: "10.10.10.0"},
		},
	}
	podList := []api.Pod{
		{
			PodMetadata: api.PodMetadata{
				Name: "blah",
			},
		},
		{
			PodMetadata: api.PodMetadata{
				Name: "blah1",
			},
		},
	}
	container := &api.Container{
		Name: "test",
	}
	nodesApi := &fakeNodesApi{nodeList}
	podsApi := &fakePodsApi{podList}
	kubeletApi := &fakeKubeletApi{container: container}
	source := NewKubePodMetrics(10250, kubeletApi, nodesApi, podsApi)
	data, err := source.GetInfo(time.Now(), time.Now().Add(time.Minute), time.Second, false)
	require.NoError(t, err)
	require.NotEmpty(t, data)
}
Example #7
0
// Using the same key to encrypt the same message, this encrypter produces two
// different ciphertexts because it produces two different nonces.  Both
// of these can be decrypted into the same data though.
func TestNACLSecretbox(t *testing.T) {
	key := make([]byte, 32)
	_, err := io.ReadFull(rand.Reader, key)
	require.NoError(t, err)

	crypter := NewNACLSecretbox(key)
	data := []byte("Hello again world")

	er1, err := crypter.Encrypt(data)
	require.NoError(t, err)

	er2, err := crypter.Encrypt(data)
	require.NoError(t, err)

	require.NotEqual(t, er1.Data, er2.Data)
	require.NotEmpty(t, er1.Nonce, er2.Nonce)

	result, err := crypter.Decrypt(*er1)
	require.NoError(t, err)
	require.Equal(t, data, result)

	result, err = crypter.Decrypt(*er2)
	require.NoError(t, err)
	require.Equal(t, data, result)
}
Example #8
0
func TestGetRepos(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	defer server.Close()

	mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, repos)
	})

	cfg := libs.NewConfig()
	cfg.Github.Username = "******"
	cfg.Github.Token = "xxx"

	gh := libs.NewGithub(cfg)
	require.NotNil(t, gh)

	gh.Client = github.NewClient(nil)
	require.NotNil(t, gh.Client)

	url, _ := url.Parse(server.URL)
	gh.Client.BaseURL = url

	gr, err := gh.GetRepos()
	require.Nil(t, err)
	require.NotNil(t, gr)

	b, err := json.Marshal(gr)
	require.Nil(t, err)
	require.NotEmpty(t, b)

	var dst bytes.Buffer
	json.Indent(&dst, b, "", "  ")

	assert.Equal(t, githubRepos, dst.String())
}
Example #9
0
func TestGetContribs(t *testing.T) {
	server := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, contribs)
		}),
	)
	defer server.Close()

	cfg := libs.NewConfig()
	gh := libs.NewGithub(cfg)
	require.NotNil(t, gh)

	gh.DocGetter = func(c *libs.Config) (*goquery.Document, error) {
		return goquery.NewDocument(server.URL)
	}

	gc, err := gh.GetContribs()
	require.Nil(t, err)
	require.NotNil(t, gc)

	b, err := json.Marshal(gc)
	require.Nil(t, err)
	require.NotEmpty(t, b)

	var dst bytes.Buffer
	json.Indent(&dst, b, "", "  ")

	assert.Equal(t, githubContribs, dst.String())
}
func TestSetupBuildProperties(t *testing.T) {
	DownloadCoresAndToolsAndLibraries(t)

	context := make(map[string]interface{})

	buildPath := SetupBuildPath(t, context)
	defer os.RemoveAll(buildPath)

	context[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION] = "10600"
	context[constants.CTX_HARDWARE_FOLDERS] = []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}
	context[constants.CTX_TOOLS_FOLDERS] = []string{"downloaded_tools", "./tools_builtin"}
	context[constants.CTX_FQBN] = "arduino:avr:uno"
	context[constants.CTX_SKETCH_LOCATION] = filepath.Join("sketch1", "sketch.ino")

	commands := []types.Command{
		&builder.SetupHumanLoggerIfMissing{},
		&builder.AddAdditionalEntriesToContext{},
		&builder.HardwareLoader{},
		&builder.ToolsLoader{},
		&builder.TargetBoardResolver{},
		&builder.SketchLoader{},
		&builder.SetupBuildProperties{},
	}

	for _, command := range commands {
		err := command.Run(context)
		NoError(t, err)
	}

	buildProperties := context[constants.CTX_BUILD_PROPERTIES].(map[string]string)

	require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE])

	require.Equal(t, "uno", buildProperties[constants.ID])
	require.Equal(t, "Arduino Uno", buildProperties["name"])
	require.Equal(t, "0x2341", buildProperties["vid.0"])
	require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"])
	require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"])

	coanProps := props.SubTree(props.SubTree(buildProperties, constants.BUILD_PROPERTIES_TOOLS_KEY), constants.COAN)
	require.Equal(t, "{path}/coan", coanProps["cmd.path"])
	require.Equal(t, "\"{cmd.path}\" source -m -E -P -kb {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} \"{source_file}\"", coanProps[constants.BUILD_PROPERTIES_PATTERN])

	require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH])
	require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH])
	require.Equal(t, "10600", buildProperties[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION])
	require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS])

	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.3a-arduino"), buildProperties["runtime.tools.bossac-1.3a-arduino.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"])
	require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.3a-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino"))
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"])

	require.Equal(t, Abs(t, filepath.Join("sketch1", "sketch.ino")), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH])
}
Example #11
0
func TestTransformResponse(t *testing.T) {
	tx := rapi.NewTransformer()

	var fixture = `{"One":"this is the one","Two":"this is the second"}`
	res := &http.Response{
		Header:     make(http.Header),
		StatusCode: http.StatusOK,
	}
	res.Body = ioutil.NopCloser(strings.NewReader(fixture))
	require.NotNil(t, res)

	var structure struct {
		One   string
		Three string
	}
	var expected = `{"One":"this is the one","Three":""}`
	ok := tx.TransformResponse(res, &structure, &structure)
	require.True(t, ok)

	body, err := ioutil.ReadAll(res.Body)
	require.Nil(t, err)
	require.NotEmpty(t, body)

	assert.Equal(t, expected, string(body))
}
Example #12
0
func TestKubeSourceDetail(t *testing.T) {
	nodeList := nodes.NodeList{
		Items: map[nodes.Host]nodes.Info{
			nodes.Host("test-machine-b"): {InternalIP: "10.10.10.1"},
			nodes.Host("test-machine-1"): {InternalIP: "10.10.10.0"},
		},
	}
	podList := []api.Pod{
		{
			Name: "blah",
		},
		{
			Name: "blah1",
		},
	}
	container := &api.Container{
		Name: "test",
	}
	nodesApi := &fakeNodesApi{nodeList}
	podsApi := &fakePodsApi{podList}
	kubeletApi := &fakeKubeletApi{container}

	kubeSource := &kubeSource{
		lastQuery:   time.Now(),
		kubeletPort: "10250",
		nodesApi:    nodesApi,
		podsApi:     podsApi,
		kubeletApi:  kubeletApi,
	}
	data, err := kubeSource.GetInfo()
	require.NoError(t, err)
	require.NotEmpty(t, data)
}
// 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"])
	}
}
Example #14
0
func TestMachineStatsIsReturned(t *testing.T) {
	fm := framework.New(t)
	defer fm.Cleanup()

	machineStats, err := fm.Cadvisor().ClientV2().MachineStats()
	if err != nil {
		t.Fatal(err)
	}

	as := assert.New(t)
	for _, stat := range machineStats {
		as.NotEqual(stat.Timestamp, time.Time{})
		as.True(stat.Cpu.Usage.Total > 0)
		as.True(len(stat.Cpu.Usage.PerCpu) > 0)
		if stat.CpuInst != nil {
			as.True(stat.CpuInst.Usage.Total > 0)
		}
		as.True(stat.Memory.Usage > 0)
		for _, nStat := range stat.Network.Interfaces {
			as.NotEqual(nStat.Name, "")
			as.NotEqual(nStat.RxBytes, 0)
		}
		for _, fsStat := range stat.Filesystem {
			as.NotEqual(fsStat.Device, "")
			as.NotNil(fsStat.Capacity)
			as.NotNil(fsStat.Usage)
			as.NotNil(fsStat.ReadsCompleted)
			require.NotEmpty(t, fsStat.Type)
			if fsStat.Type == "vfs" {
				as.NotEmpty(fsStat.InodesFree)
			}
		}
	}
}
func TestUnregisteredURLWithPort(t *testing.T) {
	resource.Require(t, resource.Database)
	defer cleaner.DeleteCreatedEntities(DB)()
	service := getServiceAsUser()
	wiRepo := workitem.NewWorkItemRepository(DB)

	description := "Related to http://some-other-domain:8080/different-path/154687364529310/ok issue"
	expectedDescription := rendering.NewMarkupContentFromLegacy(description)
	_, err := wiRepo.Create(
		context.Background(),
		workitem.SystemBug,
		map[string]interface{}{
			workitem.SystemTitle:       "specialwordforsearch_new",
			workitem.SystemDescription: expectedDescription,
			workitem.SystemCreator:     "baijum",
			workitem.SystemState:       workitem.SystemStateClosed,
		},
		"")
	require.Nil(t, err)

	controller := NewSearchController(service, gormapplication.NewGormDB(DB))
	q := `http://some-other-domain:8080/different-path/`
	_, sr := test.ShowSearchOK(t, nil, nil, controller, nil, nil, q)
	require.NotEmpty(t, sr.Data)
	r := sr.Data[0]
	assert.Equal(t, description, r.Attributes[workitem.SystemDescription])
}
func TestSearchURLWithoutPort(t *testing.T) {
	resource.Require(t, resource.Database)
	defer cleaner.DeleteCreatedEntities(DB)()
	service := getServiceAsUser()
	wiRepo := workitem.NewWorkItemRepository(DB)

	description := "This issue is related to http://localhost/detail/876394"
	expectedDescription := rendering.NewMarkupContentFromLegacy(description)
	_, err := wiRepo.Create(
		context.Background(),
		workitem.SystemBug,
		map[string]interface{}{
			workitem.SystemTitle:       "specialwordforsearch_without_port",
			workitem.SystemDescription: expectedDescription,
			workitem.SystemCreator:     "baijum",
			workitem.SystemState:       workitem.SystemStateClosed,
		},
		"")
	require.Nil(t, err)

	controller := NewSearchController(service, gormapplication.NewGormDB(DB))
	q := `"http://localhost/detail/876394"`
	_, sr := test.ShowSearchOK(t, nil, nil, controller, nil, nil, q)
	require.NotEmpty(t, sr.Data)
	r := sr.Data[0]
	assert.Equal(t, description, r.Attributes[workitem.SystemDescription])
}
func TestSearch(t *testing.T) {
	resource.Require(t, resource.Database)
	defer cleaner.DeleteCreatedEntities(DB)()

	service := getServiceAsUser()
	wiRepo := workitem.NewWorkItemRepository(DB)

	_, err := wiRepo.Create(
		context.Background(),
		workitem.SystemBug,
		map[string]interface{}{
			workitem.SystemTitle:       "specialwordforsearch",
			workitem.SystemDescription: nil,
			workitem.SystemCreator:     "baijum",
			workitem.SystemState:       workitem.SystemStateClosed,
		},
		"")
	require.Nil(t, err)
	controller := NewSearchController(service, gormapplication.NewGormDB(DB))
	q := "specialwordforsearch"
	_, sr := test.ShowSearchOK(t, nil, nil, controller, nil, nil, q)
	require.NotEmpty(t, sr.Data)
	r := sr.Data[0]
	assert.Equal(t, "specialwordforsearch", r.Attributes[workitem.SystemTitle])
}
func TestSetupBuildProperties(t *testing.T) {
	DownloadCoresAndToolsAndLibraries(t)

	ctx := &types.Context{
		HardwareFolders:   []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"},
		ToolsFolders:      []string{"downloaded_tools", "./tools_builtin"},
		SketchLocation:    filepath.Join("sketch1", "sketch.ino"),
		FQBN:              "arduino:avr:uno",
		ArduinoAPIVersion: "10600",
	}

	buildPath := SetupBuildPath(t, ctx)
	defer os.RemoveAll(buildPath)

	commands := []types.Command{
		&builder.AddAdditionalEntriesToContext{},
		&builder.HardwareLoader{},
		&builder.ToolsLoader{},
		&builder.TargetBoardResolver{},
		&builder.SketchLoader{},
		&builder.SetupBuildProperties{},
	}

	for _, command := range commands {
		err := command.Run(ctx)
		NoError(t, err)
	}

	buildProperties := ctx.BuildProperties

	require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE])

	require.Equal(t, "uno", buildProperties[constants.ID])
	require.Equal(t, "Arduino/Genuino Uno", buildProperties["name"])
	require.Equal(t, "0x2341", buildProperties["vid.0"])
	require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"])
	require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"])

	require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH])
	require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH])
	require.Equal(t, "10600", buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION])
	require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS])

	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"])
	require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino"))
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"])

	require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH])

	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST))
}
func TestSearchPagination(t *testing.T) {
	resource.Require(t, resource.Database)
	defer cleaner.DeleteCreatedEntities(DB)()
	service := getServiceAsUser()

	wiRepo := workitem.NewWorkItemRepository(DB)

	_, err := wiRepo.Create(
		context.Background(),
		workitem.SystemBug,
		map[string]interface{}{
			workitem.SystemTitle:       "specialwordforsearch2",
			workitem.SystemDescription: nil,
			workitem.SystemCreator:     "baijum",
			workitem.SystemState:       workitem.SystemStateClosed,
		},
		"")
	require.Nil(t, err)

	controller := NewSearchController(service, gormapplication.NewGormDB(DB))
	q := "specialwordforsearch2"
	_, sr := test.ShowSearchOK(t, nil, nil, controller, nil, nil, q)

	// defaults in paging.go is 'pageSizeDefault = 20'
	assert.Equal(t, "http:///api/search?page[offset]=0&page[limit]=20&q=specialwordforsearch2", *sr.Links.First)
	assert.Equal(t, "http:///api/search?page[offset]=0&page[limit]=20&q=specialwordforsearch2", *sr.Links.Last)
	require.NotEmpty(t, sr.Data)
	r := sr.Data[0]
	assert.Equal(t, "specialwordforsearch2", r.Attributes[workitem.SystemTitle])
}
Example #20
0
func TestEndpoints(t *testing.T) {
	dirs := defaultDirs
	o := newObject(t)
	o.setupService(t, &dirs)

	eps := o.service.Endpoints()
	require.NotNil(t, eps)
	for url, m := range eps {
		require.NotEmpty(t, url)
		require.NotNil(t, m)
		for method, handler := range m {
			require.NotEmpty(t, method)
			require.NotNil(t, handler)
		}
	}
}
func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) {
	DownloadCoresAndToolsAndLibraries(t)

	context := make(map[string]interface{})

	buildPath := SetupBuildPath(t, context)
	defer os.RemoveAll(buildPath)

	context[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION] = "10600"
	context[constants.CTX_HARDWARE_FOLDERS] = []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}
	context[constants.CTX_TOOLS_FOLDERS] = []string{"downloaded_tools", "./tools_builtin"}
	context[constants.CTX_FQBN] = "my_avr_platform:avr:custom_yun"
	context[constants.CTX_SKETCH_LOCATION] = filepath.Join("sketch1", "sketch.ino")

	commands := []types.Command{
		&builder.SetupHumanLoggerIfMissing{},
		&builder.ContainerSetupHardwareToolsLibsSketchAndProps{},
	}

	for _, command := range commands {
		err := command.Run(context)
		NoError(t, err)
	}

	buildProperties := context[constants.CTX_BUILD_PROPERTIES].(props.PropertiesMap)

	require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE])

	require.Equal(t, "custom_yun", buildProperties[constants.ID])
	require.Equal(t, "Arduino Yún", buildProperties["name"])
	require.Equal(t, "0x2341", buildProperties["vid.0"])
	require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"])
	require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"])

	coanProps := buildProperties.SubTree(constants.BUILD_PROPERTIES_TOOLS_KEY).SubTree(constants.COAN)
	require.Equal(t, "{path}/coan", coanProps["cmd.path"])
	require.Equal(t, "\"{cmd.path}\" source -m -E -P -kb {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} \"{source_file}\"", coanProps[constants.BUILD_PROPERTIES_PATTERN])

	require.Equal(t, Abs(t, "user_hardware/my_avr_platform/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH])
	require.Equal(t, Abs(t, "user_hardware/my_avr_platform"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH])
	require.Equal(t, "10600", buildProperties[constants.CTX_BUILD_PROPERTIES_RUNTIME_IDE_VERSION])
	require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS])

	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"])
	require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino"))
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"])
	require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"])

	require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH])

	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE))
	require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST))
}
Example #22
0
func TestOpenIDConnectExplicitFlow(t *testing.T) {
	session := &defaultSession{
		DefaultSession: &openid.DefaultSession{
			Claims: &jwt.IDTokenClaims{
				Subject: "peter",
			},
			Headers: &jwt.Headers{},
		},
	}
	f := compose.ComposeAllEnabled(new(compose.Config), fositeStore, []byte("some-secret-thats-random"), internal.MustRSAKey())
	ts := mockServer(t, f, session)

	defer ts.Close()
	oauthClient := newOAuth2Client(ts)
	fositeStore.Clients["my-client"].RedirectURIs[0] = ts.URL + "/callback"

	var state string
	for k, c := range []struct {
		description    string
		setup          func()
		authStatusCode int
	}{
		{
			description: "should pass",
			setup: func() {
				state = "12345678901234567890"
				oauthClient.Scopes = []string{"openid"}
			},
			authStatusCode: http.StatusOK,
		},
	} {
		c.setup()

		resp, err := http.Get(oauthClient.AuthCodeURL(state) + "&nonce=1234567890")
		require.Nil(t, err)
		require.Equal(t, c.authStatusCode, resp.StatusCode, "(%d) %s", k, c.description)

		if resp.StatusCode == http.StatusOK {
			token, err := oauthClient.Exchange(oauth2.NoContext, resp.Request.URL.Query().Get("code"))
			fmt.Printf("after exchange: %s\n\n", fositeStore.AuthorizeCodes)
			require.Nil(t, err, "(%d) %s", k, c.description)
			require.NotEmpty(t, token.AccessToken, "(%d) %s", k, c.description)
			require.NotEmpty(t, token.Extra("id_token"), "(%d) %s", k, c.description)
		}
		t.Logf("Passed test case (%d) %s", k, c.description)
	}
}
Example #23
0
func assertFailedEntry(t *testing.T, expected string, entries []crossdock.Entry) {
	require.True(t, len(entries) > 0, "Must have some entries %+v", entries)
	entry := entries[len(entries)-1]
	require.EqualValues(t, "failed", entry["status"], "Entries: %v", entries)
	require.NotEmpty(t, entry["output"], "Entries: %v", entries)
	output := entry["output"].(string)
	assert.True(t, strings.Contains(output, expected), "Output must contain %s: %s", expected, output)
}
Example #24
0
func TestKubePodMetricsBasic(t *testing.T) {
	nodesApi := &fakeNodesApi{nodes.NodeList{}}
	podsApi := &fakePodsApi{[]api.Pod{}}
	source := NewKubePodMetrics(10250, &fakeKubeletApi{}, nodesApi, podsApi)
	_, err := source.GetInfo(time.Now(), time.Now().Add(time.Minute), time.Second, false)
	require.NoError(t, err)
	require.NotEmpty(t, source.DebugInfo())
}
Example #25
0
func TestEntryListHasAuthor(t *testing.T) {
	nodes := htmltest.Query(t, "", "+", ".author")
	for _, node := range nodes {
		assertElem(t, node, "div")
		require.NotEmpty(t, h5.Children(node), "Empty author div!")
		checkAuthorSection(T{t}, node)
	}
}
Example #26
0
func TestEntriesHaveTagsInList(t *testing.T) {
	nodes := htmltest.Query(t, "", "+", ".tags")
	for _, node := range nodes {
		assertElem(t, node, "div")
		require.NotEmpty(t, h5.Children(node), "Empty tags div!")
		checkTagsSection(T{t}, node)
	}
}
Example #27
0
func TestEveryEntryHasCaptchaSection(t *testing.T) {
	for _, e := range testPosts {
		node := htmltest.QueryOne(t, e.URL, ".author")
		assertElem(t, node, "div")
		require.NotEmpty(t, h5.Children(node), "Empty author div!")
		checkAuthorSection(T{t}, node)
	}
}
Example #28
0
// Adding the same target twice doesn't actually add it.
func TestApplyAddTargetTwice(t *testing.T) {
	repo, _, err := testutils.EmptyRepo("docker.com/notary")
	require.NoError(t, err)
	_, err = repo.InitTargets(data.CanonicalTargetsRole)
	require.NoError(t, err)
	hash := sha256.Sum256([]byte{})
	f := &data.FileMeta{
		Length: 1,
		Hashes: map[string][]byte{
			"sha256": hash[:],
		},
	}
	fjson, err := json.Marshal(f)
	require.NoError(t, err)

	cl := changelist.NewMemChangelist()
	require.NoError(t, cl.Add(&changelist.TUFChange{
		Actn:       changelist.ActionCreate,
		Role:       changelist.ScopeTargets,
		ChangeType: "target",
		ChangePath: "latest",
		Data:       fjson,
	}))
	require.NoError(t, cl.Add(&changelist.TUFChange{
		Actn:       changelist.ActionCreate,
		Role:       changelist.ScopeTargets,
		ChangeType: "target",
		ChangePath: "latest",
		Data:       fjson,
	}))

	require.NoError(t, applyChangelist(repo, nil, cl))
	require.Len(t, repo.Targets["targets"].Signed.Targets, 1)
	require.NotEmpty(t, repo.Targets["targets"].Signed.Targets["latest"])

	require.NoError(t, applyTargetsChange(repo, nil, &changelist.TUFChange{
		Actn:       changelist.ActionCreate,
		Role:       changelist.ScopeTargets,
		ChangeType: "target",
		ChangePath: "latest",
		Data:       fjson,
	}))
	require.Len(t, repo.Targets["targets"].Signed.Targets, 1)
	require.NotEmpty(t, repo.Targets["targets"].Signed.Targets["latest"])
}
func testIngestRecordManifest(t *testing.T, _context *context.Context, dpnIngestManifest *models.DPNIngestManifest, detail string) {
	require.NotNil(t, dpnIngestManifest.PackageSummary, detail)
	require.NotNil(t, dpnIngestManifest.ValidateSummary, detail)
	require.NotNil(t, dpnIngestManifest.RecordSummary, detail)

	assert.False(t, dpnIngestManifest.PackageSummary.StartedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.PackageSummary.FinishedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.PackageSummary.HasErrors(), detail)

	assert.False(t, dpnIngestManifest.ValidateSummary.StartedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.ValidateSummary.FinishedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.ValidateSummary.HasErrors(), detail)

	assert.False(t, dpnIngestManifest.StoreSummary.StartedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.StoreSummary.FinishedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.StoreSummary.HasErrors(), detail)

	assert.False(t, dpnIngestManifest.RecordSummary.StartedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.RecordSummary.FinishedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.RecordSummary.HasErrors(), detail)

	// The items below were covered in prior post-tests, but we want to make
	// sure no data is wiped out by dpn_ingest_record.

	assert.NotNil(t, dpnIngestManifest.WorkItem, detail)
	require.NotNil(t, dpnIngestManifest.DPNBag, detail)
	assert.NotEmpty(t, dpnIngestManifest.DPNBag.UUID, detail)
	assert.NotEmpty(t, dpnIngestManifest.DPNBag.LocalId, detail)
	assert.NotEmpty(t, dpnIngestManifest.DPNBag.Member, detail)
	assert.Equal(t, dpnIngestManifest.DPNBag.UUID, dpnIngestManifest.DPNBag.FirstVersionUUID, detail)
	assert.EqualValues(t, 1, dpnIngestManifest.DPNBag.Version, detail)
	assert.Equal(t, _context.Config.DPN.LocalNode, dpnIngestManifest.DPNBag.IngestNode, detail)
	assert.Equal(t, _context.Config.DPN.LocalNode, dpnIngestManifest.DPNBag.AdminNode, detail)
	assert.Equal(t, "D", dpnIngestManifest.DPNBag.BagType, detail)
	assert.NotEqual(t, 0, dpnIngestManifest.DPNBag.Size, detail)
	assert.False(t, dpnIngestManifest.DPNBag.CreatedAt.IsZero(), detail)
	assert.False(t, dpnIngestManifest.DPNBag.UpdatedAt.IsZero(), detail)

	require.NotEmpty(t, dpnIngestManifest.DPNBag.MessageDigests, detail)
	messageDigest := dpnIngestManifest.DPNBag.MessageDigests[0]
	assert.Equal(t, dpnIngestManifest.DPNBag.UUID, messageDigest.Bag, detail)
	assert.Equal(t, constants.AlgSha256, messageDigest.Algorithm, detail)
	assert.Equal(t, _context.Config.DPN.LocalNode, messageDigest.Node, detail)
	assert.Equal(t, 64, len(messageDigest.Value), detail)
	assert.False(t, messageDigest.CreatedAt.IsZero(), detail)

	assert.NotEmpty(t, dpnIngestManifest.LocalDir, detail)
	assert.NotEmpty(t, dpnIngestManifest.LocalTarFile, detail)
	assert.True(t, strings.HasSuffix(dpnIngestManifest.LocalTarFile, ".tar"), detail)

	// Bag has been stored in Glacier, so this should be set to
	// "https://s3.amazonaws.com/aptrust.dpn.test/<UUID>.tar"
	expectedURL := fmt.Sprintf("https://s3.amazonaws.com/%s/%s.tar",
		_context.Config.DPN.DPNPreservationBucket,
		dpnIngestManifest.DPNBag.UUID)
	assert.Equal(t, expectedURL, dpnIngestManifest.StorageURL, detail)
}
Example #30
0
func TestRealCacheData(t *testing.T) {
	containers := []source_api.Container{
		getContainer("container1"),
	}
	pods := []source_api.Pod{
		{
			PodMetadata: source_api.PodMetadata{
				Name:         "pod1",
				ID:           "123",
				Namespace:    "test",
				NamespaceUID: "test-uid",
				Hostname:     "1.2.3.4",
				Status:       "Running",
			},
			Containers: containers,
		},
		{
			PodMetadata: source_api.PodMetadata{
				Name:         "pod2",
				ID:           "1234",
				Namespace:    "test",
				NamespaceUID: "test-uid",
				Hostname:     "1.2.3.5",
				Status:       "Running",
			},
			Containers: containers,
		},
	}
	cache := NewCache(time.Hour, time.Hour)
	assert := assert.New(t)
	assert.NoError(cache.StorePods(pods))
	assert.NoError(cache.StoreContainers(containers))
	actualPods := cache.GetPods(time.Time{}, time.Time{})
	actualContainer := cache.GetNodes(time.Time{}, time.Now())
	actualContainer = append(actualContainer, cache.GetFreeContainers(time.Time{}, time.Now())...)
	actualPodsMap := map[string]*PodElement{}
	for _, pod := range actualPods {
		actualPodsMap[pod.Name] = pod
	}
	for _, expectedPod := range pods {
		pod, exists := actualPodsMap[expectedPod.Name]
		require.True(t, exists)
		require.NotEmpty(t, pod.Containers)
		assert.NotEmpty(pod.Containers[0].Metrics)
	}
	actualContainerMap := map[string]*ContainerElement{}
	for _, cont := range actualContainer {
		actualContainerMap[cont.Name] = cont
	}
	for _, expectedContainer := range containers {
		ce, exists := actualContainerMap[expectedContainer.Name]
		assert.True(exists)
		assert.NotNil(ce.Metrics)
		assert.NotEmpty(ce.Metrics)
	}
}