package main

import (
	"encoding/json"
	"fmt"
	"os"
	"testing"
)

func printer(i interface{}) string {
	tmp, _ := json.Marshal(i)
	return string(tmp)
}

func TestTokenize(t *testing.T) {

	checker := func(input string, expected ...string) bool {
		output := tokenize(input)

		if len(output) != len(expected) {
			fmt.Fprintf(os.Stderr, "Test failure: got %s expected %s\n", printer(output), printer(expected))
			return false
		}

		for i, _ := range expected {
			if expected[i] != string(output[i]) {
				fmt.Fprintf(os.Stderr, "Test failure: got %s expected %s\n", printer(output), printer(expected))
				return false
			}
		}

		return true
	}

	testtable := [][]string{

		// Whitespace
		{
			"    foo    ",
			"foo",
		},

		// Successive tokens
		{
			"foo bar",
			"foo", "bar",
		},

		// Quote identification
		{
			`foo "bar"`,
			"foo", "bar",
		},

		// Quote merging
		{
			`foo"bar"`,
			"foobar",
		},

		// Single pipe
		{
			"foo | bar",
			"foo", "|", "bar",
		},

		// Double-pipe
		{
			"foo || bar",
			"foo", "||", "bar",
		},

		// Parens, NL conversion
		{
			"( foo | bar ) ; baz | quuz",
			"(", "foo", "|", "bar", ")", "\n", "baz", "|", "quuz",
		},
	}

	for _, test := range testtable {
		if !checker(test[0], test[1:]...) {
			t.Fail()
		}
	}

}
