CodeSampleX

Ejemplo

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

Muestra verificada para golang google.golang.org/protobuf v1.28.0: structpb.NewStruct. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.

sha256:145af0919f2ab55c3c067a6fd76cff1fc9d8dfc44c119f90979e3011f16c256c

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify google.golang.org/protobuf/types/known/structpb.NewStruct in pkg:golang/google.golang.org/protobuf@v1.28.0
Paquetes
Símbolos
  • google.golang.org/protobuf/types/known/structpb.NewStruct
Creado
2026-09-02T06:55:19Z

Contrato

  1. structpb.NewStruct converts Go maps into *structpb.Struct, and Struct.AsMap converts it back to map[string]interface{}, while calling AsMap on a nil receiver safely returns an empty non-nil map.
  2. structpb.NewStruct handles empty maps and nil maps, returning an empty Struct.
  3. structpb.NewStruct recursively converts nested map and slice structures into nested Struct and ListValue messages.
  4. structpb.NewStruct returns an error when passed maps containing unsupported Go types such as channels or functions.
  5. structpb.Struct supports proto binary wire serialization and protojson serialization formatting as a standard JSON object.

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Protocol Buffers structpb.NewStruct Map Conversion

A search for `google.golang.org/protobuf/types/known/structpb.NewStruct` in `google.golang.org/protobuf@v1.28.0` required verification against the target package version.

This sample tests and verifies conversion semantics between dynamic Go maps and Protocol Buffers `Struct` messages using `structpb.NewStruct`.

## Observed Behavior

1. **Map Conversion (`structpb.NewStruct` & `Struct.AsMap`)**:
   - `structpb.NewStruct(map[string]interface{})` converts Go maps to `*structpb.Struct`.
   - `st.AsMap()` extracts the values back into a `map[string]interface{}`.
   - Calling `AsMap()` on a `nil` receiver safely returns an empty non-nil `map[string]interface{}{}` without panicking.
   - `structpb.NewStruct(nil)` and `structpb.NewStruct(map[string]interface{}{})` succeed and return an empty `Struct`.

2. **Recursive Nested Map and Slice Unpacking**:
   - `structpb.NewStruct` recursively converts nested maps and slices into nested `Struct` and `ListValue` protobuf messages, and `AsMap()` roundtrips the structure back to native Go types.

3. **Error Handling on Unsupported Types**:
   - Types that cannot be represented in JSON / protobuf Struct (e.g., channels, functions) return an error when passed in a map to `structpb.NewStruct`.

4. **Serialization & Interoperability**:
   - `structpb.Struct` supports both binary protobuf wire serialization (`proto.Marshal` / `proto.Unmarshal`) and canonical JSON serialization (`protojson.Marshal` / `protojson.Unmarshal`), serializing directly as a standard JSON object.
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.NewStruct 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.NewStruct

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:fe026cc0937c2c79458ba1d21f19cf2caa1eebb308f68402c81f8f7c0b4ee839","contract":["structpb.NewStruct converts Go maps into *structpb.Struct, and Struct.AsMap converts it back to map[string]interface{}, while calling AsMap on a nil receiver safely returns an empty non-nil map.","structpb.NewStruct handles empty maps and nil maps, returning an empty Struct.","structpb.NewStruct recursively converts nested map and slice structures into nested Struct and ListValue messages.","structpb.NewStruct returns an error when passed maps containing unsupported Go types such as channels or functions.","structpb.Struct supports proto binary wire serialization and protojson serialization formatting as a standard JSON object."],"goal":"verify google.golang.org/protobuf/types/known/structpb.NewStruct 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.NewStruct"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"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.NewStruct"],"verifierAdapter":"golang@1"}
go.mod
module example.com/structpbdemo

go 1.23

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=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
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=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/structpb.NewStruct 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.NewStruct"
  ]
}
structpb_test.go
package structpbdemo_test

import (
	"reflect"
	"testing"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/structpb"
)

// TestStructPBNewStructMapConversion verifies structpb.NewStruct converts Go maps to *structpb.Struct
// and Struct.AsMap converts it back to map[string]interface{}.
func TestStructPBNewStructMapConversion(t *testing.T) {
	inputMap := map[string]interface{}{
		"name":    "service-config",
		"port":    float64(8080),
		"enabled": true,
		"tags":    []interface{}{"api", "gateway"},
		"extra":   nil,
	}

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

	if st.Fields == nil {
		t.Fatalf("expected non-nil Fields in Struct")
	}

	if nameVal := st.Fields["name"].GetStringValue(); nameVal != "service-config" {
		t.Errorf("expected name to be 'service-config', got %q", nameVal)
	}
	if portVal := st.Fields["port"].GetNumberValue(); portVal != 8080 {
		t.Errorf("expected port to be 8080, got %v", portVal)
	}
	if enabledVal := st.Fields["enabled"].GetBoolValue(); !enabledVal {
		t.Errorf("expected enabled to be true, got %v", enabledVal)
	}

	outputMap := st.AsMap()
	if !reflect.DeepEqual(inputMap, outputMap) {
		t.Fatalf("AsMap() mismatch:\nwant: %#v\ngot:  %#v", inputMap, outputMap)
	}
}

// TestStructPBNewStructNilAndEmpty verifies structpb.NewStruct behavior on nil and empty maps,
// as well as nil receiver safety for AsMap.
func TestStructPBNewStructNilAndEmpty(t *testing.T) {
	// Empty struct from nil map
	emptyStruct, err := structpb.NewStruct(nil)
	if err != nil {
		t.Fatalf("NewStruct(nil) failed: %v", err)
	}
	if len(emptyStruct.AsMap()) != 0 {
		t.Fatalf("expected empty map for NewStruct(nil), got %#v", emptyStruct.AsMap())
	}

	// Empty struct from empty map
	emptyMapStruct, err := structpb.NewStruct(map[string]interface{}{})
	if err != nil {
		t.Fatalf("NewStruct(empty) failed: %v", err)
	}
	if len(emptyMapStruct.AsMap()) != 0 {
		t.Fatalf("expected empty map for NewStruct(empty), got %#v", emptyMapStruct.AsMap())
	}

	// Nil struct safety: calling AsMap() on nil receiver safely returns empty map (not nil)
	var nilStruct *structpb.Struct
	if got := nilStruct.AsMap(); got == nil || len(got) != 0 {
		t.Fatalf("expected nilStruct.AsMap() to return empty non-nil map, got %#v", got)
	}
}

// TestStructPBNewStructNestedData verifies nested struct and list value conversions via structpb.NewStruct.
func TestStructPBNewStructNestedData(t *testing.T) {
	nestedData := map[string]interface{}{
		"service": "payments",
		"config": map[string]interface{}{
			"retries": float64(5),
			"debug":   false,
		},
		"endpoints": []interface{}{
			"https://example.com/v1",
			"https://example.com/v2",
		},
	}

	st, err := structpb.NewStruct(nestedData)
	if err != nil {
		t.Fatalf("NewStruct(nestedData) failed: %v", err)
	}

	outputMap := st.AsMap()
	if !reflect.DeepEqual(nestedData, outputMap) {
		t.Fatalf("AsMap() mismatch on nested data:\nwant: %#v\ngot:  %#v", nestedData, outputMap)
	}
}

// TestStructPBNewStructUnsupportedTypesError verifies structpb.NewStruct returns an error
// when given maps containing unsupported Go types (e.g. channels, funcs).
func TestStructPBNewStructUnsupportedTypesError(t *testing.T) {
	ch := make(chan int)
	invalidMap := map[string]interface{}{
		"invalid_chan": ch,
	}
	if _, err := structpb.NewStruct(invalidMap); err == nil {
		t.Fatalf("expected error when calling NewStruct with channel value, got nil")
	}

	fn := func() {}
	invalidMapFn := map[string]interface{}{
		"invalid_fn": fn,
	}
	if _, err := structpb.NewStruct(invalidMapFn); err == nil {
		t.Fatalf("expected error when calling NewStruct with func value, got nil")
	}
}

// TestStructPBNewStructProtoAndJSONSerialization verifies proto wire and JSON serialization of structpb.Struct.
func TestStructPBNewStructProtoAndJSONSerialization(t *testing.T) {
	data := map[string]interface{}{
		"env":     "production",
		"retries": float64(3),
		"verbose": false,
	}

	st, err := structpb.NewStruct(data)
	if err != nil {
		t.Fatalf("NewStruct failed: %v", err)
	}

	// 1. Proto wire serialization
	wireBytes, err := proto.Marshal(st)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}

	unmarshaledSt := &structpb.Struct{}
	if err := proto.Unmarshal(wireBytes, unmarshaledSt); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}

	if !proto.Equal(st, unmarshaledSt) {
		t.Fatalf("proto.Unmarshal result differs from original")
	}

	// 2. protojson serialization produces canonical JSON representation
	jsonBytes, err := protojson.Marshal(st)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}

	jsonSt := &structpb.Struct{}
	if err := protojson.Unmarshal(jsonBytes, jsonSt); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}

	if !proto.Equal(st, jsonSt) {
		t.Fatalf("protojson roundtrip mismatch")
	}
}

Seeder de origen

anónimo