Esempio n. 1
0
func TestSpecOptInlineValue(t *testing.T) {
	var f, g, x *string
	var y *[]string
	init := func(c *Cmd) {
		f = c.StringOpt("f", "", "")
		g = c.StringOpt("giraffe", "", "")
		x = c.StringOpt("x", "", "")
		y = c.StringsOpt("y", nil, "")
	}
	spec := "-x=<wolf-name> [ -f=<fish-name> | --giraffe=<giraffe-name> ] -y=<dog>..."

	okCmd(t, spec, init, []string{"-x=a", "-y=b"})
	require.Equal(t, "a", *x)
	require.Equal(t, []string{"b"}, *y)

	okCmd(t, spec, init, []string{"-x=a", "-y=b", "-y=c"})
	require.Equal(t, "a", *x)
	require.Equal(t, []string{"b", "c"}, *y)

	okCmd(t, spec, init, []string{"-x=a", "-f=f", "-y=b"})
	require.Equal(t, "a", *x)
	require.Equal(t, "f", *f)
	require.Equal(t, []string{"b"}, *y)

	okCmd(t, spec, init, []string{"-x=a", "--giraffe=g", "-y=b"})
	require.Equal(t, "a", *x)
	require.Equal(t, "g", *g)
	require.Equal(t, []string{"b"}, *y)
}
func TestArtifactURL(t *testing.T) {
	client := NewArtifactStoreClient("http://foo")
	bucket := &Bucket{
		bucket: &model.Bucket{
			Id: "bkt",
		},
		client: client,
	}

	{
		streamedArtifact := &StreamedArtifact{
			ArtifactImpl: &ArtifactImpl{
				artifact: &model.Artifact{
					Name: "safct",
				},
				bucket: bucket,
			},
		}
		require.Equal(t, "http://foo/buckets/bkt/artifacts/safct/content", streamedArtifact.GetContentURL())
	}

	{
		chunkedArtifact := &ChunkedArtifact{
			ArtifactImpl: &ArtifactImpl{
				artifact: &model.Artifact{
					Name: "cafct",
				},
				bucket: bucket,
			},
		}
		require.Equal(t, "http://foo/buckets/bkt/artifacts/cafct/content", chunkedArtifact.GetContentURL())
	}
}
func TestCollectAllSourceFilesFromFoldersWithSources(t *testing.T) {
	ctx := &types.Context{}

	sourceFiles := &types.UniqueStringQueue{}
	ctx.CollectedSourceFiles = sourceFiles
	foldersWithSources := &types.UniqueSourceFolderQueue{}
	foldersWithSources.Push(types.SourceFolder{Folder: Abs(t, "sketch_with_config"), Recurse: true})
	ctx.FoldersWithSourceFiles = foldersWithSources

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

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

	require.Equal(t, 1, len(*sourceFiles))
	require.Equal(t, 0, len(*foldersWithSources))
	sort.Strings(*sourceFiles)

	require.Equal(t, Abs(t, filepath.Join("sketch_with_config", "includes", "de bug.cpp")), sourceFiles.Pop())
	require.Equal(t, 0, len(*sourceFiles))
}
Esempio n. 4
0
func TestGetTrimmedStepName(t *testing.T) {
	stepInfo := models.StepInfoModel{
		ID:      longStr,
		Version: longStr,
	}

	result := models.StepRunResultsModel{
		StepInfo: stepInfo,
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  10000000,
		Error:    errors.New(longStr),
		ExitCode: 1,
	}

	stepName := getTrimmedStepName(result)
	require.Equal(t, "This is a very ... (...s a very long string.\n)", stepName)

	stepInfo.ID = ""
	result = models.StepRunResultsModel{
		StepInfo: stepInfo,
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  0,
		Error:    nil,
		ExitCode: 0,
	}

	stepName = getTrimmedStepName(result)
	require.Equal(t, " (...s a very long string.\n)", stepName)
}
Esempio n. 5
0
func TestDonateSimple(t *testing.T) {
	const (
		testAddr1 = "10.0.1.0"
		testAddr2 = "10.0.1.32"
		size      = 48
	)

	var (
		ipAddr1 = ip(testAddr1)
	)

	ps1 := makeSpace(ipAddr1, size)

	// Empty space set should split in two and give me the second half
	r, ok := ps1.Donate(address.NewRange(ip(testAddr1), size))
	numGivenUp := r.Size()
	require.True(t, ok, "Donate result")
	require.Equal(t, "10.0.1.24", r.Start.String(), "Invalid start")
	require.Equal(t, address.Offset(size/2), numGivenUp)
	require.Equal(t, address.Offset(size/2), ps1.NumFreeAddresses())

	// Now check we can give the rest up.
	count := 0 // count to avoid infinite loop
	for ; count < 1000; count++ {
		r, ok := ps1.Donate(address.NewRange(ip(testAddr1), size))
		if !ok {
			break
		}
		numGivenUp += r.Size()
	}
	require.Equal(t, address.Offset(0), ps1.NumFreeAddresses())
	require.Equal(t, address.Offset(size), numGivenUp)
}
Esempio n. 6
0
func TestMutlipleAdvertise(t *testing.T) {
	runRetryTest(t, func(r *retryTest) {
		r.mock.On("On", SendAdvertise).Return().
			Times(1 /* initial */ + 10 /* successful retries */)
		r.mock.On("On", Advertised).Return().Once()
		r.setAdvertiseSuccess()

		sc2, sc3 := r.ch.GetSubChannel("svc-2"), r.ch.GetSubChannel("svc-3")
		require.NoError(t, r.client.Advertise(sc2, sc3))

		// Verify that the arguments passed to 'ad' are correct.
		expectedRequest := &AdRequest{[]service{
			{Name: "my-client", Cost: 0},
			{Name: "svc-2", Cost: 0},
			{Name: "svc-3", Cost: 0},
		}}
		require.Equal(t, expectedRequest, r.req)

		// Verify readvertise happen after sleeping for ~advertiseInterval.
		r.mock.On("On", Readvertised).Return().Times(10)
		for i := 0; i < 10; i++ {
			s1 := <-r.sleepArgs
			checkAdvertiseInterval(t, s1)
			r.sleepBlock <- struct{}{}

			r.setAdvertiseSuccess()
			require.Equal(t, expectedRequest, r.req)
		}

		// Block till the last advertise completes.
		<-r.sleepArgs
	})
}
Esempio n. 7
0
func TestGetGSResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)
	storage, err := storage.New(http.DefaultClient)
	assert.Nil(t, err)

	startTS := time.Date(2014, time.December, 10, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2014, time.December, 10, 23, 59, 59, 0, time.UTC).Unix()

	// TODO(stephana): Switch this to a dedicated test bucket, so we are not
	// in danger of removing it.
	resultFiles, err := getGSResultsFileLocations(startTS, endTS, storage, "chromium-skia-gm", "dm-json-v1")
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/filelist_dec_10.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}
func TestStepResultCell(t *testing.T) {
	result := models.StepRunResultsModel{
		StepName: longStr,
		Status:   models.StepRunStatusCodeFailed,
		Idx:      0,
		RunTime:  10000000,
		Error:    errors.New(longStr),
		ExitCode: 1,
	}

	cell := stepResultCell(result)
	require.Equal(t, "| 🚫  | \x1b[31;1mThis is a very long string,\n... (exit code: 1)\x1b[0m| 0.01 sec |", cell)

	result = models.StepRunResultsModel{
		StepName: "",
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  0,
		Error:    nil,
		ExitCode: 0,
	}

	cell = stepResultCell(result)
	require.Equal(t, "| ✅  | \x1b[32;1m\x1b[0m                                              | 0.00 sec |", cell)
}
Esempio n. 9
0
func TestTransformSections(t *testing.T) {
	assert.Equal(t, `<section class="section-class">

hello

</section>
`,
		transformSections(`!section class="section-class"

hello

!/section
`))

	// Test once through the full render function as well so that we can make
	// sure that it still works even after content has been garbled by
	// Markdown.
	assert.Equal(t, `<section class="section-class">

<p>hello</p>

</section>
`,
		Render(`!section class="section-class"

hello

!/section
`))
}
Esempio n. 10
0
// This sets the threshold for a base role
func TestSwizzlerSetThresholdBaseRole(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.SetThreshold(data.CanonicalTargetsRole, 3)

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		// the threshold for base roles is set in root
		if role != data.CanonicalRootRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			signedRoot := &data.SignedRoot{}
			require.NoError(t, json.Unmarshal(newMeta, signedRoot))
			for r, roleInfo := range signedRoot.Signed.Roles {
				if r != data.CanonicalTargetsRole {
					require.Equal(t, 1, roleInfo.Threshold)
				} else {
					require.Equal(t, 3, roleInfo.Threshold)
				}
			}
		}
	}
}
func TestGetTrimmedStepName(t *testing.T) {
	result := models.StepRunResultsModel{
		StepName: longStr,
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  10000000,
		Error:    errors.New(longStr),
		ExitCode: 1,
	}

	stepName := getTrimmedStepName(result)
	require.Equal(t, "This is a very long string,\nthis is a very ...", stepName)

	result = models.StepRunResultsModel{
		StepName: "",
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  0,
		Error:    nil,
		ExitCode: 0,
	}

	stepName = getTrimmedStepName(result)
	require.Equal(t, "", stepName)
}
Esempio n. 12
0
// This modifies the metadata so that the signed part has an extra, extraneous
// field.  This does not prevent it from being unmarshalled as Signed* object,
// but the signature is no longer valid because the hash is different.
func TestSwizzlerInvalidateMetadataSignatures(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.InvalidateMetadataSignatures(data.CanonicalRootRole)

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		if role != data.CanonicalRootRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			// it be JSON unmarshallable into a data.Signed, and it's signed by
			// root, but it is NOT the correct signature because the hash
			// does not match
			origSigned, newSigned := &data.Signed{}, &data.Signed{}
			require.NoError(t, json.Unmarshal(metaBytes, origSigned))
			require.NoError(t, json.Unmarshal(newMeta, newSigned))
			require.Len(t, newSigned.Signatures, len(origSigned.Signatures))
			for i := range origSigned.Signatures {
				require.Equal(t, origSigned.Signatures[i].KeyID, newSigned.Signatures[i].KeyID)
				require.Equal(t, origSigned.Signatures[i].Method, newSigned.Signatures[i].Method)
				require.NotEqual(t, origSigned.Signatures[i].Signature, newSigned.Signatures[i].Signature)
				require.Equal(t, []byte("invalid signature"), newSigned.Signatures[i].Signature)
			}
			require.True(t, bytes.Equal(origSigned.Signed, newSigned.Signed))
		}
	}
}
Esempio n. 13
0
// This adds a single byte of whitespace to the metadata file, so it should be parsed
// and deserialized the same way, but checksums against snapshot/timestamp may fail
func TestSwizzlerAddExtraSpace(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.AddExtraSpace(data.CanonicalTargetsRole)

	snapshot := &data.SignedSnapshot{}
	require.NoError(t, json.Unmarshal(origMeta[data.CanonicalSnapshotRole], snapshot))

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		if role != data.CanonicalTargetsRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			require.True(t, bytes.Equal(metaBytes, newMeta[1:len(metaBytes)+1]))
			require.Equal(t, byte(' '), newMeta[0])
			require.Equal(t, byte(' '), newMeta[len(newMeta)-1])

			// make sure the hash is not the same as the hash in snapshot
			newHash := sha256.Sum256(newMeta)
			require.False(t, bytes.Equal(
				snapshot.Signed.Meta[data.CanonicalTargetsRole].Hashes["sha256"],
				newHash[:]))
			require.NotEqual(t,
				snapshot.Signed.Meta[data.CanonicalTargetsRole].Length,
				len(newMeta))
		}
	}
}
Esempio n. 14
0
// test to ensure encoding and decoding are the same
// decode, encode, and decode again
func TestConnackDecodeEncodeEquiv(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		0, // session not present
		0, // connection accepted
	}

	msg := NewConnackMessage()
	n, err := msg.Decode(msgBytes)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n, "Error decoding message.")

	dst := make([]byte, 100)
	n2, err := msg.Encode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n2, "Error decoding message.")
	require.Equal(t, msgBytes, dst[:n2], "Error decoding message.")

	n3, err := msg.Decode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n3, "Error decoding message.")
}
Esempio n. 15
0
func TestFibonacciEMemoFunc(t *testing.T) {
	calls := 0
	fibonacci := NewEMemoFunc(
		func(i int, f EMemoFunc) (interface{}, error) {
			calls++
			if i == 0 {
				return uint64(0), nil
			}
			if i == 1 {
				return uint64(1), nil
			}
			n1, err := f(i - 1)
			if err != nil {
				return 0, err
			}
			n2, err := f(i - 2)
			if err != nil {
				return 0, err
			}
			return n1.(uint64) + n2.(uint64), nil
		},
	)
	result, err := fibonacci(93)
	require.NoError(t, err)
	require.Equal(t, uint64(12200160415121876738), result.(uint64))
	require.Equal(t, 94, calls)
}
Esempio n. 16
0
// test large message
func TestPublishMessageEncode4(t *testing.T) {
	msgBytes := []byte{
		byte(PUBLISH << 4),
		137,
		8,
		0, // topic name MSB (0)
		7, // topic name LSB (7)
		's', 'u', 'r', 'g', 'e', 'm', 'q',
	}

	payload := make([]byte, 1024)
	msgBytes = append(msgBytes, payload...)

	msg := NewPublishMessage()
	msg.Topic = []byte("surgemq")
	msg.QoS = QosAtMostOnce
	msg.Payload = payload

	require.Equal(t, len(msgBytes), msg.Len())

	dst := make([]byte, 1100)
	n, err := msg.Encode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n, "Error decoding message.")
	require.Equal(t, msgBytes, dst[:n], "Error decoding message.")
}
Esempio n. 17
0
func TestGetStepIDStepDataPair(t *testing.T) {
	stepData := stepmanModels.StepModel{}

	t.Log("valid steplist item")
	{
		stepListItem := StepListItemModel{
			"step1": stepData,
		}

		id, _, err := GetStepIDStepDataPair(stepListItem)
		require.NoError(t, err)
		require.Equal(t, "step1", id)
	}

	t.Log("invalid steplist item - more than 1 step")
	{
		stepListItem := StepListItemModel{
			"step1": stepData,
			"step2": stepData,
		}

		id, _, err := GetStepIDStepDataPair(stepListItem)
		require.Error(t, err)
		require.Equal(t, "", id)
	}
}
Esempio n. 18
0
func TestPublishEqualDecodeEncode(t *testing.T) {
	msgBytes := []byte{
		byte(PUBLISH<<4) | 2,
		23,
		0, // topic name MSB (0)
		7, // topic name LSB (7)
		's', 'u', 'r', 'g', 'e', 'm', 'q',
		0, // packet ID MSB (0)
		7, // packet ID LSB (7)
		's', 'e', 'n', 'd', ' ', 'm', 'e', ' ', 'h', 'o', 'm', 'e',
	}

	msg := NewPublishMessage()

	n, err := msg.Decode(msgBytes)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n, "Error decoding message.")

	dst := make([]byte, 100)
	n2, err := msg.Encode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n2, "Error decoding message.")
	require.Equal(t, msgBytes, dst[:n2], "Error decoding message.")

	n3, err := msg.Decode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n3, "Error decoding message.")
}
Esempio n. 19
0
func TestSubackEqualDecodeEncode(t *testing.T) {
	msgBytes := []byte{
		byte(SUBACK << 4),
		6,
		0,    // packet ID MSB (0)
		7,    // packet ID LSB (7)
		0,    // return code 1
		1,    // return code 2
		2,    // return code 3
		0x80, // return code 4
	}

	msg := NewSubackMessage()
	n, err := msg.Decode(msgBytes)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n, "Error decoding message.")

	dst := make([]byte, 100)
	n2, err := msg.Encode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n2, "Error decoding message.")
	require.Equal(t, msgBytes, dst[:n2], "Error decoding message.")

	n3, err := msg.Decode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n3, "Error decoding message.")
}
Esempio n. 20
0
func TestPublishMessageEncode(t *testing.T) {
	msgBytes := []byte{
		byte(PUBLISH<<4) | 2,
		23,
		0, // topic name MSB (0)
		7, // topic name LSB (7)
		's', 'u', 'r', 'g', 'e', 'm', 'q',
		0, // packet ID MSB (0)
		7, // packet ID LSB (7)
		's', 'e', 'n', 'd', ' ', 'm', 'e', ' ', 'h', 'o', 'm', 'e',
	}

	msg := NewPublishMessage()
	msg.Topic = []byte("surgemq")
	msg.QoS = QosAtLeastOnce
	msg.PacketId = 7
	msg.Payload = []byte{'s', 'e', 'n', 'd', ' ', 'm', 'e', ' ', 'h', 'o', 'm', 'e'}

	dst := make([]byte, 100)
	n, err := msg.Encode(dst)

	require.NoError(t, err, "Error decoding message.")
	require.Equal(t, len(msgBytes), n, "Error decoding message.")
	require.Equal(t, msgBytes, dst[:n], "Error decoding message.")
}
Esempio n. 21
0
func TestGetLocalResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)

	err := testutils.DownloadTestDataArchive(t, TEST_DATA_STORAGE_PATH, TEST_DATA_DIR)
	assert.Nil(t, err)

	startTS := time.Date(2015, time.May, 5, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2015, time.May, 17, 23, 59, 59, 0, time.UTC).Unix()

	resultFiles, err := getLocalResultsFileLocations(startTS, endTS, filepath.Join(TEST_DATA_DIR, "nano-json-v1"))
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/local_ingest_files.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}
Esempio n. 22
0
// Check that we can prune an answer
func TestPrune(t *testing.T) {
	InitDefaultLogging(testing.Verbose())
	Info.Println("TestPrune starting")

	questionMsg := new(dns.Msg)
	questionMsg.SetQuestion("name", dns.TypeA)
	questionMsg.RecursionDesired = true
	question := &questionMsg.Question[0]
	records := []ZoneRecord{
		Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0},
	}

	reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
	reply.Answer[0].Header().Ttl = DefaultLocalTTL

	pruned := pruneAnswers(reply.Answer, 1)
	require.Equal(t, 1, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 2)
	require.Equal(t, 2, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 0)
	require.Equal(t, len(records), len(pruned), "wrong number of answers")
}
Esempio n. 23
0
func TestStepResultCell(t *testing.T) {
	stepInfo := models.StepInfoModel{
		ID:      longStr,
		Version: longStr,
	}

	result := models.StepRunResultsModel{
		StepInfo: stepInfo,
		Status:   models.StepRunStatusCodeFailed,
		Idx:      0,
		RunTime:  10000000,
		Error:    errors.New(longStr),
		ExitCode: 1,
	}

	cell := stepResultCell(result)
	require.Equal(t, "| 🚫  | \x1b[31;1m... (...s a very long string.\n) (exit code: 1)\x1b[0m| 0.01 sec |", cell)

	stepInfo.ID = ""
	result = models.StepRunResultsModel{
		StepInfo: stepInfo,
		Status:   models.StepRunStatusCodeSuccess,
		Idx:      0,
		RunTime:  0,
		Error:    nil,
		ExitCode: 0,
	}

	cell = stepResultCell(result)
	require.Equal(t, "| ✅  | \x1b[32;1m (...s a very long string.\n)\x1b[0m                  | 0.00 sec |", cell)
}
func TestTargetBoardResolverCustomYun(t *testing.T) {
	ctx := &types.Context{
		HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"},
		FQBN:            "my_avr_platform:avr:custom_yun",
	}

	commands := []types.Command{
		&builder.HardwareLoader{},
		&builder.TargetBoardResolver{},
	}

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

	targetPackage := ctx.TargetPackage
	require.Equal(t, "my_avr_platform", targetPackage.PackageId)
	targetPlatform := ctx.TargetPlatform
	require.Equal(t, "avr", targetPlatform.PlatformId)
	targetBoard := ctx.TargetBoard
	require.Equal(t, "custom_yun", targetBoard.BoardId)
	require.Equal(t, "atmega32u4", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU])
	require.Equal(t, "AVR_YUN", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD])
}
Esempio n. 25
0
func TestDonateHard(t *testing.T) {
	//common.InitDefaultLogging(true)
	var (
		start                = ip("10.0.1.0")
		size  address.Offset = 48
	)

	// Fill a fresh space
	spaceset := makeSpace(start, size)
	for i := address.Offset(0); i < size; i++ {
		ok, _ := spaceset.Allocate(address.NewRange(start, size))
		require.True(t, ok, "Failed to get IP!")
	}

	require.Equal(t, address.Offset(0), spaceset.NumFreeAddresses())

	// Now free all but the last address
	// this will force us to split the free list
	for i := address.Offset(0); i < size-1; i++ {
		require.NoError(t, spaceset.Free(address.Add(start, i)))
	}

	// Now split
	newRange, ok := spaceset.Donate(address.NewRange(start, size))
	require.True(t, ok, "GiveUpSpace result")
	require.Equal(t, ip("10.0.1.23"), newRange.Start)
	require.Equal(t, address.Offset(24), newRange.Size())
	require.Equal(t, address.Offset(23), spaceset.NumFreeAddresses())

	//Space set should now have 2 spaces
	expected := New()
	expected.Add(start, 23)
	expected.ours = add(nil, ip("10.0.1.47"), ip("10.0.1.48"))
	require.Equal(t, expected, spaceset)
}
func TestTargetBoardResolverCustomCore(t *testing.T) {
	ctx := &types.Context{
		HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"},
		FQBN:            "watterott:avr:attiny841:core=spencekonde,info=info",
	}

	commands := []types.Command{
		&builder.HardwareLoader{},
		&builder.TargetBoardResolver{},
	}

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

	targetPackage := ctx.TargetPackage
	require.Equal(t, "watterott", targetPackage.PackageId)
	targetPlatform := ctx.TargetPlatform
	require.Equal(t, "avr", targetPlatform.PlatformId)
	targetBoard := ctx.TargetBoard
	require.Equal(t, "attiny841", targetBoard.BoardId)
	require.Equal(t, "tiny841", ctx.BuildCore)
	require.Equal(t, "tiny14", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_VARIANT])
}
func TestCollectAllSourceFilesFromFoldersWithSourcesOfOldLibrary(t *testing.T) {
	ctx := &types.Context{}

	sourceFiles := &types.UniqueStringQueue{}
	ctx.CollectedSourceFiles = sourceFiles
	foldersWithSources := &types.UniqueSourceFolderQueue{}
	foldersWithSources.Push(types.SourceFolder{Folder: Abs(t, filepath.Join("libraries", "ShouldNotRecurseWithOldLibs")), Recurse: false})
	foldersWithSources.Push(types.SourceFolder{Folder: Abs(t, filepath.Join("libraries", "ShouldNotRecurseWithOldLibs", "utility")), Recurse: false})
	foldersWithSources.Push(types.SourceFolder{Folder: Abs(t, "non existent folder"), Recurse: false})
	ctx.FoldersWithSourceFiles = foldersWithSources

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

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

	require.Equal(t, 2, len(*sourceFiles))
	require.Equal(t, 0, len(*foldersWithSources))
	sort.Strings(*sourceFiles)

	require.Equal(t, Abs(t, filepath.Join("libraries", "ShouldNotRecurseWithOldLibs", "ShouldNotRecurseWithOldLibs.cpp")), sourceFiles.Pop())
	require.Equal(t, Abs(t, filepath.Join("libraries", "ShouldNotRecurseWithOldLibs", "utility", "utils.cpp")), sourceFiles.Pop())
	require.Equal(t, 0, len(*sourceFiles))
}
func TestTargetBoardResolverMega1280(t *testing.T) {
	ctx := &types.Context{
		HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"},
		FQBN:            "arduino:avr:mega:cpu=atmega1280",
	}

	commands := []types.Command{
		&builder.HardwareLoader{},
		&builder.TargetBoardResolver{},
	}

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

	targetPackage := ctx.TargetPackage
	require.Equal(t, "arduino", targetPackage.PackageId)
	targetPlatform := ctx.TargetPlatform
	require.Equal(t, "avr", targetPlatform.PlatformId)
	targetBoard := ctx.TargetBoard
	require.Equal(t, "mega", targetBoard.BoardId)
	require.Equal(t, "atmega1280", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU])
	require.Equal(t, "AVR_MEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD])
}
Esempio n. 29
0
func TestSpaceRequest(t *testing.T) {
	const (
		container1 = "cont-1"
		container2 = "cont-2"
		universe   = "10.32.0.0/12"
	)
	allocs, router, subnet := makeNetworkOfAllocators(1, universe)
	defer stopNetworkOfAllocators(allocs, router)
	alloc1 := allocs[0]

	addr, err := alloc1.Allocate(container1, subnet, true, returnFalse)
	require.Nil(t, err, "")
	// free it again so the donation splits the range neatly
	err = alloc1.Free(container1, addr)
	require.Nil(t, err, "")
	require.Equal(t, cidrRanges(universe), alloc1.OwnedRanges(), "")

	// Start a new peer
	alloc2, _ := makeAllocator("02:00:00:02:00:00", universe, 2)
	alloc2.SetInterfaces(router.Connect(alloc2.ourName, alloc2))
	alloc2.Start()
	defer alloc2.Stop()
	alloc2.Allocate(container2, subnet, true, returnFalse)

	// Test whether the universe has been split into two equal halves (GH #2009)
	require.Equal(t, cidrRanges("10.32.0.0/13"), alloc1.OwnedRanges(), "")
	require.Equal(t, cidrRanges("10.40.0.0/13"), alloc2.OwnedRanges(), "")
}
Esempio n. 30
0
func TestJSONCodec(t *testing.T) {
	type myTestType struct {
		A int
		B string
	}

	itemCodec := JSONCodec(&myTestType{})
	testInstance := &myTestType{5, "hello"}
	jsonBytes, err := itemCodec.Encode(testInstance)
	assert.Nil(t, err)

	decodedInstance, err := itemCodec.Decode(jsonBytes)
	assert.Nil(t, err)
	assert.IsType(t, &myTestType{}, decodedInstance)
	assert.Equal(t, testInstance, decodedInstance)

	arrCodec := JSONCodec([]*myTestType{})
	testArr := []*myTestType{&myTestType{1, "1"}, &myTestType{2, "2"}}
	jsonBytes, err = arrCodec.Encode(testArr)
	assert.Nil(t, err)

	decodedArr, err := arrCodec.Decode(jsonBytes)
	assert.Nil(t, err)
	assert.IsType(t, []*myTestType{}, decodedArr)
	assert.Equal(t, testArr, decodedArr)
}