<commit_before>package fval_test

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/walle/fval"
)

func TestFileExists(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Create(path)

	if !fval.FileExists(path) {
		t.Errorf("Did not indicate that existing file %s exists", path)
	}

	os.Remove(path)

	if fval.FileExists(path) {
		t.Errorf("Did indicate that non existing file %s exists", path)
	}

	os.Mkdir(path, 0766)

	if fval.FileExists(path) {
		t.Errorf("Did indicate that directory %s is a file", path)
	}
}

func TestDirExists(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0766)

	if !fval.DirExists(path) {
		t.Errorf("Did not indicate that existing directory %s exists", path)
	}

	os.Remove(path)

	if fval.DirExists(path) {
		t.Errorf("Did indicate that non existing directory %s exists", path)
	}

	os.Create(path)

	if fval.DirExists(path) {
		t.Errorf("Did indicate that file %s is a directory", path)
	}
}

func TestFileOrDirExists(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	fpath := filepath.Join(tmpDir, "test.txt")
	dpath := filepath.Join(tmpDir, "test")
	os.Create(fpath)
	os.Mkdir(dpath, 0766)

	if !fval.Exists(fpath) {
		t.Errorf("Did not indicate that existing file %s exists", fpath)
	}
	if !fval.Exists(dpath) {
		t.Errorf("Did not indicate that existing directory %s exists", dpath)
	}

	os.Remove(fpath)
	os.Remove(dpath)

	if fval.FileExists(fpath) {
		t.Errorf("Did indicate that non existing file %s exists", fpath)
	}
	if fval.FileExists(dpath) {
		t.Errorf("Did indicate that non existing directory %s exists", dpath)
	}
}

func TestDirExistsOrCreate(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test1", "test2", "test3")

	ok, err := fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error creating dir: %s", err)
	}
	if !ok {
		t.Errorf("Directory was not created")
	}
	ok, err = fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error: %s", err)
	}
	if !ok {
		t.Errorf("Directory did not exist")
	}

	os.Remove(path)

	if fval.DirExists(path) {
		t.Errorf("Directory %s should not exist", path)
	}

	ok, err = fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error creating dir: %s", err)
	}
	if !ok {
		t.Errorf("Directory was not created")
	}
	if !fval.DirExists(path) {
		t.Errorf("Directory %s was not created", path)
	}
}

func TestDirExistsOrCreateError(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0400)
	path = filepath.Join(path, "test2")
	ok, err := fval.DirExistsOrCreate(path, 0766)

	if ok {
		t.Errorf("Directory should not have been created")
	}
	if err == nil {
		t.Errorf("Error should not have been nil")
	}
}

func TestDirPurgeAndCreate(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0766)
	fpath := filepath.Join(path, "test2")
	os.Create(fpath)
	if !fval.FileExists(fpath) {
		t.Errorf("File %s does not exist", fpath)
	}
	ok, err := fval.DirPurgeAndCreate(path, 0766)
	if !ok {
		t.Errorf("Directory %s was not deleted and created", path)
	}
	if err != nil {
		t.Errorf("Error occured %s", err)
	}
	if fval.FileExists(fpath) {
		t.Errorf("File %s exist", fpath)
	}
}

func TestDirPurgeAndCreateNoDir(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	ok, err := fval.DirPurgeAndCreate(path, 0766)
	if ok {
		t.Errorf("Should not get ok")
	}
	if err == nil {
		t.Errorf("Should not get no error")
	}
	if fval.DirExists(path) {
		t.Errorf("Directory %s should not exist", path)
	}
}

func TestDirPurgeAndCreateError(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "go-arg-test")
	if err != nil {
		t.Errorf("TempDir error")
		return
	}
	defer os.RemoveAll(tmpDir)

	// Use same way of testing error to os.RemoveAll as stdlib

	// Determine if we should run the following test.
	testit := true
	if runtime.GOOS == "windows" {
		// Chmod is not supported under windows.
		testit = false
	} else {
		// Test fails as root.
		testit = os.Getuid() != 0
	}
	if testit {
		path := filepath.Join(tmpDir, "test")
		fpath := filepath.Join(path, ".file")
		os.Mkdir(path, 0766)
		os.Create(fpath)

		if err = os.Chmod(path, 0); err != nil {
			t.Fatalf("Chmod %q 0: %s", path, err)
		}

		ok, err := fval.DirPurgeAndCreate(path, 0766)
		if ok {
			t.Errorf("Directory should not have been created")
		}
		if err == nil {
			t.Errorf("Error should not have been nil")
		}
		if fval.FileExists(fpath) {
			t.Errorf("File %s should not exist", fpath)
		}
	}
}
<commit_msg>Clean up tests<commit_after>package fval_test

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/walle/fval"
)

func TestFileExists(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Create(path)

	if !fval.FileExists(path) {
		t.Errorf("Did not indicate that existing file %s exists", path)
	}

	os.Remove(path)

	if fval.FileExists(path) {
		t.Errorf("Did indicate that non existing file %s exists", path)
	}

	os.Mkdir(path, 0766)

	if fval.FileExists(path) {
		t.Errorf("Did indicate that directory %s is a file", path)
	}
}

func TestDirExists(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0766)

	if !fval.DirExists(path) {
		t.Errorf("Did not indicate that existing directory %s exists", path)
	}

	os.Remove(path)

	if fval.DirExists(path) {
		t.Errorf("Did indicate that non existing directory %s exists", path)
	}

	os.Create(path)

	if fval.DirExists(path) {
		t.Errorf("Did indicate that file %s is a directory", path)
	}
}

func TestFileOrDirExists(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	fpath := filepath.Join(tmpDir, "test.txt")
	dpath := filepath.Join(tmpDir, "test")
	os.Create(fpath)
	os.Mkdir(dpath, 0766)

	if !fval.Exists(fpath) {
		t.Errorf("Did not indicate that existing file %s exists", fpath)
	}
	if !fval.Exists(dpath) {
		t.Errorf("Did not indicate that existing directory %s exists", dpath)
	}

	os.Remove(fpath)
	os.Remove(dpath)

	if fval.FileExists(fpath) {
		t.Errorf("Did indicate that non existing file %s exists", fpath)
	}
	if fval.FileExists(dpath) {
		t.Errorf("Did indicate that non existing directory %s exists", dpath)
	}
}

func TestDirExistsOrCreate(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test1", "test2", "test3")

	ok, err := fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error creating dir: %s", err)
	}
	if !ok {
		t.Errorf("Directory was not created")
	}
	ok, err = fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error: %s", err)
	}
	if !ok {
		t.Errorf("Directory did not exist")
	}

	os.Remove(path)

	if fval.DirExists(path) {
		t.Errorf("Directory %s should not exist", path)
	}

	ok, err = fval.DirExistsOrCreate(path, 0766)
	if err != nil {
		t.Errorf("Error creating dir: %s", err)
	}
	if !ok {
		t.Errorf("Directory was not created")
	}
	if !fval.DirExists(path) {
		t.Errorf("Directory %s was not created", path)
	}
}

func TestDirExistsOrCreateError(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0400)
	path = filepath.Join(path, "test2")
	ok, err := fval.DirExistsOrCreate(path, 0766)

	if ok {
		t.Errorf("Directory should not have been created")
	}
	if err == nil {
		t.Errorf("Error should not have been nil")
	}
}

func TestDirPurgeAndCreate(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	os.Mkdir(path, 0766)
	fpath := filepath.Join(path, "test2")
	os.Create(fpath)
	if !fval.FileExists(fpath) {
		t.Errorf("File %s does not exist", fpath)
	}
	ok, err := fval.DirPurgeAndCreate(path, 0766)
	if !ok {
		t.Errorf("Directory %s was not deleted and created", path)
	}
	if err != nil {
		t.Errorf("Error occured %s", err)
	}
	if fval.FileExists(fpath) {
		t.Errorf("File %s exist", fpath)
	}
}

func TestDirPurgeAndCreateNoDir(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	path := filepath.Join(tmpDir, "test")
	ok, err := fval.DirPurgeAndCreate(path, 0766)
	if ok {
		t.Errorf("Should not get ok")
	}
	if err == nil {
		t.Errorf("Should not get no error")
	}
	if fval.DirExists(path) {
		t.Errorf("Directory %s should not exist", path)
	}
}

func TestDirPurgeAndCreateError(t *testing.T) {
	tmpDir := createTmpDir(t)
	defer os.RemoveAll(tmpDir)

	// Use same way of testing error to os.RemoveAll as stdlib

	// Determine if we should run the following test.
	testit := true
	if runtime.GOOS == "windows" {
		// Chmod is not supported under windows.
		testit = false
	} else {
		// Test fails as root.
		testit = os.Getuid() != 0
	}
	if testit {
		path := filepath.Join(tmpDir, "test")
		fpath := filepath.Join(path, ".file")
		os.Mkdir(path, 0766)
		os.Create(fpath)

		if err := os.Chmod(path, 0); err != nil {
			t.Fatalf("Chmod %q 0: %s", path, err)
		}

		ok, err := fval.DirPurgeAndCreate(path, 0766)
		if ok {
			t.Errorf("Directory should not have been created")
		}
		if err == nil {
			t.Errorf("Error should not have been nil")
		}
		if fval.FileExists(fpath) {
			t.Errorf("File %s should not exist", fpath)
		}
	}
}

func createTmpDir(t *testing.T) string {
	tmpDir, err := ioutil.TempDir("", "fval-test")
	if err != nil {
		t.Fatalf("TempDir error: %s", err)
	}
	return tmpDir
}
<|endoftext|>


<commit_before>package game

import (
	"bytes"
	"fmt"
	"io"
	"math/rand"
	"os"
	"sync"
	"time"

	"github.com/arenaio/arenaio/game/bot"
)

type Game interface {
	GetConfiguration() Properties
	GetInitInputForPlayer(playerIdx int) []string
	Prepare(round int)
	GetInputForPlayer(round int, playerIdx int) []string
	GetExpectedOutputLineCountForPlayer(playerIdx int) int
	HandlePlayerOutput(frame int, round int, playerIdx int, outputs []string)
	UpdateGame(round int)
	PopulateMessages(p Properties)
	GetGameName() string
	GetMinimumPlayerCount() int
	GetPlayerActions(playerIdx int, round int) []string
	IsPlayerDead(playerIdx int) bool
	GetDeathReason(playerIdx int) string
	GetScore(playerIdx int) int
	SetPlayerTimeout(frame int, round int, playerIdx int)
	GetMaxRoundCount(playerCount int) int
	GetMillisTimeForRound() int
	GetMillisTimeForFirstRound() int
	InitReferee(playerCount int, prop Properties)
	GetFrameDataForView(round int, frame int, keyFrame bool) []string
	GetInitDataForView() []string
}

func Run(g Game, botBinaries []string) (int, error) {
	botCount := len(botBinaries)

	// initialize bots
	bots := make(map[int]*bot.Process, botCount)
	for i := 0; i < botCount; i++ {
		bot, err := bot.NewProcess(botBinaries[i], i)
		if err != nil {
			return -1, err
		}
		bots[i] = bot
	}

	// shuffle bot positions
	for i := botCount - 1; i > 0; i-- {
		j := rand.Int() % (i + 1)
		bots[i], bots[j] = bots[j], bots[i]
	}

	winner := -1
	buffer := &bytes.Buffer{}
	for round := 1; round <= g.GetMaxRoundCount(botCount); round++ {
		firstRound := round == 1

		for b := 0; b < botCount; b++ {
			lines := make([]string, 0)
			if firstRound {
				lines = g.GetInitInputForPlayer(b)
			}
			lines = append(lines, g.GetInputForPlayer(round, b))

			for _, line := range lines {
				buffer.WriteString(line)
			}

			n, err := buffer.WriteTo(bots[b])
			fmt.Fprintf(os.Stderr, "Debug: %d bytes written to bot %d\n", n, b)
			if err != nil {
				return -1, err
			}
			buffer.Reset()

			wg := sync.WaitGroup{}
			wg.Add(1)
			go func() {
				waitFor := 50 * time.Millisecond
				if firstRound {
					waitFor = 100 * time.Millisecond
				}
				time.Sleep(waitFor)
				wg.Done()
			}()
			wg.Wait()

			n, err = buffer.ReadFrom(bots[b])
			fmt.Fprintf(os.Stderr, "Debug: Read %d bytes from bot %d\n", n, b)
			if err != nil {
				return -1, err
			}

			lines = make([]string, 0)
			for {
				line, err := buffer.ReadString('\n')
				if err == io.EOF {
					break
				}
				lines = append(lines, line)
			}
			// describe frame?
			g.HandlePlayerOutput(0, round, b, lines)
			buffer.Reset()
		}

		// TODO: update gme & check end state
		g.UpdateGame(round)
	}

	// TODO: evaluate winner
	winner = rand.Int()%(len(botBinaries)+1) - 1

	// no mapping required for draw games
	if winner == -1 {
		return winner, nil
	}

	// map winner index id to bot index
	return bots[winner].Idx(), nil
}
<commit_msg>added missing strings join<commit_after>package game

import (
	"bytes"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/arenaio/arenaio/game/bot"
)

type Game interface {
	GetConfiguration() Properties
	GetInitInputForPlayer(playerIdx int) []string
	Prepare(round int)
	GetInputForPlayer(round int, playerIdx int) []string
	GetExpectedOutputLineCountForPlayer(playerIdx int) int
	HandlePlayerOutput(frame int, round int, playerIdx int, outputs []string)
	UpdateGame(round int)
	PopulateMessages(p Properties)
	GetGameName() string
	GetMinimumPlayerCount() int
	GetPlayerActions(playerIdx int, round int) []string
	IsPlayerDead(playerIdx int) bool
	GetDeathReason(playerIdx int) string
	GetScore(playerIdx int) int
	SetPlayerTimeout(frame int, round int, playerIdx int)
	GetMaxRoundCount(playerCount int) int
	GetMillisTimeForRound() int
	GetMillisTimeForFirstRound() int
	InitReferee(playerCount int, prop Properties)
	GetFrameDataForView(round int, frame int, keyFrame bool) []string
	GetInitDataForView() []string
}

func Run(g Game, botBinaries []string) (int, error) {
	botCount := len(botBinaries)

	// initialize bots
	bots := make(map[int]*bot.Process, botCount)
	for i := 0; i < botCount; i++ {
		bot, err := bot.NewProcess(botBinaries[i], i)
		if err != nil {
			return -1, err
		}
		bots[i] = bot
	}

	// shuffle bot positions
	for i := botCount - 1; i > 0; i-- {
		j := rand.Int() % (i + 1)
		bots[i], bots[j] = bots[j], bots[i]
	}

	winner := -1
	buffer := &bytes.Buffer{}
	for round := 1; round <= g.GetMaxRoundCount(botCount); round++ {
		firstRound := round == 1

		for b := 0; b < botCount; b++ {
			lines := make([]string, 0)
			if firstRound {
				lines = g.GetInitInputForPlayer(b)
			}
			lines = append(lines, strings.Join(g.GetInputForPlayer(round, b), "\n"))

			for _, line := range lines {
				buffer.WriteString(line)
			}

			n, err := buffer.WriteTo(bots[b])
			fmt.Fprintf(os.Stderr, "Debug: %d bytes written to bot %d\n", n, b)
			if err != nil {
				return -1, err
			}
			buffer.Reset()

			wg := sync.WaitGroup{}
			wg.Add(1)
			go func() {
				waitFor := 50 * time.Millisecond
				if firstRound {
					waitFor = 100 * time.Millisecond
				}
				time.Sleep(waitFor)
				wg.Done()
			}()
			wg.Wait()

			n, err = buffer.ReadFrom(bots[b])
			fmt.Fprintf(os.Stderr, "Debug: Read %d bytes from bot %d\n", n, b)
			if err != nil {
				return -1, err
			}

			lines = make([]string, 0)
			for {
				line, err := buffer.ReadString('\n')
				if err == io.EOF {
					break
				}
				lines = append(lines, line)
			}
			// describe frame?
			g.HandlePlayerOutput(0, round, b, lines)
			buffer.Reset()
		}

		// TODO: update gme & check end state
		g.UpdateGame(round)
	}

	// TODO: evaluate winner
	winner = rand.Int()%(len(botBinaries)+1) - 1

	// no mapping required for draw games
	if winner == -1 {
		return winner, nil
	}

	// map winner index id to bot index
	return bots[winner].Idx(), nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	"github.com/gedex/inflector"
)

const templateDir = "_templates"

var funcMap = template.FuncMap{
	"apibDefaultValue": apibDefaultValue,
	"apibType":         apibType,
	"pluralize":        inflector.Pluralize,
	"requestParams":    requestParams,
	"tolower":          strings.ToLower,
	"title":            strings.Title,
}

var skeletons = []string{
	"README.md.tmpl",
	".gitignore.tmpl",
	"main.go.tmpl",
	filepath.Join("db", "db.go.tmpl"),
	filepath.Join("db", "pagination.go.tmpl"),
	filepath.Join("router", "router.go.tmpl"),
	filepath.Join("middleware", "set_db.go.tmpl"),
	filepath.Join("server", "server.go.tmpl"),
	filepath.Join("helper", "field.go.tmpl"),
	filepath.Join("version", "version.go.tmpl"),
	filepath.Join("version", "version_test.go.tmpl"),
	filepath.Join("controllers", ".gitkeep.tmpl"),
	filepath.Join("docs", ".gitkeep.tmpl"),
	filepath.Join("models", ".gitkeep.tmpl"),
}

var managedFields = []string{
	"ID",
	"CreatedAt",
	"UpdatedAt",
}

func apibDefaultValue(field *Field) string {
	switch field.Type {
	case "bool":
		return "false"
	case "string":
		return strings.ToUpper(field.Name)
	case "*time.Time":
		return "`2000-01-01 00:00:00`"
	case "uint":
		return "1"
	}

	return ""
}

func apibType(field *Field) string {
	switch field.Type {
	case "bool":
		return "boolean"
	case "string":
		return "string"
	case "*time.Time":
		return "string"
	case "uint":
		return "number"
	}

	switch field.Association.Type {
	case AssociationBelongsTo:
	case AssociationHasMany:
		return fmt.Sprintf("array[%s]", inflector.Pluralize(strings.ToLower(strings.Replace(field.Type, "[]", "", -1))))
	case AssociationHasOne:
		return inflector.Pluralize(strings.ToLower(strings.Replace(field.Type, "*", "", -1)))
	}

	return ""
}

func requestParams(fields []*Field) []*Field {
	var managed bool

	params := []*Field{}

	for _, field := range fields {
		managed = false

		for _, name := range managedFields {
			if field.Name == name {
				managed = true
			}
		}

		if !managed {
			params = append(params, field)
		}
	}

	return params
}

func generateApibIndex(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "index.apib.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("apib").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "docs", "index.apib")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateApibModel(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "model.apib.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("apib").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "docs", strings.ToLower(detail.Model.Name)+".apib")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateSkeleton(detail *Detail, outDir string) error {
	if fileExists(outDir) {
		fmt.Fprintf(os.Stderr, "%s is already exists", outDir)
		os.Exit(1)
	}

	for _, filename := range skeletons {
		srcPath := filepath.Join(templateDir, "skeleton", filename)
		dstPath := filepath.Join(outDir, strings.Replace(filename, ".tmpl", "", 1))

		body, err := Asset(srcPath)

		if err != nil {
			return err
		}

		tmpl, err := template.New("complex").Parse(string(body))

		if err != nil {
			return err
		}

		var buf bytes.Buffer

		if err := tmpl.Execute(&buf, detail); err != nil {
			return err
		}

		if !fileExists(filepath.Dir(dstPath)) {
			if err := mkdir(filepath.Dir(dstPath)); err != nil {
				return err
			}
		}

		if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
			return err
		}

		fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)
	}

	return nil
}

func generateController(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "controller.go.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("controller").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "controllers", strings.ToLower(detail.Model.Name)+".go")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateREADME(models []*Model, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "README.md.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("readme").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, models); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "README.md")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "update", dstPath)

	return nil
}

func generateRouter(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "router.go.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("router").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "router", "router.go")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "update", dstPath)

	return nil
}
<commit_msg>Include belongs_to field<commit_after>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	"github.com/gedex/inflector"
)

const templateDir = "_templates"

var funcMap = template.FuncMap{
	"apibDefaultValue": apibDefaultValue,
	"apibType":         apibType,
	"pluralize":        inflector.Pluralize,
	"requestParams":    requestParams,
	"tolower":          strings.ToLower,
	"title":            strings.Title,
}

var skeletons = []string{
	"README.md.tmpl",
	".gitignore.tmpl",
	"main.go.tmpl",
	filepath.Join("db", "db.go.tmpl"),
	filepath.Join("db", "pagination.go.tmpl"),
	filepath.Join("router", "router.go.tmpl"),
	filepath.Join("middleware", "set_db.go.tmpl"),
	filepath.Join("server", "server.go.tmpl"),
	filepath.Join("helper", "field.go.tmpl"),
	filepath.Join("version", "version.go.tmpl"),
	filepath.Join("version", "version_test.go.tmpl"),
	filepath.Join("controllers", ".gitkeep.tmpl"),
	filepath.Join("docs", ".gitkeep.tmpl"),
	filepath.Join("models", ".gitkeep.tmpl"),
}

var managedFields = []string{
	"ID",
	"CreatedAt",
	"UpdatedAt",
}

func apibDefaultValue(field *Field) string {
	switch field.Type {
	case "bool":
		return "false"
	case "string":
		return strings.ToUpper(field.Name)
	case "*time.Time":
		return "`2000-01-01 00:00:00`"
	case "uint":
		return "1"
	}

	return ""
}

func apibType(field *Field) string {
	switch field.Type {
	case "bool":
		return "boolean"
	case "string":
		return "string"
	case "*time.Time":
		return "string"
	case "uint":
		return "number"
	}

	switch field.Association.Type {
	case AssociationBelongsTo:
		return inflector.Pluralize(strings.ToLower(strings.Replace(field.Type, "*", "", -1)))
	case AssociationHasMany:
		return fmt.Sprintf("array[%s]", inflector.Pluralize(strings.ToLower(strings.Replace(field.Type, "[]", "", -1))))
	case AssociationHasOne:
		return inflector.Pluralize(strings.ToLower(strings.Replace(field.Type, "*", "", -1)))
	}

	return ""
}

func requestParams(fields []*Field) []*Field {
	var managed bool

	params := []*Field{}

	for _, field := range fields {
		managed = false

		for _, name := range managedFields {
			if field.Name == name {
				managed = true
			}
		}

		if !managed {
			params = append(params, field)
		}
	}

	return params
}

func generateApibIndex(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "index.apib.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("apib").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "docs", "index.apib")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateApibModel(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "model.apib.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("apib").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "docs", strings.ToLower(detail.Model.Name)+".apib")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateSkeleton(detail *Detail, outDir string) error {
	if fileExists(outDir) {
		fmt.Fprintf(os.Stderr, "%s is already exists", outDir)
		os.Exit(1)
	}

	for _, filename := range skeletons {
		srcPath := filepath.Join(templateDir, "skeleton", filename)
		dstPath := filepath.Join(outDir, strings.Replace(filename, ".tmpl", "", 1))

		body, err := Asset(srcPath)

		if err != nil {
			return err
		}

		tmpl, err := template.New("complex").Parse(string(body))

		if err != nil {
			return err
		}

		var buf bytes.Buffer

		if err := tmpl.Execute(&buf, detail); err != nil {
			return err
		}

		if !fileExists(filepath.Dir(dstPath)) {
			if err := mkdir(filepath.Dir(dstPath)); err != nil {
				return err
			}
		}

		if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
			return err
		}

		fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)
	}

	return nil
}

func generateController(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "controller.go.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("controller").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "controllers", strings.ToLower(detail.Model.Name)+".go")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)

	return nil
}

func generateREADME(models []*Model, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "README.md.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("readme").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, models); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "README.md")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "update", dstPath)

	return nil
}

func generateRouter(detail *Detail, outDir string) error {
	body, err := Asset(filepath.Join(templateDir, "router.go.tmpl"))

	if err != nil {
		return err
	}

	tmpl, err := template.New("router").Funcs(funcMap).Parse(string(body))

	if err != nil {
		return err
	}

	var buf bytes.Buffer

	if err := tmpl.Execute(&buf, detail); err != nil {
		return err
	}

	dstPath := filepath.Join(outDir, "router", "router.go")

	if !fileExists(filepath.Dir(dstPath)) {
		if err := mkdir(filepath.Dir(dstPath)); err != nil {
			return err
		}
	}

	if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	fmt.Fprintf(os.Stdout, "\t\x1b[32m%s\x1b[0m %s\n", "update", dstPath)

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"html/template"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

func GeneratorHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		t, err := template.ParseFiles("templates/generator.html")

		if err != nil {
			log.Println("Failed to parse files")
		}
		t.Execute(w, nil)

	case "POST":
		if err := r.ParseForm(); err != nil {
			log.Println("Failed to get post values")
		}

		rawText := r.PostFormValue("desc")
		titleField := ParseTitle(rawText)
		dateField := ParseDate(rawText)
		//desc := blackfriday.MarkdownCommon([]byte(rawText))

		docId, err := pageCol.Insert(map[string]interface{}{
			"title": titleField,
			"desc":  rawText,
			"date":  dateField,
		})

		if err != nil {
			log.Println(err)
		}
		http.Redirect(w, r, "/p/"+strconv.Itoa(docId), http.StatusFound)
	default:
		http.Error(w, "Method not allowed", 405)

	}
}

func ParseDate(sample string) time.Time {
	datePattern, err := regexp.Compile(`(\d{1,2}\b\D{3,9}\b\d{4})|([a-zA-Z]{3,9}\s\d{1,2}\s\d{4})`)

	if err != nil {
		panic(err)
	}

	colloquialPattern, err := regexp.Compile(`(\d{1,2}\b\D{3,9}\b\d{4})`)

	if err != nil {
		panic(err)
	}

	americanPattern, err := regexp.Compile(`([a-zA-Z]{3,9}\s\d{1,2}\s\d{4})`)
	if err != nil {
		panic(err)
	}
	var t time.Time
	dateString := datePattern.FindString(sample)
	switch {
	case americanPattern.MatchString(dateString):
		t, _ = time.Parse("January 2 2006", datePattern.FindString(sample))

	case colloquialPattern.MatchString(dateString):
		t, _ = time.Parse("2 January 2006", datePattern.FindString(sample))
	}
	return t
}

func ParseTitle(sample string) (title string) {
 titlePattern, err := regexp.Compile(`^(#\s).*`)

 if err != nil {
 	panic(err)
 }

 title = titlePattern.FindString(sample)

 return title

}
<commit_msg>removed extra bang symbol from title generated<commit_after>package main

import (
	"html/template"
	"log"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

func GeneratorHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		t, err := template.ParseFiles("templates/generator.html")

		if err != nil {
			log.Println("Failed to parse files")
		}
		t.Execute(w, nil)

	case "POST":
		if err := r.ParseForm(); err != nil {
			log.Println("Failed to get post values")
		}

		rawText := r.PostFormValue("desc")
		titleField := ParseTitle(rawText)
		dateField := ParseDate(rawText)
		//desc := blackfriday.MarkdownCommon([]byte(rawText))

		docId, err := pageCol.Insert(map[string]interface{}{
			"title": titleField,
			"desc":  rawText,
			"date":  dateField,
		})

		if err != nil {
			log.Println(err)
		}
		http.Redirect(w, r, "/p/"+strconv.Itoa(docId), http.StatusFound)
	default:
		http.Error(w, "Method not allowed", 405)

	}
}

func ParseDate(sample string) time.Time {
	datePattern, err := regexp.Compile(`(\d{1,2}\b\D{3,9}\b\d{4})|([a-zA-Z]{3,9}\s\d{1,2}\s\d{4})`)

	if err != nil {
		panic(err)
	}

	colloquialPattern, err := regexp.Compile(`(\d{1,2}\b\D{3,9}\b\d{4})`)

	if err != nil {
		panic(err)
	}

	americanPattern, err := regexp.Compile(`([a-zA-Z]{3,9}\s\d{1,2}\s\d{4})`)
	if err != nil {
		panic(err)
	}
	var t time.Time
	dateString := datePattern.FindString(sample)
	switch {
	case americanPattern.MatchString(dateString):
		t, _ = time.Parse("January 2 2006", datePattern.FindString(sample))

	case colloquialPattern.MatchString(dateString):
		t, _ = time.Parse("2 January 2006", datePattern.FindString(sample))
	}
	return t
}

func ParseTitle(sample string) (title string) {
 titlePattern, err := regexp.Compile(`^(#\s).*`)

 if err != nil {
 	panic(err)
 }

 title = titlePattern.FindString(sample)
 title = title[2:]
 return title

}
<|endoftext|>


<commit_before>// Copyright 2014 Mathias Fiedler
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gl

// #include <GLES2/gl2.h>
import "C"
import (
	"unsafe"
)

type VertexAttrib interface {
	Index() C.GLuint
	Enable()
	Disable()
}

type FloatAttrib struct {
	index C.GLuint
}

type Vec2Attrib struct {
	FloatAttrib
}

type Vec3Attrib struct {
	FloatAttrib
}

type Vec4Attrib struct {
	FloatAttrib
}

func (attrib FloatAttrib) Index() C.GLuint {
	return attrib.index
}

// func VertexAttrib1f(indx uint, GLfloat x) {
// 	C.glVertexAttrib1f(GLuint indx, GLfloat x)
// }

// func VertexAttrib1fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib1fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib2f(indx uint, GLfloat x, GLfloat y) {
// 	C.glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
// }

// func VertexAttrib2fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib2fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib3f(indx uint, GLfloat x, GLfloat y, GLfloat z) {
// 	C.glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
// }

// func VertexAttrib3fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib3fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib4f(indx uint, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
// 	C.glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
// }

// func VertexAttrib4fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib4fv(GLuint indx, const GLfloat* values)
// }

func (attrib FloatAttrib) Pointer(size int, datatype DataType, stride int, data []float32) {
	C.glVertexAttribPointer(attrib.index, C.GLint(size), C.GLenum(datatype), C.GL_FALSE, C.GLsizei(stride), unsafe.Pointer(&data[0]))
}

// func (attrib VertexAttrib) Pointer(size int, datatype DataType, normalized bool, stride int, offset uintptr) {
// 	nflag := C.GLboolean(C.GL_FALSE)
// 	if normalized {
// 		nflag = C.GLboolean(C.GL_TRUE)
// 	}
// 	C.glVertexAttribPointer(C.GLuint(attrib), C.GLint(size), C.GLenum(datatype), nflag, C.GLsizei(stride), unsafe.Pointer(offset))
// }

// func (attrib VertexAttrib) Pointerf(size int, datatype DataType, stride int, data []float32) {
// 	C.glVertexAttribPointer(C.GLuint(attrib), C.GLint(size), C.GLenum(datatype), C.GL_FALSE, C.GLsizei(stride), unsafe.Pointer(&data[0]))
// }

func (attrib FloatAttrib) Enable() {
	C.glEnableVertexAttribArray(attrib.index)
}

func (attrib FloatAttrib) Disable() {
	C.glDisableVertexAttribArray(attrib.index)
}
<commit_msg>work on methods for glVertexAttribPointer<commit_after>// Copyright 2014 Mathias Fiedler
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gl

// #include <GLES2/gl2.h>
import "C"
import (
	"unsafe"
)

type VertexAttrib interface {
	Index() C.GLuint
	Enable()
	Disable()
}

type FloatAttrib struct {
	index C.GLuint
}

type Vec2Attrib struct {
	FloatAttrib
}

type Vec3Attrib struct {
	FloatAttrib
}

type Vec4Attrib struct {
	FloatAttrib
}

func (attrib FloatAttrib) Index() C.GLuint {
	return attrib.index
}

// func VertexAttrib1f(indx uint, GLfloat x) {
// 	C.glVertexAttrib1f(GLuint indx, GLfloat x)
// }

// func VertexAttrib1fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib1fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib2f(indx uint, GLfloat x, GLfloat y) {
// 	C.glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
// }

// func VertexAttrib2fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib2fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib3f(indx uint, GLfloat x, GLfloat y, GLfloat z) {
// 	C.glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
// }

// func VertexAttrib3fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib3fv(GLuint indx, const GLfloat* values)
// }

// func VertexAttrib4f(indx uint, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
// 	C.glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
// }

// func VertexAttrib4fv(indx uint, const GLfloat* values) {
// 	C.glVertexAttrib4fv(GLuint indx, const GLfloat* values)
// }

func (attrib FloatAttrib) Pointerf(size int, stride int, data []float32) {
	C.glVertexAttribPointer(attrib.index, C.GLint(size), C.GL_FLOAT, C.GL_FALSE, C.GLsizei(stride), unsafe.Pointer(&data[0]))
}

func (attrib FloatAttrib) Pointer(size int, stride int, offset uintptr) {
	C.glVertexAttribPointer(attrib.index, C.GLint(size), C.GL_FLOAT, C.GL_FALSE, C.GLsizei(stride), unsafe.Pointer(offset))
}

// func (attrib VertexAttrib) Pointer(size int, datatype DataType, normalized bool, stride int, offset uintptr) {
// 	nflag := C.GLboolean(C.GL_FALSE)
// 	if normalized {
// 		nflag = C.GLboolean(C.GL_TRUE)
// 	}
// 	C.glVertexAttribPointer(C.GLuint(attrib), C.GLint(size), C.GLenum(datatype), nflag, C.GLsizei(stride), unsafe.Pointer(offset))
// }

// func (attrib VertexAttrib) Pointerf(size int, datatype DataType, stride int, data []float32) {
// 	C.glVertexAttribPointer(C.GLuint(attrib), C.GLint(size), C.GLenum(datatype), C.GL_FALSE, C.GLsizei(stride), unsafe.Pointer(&data[0]))
// }

func (attrib FloatAttrib) Enable() {
	C.glEnableVertexAttribArray(attrib.index)
}

func (attrib FloatAttrib) Disable() {
	C.glDisableVertexAttribArray(attrib.index)
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	c "github.com/wsxiaoys/terminal/color"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

var (
	msgFail = "%v method fails. Expects %v, returns %v"
	exists  = false
)

func TestGobiHelp(t *testing.T) {
	setup()
	defer teardown()
	c.Println("@{!b} $ gobi help")
	out, err := exec.Command("gobi", "help").Output()
	if err != nil {
		t.Errorf("%v", err)
	}
	fmt.Println(string(out))
}

func TestGobiVersion(t *testing.T) {
	setup()
	defer teardown()
	c.Println("@{!b} $ gobi version")
	out, err := exec.Command("gobi", "version").Output()
	if err != nil {
		t.Errorf("%v", err)
	}
	fmt.Println(string(out))
}

func TestGobiWhoami(t *testing.T) {
	setup()
	defer teardown()
	c.Println("@{!b} $ gobi whoami")
	out, err := exec.Command("gobi", "whoami").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))
}

func TestGobiCl(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	c.Println("@{!b} $ gobi cl clapp")
	out, err := exec.Command("gobi", "cl", "clapp").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi cl clapp/app")
	out, err = exec.Command("gobi", "cl", "clapp/app").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi cl clapp")
	out, err = exec.Command("gobi", "cl", "clapp").Output()
	if err == nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi cl clapp2/app")
	out, err = exec.Command("gobi", "cl", "clapp2/app").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))
}

func TestGobiPkg(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	c.Println("@{!b} $ gobi pkg gopkg")
	out, err := exec.Command("gobi", "pkg", "gopkg").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi pkg gopkg/pkg")
	out, err = exec.Command("gobi", "pkg", "gopkg/pkg").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi pkg gopkg")
	out, err = exec.Command("gobi", "pkg", "gopkg").Output()
	if err == nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi pkg gopkg2/pkg")
	out, err = exec.Command("gobi", "pkg", "gopkg2/pkg").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))
}

func TestGobiWeb(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	c.Println("@{!b} $ gobi web goweb")
	out, err := exec.Command("gobi", "web", "goweb").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi web goweb/web")
	out, err = exec.Command("gobi", "web", "goweb/web").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi web goweb")
	out, err = exec.Command("gobi", "web", "goweb").Output()
	if err == nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi web goweb2/web")
	out, err = exec.Command("gobi", "web", "goweb2/web").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))
}

func TestGobiMix(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	c.Println("@{!b} $ gobi pkg gomix")
	out, err := exec.Command("gobi", "pkg", "gomix").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi web gomix/site")
	out, err = exec.Command("gobi", "web", "gomix/site").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi cl gomix/cli")
	out, err = exec.Command("gobi", "cl", "gomix/cli").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))

	c.Println("@{!b} $ gobi pkg gomix/mix")
	out, err = exec.Command("gobi", "pkg", "gomix/mix").Output()
	if err != nil {
		t.Error()
	}
	fmt.Println(string(out))
}

func setup() {
	if _, err := os.Stat(GOBI_CONFIG); err == nil {
		exists = true
		os.Rename(GOBI_CONFIG, GOBI_CONFIG+".tmp")
		createTestConfig()
	} else {
		createTestConfig()
	}
}

func teardown() {
	if exists {
		os.Rename(GOBI_CONFIG+".tmp", GOBI_CONFIG)
	} else {
		os.Remove(GOBI_CONFIG)
	}
	exists = false
}

func createTestConfig() {
	conf := &UserConfig{"Test Name", "testUserName", "github.com", "test@mail.com", "MIT"}
	b, _ := json.Marshal(conf)
	ioutil.WriteFile(GOBI_CONFIG, []byte(b), 0744)
}

func cleanupFiles(path string) {
	os.RemoveAll(path)
}
<commit_msg>Epic refactoring for tests<commit_after>package main

import (
	"encoding/json"
	"fmt"
	c "github.com/wsxiaoys/terminal/color"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

var exists = false

func TestGobiHelp(t *testing.T) {
	setup()
	defer teardown()
	assertCommand(t, true, "gobi help")
}

func TestGobiVersion(t *testing.T) {
	setup()
	defer teardown()
	assertCommand(t, true, "gobi version")
}

func TestGobiWhoami(t *testing.T) {
	setup()
	defer teardown()
	assertCommand(t, true, "gobi whoami")
}

func TestGobiCl(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	assertCommand(t, true, "gobi cl clapp")
	assertCommand(t, true, "gobi cl clapp/app")
	assertCommand(t, false, "gobi cl clapp")
	assertCommand(t, true, "gobi cl clapp2/app")
}

func TestGobiPkg(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	assertCommand(t, true, "gobi pkg gopkg")
	assertCommand(t, true, "gobi pkg gopkg/pkg")
	assertCommand(t, false, "gobi pkg gopkg")
	assertCommand(t, true, "gobi pkg gopkg2/pkg")
}

func TestGobiWeb(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	assertCommand(t, true, "gobi web goweb")
	assertCommand(t, true, "gobi web goweb/web")
	assertCommand(t, false, "gobi web goweb")
	assertCommand(t, true, "gobi web goweb2/web")
}

func TestGobiMix(t *testing.T) {
	setup()
	defer teardown()
	defer cleanupFiles(filepath.Join(SRCPATH, GITHUB, "testUserName"))
	assertCommand(t, true, "gobi pkg gomix")
	assertCommand(t, true, "gobi web gomix/site")
	assertCommand(t, true, "gobi cl gomix/cli")
	assertCommand(t, true, "gobi pkg gomix/mix")
}

func assertCommand(t *testing.T, b bool, cmd string) {
	c.Println("@{!b} $", cmd)
	cmdSl := strings.Split(cmd, " ")
	out, err := exec.Command(cmdSl[0], cmdSl[1:]...).Output()
	if b {
		if err != nil {
			t.Error()
		}
	} else {
		if err == nil {
			t.Error()
		}
	}
	fmt.Println(string(out))
}

func setup() {
	if _, err := os.Stat(GOBI_CONFIG); err == nil {
		exists = true
		os.Rename(GOBI_CONFIG, GOBI_CONFIG+".tmp")
		createTestConfig()
	} else {
		createTestConfig()
	}
}

func teardown() {
	if exists {
		os.Rename(GOBI_CONFIG+".tmp", GOBI_CONFIG)
	} else {
		os.Remove(GOBI_CONFIG)
	}
	exists = false
}

func createTestConfig() {
	conf := &UserConfig{"Test Name", "testUserName", "github.com", "test@mail.com", "MIT"}
	b, _ := json.Marshal(conf)
	ioutil.WriteFile(GOBI_CONFIG, []byte(b), 0744)
}

func cleanupFiles(path string) {
	os.RemoveAll(path)
}
<|endoftext|>


<commit_before>package main

import (
	"net"
	"encoding/xml"
	"github.com/dotdoom/goxmpp"
)

type C2s struct {
	Conn net.Conn
	Authenticated bool
}

var clients map[string]C2s

func C2sServer() error {
	listener, err := net.Listen("tcp", "0.0.0.0:5222")
	if err != nil { return err }

	for {
		conn, err := listener.Accept()
		if err == nil {
			go C2sConnection(conn)
		} else {
			println(err.Error());
		}
	}
}

func main() {
	err := C2sServer()
	if err != nil { println(err.Error()) }
}

func C2sConnection(conn net.Conn) error {
	println("New connection")
	sw := goxmpp.NewStreamWrapper(conn)

	stream, err := sw.ReadStreamOpen()
	if err != nil { return err }
	stream.From, stream.To = stream.To, ""
	sw.WriteStreamOpen(stream, "jabber:client")

	println("** Received stream to:", stream.From)

	var features goxmpp.Features
	features.StartTLS = nil //new(goxmpp.StartTLS)
	features.Mechanisms = new(goxmpp.Mechanisms)
	features.Mechanisms.Names = append(features.Mechanisms.Names, "PLAIN", "DIGEST-MD5")
	sw.Encoder.Encode(features)

	mechanisms := map[[2]string](func(xml.StartElement) interface{}){
		[2]string{"auth", "urn:ietf:params:xml:ns:xmpp-sasl"}: func(e xml.StartElement) interface{} {
			// Look up e.attr[mechanism] to find the mechanism they want
			return new(goxmpp.DigestMD5Auth)
		},
	}

	c, err := sw.ReadXMLChunk(mechanisms)
	if err == nil {
		switch c := c.(type) {
		case *goxmpp.PlainAuth:
			println("** PLAIN:", c.Nonce)
		case *goxmpp.DigestMD5Auth:
			println("** MD5:", c.ID)
		}
	} else {
		println(err.Error())
	}

	// Just kidding...
	sw.RW.Write([]byte("<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"))

/*
<stream:features>
	<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
	<compression xmlns="http://jabber.org/features/compress">
		<method>zlib</method>
	</compression>
	<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
		<mechanism>PLAIN</mechanism>
		<mechanism>DIGEST-MD5</mechanism>
		<mechanism>SCRAM-SHA-1</mechanism>
	</mechanisms>
	<c xmlns="http://jabber.org/protocol/caps" node="http://www.process-one.net/en/ejabberd/" ver="rvAR01fKsc40hT0hOLGDuG25y9o=" hash="sha-1"/>
	<register xmlns="http://jabber.org/features/iq-register"/>
</stream:features>
*/

	println("Closing connection");
	return conn.Close()
}
<commit_msg>Endless features sending loop<commit_after>package main

import (
	"net"
	//"encoding/xml"
	"github.com/dotdoom/goxmpp"
)

type C2s struct {
	Conn net.Conn
	Authenticated bool
}

var clients map[string]C2s

func C2sServer() error {
	listener, err := net.Listen("tcp", "0.0.0.0:5222")
	if err != nil { return err }

	for {
		conn, err := listener.Accept()
		if err == nil {
			go C2sConnection(conn)
		} else {
			println(err.Error());
		}
	}
}

func main() {
	goxmpp.RegisterFeatures()

	err := C2sServer()
	if err != nil { println(err.Error()) }
}

func C2sConnection(conn net.Conn) error {
	println("New connection")
	defer conn.Close()

	sw := goxmpp.NewStreamWrapper(conn)

	stream, err := sw.ReadStreamOpen()
	if err != nil { return err }
	stream.From, stream.To = stream.To, ""
	sw.WriteStreamOpen(stream, "jabber:client")

	println("** Received stream to:", stream.From)

	for {
		sw.Encoder.Encode(goxmpp.StreamFeatures.ExposeTo(sw))
		sw.Decoder.Token()
		sw.Decoder.Skip()
	}

	/*
	var features goxmpp.Features
	features.StartTLS = nil //new(goxmpp.StartTLS)
	features.Mechanisms = new(goxmpp.Mechanisms)
	features.Mechanisms.Names = append(features.Mechanisms.Names, "PLAIN", "DIGEST-MD5")
	sw.Encoder.Encode(features)

	mechanisms := map[[2]string](func(xml.StartElement) interface{}){
		[2]string{"auth", "urn:ietf:params:xml:ns:xmpp-sasl"}: func(e xml.StartElement) interface{} {
			// Look up e.attr[mechanism] to find the mechanism they want
			return new(goxmpp.DigestMD5Auth)
		},
	}

	c, err := sw.ReadXMLChunk(mechanisms)
	if err == nil {
		switch c := c.(type) {
		case *goxmpp.PlainAuth:
			println("** PLAIN:", c.Nonce)
		case *goxmpp.DigestMD5Auth:
			println("** MD5:", c.ID)
		}
	} else {
		println(err.Error())
	}

	// Just kidding...
	sw.RW.Write([]byte("<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"))*/

/*
<stream:features>
	<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
	<compression xmlns="http://jabber.org/features/compress">
		<method>zlib</method>
	</compression>
	<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
		<mechanism>PLAIN</mechanism>
		<mechanism>DIGEST-MD5</mechanism>
		<mechanism>SCRAM-SHA-1</mechanism>
	</mechanisms>
	<c xmlns="http://jabber.org/protocol/caps" node="http://www.process-one.net/en/ejabberd/" ver="rvAR01fKsc40hT0hOLGDuG25y9o=" hash="sha-1"/>
	<register xmlns="http://jabber.org/features/iq-register"/>
</stream:features>
*/

	println("Closing connection");
	return nil
}
<|endoftext|>


<commit_before>package golangsdk

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

const (
	zincBaseURL = "https://api.zinc.io/v1"
)

type Retailer string

const (
	Amazon     Retailer = "amazon"
	AmazonUK   Retailer = "amazon_uk"
	AmazonCA   Retailer = "amazon_ca"
	AmazonMX   Retailer = "amazon_mx"
	Walmart    Retailer = "walmart"
	Aliexpress Retailer = "aliexpress"
)

var DefaultProductOptions = ProductOptions{
	Timeout: time.Duration(time.Second * 90),
}

type Zinc struct {
	ClientToken string
	ZincBaseURL string
}

func GetRetailer(retailer string) (Retailer, error) {
	switch retailer {
	case "amazon":
		return Amazon, nil
	case "amazon_uk":
		return AmazonUK, nil
	case "amazon_ca":
		return AmazonCA, nil
	case "amazon_mx":
		return AmazonMX, nil
	case "walmart":
		return Walmart, nil
	case "aliexpress":
		return Aliexpress, nil
	default:
		return Amazon, fmt.Errorf("Invalid retailer string")
	}
}

func NewZinc(clientToken string) (*Zinc, error) {
	z := Zinc{
		ClientToken: clientToken,
		ZincBaseURL: zincBaseURL,
	}
	return &z, nil
}

type OrderRequest struct {
	Retailer            Retailer             `json:"retailer"`
	Products            []Product            `json:"products"`
	ShippingMethod      string               `json:"shipping_method,omitempty"`
	Shipping            *Shipping            `json:"shipping,omitempty"`
	ShippingAddress     *Address             `json:"shipping_address"`
	BillingAddress      *Address             `json:"billing_address,omitempty"`
	PaymentMethod       *PaymentMethod       `json:"payment_method,omitempty"`
	RetailerCredentials *RetailerCredentials `json:"retailer_credentials,omitempty"`
	GiftMessage         string               `json:"gift_message,omitempty"`
	IsGift              bool                 `json:"is_gift"`
	MaxPrice            int                  `json:"max_price"`
	Webhooks            *Webhooks            `json:"webhooks,omitempty"`
	Bundled             bool                 `json:"bundled"`
	Addax               bool                 `json:"addax"`
}

type Product struct {
	ProductId               string                   `json:"product_id"`
	Quantity                int                      `json:"quantity"`
	Fresh                   bool                     `json:"fresh"`
	SellerSelectionCriteria *SellerSelectionCriteria `json:"seller_selection_criteria,omitempty"`
}

type Shipping struct {
	OrderBy  string `json:"order_by,omitempty"`
	MaxDays  int    `json:"max_days"`
	MaxPrice int    `json:"max_price"`
}

type Address struct {
	FirstName    string `json:"first_name"`
	LastName     string `json:"last_name"`
	AddressLine1 string `json:"address_line1"`
	AddressLine2 string `json:"address_line2"`
	ZipCode      string `json:"zip_code"`
	City         string `json:"city"`
	State        string `json:"state"`
	Country      string `json:"country"`
	PhoneNumber  string `json:"phone_number"`
}

type PaymentMethod struct {
	NameOnCard      string `json:"name_on_card,omitempty"`
	Number          string `json:"number,omitempty"`
	SecurityCode    string `json:"security_code,omitempty"`
	ExpirationMonth int    `json:"expiration_month,omitempty"`
	ExpirationYear  int    `json:"expiration_year,omitempty"`
	UseGift         bool   `json:"use_gift"`
}

type RetailerCredentials struct {
	Email            string `json:"email"`
	Password         string `json:"password"`
	VerificationCode string `json:"verification_code,omitempty"`
}

type Webhooks struct {
	RequestSucceeded string `json:"request_succeeded"`
	RequestFailed    string `json:"request_failed"`
	TrackingObtained string `json:"tracking_obtained"`
	StatusUpdated    string `json:"status_updated"`
}

type SellerSelectionCriteria struct {
	Prime bool `json:"prime"`
}

type OrderResponse struct {
	RequestId        string             `json:"request_id"`
	Type             string             `json:"_type"`
	Code             string             `json:"code"`
	Data             *ErrorDataResponse `json:"data,omitempty"`
	ErrorMessage     string             `json:"message"`
	PriceComponents  *PriceComponents   `json:"price_components,omitempty"`
	MerchantOrderIds []MerchantOrderId  `json:"merchant_order_ids"`
	Tracking         []Tracking         `json:"tracking"`
	Request          *OrderRequest      `json:"request,omitempty"`
}

type PriceComponents struct {
	Shipping int `json:"shipping"`
	Subtotal int `json:"subtotal"`
	Tax      int `json:"tax"`
	Total    int `json:"total"`
}

type MerchantOrderId struct {
	MerchantOrderId string    `json:"merchant_order_id"`
	Merchant        string    `json:"merchant"`
	Account         string    `json:"account"`
	PlacedAt        time.Time `json:"placed_at"`
}

type Tracking struct {
	MerchantOrderId string    `json:"merchant_order_id"`
	ObtainedAt      time.Time `json:"obtained_at"`
	Carrier         string    `json:"carrier"`
	TrackingNumber  string    `json:"tracking_number"`
	ProductIds      []string  `json:"product_ids"`
	TrackingURL     string    `json:"tracking_url"`
}

type ProductOffersResponse struct {
	Code     string            `json:"code"`
	Data     ErrorDataResponse `json:"data"`
	Status   string            `json:"status"`
	Retailer string            `json:"retailer"`
	Offers   []ProductOffer    `json:"offers"`
}

type ProductOffer struct {
	Available            bool             `json:"available"`
	Addon                bool             `json:"addon"`
	Condition            string           `json:"condition"`
	ShippingOptions      []ShippingOption `json:"shipping_options"`
	HandlingDays         HandlingDays     `json:"handling_days"`
	PrimeOnly            bool             `json:"prime_only"`
	MarketplaceFulfilled bool             `json:"marketplace_fulfilled"`
	Currency             string           `json:"currency"`
	Seller               Seller           `json:"seller"`
	BuyBoxWinner         bool             `json:"buy_box_winner"`
	International        bool             `json:"international"`
	OfferId              string           `json:"offer_id"`
	Price                int              `json:"price"`
}

type ShippingOption struct {
	Price int `json:"price"`
}

type HandlingDays struct {
	Max int `json:"max"`
	Min int `json:"min"`
}

type Seller struct {
	NumRatings      int    `json:"num_ratings"`
	PercentPositive int    `json:"percent_positive"`
	FirstParty      bool   `json:"first_party"`
	Name            string `json:"name"`
	Id              string `json:"id"`
}

type ProductDetailsResponse struct {
	Code               string              `json:"code"`
	Data               ErrorDataResponse   `json:"data"`
	Status             string              `json:"status"`
	ProductDescription string              `json:"product_description"`
	PostDescription    string              `json:"post_description"`
	Retailer           string              `json:"retailer"`
	Epids              []ExternalProductId `json:"epids"`
	ProductDetails     []string            `json:"product_details"`
	Title              string              `json:"title"`
	VariantSpecifics   []VariantSpecific   `json:"variant_specifics"`
	ProductId          string              `json:"product_id"`
	MainImage          string              `json:"main_image"`
	Brand              string              `json:"brand"`
	MPN                string              `json:"mpn"`
	Images             []string            `json:"images"`
	FeatureBullets     []string            `json:"feature_bullets"`
}

type ExternalProductId struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type VariantSpecific struct {
	Dimension string `json:"dimension"`
	Value     string `json:"value"`
}

type ErrorDataResponse struct {
	Message         string           `json:"message"`
	ValidatorErrors []ValidatorError `json:"validator_errors"`
	AllVariants     []Variant        `json:"all_variants"`
}

type ValidatorError struct {
	Message string `json:"message"`
	Path    string `json:"path"`
	Value   string `json:"value"`
}

type Variant struct {
	VariantSpecifics []VariantSpecific `json:"variant_specifics"`
	ProductId        string            `json:"product_id"`
}

type ProductOptions struct {
	MaxAge    int           `json:"max_age"`
	Priority  int           `json:"priority"`
	NewerThan time.Time     `json:"newer_than"`
	Timeout   time.Duration `json:"timeout"`
}

type ZincError struct {
	ErrorMessage string            `json:"error"`
	Code         string            `json:"code"`
	Data         ErrorDataResponse `json:"data"`
}

func (z ZincError) Error() string {
	return z.ErrorMessage
}

func SimpleError(errorStr string) ZincError {
	return ZincError{ErrorMessage: errorStr}
}

func (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {
	offersChan := make(chan *ProductOffersResponse, 1)
	detailsChan := make(chan *ProductDetailsResponse, 1)
	errorsChan := make(chan error, 2)

	go func() {
		offers, err := z.GetProductOffers(productId, retailer, options)
		errorsChan <- err
		offersChan <- offers
	}()

	go func() {
		details, err := z.GetProductDetails(productId, retailer, options)
		errorsChan <- err
		detailsChan <- details
	}()

	offers := <-offersChan
	details := <-detailsChan
	for i := 0; i < 2; i++ {
		err := <-errorsChan
		if err != nil {
			return nil, nil, err
		}
	}
	return offers, details, nil
}

func (z Zinc) SendOrder(order OrderRequest) (*OrderResponse, error) {
	requestPath := fmt.Sprintf("%v/orders", z.ZincBaseURL)
	body := new(bytes.Buffer)
	if err := json.NewEncoder(body).Encode(order); err != nil {
		return nil, SimpleError(err.Error())
	}
	var resp OrderResponse
	if err := z.SendRequest("POST", requestPath, body, time.Duration(time.Second*30), &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	return &resp, nil
}

func (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	values.Set("version", "2")
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v/offers?%v", z.ZincBaseURL, productId, values.Encode())

	var resp ProductOffersResponse
	if err := z.SendRequest("GET", requestPath, nil, options.Timeout, &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	if resp.Status == "failed" {
		msg := fmt.Sprintf("Zinc API returned status 'failed' data=%+v", resp.Data)
		return &resp, ZincError{Code: resp.Code, ErrorMessage: msg, Data: resp.Data}
	}
	return &resp, nil
}

func (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	if options.Priority != 0 {
		values.Set("priority", strconv.Itoa(options.Priority))
	}
	requestPath := fmt.Sprintf("%v/products/%v?%v", z.ZincBaseURL, productId, values.Encode())

	var resp ProductDetailsResponse
	if err := z.SendRequest("GET", requestPath, nil, options.Timeout, &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	if resp.Status == "failed" {
		msg := fmt.Sprintf("Zinc API returned status 'failed' data=%+v", resp.Data)
		return &resp, ZincError{Code: resp.Code, ErrorMessage: msg, Data: resp.Data}
	}
	return &resp, nil
}

func cleanRespBody(respBody []byte) []byte {
	str := string(respBody)
	i := strings.Index(str, "HTTP/1.1 200 OK")
	if i == -1 {
		return respBody
	}
	return []byte(str[:i])
}

func (z Zinc) SendRequest(method, requestPath string, body io.Reader, timeout time.Duration, resp interface{}) error {
	httpReq, err := http.NewRequest(method, requestPath, body)
	if err != nil {
		return err
	}
	httpReq.SetBasicAuth(z.ClientToken, "")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: timeout}
	httpResp, err := client.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	respBody, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return err
	}
	cleanedBody := cleanRespBody(respBody)
	if err := json.Unmarshal(cleanedBody, resp); err != nil {
		log.Printf("[Golangsdk] Unable to unmarshal response request_path=%v body=%v", requestPath, string(cleanedBody))
		return SimpleError(err.Error())
	}
	return nil
}
<commit_msg>Add totp 2fa key param to retailer credentials.<commit_after>package golangsdk

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

const (
	zincBaseURL = "https://api.zinc.io/v1"
)

type Retailer string

const (
	Amazon     Retailer = "amazon"
	AmazonUK   Retailer = "amazon_uk"
	AmazonCA   Retailer = "amazon_ca"
	AmazonMX   Retailer = "amazon_mx"
	Walmart    Retailer = "walmart"
	Aliexpress Retailer = "aliexpress"
)

var DefaultProductOptions = ProductOptions{
	Timeout: time.Duration(time.Second * 90),
}

type Zinc struct {
	ClientToken string
	ZincBaseURL string
}

func GetRetailer(retailer string) (Retailer, error) {
	switch retailer {
	case "amazon":
		return Amazon, nil
	case "amazon_uk":
		return AmazonUK, nil
	case "amazon_ca":
		return AmazonCA, nil
	case "amazon_mx":
		return AmazonMX, nil
	case "walmart":
		return Walmart, nil
	case "aliexpress":
		return Aliexpress, nil
	default:
		return Amazon, fmt.Errorf("Invalid retailer string")
	}
}

func NewZinc(clientToken string) (*Zinc, error) {
	z := Zinc{
		ClientToken: clientToken,
		ZincBaseURL: zincBaseURL,
	}
	return &z, nil
}

type OrderRequest struct {
	Retailer            Retailer             `json:"retailer"`
	Products            []Product            `json:"products"`
	ShippingMethod      string               `json:"shipping_method,omitempty"`
	Shipping            *Shipping            `json:"shipping,omitempty"`
	ShippingAddress     *Address             `json:"shipping_address"`
	BillingAddress      *Address             `json:"billing_address,omitempty"`
	PaymentMethod       *PaymentMethod       `json:"payment_method,omitempty"`
	RetailerCredentials *RetailerCredentials `json:"retailer_credentials,omitempty"`
	GiftMessage         string               `json:"gift_message,omitempty"`
	IsGift              bool                 `json:"is_gift"`
	MaxPrice            int                  `json:"max_price"`
	Webhooks            *Webhooks            `json:"webhooks,omitempty"`
	Bundled             bool                 `json:"bundled"`
	Addax               bool                 `json:"addax"`
}

type Product struct {
	ProductId               string                   `json:"product_id"`
	Quantity                int                      `json:"quantity"`
	Fresh                   bool                     `json:"fresh"`
	SellerSelectionCriteria *SellerSelectionCriteria `json:"seller_selection_criteria,omitempty"`
}

type Shipping struct {
	OrderBy  string `json:"order_by,omitempty"`
	MaxDays  int    `json:"max_days"`
	MaxPrice int    `json:"max_price"`
}

type Address struct {
	FirstName    string `json:"first_name"`
	LastName     string `json:"last_name"`
	AddressLine1 string `json:"address_line1"`
	AddressLine2 string `json:"address_line2"`
	ZipCode      string `json:"zip_code"`
	City         string `json:"city"`
	State        string `json:"state"`
	Country      string `json:"country"`
	PhoneNumber  string `json:"phone_number"`
}

type PaymentMethod struct {
	NameOnCard      string `json:"name_on_card,omitempty"`
	Number          string `json:"number,omitempty"`
	SecurityCode    string `json:"security_code,omitempty"`
	ExpirationMonth int    `json:"expiration_month,omitempty"`
	ExpirationYear  int    `json:"expiration_year,omitempty"`
	UseGift         bool   `json:"use_gift"`
}

type RetailerCredentials struct {
	Email            string `json:"email"`
	Password         string `json:"password"`
	VerificationCode string `json:"verification_code,omitempty"`
	Totp2FAKey       string `json:"totp_2fa_key"`
}

type Webhooks struct {
	RequestSucceeded string `json:"request_succeeded"`
	RequestFailed    string `json:"request_failed"`
	TrackingObtained string `json:"tracking_obtained"`
	StatusUpdated    string `json:"status_updated"`
}

type SellerSelectionCriteria struct {
	Prime bool `json:"prime"`
}

type OrderResponse struct {
	RequestId        string             `json:"request_id"`
	Type             string             `json:"_type"`
	Code             string             `json:"code"`
	Data             *ErrorDataResponse `json:"data,omitempty"`
	ErrorMessage     string             `json:"message"`
	PriceComponents  *PriceComponents   `json:"price_components,omitempty"`
	MerchantOrderIds []MerchantOrderId  `json:"merchant_order_ids"`
	Tracking         []Tracking         `json:"tracking"`
	Request          *OrderRequest      `json:"request,omitempty"`
}

type PriceComponents struct {
	Shipping int `json:"shipping"`
	Subtotal int `json:"subtotal"`
	Tax      int `json:"tax"`
	Total    int `json:"total"`
}

type MerchantOrderId struct {
	MerchantOrderId string    `json:"merchant_order_id"`
	Merchant        string    `json:"merchant"`
	Account         string    `json:"account"`
	PlacedAt        time.Time `json:"placed_at"`
}

type Tracking struct {
	MerchantOrderId string    `json:"merchant_order_id"`
	ObtainedAt      time.Time `json:"obtained_at"`
	Carrier         string    `json:"carrier"`
	TrackingNumber  string    `json:"tracking_number"`
	ProductIds      []string  `json:"product_ids"`
	TrackingURL     string    `json:"tracking_url"`
}

type ProductOffersResponse struct {
	Code     string            `json:"code"`
	Data     ErrorDataResponse `json:"data"`
	Status   string            `json:"status"`
	Retailer string            `json:"retailer"`
	Offers   []ProductOffer    `json:"offers"`
}

type ProductOffer struct {
	Available            bool             `json:"available"`
	Addon                bool             `json:"addon"`
	Condition            string           `json:"condition"`
	ShippingOptions      []ShippingOption `json:"shipping_options"`
	HandlingDays         HandlingDays     `json:"handling_days"`
	PrimeOnly            bool             `json:"prime_only"`
	MarketplaceFulfilled bool             `json:"marketplace_fulfilled"`
	Currency             string           `json:"currency"`
	Seller               Seller           `json:"seller"`
	BuyBoxWinner         bool             `json:"buy_box_winner"`
	International        bool             `json:"international"`
	OfferId              string           `json:"offer_id"`
	Price                int              `json:"price"`
}

type ShippingOption struct {
	Price int `json:"price"`
}

type HandlingDays struct {
	Max int `json:"max"`
	Min int `json:"min"`
}

type Seller struct {
	NumRatings      int    `json:"num_ratings"`
	PercentPositive int    `json:"percent_positive"`
	FirstParty      bool   `json:"first_party"`
	Name            string `json:"name"`
	Id              string `json:"id"`
}

type ProductDetailsResponse struct {
	Code               string              `json:"code"`
	Data               ErrorDataResponse   `json:"data"`
	Status             string              `json:"status"`
	ProductDescription string              `json:"product_description"`
	PostDescription    string              `json:"post_description"`
	Retailer           string              `json:"retailer"`
	Epids              []ExternalProductId `json:"epids"`
	ProductDetails     []string            `json:"product_details"`
	Title              string              `json:"title"`
	VariantSpecifics   []VariantSpecific   `json:"variant_specifics"`
	ProductId          string              `json:"product_id"`
	MainImage          string              `json:"main_image"`
	Brand              string              `json:"brand"`
	MPN                string              `json:"mpn"`
	Images             []string            `json:"images"`
	FeatureBullets     []string            `json:"feature_bullets"`
}

type ExternalProductId struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type VariantSpecific struct {
	Dimension string `json:"dimension"`
	Value     string `json:"value"`
}

type ErrorDataResponse struct {
	Message         string           `json:"message"`
	ValidatorErrors []ValidatorError `json:"validator_errors"`
	AllVariants     []Variant        `json:"all_variants"`
}

type ValidatorError struct {
	Message string `json:"message"`
	Path    string `json:"path"`
	Value   string `json:"value"`
}

type Variant struct {
	VariantSpecifics []VariantSpecific `json:"variant_specifics"`
	ProductId        string            `json:"product_id"`
}

type ProductOptions struct {
	MaxAge    int           `json:"max_age"`
	Priority  int           `json:"priority"`
	NewerThan time.Time     `json:"newer_than"`
	Timeout   time.Duration `json:"timeout"`
}

type ZincError struct {
	ErrorMessage string            `json:"error"`
	Code         string            `json:"code"`
	Data         ErrorDataResponse `json:"data"`
}

func (z ZincError) Error() string {
	return z.ErrorMessage
}

func SimpleError(errorStr string) ZincError {
	return ZincError{ErrorMessage: errorStr}
}

func (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {
	offersChan := make(chan *ProductOffersResponse, 1)
	detailsChan := make(chan *ProductDetailsResponse, 1)
	errorsChan := make(chan error, 2)

	go func() {
		offers, err := z.GetProductOffers(productId, retailer, options)
		errorsChan <- err
		offersChan <- offers
	}()

	go func() {
		details, err := z.GetProductDetails(productId, retailer, options)
		errorsChan <- err
		detailsChan <- details
	}()

	offers := <-offersChan
	details := <-detailsChan
	for i := 0; i < 2; i++ {
		err := <-errorsChan
		if err != nil {
			return nil, nil, err
		}
	}
	return offers, details, nil
}

func (z Zinc) SendOrder(order OrderRequest) (*OrderResponse, error) {
	requestPath := fmt.Sprintf("%v/orders", z.ZincBaseURL)
	body := new(bytes.Buffer)
	if err := json.NewEncoder(body).Encode(order); err != nil {
		return nil, SimpleError(err.Error())
	}
	var resp OrderResponse
	if err := z.SendRequest("POST", requestPath, body, time.Duration(time.Second*30), &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	return &resp, nil
}

func (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	values.Set("version", "2")
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v/offers?%v", z.ZincBaseURL, productId, values.Encode())

	var resp ProductOffersResponse
	if err := z.SendRequest("GET", requestPath, nil, options.Timeout, &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	if resp.Status == "failed" {
		msg := fmt.Sprintf("Zinc API returned status 'failed' data=%+v", resp.Data)
		return &resp, ZincError{Code: resp.Code, ErrorMessage: msg, Data: resp.Data}
	}
	return &resp, nil
}

func (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	if options.Priority != 0 {
		values.Set("priority", strconv.Itoa(options.Priority))
	}
	requestPath := fmt.Sprintf("%v/products/%v?%v", z.ZincBaseURL, productId, values.Encode())

	var resp ProductDetailsResponse
	if err := z.SendRequest("GET", requestPath, nil, options.Timeout, &resp); err != nil {
		return nil, SimpleError(err.Error())
	}
	if resp.Status == "failed" {
		msg := fmt.Sprintf("Zinc API returned status 'failed' data=%+v", resp.Data)
		return &resp, ZincError{Code: resp.Code, ErrorMessage: msg, Data: resp.Data}
	}
	return &resp, nil
}

func cleanRespBody(respBody []byte) []byte {
	str := string(respBody)
	i := strings.Index(str, "HTTP/1.1 200 OK")
	if i == -1 {
		return respBody
	}
	return []byte(str[:i])
}

func (z Zinc) SendRequest(method, requestPath string, body io.Reader, timeout time.Duration, resp interface{}) error {
	httpReq, err := http.NewRequest(method, requestPath, body)
	if err != nil {
		return err
	}
	httpReq.SetBasicAuth(z.ClientToken, "")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: timeout}
	httpResp, err := client.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	respBody, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return err
	}
	cleanedBody := cleanRespBody(respBody)
	if err := json.Unmarshal(cleanedBody, resp); err != nil {
		log.Printf("[Golangsdk] Unable to unmarshal response request_path=%v body=%v", requestPath, string(cleanedBody))
		return SimpleError(err.Error())
	}
	return nil
}
<|endoftext|>


<commit_before>package goon

import (
	"github.com/favclip/testerator"
	"github.com/mjibson/goon"
)

func init() {
	testerator.DefaultSetup.Cleaners = append(testerator.DefaultSetup.Cleaners, goonCleanUp)
}

func goonCleanUp(s *testerator.Setup) error {
	goon.FromContext(s.Context).FlushLocalCache()
	return nil
}
<commit_msg>remove goon package. it was a waste<commit_after><|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
)

var readmeTempl = `#%s

This is the awesome description for %s.`

var docTempl = `// Add some documentation to your package.
package %s`

var mainTempl = `package main

import (
	"fmt"
)

func main() {
	fmt.Prinln("Hello from Gootstrap!")
}
`

func main() {

	pack_name := os.Args[2]
	log.Printf("Creating package %s", pack_name)

	switch os.Args[1] {
	case "new":
		createPackage(pack_name)
		log.Printf("Package created! cd %s to access.", pack_name)
	}

}

func createPackage(pack_name string) {
	sep := string(filepath.Separator)

	// Creates the project's folder

	if _, err := os.Stat(pack_name); os.IsNotExist(err) {
		os.Mkdir(pack_name, 0777)
		log.Println("Creating directory")
	}

	//Creates README.md
	readme := fmt.Sprintf("%s%sREADME.md", pack_name, sep)
	readme_file, err := os.Create(readme)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer readme_file.Close()
	fReadme := fmt.Sprintf(readmeTempl, pack_name, pack_name)
	readme_file.WriteString(fReadme)
	log.Println("Creating README.md")

	// Creates main .go file
	mainpack := fmt.Sprintf("%s%s%s.go", pack_name, sep, pack_name)
	mainpack_file, err := os.Create(mainpack)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mainpack_file.Close()
	mainpack_file.WriteString(mainTempl)
	log.Println("Creating main .go file.")

	// Creates main doc.go file
	doc := fmt.Sprintf("%s%sdoc.go", pack_name, sep)
	doc_file, err := os.Create(doc)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer doc_file.Close()
	dReadme := fmt.Sprintf(docTempl, pack_name)
	doc_file.WriteString(dReadme)
	log.Println("Creating doc.go")
}
<commit_msg>add doc to gootstrap.go<commit_after>//Gootstrap is a simple package that bootstrap new Go packages. It creates a REAME.md, a doc.go and main (package name).go file as a placeholder. I did it because I was repeating myself a lot when starting new projects.
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
)

var readmeTempl = `#%s

This is the awesome description for %s.`

var docTempl = `// Add some documentation to your package.
package %s`

var mainTempl = `package main

import (
	"fmt"
)

func main() {
	fmt.Prinln("Hello from Gootstrap!")
}
`

func main() {

	pack_name := os.Args[2]
	log.Printf("Creating package %s", pack_name)

	switch os.Args[1] {
	case "new":
		createPackage(pack_name)
		log.Printf("Package created! cd %s to access.", pack_name)
	}

}

func createPackage(pack_name string) {
	sep := string(filepath.Separator)

	// Creates the project's folder

	if _, err := os.Stat(pack_name); os.IsNotExist(err) {
		os.Mkdir(pack_name, 0777)
		log.Println("Creating directory")
	}

	//Creates README.md
	readme := fmt.Sprintf("%s%sREADME.md", pack_name, sep)
	readme_file, err := os.Create(readme)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer readme_file.Close()
	fReadme := fmt.Sprintf(readmeTempl, pack_name, pack_name)
	readme_file.WriteString(fReadme)
	log.Println("Creating README.md")

	// Creates main .go file
	mainpack := fmt.Sprintf("%s%s%s.go", pack_name, sep, pack_name)
	mainpack_file, err := os.Create(mainpack)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer mainpack_file.Close()
	mainpack_file.WriteString(mainTempl)
	log.Println("Creating main .go file.")

	// Creates main doc.go file
	doc := fmt.Sprintf("%s%sdoc.go", pack_name, sep)
	doc_file, err := os.Create(doc)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer doc_file.Close()
	dReadme := fmt.Sprintf(docTempl, pack_name)
	doc_file.WriteString(dReadme)
	log.Println("Creating doc.go")
}
<|endoftext|>


<commit_before>package main

import "fmt"
import "flag"
import "math/rand"
import "time"

var width = flag.Int("width", 10, "Horizontal width of the grid. Default is 10.")
var height = flag.Int("height", 10, "Vertical height of the grid. Default is 10.")

func main() {
	flag.Parse()

	rand.Seed(time.Now().UTC().UnixNano())

	grid := Grid{}
	grid.Build()

	PlayLoop(grid)

}
func PlayLoop(grid Grid) {
	found := false
	for !found {
		fmt.Printf("\nEnter Guess:")
		var guess_str string
		_, err := fmt.Scanf("%v", &guess_str)
		if err != nil {
			fmt.Printf("Error: %v.\n", err)
		}
		gresult, err_result := grid.ProcessGuess(guess_str)
		if err_result != nil {
			fmt.Printf("%v.\n", err_result)
		}
		fmt.Printf("%v\n", gresult)
		if gresult.VerticalPosition == cFound && gresult.HorizontalPosition == cFound {
			found = true
		}
	}
}
<commit_msg>Added Color Used go-colortext Change colors for different outputs.<commit_after>package main

import "fmt"
import "flag"
import "math/rand"
import "time"
import "github.com/daviddengcn/go-colortext"

var width = flag.Int("width", 10, "Horizontal width of the grid. Default is 10.")
var height = flag.Int("height", 10, "Vertical height of the grid. Default is 10.")

func main() {
	flag.Parse()

	rand.Seed(time.Now().UTC().UnixNano())

	grid := Grid{}
	grid.Build()

	PlayLoop(grid)

}
func PlayLoop(grid Grid) {
	found := false
	for !found {
		ct.ChangeColor(ct.Blue, true, ct.Black, false)
		fmt.Printf("\nEnter Guess:")
		var guess_str string
		_, err := fmt.Scanf("%v", &guess_str)
		if err != nil {
			ct.ChangeColor(ct.Red, true, ct.Black, false)
			fmt.Printf("Error: %v.\n", err)
		}
		gresult, err_result := grid.ProcessGuess(guess_str)
		if err_result != nil {
			ct.ChangeColor(ct.Red, true, ct.Black, false)
			fmt.Printf("%v.\n", err_result)
		}
		ct.ChangeColor(ct.Yellow, true, ct.Black, false)
		if gresult.VerticalPosition == cFound && gresult.HorizontalPosition == cFound {
			found = true
			ct.ChangeColor(ct.Green, true, ct.Black, false)
		}
		fmt.Printf("%v\n", gresult)
	}
	fmt.Printf("\n\n")
}
<|endoftext|>


<commit_before>package gzmq

import (
	"testing"
	"time"

	zmq "github.com/alecthomas/gozmq"
)

func TestPolling(t *testing.T) {
	var (
		context zmq.Context
		pull    zmq.Socket
		push    zmq.Socket
		polling Polling
		cpull   <-chan [][]byte
		err     error
	)
	if context, err = zmq.NewContext(); err != nil {
		t.Fatalf(err.Error())
	}
	if pull, err = context.NewSocket(zmq.PULL); err != nil {
		t.Fatalf(err.Error())
	}
	if err = pull.Bind("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	if push, err = context.NewSocket(zmq.PUSH); err != nil {
		t.Fatalf(err.Error())
	}
	if err = push.Connect("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	polling, err = NewPolling(context)
	push.Send([]byte("test"), 0)
	cpull, err = polling.Include(pull)
	select {
	case <-cpull:
	case <-time.After(10 * time.Millisecond):
		t.Errorf("failed to receive message within timeout.")
	}
	if err = polling.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	if err = push.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	if err = pull.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	context.Close()
}

func TestPolling_Sync(t *testing.T) {
	var (
		context    zmq.Context
		reQ, reP   zmq.Socket
		polling    Polling
		creQ, creP <-chan [][]byte
		err        error
	)
	if context, err = zmq.NewContext(); err != nil {
		t.Fatalf(err.Error())
	}
	if reQ, err = context.NewSocket(zmq.REQ); err != nil {
		t.Fatalf(err.Error())
	}
	if err = reQ.Bind("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	if reP, err = context.NewSocket(zmq.REP); err != nil {
		t.Fatalf(err.Error())
	}
	if err = reP.Connect("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	polling, err = NewPolling(context)
	if creP, err = polling.Include(reP); err != nil {
		t.Fatalf(err.Error())
	}
	if creQ, err = polling.Include(reQ); err != nil {
		t.Fatalf(err.Error())
	}
	polling.Sync(func() { reQ.Send([]byte("request"), 0) })
	done := false
	for !done {
		select {
		case <-creP:
			polling.Sync(func() { reP.Send([]byte("response"), 0) })
		case <-creQ:
			done = true
		case <-time.After(10 * time.Millisecond):
			t.Errorf("failed to receive message within timeout.")
			done = true
		}
	}
	if err = polling.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	if err = reP.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	if err = reQ.Close(); err != nil {
		t.Fatalf(err.Error())
	}
	context.Close()
}
<commit_msg>Use defer to close in tests.<commit_after>package gzmq

import (
	"testing"
	"time"

	zmq "github.com/alecthomas/gozmq"
)

func TestPolling(t *testing.T) {
	var (
		context zmq.Context
		pull    zmq.Socket
		push    zmq.Socket
		polling Polling
		cpull   <-chan [][]byte
		err     error
	)
	if context, err = zmq.NewContext(); err != nil {
		t.Fatalf(err.Error())
	}
	defer context.Close()
	if pull, err = context.NewSocket(zmq.PULL); err != nil {
		t.Fatalf(err.Error())
	}
	defer pull.Close()
	if err = pull.Bind("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	if push, err = context.NewSocket(zmq.PUSH); err != nil {
		t.Fatalf(err.Error())
	}
	defer push.Close()
	if err = push.Connect("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	polling, err = NewPolling(context)
	defer polling.Close()
	push.Send([]byte("test"), 0)
	cpull, err = polling.Include(pull)
	select {
	case <-cpull:
	case <-time.After(10 * time.Millisecond):
		t.Errorf("failed to receive message within timeout.")
	}
}

func TestPolling_Sync(t *testing.T) {
	var (
		context    zmq.Context
		reQ, reP   zmq.Socket
		polling    Polling
		creQ, creP <-chan [][]byte
		err        error
	)
	if context, err = zmq.NewContext(); err != nil {
		t.Fatalf(err.Error())
	}
	defer context.Close()
	if reQ, err = context.NewSocket(zmq.REQ); err != nil {
		t.Fatalf(err.Error())
	}
	defer reQ.Close()
	if err = reQ.Bind("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	if reP, err = context.NewSocket(zmq.REP); err != nil {
		t.Fatalf(err.Error())
	}
	defer reP.Close()
	if err = reP.Connect("inproc://test"); err != nil {
		t.Fatalf(err.Error())
	}
	polling, err = NewPolling(context)
	defer polling.Close()
	if creP, err = polling.Include(reP); err != nil {
		t.Fatalf(err.Error())
	}
	if creQ, err = polling.Include(reQ); err != nil {
		t.Fatalf(err.Error())
	}
	polling.Sync(func() { reQ.Send([]byte("request"), 0) })
	done := false
	for !done {
		select {
		case <-creP:
			polling.Sync(func() { reP.Send([]byte("response"), 0) })
		case <-creQ:
			done = true
		case <-time.After(10 * time.Millisecond):
			t.Errorf("failed to receive message within timeout.")
			done = true
		}
	}
}
<|endoftext|>