~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/atirc-ios-client

0
1
main
61 lines · 1.7 KB Raw History
package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestMain(m *testing.M) {
	if d := os.Getenv("CACHEPROG_TEST_SERVE"); d != "" {
		serve(d, os.Stdin, os.Stdout)
		return
	}
	os.Exit(m.Run())
}

// TestRemoteGet serves a one-entry GOCACHE to a client: a hit, a miss, a put.
func TestRemoteGet(t *testing.T) {
	gocache := t.TempDir()
	a, o := strings.Repeat("ab", 32), strings.Repeat("cd", 32)
	os.MkdirAll(filepath.Join(gocache, "ab"), 0o755)
	os.MkdirAll(filepath.Join(gocache, "cd"), 0o755)
	os.WriteFile(filepath.Join(gocache, "ab", a+"-a"), []byte(fmt.Sprintf("v1 %s %s %20d %20d\n", a, o, 5, 42)), 0o644)
	os.WriteFile(filepath.Join(gocache, "cd", o+"-d"), []byte("hello"), 0o644)
	t.Setenv("CACHEPROG_TEST_SERVE", gocache)

	c, err := newClient(t.TempDir(), []string{os.Args[0]})
	if err != nil {
		t.Fatal(err)
	}
	aid, _ := hexBytes(a)
	res := c.get(request{ID: 1, ActionID: aid})
	if res.Miss || res.Size != 5 || res.Time.UnixNano() != 42 {
		t.Fatalf("hit: %+v", res)
	}
	if b, _ := os.ReadFile(res.DiskPath); string(b) != "hello" {
		t.Fatalf("hit body %q", b)
	}
	if res := c.get(request{ID: 2, ActionID: bytes.Repeat([]byte{1}, 32)}); !res.Miss {
		t.Fatalf("miss: %+v", res)
	}
	pid := bytes.Repeat([]byte{2}, 32)
	if res := c.put(request{ID: 3, ActionID: pid, OutputID: pid, BodySize: 2}, []byte("hi")); res.Err != "" {
		t.Fatalf("put: %+v", res)
	}
	if res := c.get(request{ID: 4, ActionID: pid}); res.Miss || res.Size != 2 {
		t.Fatalf("get after put: %+v", res)
	}
	if c.hits != 1 || c.gets != 2 {
		t.Fatalf("hits %d gets %d", c.hits, c.gets)
	}
}

func hexBytes(s string) ([]byte, error) {
	var b []byte
	_, err := fmt.Sscanf(s, "%x", &b)
	return b, err
}