Skip to content
quarry Artifact [788623b8d1]
Login

Artifact [788623b8d1]

Artifact 788623b8d173480c321eae845bb33d782799ce66bf6c4cced1c753d43e1b1f97:


package ingest

import (
	"bytes"
	"log"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/events"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/zitcli"
)

// An index opened from an older schema is rebuilt once. The first
// round's tip check rebuilt it without clearing the stale mark, and the
// next round rebuilt it again (quarry#447).
func TestAStaleIndexIsRebuiltOnce(t *testing.T) {
	_, ix0, repo := testPipeline(t)
	ix0.Close()

	path := filepath.Join(t.TempDir(), "index.db")
	ix, err := index.Open(path)
	if err != nil {
		t.Fatal(err)
	}
	if _, err := ix.RawDB().Exec(`PRAGMA user_version = 4`); err != nil {
		t.Fatal(err)
	}
	ix.Close()
	ix, err = index.Open(path)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ix.Close() })
	if !ix.Stale() {
		t.Fatal("FAIL: the index of an older schema is not stale")
	}
	ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(ev.Close)
	p := NewPipeline(zitcli.New(repo), ev, ix, "test", "n1")

	var buf bytes.Buffer
	log.SetOutput(&buf)
	t.Cleanup(func() { log.SetOutput(os.Stderr) })
	for i := 0; i < 3; i++ {
		if _, err := p.Sync(); err != nil {
			t.Fatal(err)
		}
	}
	if n := strings.Count(buf.String(), "ingest: test: rebuilt "); n != 1 {
		t.Errorf("FAIL: %d rebuilds, want 1\n%s", n, buf.String())
	}
	if ix.Stale() {
		t.Errorf("FAIL: the index is still stale after a rebuild")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}