Exemplo n.º 1
0
func TestGetSingleValueFromHeader(t *testing.T) {
	t.Log("Simple OK")
	{
		val, err := GetSingleValueFromHeader("Key", http.Header{"Key": {"value1"}})
		require.NoError(t, err)
		require.Equal(t, "value1", val)
	}

	t.Log("Not found - empty header")
	{
		_, err := GetSingleValueFromHeader("No-Key", http.Header{})
		require.EqualError(t, err, "No value found in HEADER for the key: No-Key")
	}

	t.Log("Not found - different key")
	{
		_, err := GetSingleValueFromHeader("No-Key", http.Header{"Key": {"value1"}})
		require.EqualError(t, err, "No value found in HEADER for the key: No-Key")
	}

	t.Log("Multiple values")
	{
		_, err := GetSingleValueFromHeader("Key", http.Header{"Key": {"value1", "value2"}})
		require.EqualError(t, err, "Multiple values found in HEADER for the key: Key")
	}
}
Exemplo n.º 2
0
func Test_transformTagPushEvent(t *testing.T) {
	t.Log("Do Transform")
	{
		tagPush := TagPushEventModel{
			ObjectKind:  "tag_push",
			Ref:         "refs/tags/v0.0.2",
			CheckoutSHA: "7f29cdf31fdff43d7f31a279eec06c9f19ae0d6b",
		}
		hookTransformResult := transformTagPushEvent(tagPush)
		require.NoError(t, hookTransformResult.Error)
		require.False(t, hookTransformResult.ShouldSkip)
		require.Equal(t, []bitriseapi.TriggerAPIParamsModel{
			{
				BuildParams: bitriseapi.BuildParamsModel{
					Tag:        "v0.0.2",
					CommitHash: "7f29cdf31fdff43d7f31a279eec06c9f19ae0d6b",
				},
			},
		}, hookTransformResult.TriggerAPIParams)
	}

	t.Log("No CheckoutSHA (tag delete)")
	{
		tagPush := TagPushEventModel{
			ObjectKind:  "tag_push",
			Ref:         "refs/tags/v0.0.2",
			CheckoutSHA: "",
		}
		hookTransformResult := transformTagPushEvent(tagPush)
		require.EqualError(t, hookTransformResult.Error, "This is a Tag Deleted event, no build is required")
		require.True(t, hookTransformResult.ShouldSkip)
		require.Nil(t, hookTransformResult.TriggerAPIParams)
	}

	t.Log("Not a tags ref")
	{
		tagPush := TagPushEventModel{
			ObjectKind:  "tag_push",
			Ref:         "refs/not/a/tag",
			CheckoutSHA: "7f29cdf31fdff43d7f31a279eec06c9f19ae0d6b",
		}
		hookTransformResult := transformTagPushEvent(tagPush)
		require.EqualError(t, hookTransformResult.Error, "Ref (refs/not/a/tag) is not a tags ref")
		require.False(t, hookTransformResult.ShouldSkip)
		require.Nil(t, hookTransformResult.TriggerAPIParams)
	}

	t.Log("Not a tag_push object")
	{
		tagPush := TagPushEventModel{
			ObjectKind:  "not-a-tag_push",
			Ref:         "refs/tags/v0.0.2",
			CheckoutSHA: "7f29cdf31fdff43d7f31a279eec06c9f19ae0d6b",
		}
		hookTransformResult := transformTagPushEvent(tagPush)
		require.EqualError(t, hookTransformResult.Error, "Not a Tag Push object: not-a-tag_push")
		require.False(t, hookTransformResult.ShouldSkip)
		require.Nil(t, hookTransformResult.TriggerAPIParams)
	}
}
Exemplo n.º 3
0
func Test_detectContentTypeAndEventID(t *testing.T) {
	t.Log("Code Push event")
	{
		header := http.Header{
			"X-Gogs-Event": {"push"},
			"Content-Type": {"application/json"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.NoError(t, err)
		require.Equal(t, "application/json", contentType)
		require.Equal(t, "push", eventID)
	}

	t.Log("Missing X-Gogs-Event header")
	{
		header := http.Header{
			"Content-Type": {"application/json"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.EqualError(t, err, "Issue with X-Gogs-Event Header: No value found in HEADER for the key: X-Gogs-Event")
		require.Equal(t, "", contentType)
		require.Equal(t, "", eventID)
	}

	t.Log("Missing Content-Type")
	{
		header := http.Header{
			"X-Gogs-Event": {"push"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.EqualError(t, err, "Issue with Content-Type Header: No value found in HEADER for the key: Content-Type")
		require.Equal(t, "", contentType)
		require.Equal(t, "", eventID)
	}
}
Exemplo n.º 4
0
func TestSignedFullSerializeAndToken(t *testing.T) {
	b := Signed(rsaSigner).Claims(&testClaims{"foo"})

	jwt, err := b.FullSerialize()
	require.NoError(t, err, "Error creating JWT.")
	parsed, err := ParseSigned(jwt)
	require.NoError(t, err, "Error parsing JWT.")
	out := &testClaims{}
	if assert.NoError(t, parsed.Claims(&testPrivRSAKey1.PublicKey, &out), "Error unmarshaling claims.") {
		assert.Equal(t, &testClaims{
			Subject: "foo",
		}, out)
	}

	jwt2, err := b.Token()
	require.NoError(t, err, "Error creating JWT.")
	out2 := &testClaims{}
	if assert.NoError(t, jwt2.Claims(&testPrivRSAKey1.PublicKey, &out2), "Error unmarshaling claims.") {
		assert.Equal(t, &testClaims{
			Subject: "foo",
		}, out2)
	}

	b2 := Signed(rsaSigner).Claims(&invalidMarshalClaims{})
	_, err = b2.FullSerialize()
	require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.")
	_, err = b2.Token()
	require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.")
}
Exemplo n.º 5
0
func Test_HookProvider_TransformRequest(t *testing.T) {
	provider := HookProvider{}

	t.Log("Should be OK")
	{
		request := http.Request{
			Header: http.Header{
				"Content-Type": {"application/x-www-form-urlencoded"},
			},
		}
		form := url.Values{}
		form.Add("trigger_word", "bitrise:")
		form.Add("text", "bitrise: branch:master")
		request.PostForm = form

		hookTransformResult := provider.TransformRequest(&request)
		require.NoError(t, hookTransformResult.Error)
		require.False(t, hookTransformResult.ShouldSkip)
		require.Equal(t, []bitriseapi.TriggerAPIParamsModel{
			{
				BuildParams: bitriseapi.BuildParamsModel{
					Branch:       "master",
					Environments: []bitriseapi.EnvironmentItem{},
				},
			},
		}, hookTransformResult.TriggerAPIParams)
	}

	t.Log("Unsupported Event Type")
	{
		request := http.Request{
			Header: http.Header{
				"Content-Type": {"application/json"},
			},
		}
		hookTransformResult := provider.TransformRequest(&request)
		require.False(t, hookTransformResult.ShouldSkip)
		require.EqualError(t, hookTransformResult.Error, "Content-Type is not supported: application/json")
	}

	t.Log("Missing 'text' from request data")
	{
		request := http.Request{
			Header: http.Header{
				"Content-Type": {"application/x-www-form-urlencoded"},
			},
		}
		form := url.Values{}
		form.Add("trigger_word", "the trigger word")
		request.PostForm = form

		hookTransformResult := provider.TransformRequest(&request)
		require.False(t, hookTransformResult.ShouldSkip)
		require.EqualError(t, hookTransformResult.Error, "Failed to parse the request/message: 'trigger_word' parameter found, but 'text' parameter is missing or empty")
	}
}
func TestBrokenCall(t *testing.T) {
	cli, listener, conn := prepTest(t)
	defer endTest(t, conn, listener)

	err := cli.BrokenMethod()
	require.EqualError(t, err, "method 'broken' not found in protocol 'test.1.testp'")

	err = cli.BrokenProtocol()
	require.EqualError(t, err, "protocol not found: test.2.testp")
}
Exemplo n.º 7
0
func TestSetNotifiesStage(t *testing.T) {
	tnflog := &testNflog{}
	s := &SetNotifiesStage{
		recv:  &nflogpb.Receiver{GroupName: "test"},
		nflog: tnflog,
	}
	alerts := []*types.Alert{{}, {}, {}}
	ctx := context.Background()

	resctx, res, err := s.Exec(ctx, alerts...)
	require.EqualError(t, err, "notification hash missing")
	require.Nil(t, res)
	require.NotNil(t, resctx)

	ctx = WithNotificationHash(ctx, []byte{1, 2, 3})

	_, res, err = s.Exec(ctx, alerts...)
	require.EqualError(t, err, "group key missing")
	require.Nil(t, res)
	require.NotNil(t, resctx)

	ctx = WithGroupKey(ctx, 1)

	s.resolved = func([]*types.Alert) bool { return false }
	tnflog.logActiveFunc = func(r *nflogpb.Receiver, gkey, hash []byte) error {
		require.Equal(t, s.recv, r)
		require.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, 1}, gkey)
		require.Equal(t, []byte{1, 2, 3}, hash)
		return nil
	}
	tnflog.logResolvedFunc = func(r *nflogpb.Receiver, gkey, hash []byte) error {
		t.Fatalf("LogResolved called unexpectedly")
		return nil
	}
	resctx, res, err = s.Exec(ctx, alerts...)
	require.Nil(t, err)
	require.Equal(t, alerts, res)
	require.NotNil(t, resctx)

	s.resolved = func([]*types.Alert) bool { return true }
	tnflog.logActiveFunc = func(r *nflogpb.Receiver, gkey, hash []byte) error {
		t.Fatalf("LogActive called unexpectedly")
		return nil
	}
	tnflog.logResolvedFunc = func(r *nflogpb.Receiver, gkey, hash []byte) error {
		require.Equal(t, s.recv, r)
		require.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, 1}, gkey)
		require.Equal(t, []byte{1, 2, 3}, hash)
		return nil
	}
	resctx, res, err = s.Exec(ctx, alerts...)
	require.Nil(t, err)
	require.Equal(t, alerts, res)
	require.NotNil(t, resctx)
}
Exemplo n.º 8
0
func Test_getInputTextFromFormRequest(t *testing.T) {
	t.Log("Proper Form content")
	{
		request := http.Request{}
		form := url.Values{}
		form.Add("trigger_word", "the trigger word")
		form.Add("text", "the trigger word        the text")
		request.PostForm = form

		text, err := getInputTextFromFormRequest(&request)
		require.NoError(t, err)
		require.Equal(t, "the text", text)
	}

	t.Log("Missing trigger_word")
	{
		request := http.Request{}
		form := url.Values{}
		form.Add("text", "the text")
		request.PostForm = form

		text, err := getInputTextFromFormRequest(&request)
		require.EqualError(t, err, "Missing required parameter: either 'command' or 'trigger_word' should be specified")
		require.Equal(t, "", text)
	}

	t.Log("Missing text - trigger_word")
	{
		request := http.Request{}
		form := url.Values{}
		form.Add("trigger_word", "the trigger word")
		request.PostForm = form

		text, err := getInputTextFromFormRequest(&request)
		require.EqualError(t, err, "'trigger_word' parameter found, but 'text' parameter is missing or empty")
		require.Equal(t, "", text)
	}

	t.Log("Missing text - command")
	{
		request := http.Request{}
		form := url.Values{}
		form.Add("command", "the-command")
		request.PostForm = form

		text, err := getInputTextFromFormRequest(&request)
		require.EqualError(t, err, "'command' parameter found, but 'text' parameter is missing or empty")
		require.Equal(t, "", text)
	}
}
func TestLongCallCancel(t *testing.T) {
	cli, listener, conn := prepTest(t)
	defer endTest(t, conn, listener)

	ctx, cancel := context.WithCancel(context.Background())
	ctx = AddRpcTagsToContext(ctx, CtxRpcTags{"hello": []string{"world"}})

	resultCh := make(chan longCallResult)
	runInBg(func() error {
		var longResult interface{}
		var err error
		longResult, err = cli.LongCall(ctx)
		resultCh <- longCallResult{longResult, err}
		longResult, err = cli.LongCallResult(context.Background())
		resultCh <- longCallResult{longResult, err}
		longResult, err = cli.LongCallDebugTags(context.Background())
		resultCh <- longCallResult{longResult, err}
		return nil
	})
	// TODO figure out a way to avoid this sleep
	time.Sleep(time.Millisecond)
	cancel()
	res := <-resultCh
	require.EqualError(t, res.err, context.Canceled.Error())
	require.Equal(t, 0, res.res, "call should be canceled")

	res = <-resultCh
	require.Nil(t, res.err, "call should have succeeded")
	require.Equal(t, -1, res.res, "canceled call should have set the longCallResult to canceled")

	res = <-resultCh
	require.Nil(t, res.err, "call should have succeeded")
	require.Equal(t, CtxRpcTags{"hello": []interface{}{"world"}}, res.res, "canceled call should have set the debug tags")
}
Exemplo n.º 10
0
func TestCloseReceiver(t *testing.T) {
	// Call error status
	waitCh := make(chan error, 1)
	p := &Protocol{
		Name: "waiter",
		Methods: map[string]ServeHandlerDescription{
			"wait": {
				MakeArg: func() interface{} {
					return nil
				},
				Handler: func(c context.Context, i interface{}) (interface{}, error) {
					<-c.Done()
					waitCh <- c.Err()
					return nil, c.Err()
				},
				MethodType: MethodCall,
			},
		},
	}
	receiver, _ := testReceive(
		t,
		p,
		makeCall(
			0,
			"waiter.wait",
			nil,
		),
	)
	<-receiver.Close()

	err := <-waitCh
	require.EqualError(t, err, context.Canceled.Error())
}
func Test_MachineConfigModel_normalizeAndValidate(t *testing.T) {

	t.Log("Invalid CleanupMode")
	{
		configModel := MachineConfigModel{CleanupMode: ""}
		require.EqualError(t, configModel.normalizeAndValidate(), "Invalid CleanupMode: ")
	}

	t.Log("Minimal valid")
	{
		configModel := MachineConfigModel{
			CleanupMode:          CleanupModeRollback,
			IsCleanupBeforeSetup: true,
			IsDoTimesyncAtSetup:  false,
		}

		t.Logf("configModel: %#v", configModel)
		require.NoError(t, configModel.normalizeAndValidate())
		require.Equal(t, true, configModel.IsCleanupBeforeSetup)
		require.Equal(t, false, configModel.IsDoTimesyncAtSetup)
		// defaults
		require.Equal(t, EnvItemsModel{}, configModel.Envs)
		require.Equal(t, map[string]EnvItemsModel{}, configModel.ConfigTypeEnvs)
	}
}
Exemplo n.º 12
0
func TestBadStatusCode(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusServiceUnavailable)
		json.NewEncoder(w).Encode(`{
      "errors": {
        "system": [
          "The API is currently down for maintenance. It'll be back shortly."
        ]
      }
    }`)
	}))
	defer ts.Close()

	l := NewLibrato(ts.URL)
	l.ApiUser = "******"
	l.ApiToken = "123456"
	err := l.Connect()
	require.NoError(t, err)
	err = l.Write(testutil.MockBatchPoints().Points())
	if err == nil {
		t.Errorf("error expected but none returned")
	} else {
		require.EqualError(t, fmt.Errorf("received bad status code, 503\n"), err.Error())
	}
}
Exemplo n.º 13
0
func Test_InvalidCommand(t *testing.T) {
	t.Log("Invalid command")
	{
		_, err := cmdex.RunCommandAndReturnCombinedStdoutAndStderr(binPath(), "invalidcmd")
		require.EqualError(t, err, "exit status 1")
	}
}
Exemplo n.º 14
0
func Test_detectContentTypeAndEventID(t *testing.T) {
	t.Log("Code Push event")
	{
		header := http.Header{
			"X-Gitlab-Event": {"Push Hook"},
			"Content-Type":   {"application/json"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.NoError(t, err)
		require.Equal(t, "application/json", contentType)
		require.Equal(t, "Push Hook", eventID)
	}

	t.Log("Unsupported event - will be handled in Transform")
	{
		header := http.Header{
			"X-Gitlab-Event": {"Tag Push Hook"},
			"Content-Type":   {"application/json"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.NoError(t, err)
		require.Equal(t, "application/json", contentType)
		require.Equal(t, "Tag Push Hook", eventID)
	}

	t.Log("Missing X-Gitlab-Event header")
	{
		header := http.Header{
			"Content-Type": {"application/json"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.EqualError(t, err, "Issue with X-Gitlab-Event Header: No value found in HEADER for the key: X-Gitlab-Event")
		require.Equal(t, "", contentType)
		require.Equal(t, "", eventID)
	}

	t.Log("Missing Content-Type")
	{
		header := http.Header{
			"X-Gitlab-Event": {"Push Hook"},
		}
		contentType, eventID, err := detectContentTypeAndEventID(header)
		require.EqualError(t, err, "Issue with Content-Type Header: No value found in HEADER for the key: Content-Type")
		require.Equal(t, "", contentType)
		require.Equal(t, "", eventID)
	}
}
Exemplo n.º 15
0
func Test_parseGoVersionFromGoVersionOutput(t *testing.T) {
	t.Log("Example OK")
	{
		verStr, err := parseGoVersionFromGoVersionOutput("go version go1.7 darwin/amd64")
		require.NoError(t, err)
		require.Equal(t, "1.7", verStr)
	}

	t.Log("Example OK 2")
	{
		verStr, err := parseGoVersionFromGoVersionOutput(`go version go1.7 darwin/amd64

`)
		require.NoError(t, err)
		require.Equal(t, "1.7", verStr)
	}

	t.Log("Example OK 3")
	{
		verStr, err := parseGoVersionFromGoVersionOutput("go version go1.7.1 darwin/amd64")
		require.NoError(t, err)
		require.Equal(t, "1.7.1", verStr)
	}

	t.Log("Empty")
	{
		verStr, err := parseGoVersionFromGoVersionOutput("")
		require.EqualError(t, err, "Failed to parse Go version, error: version call output was empty")
		require.Equal(t, "", verStr)
	}

	t.Log("Empty 2")
	{
		verStr, err := parseGoVersionFromGoVersionOutput(`

`)
		require.EqualError(t, err, "Failed to parse Go version, error: version call output was empty")
		require.Equal(t, "", verStr)
	}

	t.Log("Invalid")
	{
		verStr, err := parseGoVersionFromGoVersionOutput("go version REMOVED darwin/amd64")
		require.EqualError(t, err, "Failed to parse Go version, error: failed to find version in input: go version REMOVED darwin/amd64")
		require.Equal(t, "", verStr)
	}
}
Exemplo n.º 16
0
func TestSnapshotMarshalJSONMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	sn := SignedSnapshot{
		Signed: Snapshot{Type: "Snapshot", Version: 2, Expires: time.Now()},
	}
	_, err := sn.MarshalJSON()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 17
0
func TestTimeToFormattedSeconds(t *testing.T) {
	t.Log("formatted print rounds")
	{
		timeStr, err := FormattedSecondsToMax8Chars(secToDuration(0.999))
		require.NoError(t, err)
		require.Equal(t, "1.00 sec", timeStr)
	}

	t.Log("sec < 1.0")
	{
		timeStr, err := FormattedSecondsToMax8Chars(secToDuration(0.111))
		require.NoError(t, err)
		require.Equal(t, "0.11 sec", timeStr)
	}

	t.Log("sec < 10.0")
	{
		timeStr, err := FormattedSecondsToMax8Chars(secToDuration(9.111))
		require.NoError(t, err)
		require.Equal(t, "9.11 sec", timeStr)
	}

	t.Log("sec < 600 | min < 10")
	{
		timeStr, err := FormattedSecondsToMax8Chars(secToDuration(599.111))
		require.NoError(t, err)
		require.Equal(t, "599 sec", timeStr)
	}

	t.Log("min < 60")
	{
		timeStr, err := FormattedSecondsToMax8Chars(minToDuration(59.111))
		require.NoError(t, err)
		require.Equal(t, "59.1 min", timeStr)
	}

	t.Log("hour < 10")
	{
		timeStr, err := FormattedSecondsToMax8Chars(hourToDuration(9.111))
		require.NoError(t, err)
		require.Equal(t, "9.1 hour", timeStr)
	}

	t.Log("hour < 1000")
	{
		timeStr, err := FormattedSecondsToMax8Chars(hourToDuration(999.111))
		require.NoError(t, err)
		require.Equal(t, "999 hour", timeStr)
	}

	t.Log("hour >= 1000")
	{
		timeStr, err := FormattedSecondsToMax8Chars(hourToDuration(1000))
		require.EqualError(t, err, "time (1000.000000 hour) greater then max allowed (999 hour)")
		require.Equal(t, "", timeStr)
	}
}
Exemplo n.º 18
0
func TestFailureCase(t *testing.T) {
	fakeClient := &fakeFleetClientApi{}
	fakeClient.f = func() ([]machine.MachineState, error) {
		return nil, fmt.Errorf("test error")
	}
	nodesApi := &fleetNodes{client: fakeClient}
	_, err := nodesApi.List()
	require.EqualError(t, err, "test error")
}
Exemplo n.º 19
0
func TestTargetsToSignedMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	tg := SignedTargets{
		Signed: Targets{SignedCommon: SignedCommon{Type: "Targets", Version: 2, Expires: time.Now()}},
	}
	_, err := tg.ToSigned()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 20
0
func TestTimestampMarshalJSONMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	ts := SignedTimestamp{
		Signed: Timestamp{Type: "Timestamp", Version: 2, Expires: time.Now()},
	}
	_, err := ts.MarshalJSON()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 21
0
func TestRootToSignedMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	r := SignedRoot{
		Signed: Root{Type: "root", Version: 2, Expires: time.Now()},
	}
	_, err := r.ToSigned()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 22
0
func TestSnapshotToSignedMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	sn := SignedSnapshot{
		Signed: Snapshot{SignedCommon: SignedCommon{
			Type: TUFTypes[CanonicalSnapshotRole], Version: 2, Expires: time.Now()}},
	}
	_, err := sn.ToSigned()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 23
0
func TestSnapshotFromSignedUnmarshallingErrorsPropagated(t *testing.T) {
	signed, err := validSnapshotTemplate().ToSigned()
	require.NoError(t, err)

	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})

	_, err = SnapshotFromSigned(signed)
	require.EqualError(t, err, "bad")
}
Exemplo n.º 24
0
func TestRootMarshalJSONMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	r := SignedRoot{
		Signed: Root{SignedCommon: SignedCommon{
			Type: TUFTypes[CanonicalRootRole], Version: 2, Expires: time.Now()}},
	}
	_, err := r.MarshalJSON()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 25
0
func TestTimestampToSignedMarshallingErrorsPropagated(t *testing.T) {
	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})
	ts := SignedTimestamp{
		Signed: Timestamp{SignedCommon: SignedCommon{
			Type: TUFTypes[CanonicalTimestampRole], Version: 2, Expires: time.Now()}},
	}
	_, err := ts.ToSigned()
	require.EqualError(t, err, "bad")
}
Exemplo n.º 26
0
func TestTargetsFromSignedUnmarshallingErrorsPropagated(t *testing.T) {
	signed, err := validTargetsTemplate().ToSigned()
	require.NoError(t, err)

	setDefaultSerializer(errorSerializer{})
	defer setDefaultSerializer(canonicalJSON{})

	_, err = TargetsFromSigned(signed, CanonicalTargetsRole)
	require.EqualError(t, err, "bad")
}
Exemplo n.º 27
0
func TestSelectFromStringsFromReader(t *testing.T) {
	availableOptions := []string{"first", "second", "third"}

	t.Log("TestSelectFromStringsFromReader - NO input")
	{
		_, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader(""))
		require.Error(t, err)
	}

	t.Log("TestSelectFromStringsFromReader - INVALID input")
	{
		_, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader("-1"))
		require.EqualError(t, err, "Invalid option: You entered a number less than 1")
	}

	t.Log("TestSelectFromStringsFromReader - input")
	{
		res, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader("1"))
		require.NoError(t, err)
		require.Equal(t, "first", res)
	}

	t.Log("TestSelectFromStringsFromReader - input")
	{
		res, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader("2"))
		require.NoError(t, err)
		require.Equal(t, "second", res)
	}

	t.Log("TestSelectFromStringsFromReader - input")
	{
		res, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader("3"))
		require.NoError(t, err)
		require.Equal(t, "third", res)
	}

	t.Log("TestSelectFromStringsFromReader - INVALID input")
	{
		_, err := SelectFromStringsFromReader("Select something", availableOptions, strings.NewReader("4"))
		require.EqualError(t, err, "Invalid option: You entered a number greater than the last option's number")
	}
}
Exemplo n.º 28
0
func TestReceiveResponseNilCall(t *testing.T) {
	c := &rpcResponseMessage{c: &call{}}
	_, errCh := testReceive(
		t,
		nil,
		c,
	)
	err := <-errCh

	require.True(t, shouldContinue(err))
	require.EqualError(t, err, "Call not found for sequence number 0")
}
Exemplo n.º 29
0
func TestEncryptedFullSerializeAndToken(t *testing.T) {
	recipient := jose.Recipient{
		Algorithm: jose.RSA1_5,
		Key:       testPrivRSAKey1.Public(),
	}
	encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recipient, nil)
	require.NoError(t, err, "Error creating encrypter.")

	b := Encrypted(encrypter).Claims(&testClaims{"foo"})

	jwt, err := b.FullSerialize()
	require.NoError(t, err, "Error creating JWT.")
	parsed, err := ParseEncrypted(jwt)
	require.NoError(t, err, "Error parsing JWT.")
	out := &testClaims{}
	if assert.NoError(t, parsed.Claims(testPrivRSAKey1, &out)) {
		assert.Equal(t, &testClaims{
			Subject: "foo",
		}, out)
	}

	jwt2, err := b.Token()
	require.NoError(t, err, "Error creating JWT.")
	out2 := &testClaims{}
	if assert.NoError(t, jwt2.Claims(testPrivRSAKey1, &out2)) {
		assert.Equal(t, &testClaims{
			Subject: "foo",
		}, out2)
	}

	b2 := Encrypted(encrypter).Claims(&invalidMarshalClaims{})

	_, err = b2.FullSerialize()
	require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.")
	_, err = b2.Token()
	require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.")
}
Exemplo n.º 30
0
func TestAcceptGone(t *testing.T) {
	defer sleepWhile(&mu, func() bool { return len(sockets) != 0 })
	s, err := NewSocket("udp", "localhost:0")
	require.NoError(t, err)
	defer s.Close()
	_, err = DialTimeout(s.Addr().String(), time.Millisecond)
	require.Error(t, err)
	// Will succeed because we don't signal that we give up dialing, or check
	// that the handshake is completed before returning the new Conn.
	c, err := s.Accept()
	require.NoError(t, err)
	defer c.Close()
	err = c.SetReadDeadline(time.Now().Add(time.Millisecond))
	_, err = c.Read(nil)
	require.EqualError(t, err, "i/o timeout")
}