CodeSampleX

샘플

golang.org/x/net v0.47.0: html.Node

검증된 샘플 — golang golang.org/x/net v0.47.0: html.Node. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: html.Parse parses HTML documents into a…

sha256:d640cc7826d846584d9dd12e00733a7951fdb814cc77dcb1b9dd116336bbd624

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-10-10

케이스

HOW
목표
verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0
패키지
심벌
  • golang.org/x/net/html.Node
환경
go
생성일
2026-10-10T19:25:24Z

컨트랙트

  1. html.Parse parses HTML documents into a DocumentNode tree maintaining hierarchical Parent, FirstChild, LastChild, PrevSibling, and NextSibling pointer links.
  2. html.Node DOM manipulation methods (AppendChild, InsertBefore, RemoveChild) update child lists and bidirectional sibling links without breaking existing subtree structures.
  3. html.Node represents HTML elements, text, and comments with accurate NodeType, DataAtom, Data, and slice of Attribute key-value pairs.
  4. html.Render serializes an html.Node tree back to standard HTML matching the in-memory DOM mutations.
  5. html.ParseFragment parses HTML fragments within a specified context element node, returning isolated root nodes suitable for DOM insertion.

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • node_test.go
  • spec.json

소스 아티팩트 내려받기 (tar.gz)

소스

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 golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.47.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/html.Node

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:0179f61480158de28f8eba549b4b13ab904db3bd6bd51ac5f924b0f9dd89d23e","contract":["html.Parse parses HTML documents into a DocumentNode tree maintaining hierarchical Parent, FirstChild, LastChild, PrevSibling, and NextSibling pointer links.","html.Node DOM manipulation methods (AppendChild, InsertBefore, RemoveChild) update child lists and bidirectional sibling links without breaking existing subtree structures.","html.Node represents HTML elements, text, and comments with accurate NodeType, DataAtom, Data, and slice of Attribute key-value pairs.","html.Render serializes an html.Node tree back to standard HTML matching the in-memory DOM mutations.","html.ParseFragment parses HTML fragments within a specified context element node, returning isolated root nodes suitable for DOM insertion."],"goal":"verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.47.0"],"schemaVersion":1,"symbols":["golang.org/x/net/html.Node"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/net@v0.47.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.47.0","symbols":["golang.org/x/net/html.Node"],"verifierAdapter":"golang@1"}
go.mod
module example.com/htmlnode

go 1.24.0

require golang.org/x/net v0.47.0
go.sum
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
node_test.go
package htmlnode

import (
	"bytes"
	"strings"
	"testing"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// Helper function to find a node by element tag name recursively
func findFirstElementByTag(n *html.Node, tag string) *html.Node {
	if n == nil {
		return nil
	}
	if n.Type == html.ElementNode && n.Data == tag {
		return n
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if found := findFirstElementByTag(c, tag); found != nil {
			return found
		}
	}
	return nil
}

// Helper function to get attribute value by key
func getAttr(n *html.Node, key string) (string, bool) {
	for _, attr := range n.Attr {
		if attr.Key == key {
			return attr.Val, true
		}
	}
	return "", false
}

func TestNodeDOMTreeStructureAndTraversal(t *testing.T) {
	rawHTML := `<!DOCTYPE html><html><head><title>Sample Title</title></head><body><div id="container" class="box"><p>First Paragraph</p><p>Second Paragraph</p></div></body></html>`

	doc, err := html.Parse(strings.NewReader(rawHTML))
	if err != nil {
		t.Fatalf("html.Parse failed: %v", err)
	}

	if doc.Type != html.DocumentNode {
		t.Fatalf("expected root node to be DocumentNode, got %v", doc.Type)
	}

	// Verify doctype node
	doctypeNode := doc.FirstChild
	if doctypeNode == nil || doctypeNode.Type != html.DoctypeNode {
		t.Fatalf("expected first child of document to be DoctypeNode")
	}
	if doctypeNode.Data != "html" {
		t.Fatalf("expected doctype data 'html', got '%s'", doctypeNode.Data)
	}

	// Verify html element
	htmlNode := doctypeNode.NextSibling
	if htmlNode == nil || htmlNode.Type != html.ElementNode || htmlNode.Data != "html" {
		t.Fatalf("expected html element after doctype")
	}
	if htmlNode.Parent != doc {
		t.Fatalf("html element parent pointer does not point to root document")
	}

	// Traverse to head and body
	headNode := htmlNode.FirstChild
	if headNode == nil || headNode.Data != "head" {
		t.Fatalf("expected head element as first child of html")
	}
	bodyNode := headNode.NextSibling
	if bodyNode == nil || bodyNode.Data != "body" {
		t.Fatalf("expected body element as next sibling of head")
	}
	if bodyNode.PrevSibling != headNode {
		t.Fatalf("body.PrevSibling must point back to head")
	}

	// Locate container div
	divNode := findFirstElementByTag(doc, "div")
	if divNode == nil {
		t.Fatalf("div element not found in parsed tree")
	}
	if divNode.DataAtom != atom.Div {
		t.Fatalf("expected atom.Div, got %v", divNode.DataAtom)
	}

	// Validate attributes
	if idVal, ok := getAttr(divNode, "id"); !ok || idVal != "container" {
		t.Fatalf("expected id attribute 'container', got '%s' (ok=%v)", idVal, ok)
	}
	if classVal, ok := getAttr(divNode, "class"); !ok || classVal != "box" {
		t.Fatalf("expected class attribute 'box', got '%s' (ok=%v)", classVal, ok)
	}

	// Count child p elements
	var pElements []*html.Node
	for c := divNode.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == html.ElementNode && c.Data == "p" {
			pElements = append(pElements, c)
		}
	}
	if len(pElements) != 2 {
		t.Fatalf("expected 2 paragraph child nodes, got %d", len(pElements))
	}

	// Verify text content in first paragraph
	p1Text := pElements[0].FirstChild
	if p1Text == nil || p1Text.Type != html.TextNode || p1Text.Data != "First Paragraph" {
		t.Fatalf("expected TextNode with 'First Paragraph', got %+v", p1Text)
	}
}

func TestNodeDOMTreeManipulation(t *testing.T) {
	rawHTML := `<div id="root"><span id="first">Item 1</span><span id="last">Item 3</span></div>`
	doc, err := html.Parse(strings.NewReader(rawHTML))
	if err != nil {
		t.Fatalf("html.Parse failed: %v", err)
	}

	rootDiv := findFirstElementByTag(doc, "div")
	if rootDiv == nil {
		t.Fatalf("root div not found")
	}

	lastSpan := findFirstElementByTag(rootDiv, "span")
	for c := rootDiv.FirstChild; c != nil; c = c.NextSibling {
		if idVal, _ := getAttr(c, "id"); idVal == "last" {
			lastSpan = c
			break
		}
	}
	if lastSpan == nil {
		t.Fatalf("lastSpan not found")
	}

	// 1. Test InsertBefore: Insert middle span between first and last
	midSpan := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.Span,
		Data:     "span",
		Attr:     []html.Attribute{{Key: "id", Val: "middle"}},
	}
	midText := &html.Node{
		Type: html.TextNode,
		Data: "Item 2",
	}
	midSpan.AppendChild(midText)

	rootDiv.InsertBefore(midSpan, lastSpan)

	if midSpan.Parent != rootDiv {
		t.Fatalf("midSpan parent must be rootDiv")
	}
	if midSpan.NextSibling != lastSpan {
		t.Fatalf("midSpan.NextSibling must be lastSpan")
	}
	if lastSpan.PrevSibling != midSpan {
		t.Fatalf("lastSpan.PrevSibling must be midSpan")
	}

	// 2. Test AppendChild: Append a new footer paragraph
	footerP := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.P,
		Data:     "p",
		Attr:     []html.Attribute{{Key: "class", Val: "footer"}},
	}
	footerText := &html.Node{
		Type: html.TextNode,
		Data: "Footer Content",
	}
	footerP.AppendChild(footerText)
	rootDiv.AppendChild(footerP)

	if rootDiv.LastChild != footerP {
		t.Fatalf("rootDiv.LastChild must be footerP")
	}
	if footerP.PrevSibling != lastSpan {
		t.Fatalf("footerP.PrevSibling must be lastSpan")
	}

	// 3. Test RemoveChild: Remove the middle span
	rootDiv.RemoveChild(midSpan)
	if midSpan.Parent != nil || midSpan.PrevSibling != nil || midSpan.NextSibling != nil {
		t.Fatalf("midSpan pointers were not cleared on RemoveChild")
	}
	if lastSpan.PrevSibling == midSpan {
		t.Fatalf("lastSpan.PrevSibling should not point to removed midSpan")
	}

	// 4. Render and verify HTML serialization
	var buf bytes.Buffer
	if err := html.Render(&buf, rootDiv); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}

	rendered := buf.String()
	expectedSubstrings := []string{
		`<span id="first">Item 1</span>`,
		`<span id="last">Item 3</span>`,
		`<p class="footer">Footer Content</p>`,
	}
	for _, substr := range expectedSubstrings {
		if !strings.Contains(rendered, substr) {
			t.Errorf("rendered output missing expected substring %q: got %s", substr, rendered)
		}
	}
	if strings.Contains(rendered, "Item 2") {
		t.Errorf("rendered output contains removed item: %s", rendered)
	}
}

func TestNodeParseFragment(t *testing.T) {
	contextNode := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.Tbody,
		Data:     "tbody",
	}

	fragmentHTML := `<tr><td>Cell 1</td><td>Cell 2</td></tr><!-- row end -->`
	nodes, err := html.ParseFragment(strings.NewReader(fragmentHTML), contextNode)
	if err != nil {
		t.Fatalf("html.ParseFragment failed: %v", err)
	}

	if len(nodes) != 2 {
		t.Fatalf("expected 2 root nodes from fragment, got %d", len(nodes))
	}

	trNode := nodes[0]
	if trNode.Type != html.ElementNode || trNode.Data != "tr" {
		t.Fatalf("expected first node to be tr ElementNode, got %+v", trNode)
	}

	commentNode := nodes[1]
	if commentNode.Type != html.CommentNode || commentNode.Data != " row end " {
		t.Fatalf("expected second node to be CommentNode, got %+v", commentNode)
	}

	// Append parsed fragment nodes into contextNode
	for _, n := range nodes {
		contextNode.AppendChild(n)
	}

	if contextNode.FirstChild != trNode {
		t.Fatalf("contextNode.FirstChild must be trNode")
	}
	if contextNode.LastChild != commentNode {
		t.Fatalf("contextNode.LastChild must be commentNode")
	}

	var buf bytes.Buffer
	if err := html.Render(&buf, contextNode); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}
	rendered := buf.String()
	if !strings.Contains(rendered, "<tbody><tr><td>Cell 1</td><td>Cell 2</td></tr><!-- row end --></tbody>") {
		t.Fatalf("unexpected rendered fragment: %s", rendered)
	}
}

func TestNodeAttributeModifications(t *testing.T) {
	node := &html.Node{
		Type:     html.ElementNode,
		DataAtom: atom.A,
		Data:     "a",
		Attr: []html.Attribute{
			{Key: "href", Val: "https://example.com"},
			{Key: "target", Val: "_blank"},
		},
	}

	// Mutate attribute value
	for i := range node.Attr {
		if node.Attr[i].Key == "target" {
			node.Attr[i].Val = "_self"
		}
	}

	// Add new attribute
	node.Attr = append(node.Attr, html.Attribute{Key: "rel", Val: "noopener"})

	var buf bytes.Buffer
	if err := html.Render(&buf, node); err != nil {
		t.Fatalf("html.Render failed: %v", err)
	}

	rendered := buf.String()
	if !strings.Contains(rendered, `target="_self"`) {
		t.Errorf("expected mutated target attribute: %s", rendered)
	}
	if !strings.Contains(rendered, `rel="noopener"`) {
		t.Errorf("expected added rel attribute: %s", rendered)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/html.Node in pkg:golang/golang.org/x/net@v0.47.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.47.0"
  ],
  "symbols": [
    "golang.org/x/net/html.Node"
  ]
}

오리진 시더

익명