CodeSampleX

Пример

google.golang.org/protobuf v1.28.0: structpb.NewValue

Проверенный пример — golang google.golang.org/protobuf v1.28.0: structpb.NewValue. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден…

sha256:88107fbdb9ee315bb40584b1df85d7a0e678eb775e566010e110dfb5f45db274

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go linux 24 · ubuntu · glibc 2.39 x64 go go go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-02

Кейс

HOW
Цель
verify google.golang.org/protobuf/types/known/structpb.NewValue in pkg:golang/google.golang.org/protobuf@v1.28.0
Пакеты
Символы
  • google.golang.org/protobuf/types/known/structpb.NewValue
Окружение
go
Создан
2026-09-02T06:57:13Z

Контракт

  1. structpb.NewValue converts nil to Value_NullValue whose AsInterface() returns nil.
  2. structpb.NewValue converts boolean values to Value_BoolValue and round-trips via AsInterface().
  3. structpb.NewValue converts supported numbers (int, int32, int64, uint, uint32, uint64, float32, float64) to Value_NumberValue with float64 representation, returning errors for unhandled numeric types like int8, int16, uint8, and uint16.
  4. structpb.NewValue converts UTF-8 strings to Value_StringValue and byte slices to base64-encoded Value_StringValue, while returning an error for invalid UTF-8 strings.
  5. structpb.NewValue converts map[string]interface{} and []interface{} into nested StructValue and ListValue respectively and unwraps them via AsInterface().
  6. structpb.NewValue returns an error for unsupported Go types including channels, functions, unmapped structs, and nested unsupported values.

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • newvalue_test.go
  • spec.json

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Verification of `structpb.NewValue` in `google.golang.org/protobuf@v1.28.0`

This sample verifies the exact behavior and type conversion rules of `google.golang.org/protobuf/types/known/structpb.NewValue`.

## Verified Semantics

1. **Nil Conversion**:
   - `structpb.NewValue(nil)` produces a `*structpb.Value` with kind `Value_NullValue` set to `NullValue_NULL_VALUE`.
   - Calling `AsInterface()` on a null value safely returns `nil`.

2. **Boolean Conversion**:
   - `structpb.NewValue(true)` and `structpb.NewValue(false)` produce `*structpb.Value` with kind `Value_BoolValue`.
   - Calling `AsInterface()` returns the original boolean.

3. **Number Conversions**:
   - Supported numeric types: `int`, `int32`, `int64`, `uint`, `uint32`, `uint64`, `float32`, `float64`. All are stored as `Value_NumberValue` represented by a `float64`.
   - Other numeric types (such as `int8`, `int16`, `uint8`, `uint16`) are not converted directly and return an error from `structpb.NewValue`.

4. **String and Byte Slice Conversions**:
   - Valid UTF-8 strings are stored as `Value_StringValue`.
   - Byte slices (`[]byte`) are base64-encoded and stored as `Value_StringValue`.
   - Invalid UTF-8 strings return an error.

5. **Maps and Slices**:
   - `map[string]interface{}` is converted to `Value_StructValue`.
   - `[]interface{}` is converted to `Value_ListValue`.
   - `AsInterface()` recursively unpacks nested structs into `map[string]interface{}` and lists into `[]interface{}`.

6. **Error Handling**:
   - Unsupported types like `chan`, `func`, or unmapped custom structs return non-nil errors.
   - Nested unsupported types within maps or slices fail conversion with an error.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify google.golang.org/protobuf/types/known/structpb.NewValue in pkg:golang/google.golang.org/protobuf@v1.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.28.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/structpb.NewValue
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:52940d2ae8d279fc23e3124200f2b78c9462f3a947574dba64d44f202a53fa90","contract":["structpb.NewValue converts nil to Value_NullValue whose AsInterface() returns nil.","structpb.NewValue converts boolean values to Value_BoolValue and round-trips via AsInterface().","structpb.NewValue converts supported numbers (int, int32, int64, uint, uint32, uint64, float32, float64) to Value_NumberValue with float64 representation, returning errors for unhandled numeric types like int8, int16, uint8, and uint16.","structpb.NewValue converts UTF-8 strings to Value_StringValue and byte slices to base64-encoded Value_StringValue, while returning an error for invalid UTF-8 strings.","structpb.NewValue converts map[string]interface{} and []interface{} into nested StructValue and ListValue respectively and unwraps them via AsInterface().","structpb.NewValue returns an error for unsupported Go types including channels, functions, unmapped structs, and nested unsupported values."],"goal":"verify google.golang.org/protobuf/types/known/structpb.NewValue in pkg:golang/google.golang.org/protobuf@v1.28.0","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.28.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/structpb.NewValue"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.28.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.28.0","symbols":["google.golang.org/protobuf/types/known/structpb.NewValue"],"verifierAdapter":"golang@1"}
go.mod
module example.com/structpbnewvalue

go 1.22

require google.golang.org/protobuf v1.28.0
go.sum
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
newvalue_test.go
package structpbnewvalue_test

import (
	"encoding/base64"
	"math"
	"reflect"
	"testing"

	"google.golang.org/protobuf/types/known/structpb"
)

// TestNewValue_Nil verifies structpb.NewValue(nil) returns a Value with NullValue
// and that AsInterface() returns nil.
func TestNewValue_Nil(t *testing.T) {
	val, err := structpb.NewValue(nil)
	if err != nil {
		t.Fatalf("NewValue(nil) returned unexpected error: %v", err)
	}

	nullKind, ok := val.GetKind().(*structpb.Value_NullValue)
	if !ok {
		t.Fatalf("expected *structpb.Value_NullValue, got %T", val.GetKind())
	}
	if nullKind.NullValue != structpb.NullValue_NULL_VALUE {
		t.Fatalf("expected NullValue_NULL_VALUE, got %v", nullKind.NullValue)
	}

	if got := val.AsInterface(); got != nil {
		t.Fatalf("expected AsInterface() for null value to return nil, got %#v", got)
	}
}

// TestNewValue_Bool verifies structpb.NewValue for booleans produces BoolValue
// and AsInterface() round-trips the boolean value.
func TestNewValue_Bool(t *testing.T) {
	for _, b := range []bool{true, false} {
		val, err := structpb.NewValue(b)
		if err != nil {
			t.Fatalf("NewValue(%v) failed: %v", b, err)
		}

		boolKind, ok := val.GetKind().(*structpb.Value_BoolValue)
		if !ok {
			t.Fatalf("expected *structpb.Value_BoolValue for %v, got %T", b, val.GetKind())
		}
		if boolKind.BoolValue != b {
			t.Fatalf("expected BoolValue %v, got %v", b, boolKind.BoolValue)
		}

		if got := val.AsInterface(); got != b {
			t.Fatalf("expected AsInterface() to return %v, got %v", b, got)
		}
	}
}

// TestNewValue_Numbers verifies structpb.NewValue accepts supported numeric types
// (int, int32, int64, uint, uint32, uint64, float32, float64) storing them as float64 NumberValue,
// while unhandled numeric types (e.g. int8, int16, uint8, uint16) return an error.
func TestNewValue_Numbers(t *testing.T) {
	supportedNumbers := []struct {
		input    interface{}
		expected float64
	}{
		{int(42), 42.0},
		{int32(-32000), -32000.0},
		{int64(640000), 640000.0},
		{uint(100), 100.0},
		{uint32(100000), 100000.0},
		{uint64(200000), 200000.0},
		{float32(3.14), float64(float32(3.14))},
		{float64(2.718281828), 2.718281828},
	}

	for _, tc := range supportedNumbers {
		val, err := structpb.NewValue(tc.input)
		if err != nil {
			t.Fatalf("NewValue(%T(%v)) failed: %v", tc.input, tc.input, err)
		}

		numKind, ok := val.GetKind().(*structpb.Value_NumberValue)
		if !ok {
			t.Fatalf("expected *structpb.Value_NumberValue for %T, got %T", tc.input, val.GetKind())
		}
		if math.Abs(numKind.NumberValue-tc.expected) > 1e-6 {
			t.Fatalf("expected %v, got %v", tc.expected, numKind.NumberValue)
		}

		gotInterface := val.AsInterface()
		if gotFloat, ok := gotInterface.(float64); !ok || math.Abs(gotFloat-tc.expected) > 1e-6 {
			t.Fatalf("expected AsInterface() to return float64 %v, got %v (%T)", tc.expected, gotInterface, gotInterface)
		}
	}

	unsupportedNumbers := []interface{}{int8(1), int16(2), uint8(3), uint16(4)}
	for _, unhandled := range unsupportedNumbers {
		if _, err := structpb.NewValue(unhandled); err == nil {
			t.Fatalf("expected error for unhandled numeric type %T, got nil", unhandled)
		}
	}
}

// TestNewValue_StringAndBytes verifies structpb.NewValue converts strings to StringValue
// and byte slices to base64-encoded StringValue.
func TestNewValue_StringAndBytes(t *testing.T) {
	// String
	strVal, err := structpb.NewValue("sample-text")
	if err != nil {
		t.Fatalf("NewValue(string) failed: %v", err)
	}
	strKind, ok := strVal.GetKind().(*structpb.Value_StringValue)
	if !ok || strKind.StringValue != "sample-text" {
		t.Fatalf("expected StringValue('sample-text'), got %#v", strVal.GetKind())
	}
	if got := strVal.AsInterface(); got != "sample-text" {
		t.Fatalf("expected AsInterface() to return 'sample-text', got %v", got)
	}

	// Bytes (encoded as base64 string)
	rawBytes := []byte("binary data payload")
	bytesVal, err := structpb.NewValue(rawBytes)
	if err != nil {
		t.Fatalf("NewValue([]byte) failed: %v", err)
	}
	bytesKind, ok := bytesVal.GetKind().(*structpb.Value_StringValue)
	expectedB64 := base64.StdEncoding.EncodeToString(rawBytes)
	if !ok || bytesKind.StringValue != expectedB64 {
		t.Fatalf("expected base64 encoded string %q, got %q", expectedB64, bytesKind.StringValue)
	}

	// Invalid UTF-8 string returns error
	invalidUTF8 := string([]byte{0xff, 0xfe, 0xfd})
	if _, err := structpb.NewValue(invalidUTF8); err == nil {
		t.Fatalf("expected error for invalid UTF-8 string, got nil")
	}
}

// TestNewValue_MapsAndSlices verifies structpb.NewValue converts map[string]interface{} into StructValue
// and []interface{} into ListValue, and recursively unpacks them with AsInterface().
func TestNewValue_MapsAndSlices(t *testing.T) {
	inputMap := map[string]interface{}{
		"host": "localhost",
		"port": float64(8080),
		"tags": []interface{}{"web", "secure"},
		"metadata": map[string]interface{}{
			"version": "1.0",
		},
		"enabled": true,
		"extra":   nil,
	}

	val, err := structpb.NewValue(inputMap)
	if err != nil {
		t.Fatalf("NewValue(map) failed: %v", err)
	}

	if _, ok := val.GetKind().(*structpb.Value_StructValue); !ok {
		t.Fatalf("expected StructValue kind, got %T", val.GetKind())
	}

	gotInterface := val.AsInterface()
	if !reflect.DeepEqual(inputMap, gotInterface) {
		t.Fatalf("AsInterface() mismatch:\nwant: %#v\ngot:  %#v", inputMap, gotInterface)
	}

	inputSlice := []interface{}{"alpha", float64(100), false, nil}
	sliceVal, err := structpb.NewValue(inputSlice)
	if err != nil {
		t.Fatalf("NewValue(slice) failed: %v", err)
	}

	if _, ok := sliceVal.GetKind().(*structpb.Value_ListValue); !ok {
		t.Fatalf("expected ListValue kind, got %T", sliceVal.GetKind())
	}

	gotSlice := sliceVal.AsInterface()
	if !reflect.DeepEqual(inputSlice, gotSlice) {
		t.Fatalf("AsInterface() mismatch on slice:\nwant: %#v\ngot:  %#v", inputSlice, gotSlice)
	}
}

// TestNewValue_UnsupportedTypes verifies structpb.NewValue returns an error for unsupported Go types
// such as channels, funcs, unmapped structs, or nested unsupported values.
func TestNewValue_UnsupportedTypes(t *testing.T) {
	// Channels
	ch := make(chan int)
	if _, err := structpb.NewValue(ch); err == nil {
		t.Fatalf("expected error for channel type, got nil")
	}

	// Functions
	fn := func() string { return "fn" }
	if _, err := structpb.NewValue(fn); err == nil {
		t.Fatalf("expected error for function type, got nil")
	}

	// Custom struct without proto mapping
	type custom struct{ Name string }
	if _, err := structpb.NewValue(custom{Name: "custom"}); err == nil {
		t.Fatalf("expected error for unhandled struct type, got nil")
	}

	// Nested unsupported type inside map
	invalidMap := map[string]interface{}{
		"ok":   "valid",
		"fail": ch,
	}
	if _, err := structpb.NewValue(invalidMap); err == nil {
		t.Fatalf("expected error for map containing channel, got nil")
	}

	// Nested unsupported type inside slice
	invalidSlice := []interface{}{"valid", fn}
	if _, err := structpb.NewValue(invalidSlice); err == nil {
		t.Fatalf("expected error for slice containing func, got nil")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/structpb.NewValue in pkg:golang/google.golang.org/protobuf@v1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.28.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/structpb.NewValue"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}

Исходный сидер

аноним