server_randomized_test.go

FindServer / server_randomized_test.go

package main

import (
	"bufio"
	"math/rand"
	"reflect"
	"strings"
	"testing"
	"testing/quick"
)

const alphabet = "abcdefgh"

type term string

func (t term) Generate(rand *rand.Rand, size int) reflect.Value {
	ret := ""
	for i := 0; i != 3; i++ {
		ret += string(alphabet[rand.Int()%len(alphabet)])
	}
	return reflect.ValueOf(term(ret))
}

type word string

func (w word) Generate(rand *rand.Rand, size int) reflect.Value {
	ret := ""
	for i := 0; i != size; i++ {
		ret += string(alphabet[rand.Int()%len(alphabet)])
	}
	return reflect.ValueOf(word(ret))
}

type line []word

func (l line) String() string {
	ret := ""
	for _, word := range l {
		ret += string(word) + " "
	}
	return ret
}

type lines []line

func (l lines) String() string {
	ret := ""
	for _, line := range l {
		ret += string(line.String()) + "\n"
	}
	return ret
}

func naiveSearch(t term, i lines, path Path) SearchResult {
	term := string(t)
	input := i.String()
	s := bufio.NewScanner(strings.NewReader(input))
	locs := Locations{}
	line := Line(0)
	for s.Scan() {
		if strings.Contains(s.Text(), term) {
			locs = append(locs, line)
		}
		line++
	}
	if len(locs) == 0 {
		return SearchResult{}
	}
	ret := SearchResult{
		path: locs,
	}
	return ret
}

func TestRandomized(t *testing.T) {
	path := Path("test")

	naive := func(i lines, t term) SearchResult {
		return naiveSearch(t, i, path)
	}

	real := func(i lines, t term) SearchResult {
		term := string(t)
		input := i.String()
		server := NewServer()
		source := stringSource{path, input}
		server.AddSource(&source)
		results, _ := server.Search(term)
		return results
	}

	if err := quick.CheckEqual(naive, real, nil); err != nil {
		t.Fatal(err)
	}
}