<commit_before>package vcs

import (
	"errors"

	"golang.org/x/tools/godoc/vfs"
)

// A Repository is a VCS repository.
type Repository interface {
	// ResolveRevision returns the revision that the given revision
	// specifier resolves to, or a non-nil error if there is no such
	// revision.
	//
	// Implementations may choose to return ErrRevisionNotFound in all
	// cases where the revision is not found, or more specific errors
	// (such as ErrCommitNotFound) if spec can be partially resolved
	// or determined to be a certain kind of revision specifier.
	ResolveRevision(spec string) (CommitID, error)

	// ResolveTag returns the tag with the given name, or
	// ErrTagNotFound if no such tag exists.
	ResolveTag(name string) (CommitID, error)

	// ResolveBranch returns the branch with the given name, or
	// ErrBranchNotFound if no such branch exists.
	ResolveBranch(name string) (CommitID, error)

	// Branches returns a list of all branches in the repository.
	Branches(BranchesOptions) ([]*Branch, error)

	// Tags returns a list of all tags in the repository.
	Tags() ([]*Tag, error)

	// GetCommit returns the commit with the given commit ID, or
	// ErrCommitNotFound if no such commit exists.
	GetCommit(CommitID) (*Commit, error)

	// Commits returns all commits matching the options, as well as
	// the total number of commits (the count of which is not subject
	// to the N/Skip options).
	//
	// Optionally, the caller can request the total not to be computed,
	// as this can be expensive for large branches.
	Commits(CommitsOptions) (commits []*Commit, total uint, err error)

	// Committers returns the per-author commit statistics of the repo.
	Committers(CommittersOptions) ([]*Committer, error)

	// FileSystem opens the repository file tree at a given commit ID.
	//
	// Implementations may choose to check that the commit exists
	// before FileSystem returns or to defer the check until
	// operations are performed on the filesystem. (For example, an
	// implementation proxying a remote filesystem may not want to
	// incur the round-trip to check that the commit exists.)
	FileSystem(at CommitID) (vfs.FileSystem, error)
}

// A Blamer is a repository that can blame portions of a file.
type Blamer interface {
	BlameFile(path string, opt *BlameOptions) ([]*Hunk, error)
}

// BlameOptions configures a blame.
type BlameOptions struct {
	NewestCommit CommitID `json:",omitempty" url:",omitempty"`
	OldestCommit CommitID `json:",omitempty" url:",omitempty"` // or "" for the root commit

	StartLine int `json:",omitempty" url:",omitempty"` // 1-indexed start byte (or 0 for beginning of file)
	EndLine   int `json:",omitempty" url:",omitempty"` // 1-indexed end byte (or 0 for end of file)
}

// A Hunk is a contiguous portion of a file associated with a commit.
type Hunk struct {
	StartLine int // 1-indexed start line number
	EndLine   int // 1-indexed end line number
	StartByte int // 0-indexed start byte position (inclusive)
	EndByte   int // 0-indexed end byte position (exclusive)
	CommitID
	Author Signature
}

// A Differ is a repository that can compute diffs between two
// commits.
type Differ interface {
	// Diff shows changes between two commits. If base or head do not
	// exist, an error is returned.
	Diff(base, head CommitID, opt *DiffOptions) (*Diff, error)
}

// A CrossRepoDiffer is a repository that can compute diffs with
// respect to a commit in a different repository.
type CrossRepoDiffer interface {
	// CrossRepoDiff shows changes between two commits in different
	// repositories. If base or head do not exist, an error is
	// returned.
	CrossRepoDiff(base CommitID, headRepo Repository, head CommitID, opt *DiffOptions) (*Diff, error)
}

var (
	ErrRefNotFound      = errors.New("ref not found")
	ErrBranchNotFound   = errors.New("branch not found")
	ErrCommitNotFound   = errors.New("commit not found")
	ErrRevisionNotFound = errors.New("revision not found")
	ErrTagNotFound      = errors.New("tag not found")
)

type CommitID string

// Marshal implements proto.Marshaler.
func (c CommitID) Marshal() ([]byte, error) {
	return []byte(c), nil
}

// Unmarshal implements proto.Unmarshaler.
func (c *CommitID) Unmarshal(data []byte) error {
	*c = CommitID(data)
	return nil
}

// CommitsOptions specifies limits on the list of commits returned by
// (Repository).Commits.
type CommitsOptions struct {
	Head CommitID // include all commits reachable from this commit (required)
	Base CommitID // exlude all commits reachable from this commit (optional, like `git log Base..Head`)

	N    uint // limit the number of returned commits to this many (0 means no limit)
	Skip uint // skip this many commits at the beginning

	Path string // only commits modifying the given path are selected (optional)

	NoTotal bool // avoid counting the total number of commits
}

// CommittersOptions specifies limits on the list of committers returned by
// (Repository).Committers.
type CommittersOptions struct {
	N int // limit the number of returned committers, ordered by decreasing number of commits (0 means no limit)

	Rev string // the rev for which committer stats will be fetched ("" means use the current revision)
}

// DiffOptions configures a diff.
type DiffOptions struct {
	Paths                 []string // constrain diff to these pathspecs
	DetectRenames         bool
	OrigPrefix, NewPrefix string // prefixes for orig and new filenames (e.g., "a/", "b/")

	ExcludeReachableFromBoth bool // like "<rev1>...<rev2>" (see `git rev-parse --help`)
}

// A Diff represents changes between two commits.
type Diff struct {
	Raw string // the raw diff output
}

type Branches []*Branch

func (p Branches) Len() int           { return len(p) }
func (p Branches) Less(i, j int) bool { return p[i].Name < p[j].Name }
func (p Branches) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// ByAuthorDate sorts by author date. Requires full commit information to be included.
type ByAuthorDate []*Branch

func (p ByAuthorDate) Len() int { return len(p) }
func (p ByAuthorDate) Less(i, j int) bool {
	return p[i].Commit.Author.Date.Time().Before(p[j].Commit.Author.Date.Time())
}
func (p ByAuthorDate) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

type Tags []*Tag

func (p Tags) Len() int           { return len(p) }
func (p Tags) Less(i, j int) bool { return p[i].Name < p[j].Name }
func (p Tags) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// A FileLister is a repository that can perform actions related to
// listing the entire file tree.
type FileLister interface {
	// ListFiles returns list of all file names in the repo at the
	// given commit. Returned file paths are forward slash separated
	// and are relative to the base directory of the repository.
	// Eg. returned paths have the form "path/to/file.txt"
	ListFiles(CommitID) ([]string, error)
}
<commit_msg>Change vcs.ListFiles interface to also guarantee sort order.<commit_after>package vcs

import (
	"errors"

	"golang.org/x/tools/godoc/vfs"
)

// A Repository is a VCS repository.
type Repository interface {
	// ResolveRevision returns the revision that the given revision
	// specifier resolves to, or a non-nil error if there is no such
	// revision.
	//
	// Implementations may choose to return ErrRevisionNotFound in all
	// cases where the revision is not found, or more specific errors
	// (such as ErrCommitNotFound) if spec can be partially resolved
	// or determined to be a certain kind of revision specifier.
	ResolveRevision(spec string) (CommitID, error)

	// ResolveTag returns the tag with the given name, or
	// ErrTagNotFound if no such tag exists.
	ResolveTag(name string) (CommitID, error)

	// ResolveBranch returns the branch with the given name, or
	// ErrBranchNotFound if no such branch exists.
	ResolveBranch(name string) (CommitID, error)

	// Branches returns a list of all branches in the repository.
	Branches(BranchesOptions) ([]*Branch, error)

	// Tags returns a list of all tags in the repository.
	Tags() ([]*Tag, error)

	// GetCommit returns the commit with the given commit ID, or
	// ErrCommitNotFound if no such commit exists.
	GetCommit(CommitID) (*Commit, error)

	// Commits returns all commits matching the options, as well as
	// the total number of commits (the count of which is not subject
	// to the N/Skip options).
	//
	// Optionally, the caller can request the total not to be computed,
	// as this can be expensive for large branches.
	Commits(CommitsOptions) (commits []*Commit, total uint, err error)

	// Committers returns the per-author commit statistics of the repo.
	Committers(CommittersOptions) ([]*Committer, error)

	// FileSystem opens the repository file tree at a given commit ID.
	//
	// Implementations may choose to check that the commit exists
	// before FileSystem returns or to defer the check until
	// operations are performed on the filesystem. (For example, an
	// implementation proxying a remote filesystem may not want to
	// incur the round-trip to check that the commit exists.)
	FileSystem(at CommitID) (vfs.FileSystem, error)
}

// A Blamer is a repository that can blame portions of a file.
type Blamer interface {
	BlameFile(path string, opt *BlameOptions) ([]*Hunk, error)
}

// BlameOptions configures a blame.
type BlameOptions struct {
	NewestCommit CommitID `json:",omitempty" url:",omitempty"`
	OldestCommit CommitID `json:",omitempty" url:",omitempty"` // or "" for the root commit

	StartLine int `json:",omitempty" url:",omitempty"` // 1-indexed start byte (or 0 for beginning of file)
	EndLine   int `json:",omitempty" url:",omitempty"` // 1-indexed end byte (or 0 for end of file)
}

// A Hunk is a contiguous portion of a file associated with a commit.
type Hunk struct {
	StartLine int // 1-indexed start line number
	EndLine   int // 1-indexed end line number
	StartByte int // 0-indexed start byte position (inclusive)
	EndByte   int // 0-indexed end byte position (exclusive)
	CommitID
	Author Signature
}

// A Differ is a repository that can compute diffs between two
// commits.
type Differ interface {
	// Diff shows changes between two commits. If base or head do not
	// exist, an error is returned.
	Diff(base, head CommitID, opt *DiffOptions) (*Diff, error)
}

// A CrossRepoDiffer is a repository that can compute diffs with
// respect to a commit in a different repository.
type CrossRepoDiffer interface {
	// CrossRepoDiff shows changes between two commits in different
	// repositories. If base or head do not exist, an error is
	// returned.
	CrossRepoDiff(base CommitID, headRepo Repository, head CommitID, opt *DiffOptions) (*Diff, error)
}

var (
	ErrRefNotFound      = errors.New("ref not found")
	ErrBranchNotFound   = errors.New("branch not found")
	ErrCommitNotFound   = errors.New("commit not found")
	ErrRevisionNotFound = errors.New("revision not found")
	ErrTagNotFound      = errors.New("tag not found")
)

type CommitID string

// Marshal implements proto.Marshaler.
func (c CommitID) Marshal() ([]byte, error) {
	return []byte(c), nil
}

// Unmarshal implements proto.Unmarshaler.
func (c *CommitID) Unmarshal(data []byte) error {
	*c = CommitID(data)
	return nil
}

// CommitsOptions specifies limits on the list of commits returned by
// (Repository).Commits.
type CommitsOptions struct {
	Head CommitID // include all commits reachable from this commit (required)
	Base CommitID // exlude all commits reachable from this commit (optional, like `git log Base..Head`)

	N    uint // limit the number of returned commits to this many (0 means no limit)
	Skip uint // skip this many commits at the beginning

	Path string // only commits modifying the given path are selected (optional)

	NoTotal bool // avoid counting the total number of commits
}

// CommittersOptions specifies limits on the list of committers returned by
// (Repository).Committers.
type CommittersOptions struct {
	N int // limit the number of returned committers, ordered by decreasing number of commits (0 means no limit)

	Rev string // the rev for which committer stats will be fetched ("" means use the current revision)
}

// DiffOptions configures a diff.
type DiffOptions struct {
	Paths                 []string // constrain diff to these pathspecs
	DetectRenames         bool
	OrigPrefix, NewPrefix string // prefixes for orig and new filenames (e.g., "a/", "b/")

	ExcludeReachableFromBoth bool // like "<rev1>...<rev2>" (see `git rev-parse --help`)
}

// A Diff represents changes between two commits.
type Diff struct {
	Raw string // the raw diff output
}

type Branches []*Branch

func (p Branches) Len() int           { return len(p) }
func (p Branches) Less(i, j int) bool { return p[i].Name < p[j].Name }
func (p Branches) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// ByAuthorDate sorts by author date. Requires full commit information to be included.
type ByAuthorDate []*Branch

func (p ByAuthorDate) Len() int { return len(p) }
func (p ByAuthorDate) Less(i, j int) bool {
	return p[i].Commit.Author.Date.Time().Before(p[j].Commit.Author.Date.Time())
}
func (p ByAuthorDate) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

type Tags []*Tag

func (p Tags) Len() int           { return len(p) }
func (p Tags) Less(i, j int) bool { return p[i].Name < p[j].Name }
func (p Tags) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

// A FileLister is a repository that can perform actions related to
// listing the entire file tree.
type FileLister interface {
	// ListFiles returns list of all file names in the repo at the
	// given commit. Returned file paths are forward slash separated,
	// relative to the base directory of the repository, and sorted
	// alphabetically. E.g., returned paths have the form "path/to/file.txt".
	ListFiles(CommitID) ([]string, error)
}
<|endoftext|>


<commit_before>package turn

import (
	"net"
	"testing"
	"time"

	"github.com/pion/logging"
	"github.com/pion/transport/vnet"
	"github.com/stretchr/testify/assert"
)

func createListeningTestClient(t *testing.T, loggerFactory logging.LoggerFactory) (*Client, bool) {
	conn, err := net.ListenPacket("udp4", "0.0.0.0:0")
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}
	c, err := NewClient(&ClientConfig{
		Conn:          conn,
		Software:      "TEST SOFTWARE",
		LoggerFactory: loggerFactory,
	})
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}
	err = c.Listen()
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}

	return c, true
}

func createListeningTestClientWithSTUNServ(t *testing.T, loggerFactory logging.LoggerFactory) (*Client, bool) {
	conn, err := net.ListenPacket("udp4", "0.0.0.0:0")
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}
	c, err := NewClient(&ClientConfig{
		STUNServerAddr: "stun1.l.google.com:19302",
		Conn:           conn,
		Net:            vnet.NewNet(nil),
		LoggerFactory:  loggerFactory,
	})
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}
	err = c.Listen()
	if !assert.NoError(t, err, "should succeed") {
		return nil, false
	}

	return c, true
}

func TestClientWithSTUN(t *testing.T) {
	loggerFactory := logging.NewDefaultLoggerFactory()
	log := loggerFactory.NewLogger("test")

	t.Run("SendBindingRequest", func(t *testing.T) {
		c, ok := createListeningTestClientWithSTUNServ(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		resp, err := c.SendBindingRequest()
		assert.NoError(t, err, "should succeed")
		log.Debugf("mapped-addr: %s", resp.String())
		assert.Equal(t, 0, c.trMap.Size(), "should be no transaction left")
	})

	t.Run("SendBindingRequestTo Parallel", func(t *testing.T) {
		c, ok := createListeningTestClient(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		// simple channel fo go routine start signaling
		started := make(chan struct{})
		finished := make(chan struct{})
		var err1 error

		to, err := net.ResolveUDPAddr("udp4", "stun1.l.google.com:19302")
		if !assert.NoError(t, err, "should succeed") {
			return
		}

		// stun1.l.google.com:19302, more at https://gist.github.com/zziuni/3741933#file-stuns-L5
		go func() {
			close(started)
			_, err1 = c.SendBindingRequestTo(to)
			close(finished)
		}()

		// block until go routine is started to make two almost parallel requests

		<-started

		if _, err = c.SendBindingRequestTo(to); err != nil {
			t.Fatal(err)
		}

		<-finished
		if err1 != nil {
			t.Fatal(err)
		}
	})

	t.Run("NewClient should fail if Conn is nil", func(t *testing.T) {
		_, err := NewClient(&ClientConfig{
			LoggerFactory: loggerFactory,
		})
		assert.Error(t, err, "should fail")
	})

	t.Run("SendBindingRequestTo timeout", func(t *testing.T) {
		c, ok := createListeningTestClient(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		to, err := net.ResolveUDPAddr("udp4", "127.0.0.1:9")
		if !assert.NoError(t, err, "should succeed") {
			return
		}

		c.rto = 10 * time.Millisecond // force short timeout

		_, err = c.SendBindingRequestTo(to)
		log.Debug(err.Error())
	})
}
<commit_msg>Fix routine leaks in client tests<commit_after>package turn

import (
	"net"
	"testing"
	"time"

	"github.com/pion/logging"
	"github.com/pion/transport/vnet"
	"github.com/stretchr/testify/assert"
)

func createListeningTestClient(t *testing.T, loggerFactory logging.LoggerFactory) (*Client, net.PacketConn, bool) {
	conn, err := net.ListenPacket("udp4", "0.0.0.0:0")
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}
	c, err := NewClient(&ClientConfig{
		Conn:          conn,
		Software:      "TEST SOFTWARE",
		LoggerFactory: loggerFactory,
	})
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}
	err = c.Listen()
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}

	return c, conn, true
}

func createListeningTestClientWithSTUNServ(t *testing.T, loggerFactory logging.LoggerFactory) (*Client, net.PacketConn, bool) {
	conn, err := net.ListenPacket("udp4", "0.0.0.0:0")
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}
	c, err := NewClient(&ClientConfig{
		STUNServerAddr: "stun1.l.google.com:19302",
		Conn:           conn,
		Net:            vnet.NewNet(nil),
		LoggerFactory:  loggerFactory,
	})
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}
	err = c.Listen()
	if !assert.NoError(t, err, "should succeed") {
		return nil, nil, false
	}

	return c, conn, true
}

func TestClientWithSTUN(t *testing.T) {
	loggerFactory := logging.NewDefaultLoggerFactory()
	log := loggerFactory.NewLogger("test")

	t.Run("SendBindingRequest", func(t *testing.T) {
		c, pc, ok := createListeningTestClientWithSTUNServ(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		resp, err := c.SendBindingRequest()
		assert.NoError(t, err, "should succeed")
		log.Debugf("mapped-addr: %s", resp.String())
		assert.Equal(t, 0, c.trMap.Size(), "should be no transaction left")
		assert.NoError(t, pc.Close())
	})

	t.Run("SendBindingRequestTo Parallel", func(t *testing.T) {
		c, pc, ok := createListeningTestClient(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		// simple channel fo go routine start signaling
		started := make(chan struct{})
		finished := make(chan struct{})
		var err1 error

		to, err := net.ResolveUDPAddr("udp4", "stun1.l.google.com:19302")
		if !assert.NoError(t, err, "should succeed") {
			return
		}

		// stun1.l.google.com:19302, more at https://gist.github.com/zziuni/3741933#file-stuns-L5
		go func() {
			close(started)
			_, err1 = c.SendBindingRequestTo(to)
			close(finished)
		}()

		// block until go routine is started to make two almost parallel requests

		<-started

		if _, err = c.SendBindingRequestTo(to); err != nil {
			t.Fatal(err)
		}

		<-finished
		if err1 != nil {
			t.Fatal(err)
		}

		assert.NoError(t, pc.Close())
	})

	t.Run("NewClient should fail if Conn is nil", func(t *testing.T) {
		_, err := NewClient(&ClientConfig{
			LoggerFactory: loggerFactory,
		})
		assert.Error(t, err, "should fail")
	})

	t.Run("SendBindingRequestTo timeout", func(t *testing.T) {
		c, pc, ok := createListeningTestClient(t, loggerFactory)
		if !ok {
			return
		}
		defer c.Close()

		to, err := net.ResolveUDPAddr("udp4", "127.0.0.1:9")
		if !assert.NoError(t, err, "should succeed") {
			return
		}

		c.rto = 10 * time.Millisecond // force short timeout

		_, err = c.SendBindingRequestTo(to)
		assert.NotNil(t, err)
		assert.NoError(t, pc.Close())
	})
}
<|endoftext|>


<commit_before>package marionette_client

import (
	"testing"
	"time"
)

const (
	TARGET_URL        = "http://www.abola.pt/"
	ID_SELECTOR       = "clubes-hp"
	CSS_SELECTOR_LI   = "li"
	ID_SELECTOR_INPUT = "topo_txtPesquisa"
)

var client *Client

func init() {
	client = NewClient()
	client.Transport(&MarionetteTransport{})
	RunningInDebugMode = true
}

func TestNewSession(t *testing.T) {
	err := client.Connect("", 0)
	if err != nil {
		t.Error(err)
	}

	r, err := client.NewSession("", nil)
	if err != nil {
		t.Error(err)
	}

	t.Log(r.Value)
}

// working
func TestGetSessionID(t *testing.T) {
	if client.SessionId != client.SessionID() {
		t.Fatalf("SessionId differ...")
	}

	t.Log("session is : ", client.SessionId)
}

func TestGetPage(t *testing.T) {
	r, err := client.Navigate(TARGET_URL)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestCurrentUrl(t *testing.T) {
	url, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if url != TARGET_URL {
		t.Fatalf("Current Url %v not equal to target url %v", url, TARGET_URL)
	}

}

func TestGetCookies(t *testing.T) {
	r, err := client.Cookies()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetCookie(t *testing.T) {
	r, err := client.Cookie("abolaCookie")
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

//func TestConnectWithActiveConnection(t *testing.T) {
//	err := client.Connect("", 0)
//	if err == nil {
//		t.Fatalf("%#v", err)
//	}
//
//	t.Log("No Error..")
//}

// working
func TestGetSessionCapabilities(t *testing.T) {
	r, err := client.Capabilities()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.BrowserName)
}

// working
func TestScreenshot(t *testing.T) {
	_, err := client.Screenshot()
	if err != nil {
		t.Fatal(err)
	}

	//this print ise a problem for travis builds, since it can surpass the 4 MB of log size.
	// don't print the base64 encoded image.
	//println(base64encoded)
}

// working
func TestLog(t *testing.T) {
	r, err := client.Log("message testing", "warning")
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

// working
func TestGetLogs(t *testing.T) {
	r, err := client.Logs()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetContext(t *testing.T) {
	r, err := client.SetContext(Context(CHROME))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

	r, err = client.SetContext(Context(CONTENT))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetContext(t *testing.T) {
	r, err := client.Context()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetPageSource(t *testing.T) {
	r, err := client.SetContext(Context(CHROME))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

	r, err = client.SetContext(Context(CONTENT))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

}

func TestSetScriptTimout(t *testing.T) {
	r, err := client.SetScriptTimeout(1000)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetPageTimout(t *testing.T) {
	r, err := client.SetPageTimeout(1000)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetSearchTimout(t *testing.T) {
	r, err := client.SetSearchTimeout(1000)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestPageSource(t *testing.T) {
	_, err := client.PageSource()
	if err != nil {
		t.Fatalf("%#v", err)
	}
}

func TestExecuteScriptWithoutFunction(t *testing.T) {
	script := "return (document.readyState == 'complete');"
	args := []interface{}{}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestExecuteScript(t *testing.T) {
	script := "function testMyGoMarionetteClient() { return 'yes'; } return testMyGoMarionetteClient();"
	args := []interface{}{}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestExecuteScriptWithArgs(t *testing.T) {
	script := "function testMyGoMarionetteClientArgs(a, b) { return a + b; }; return testMyGoMarionetteClientArgs(arguments[0], arguments[1]);"
	args := []interface{}{1, 3}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetTitle(t *testing.T) {
	title, err := client.Title()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(title)

}
func TestFindElement(t *testing.T) {
	element, err := client.FindElement(By(ID), ID_SELECTOR)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(element.Id())
	t.Log(element.Enabled())
	t.Log(element.Selected())
	t.Log(element.Displayed())
	t.Log(element.TagName())
	t.Log(element.Text())
	t.Log(element.Attribute("id"))
	t.Log(element.CssValue("text-decoration"))
	rect, err := element.Rect()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(rect)

	// size
	w, h, err := element.Location()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log("width: %f, height: %f", w, h)

	//location
	x, y, err := element.Size()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log("x: %f, y: %f", x, y)

	collection, err := element.FindElements(By(CSS_SELECTOR), CSS_SELECTOR_LI)
	if 18 != len(collection) {
		t.FailNow()
	}

	t.Logf("%T %#V", collection, collection)
}

func TestSendKeys(t *testing.T) {
	e, err := client.FindElement(By(ID), ID_SELECTOR_INPUT)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	e.SendKeys("teste")
}

func TestFindElements(t *testing.T) {
	elements, err := client.FindElements(By(CSS_SELECTOR), CSS_SELECTOR_LI)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(len(elements))
}

func TestCurrentChromeWindowHandle(t *testing.T) {
	r, err := client.CurrentChromeWindowHandle()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestWindowHandles(t *testing.T) {
	w, err := client.CurrentWindowHandle()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(w)

	r, err := client.WindowHandles()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	for _, w := range r {
		err := client.SwitchToWindow(w)
		if err != nil {
			t.Fatalf("%#v", err)
		}

		time.Sleep(time.Duration(time.Second))
	}

	// return to original window.
	client.SwitchToWindow(w)
}

func TestNavigatorMethods(t *testing.T) {
	client.SetContext(Context(CONTENT))
	url1 := "https://www.google.pt/"
	url2 := "https://www.bing.com/"

	client.Navigate(url1)
	sleep := time.Duration(2) * time.Second
	time.Sleep(sleep)

	client.Navigate(url2)
	time.Sleep(sleep)

	client.Back()
	client.Refresh()
	time.Sleep(sleep)

	firstUrl, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if firstUrl != url1 {
		t.Fatalf("Expected url %v - received url %v", url1, firstUrl[0:len(url1)])
	}

	client.Forward()
	secondUrl, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if secondUrl != url2 {
		t.Fatalf("Expected url %v - received url %v", url2, secondUrl[:len(url2)])
	}
}
<commit_msg>extending the Timeout values to 10 seconds so travis tests doesn't fail.<commit_after>package marionette_client

import (
	"testing"
	"time"
)

const (
	TARGET_URL          = "http://www.abola.pt/"
	ID_SELECTOR         = "clubes-hp"
	CSS_SELECTOR_LI     = "li"
	ID_SELECTOR_INPUT   = "topo_txtPesquisa"
	TIMEOUT             = 10000 // milliseconds
)

var client *Client

func init() {
	client = NewClient()
	client.Transport(&MarionetteTransport{})
	RunningInDebugMode = true
}

func TestNewSession(t *testing.T) {
	err := client.Connect("", 0)
	if err != nil {
		t.Error(err)
	}

	r, err := client.NewSession("", nil)
	if err != nil {
		t.Error(err)
	}

	t.Log(r.Value)
}

// working
func TestGetSessionID(t *testing.T) {
	if client.SessionId != client.SessionID() {
		t.Fatalf("SessionId differ...")
	}

	t.Log("session is : ", client.SessionId)
}

func TestGetPage(t *testing.T) {
	r, err := client.Navigate(TARGET_URL)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestCurrentUrl(t *testing.T) {
	url, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if url != TARGET_URL {
		t.Fatalf("Current Url %v not equal to target url %v", url, TARGET_URL)
	}

}

func TestGetCookies(t *testing.T) {
	r, err := client.Cookies()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetCookie(t *testing.T) {
	r, err := client.Cookie("abolaCookie")
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

//func TestConnectWithActiveConnection(t *testing.T) {
//	err := client.Connect("", 0)
//	if err == nil {
//		t.Fatalf("%#v", err)
//	}
//
//	t.Log("No Error..")
//}

// working
func TestGetSessionCapabilities(t *testing.T) {
	r, err := client.Capabilities()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.BrowserName)
}

// working
func TestScreenshot(t *testing.T) {
	_, err := client.Screenshot()
	if err != nil {
		t.Fatal(err)
	}

	//this print ise a problem for travis builds, since it can surpass the 4 MB of log size.
	// don't print the base64 encoded image.
	//println(base64encoded)
}

// working
func TestLog(t *testing.T) {
	r, err := client.Log("message testing", "warning")
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

// working
func TestGetLogs(t *testing.T) {
	r, err := client.Logs()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetContext(t *testing.T) {
	r, err := client.SetContext(Context(CHROME))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

	r, err = client.SetContext(Context(CONTENT))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetContext(t *testing.T) {
	r, err := client.Context()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetPageSource(t *testing.T) {
	r, err := client.SetContext(Context(CHROME))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

	r, err = client.SetContext(Context(CONTENT))
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)

}

func TestSetScriptTimout(t *testing.T) {
	r, err := client.SetScriptTimeout(TIMEOUT)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetPageTimout(t *testing.T) {
	r, err := client.SetPageTimeout(TIMEOUT)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestSetSearchTimout(t *testing.T) {
	r, err := client.SetSearchTimeout(TIMEOUT)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestPageSource(t *testing.T) {
	_, err := client.PageSource()
	if err != nil {
		t.Fatalf("%#v", err)
	}
}

func TestExecuteScriptWithoutFunction(t *testing.T) {
	script := "return (document.readyState == 'complete');"
	args := []interface{}{}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestExecuteScript(t *testing.T) {
	script := "function testMyGoMarionetteClient() { return 'yes'; } return testMyGoMarionetteClient();"
	args := []interface{}{}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestExecuteScriptWithArgs(t *testing.T) {
	script := "function testMyGoMarionetteClientArgs(a, b) { return a + b; }; return testMyGoMarionetteClientArgs(arguments[0], arguments[1]);"
	args := []interface{}{1, 3}
	r, err := client.ExecuteScript(script, args, 1000, false)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestGetTitle(t *testing.T) {
	title, err := client.Title()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(title)

}
func TestFindElement(t *testing.T) {
	element, err := client.FindElement(By(ID), ID_SELECTOR)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(element.Id())
	t.Log(element.Enabled())
	t.Log(element.Selected())
	t.Log(element.Displayed())
	t.Log(element.TagName())
	t.Log(element.Text())
	t.Log(element.Attribute("id"))
	t.Log(element.CssValue("text-decoration"))
	rect, err := element.Rect()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(rect)

	// size
	w, h, err := element.Location()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log("width: %f, height: %f", w, h)

	//location
	x, y, err := element.Size()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log("x: %f, y: %f", x, y)

	collection, err := element.FindElements(By(CSS_SELECTOR), CSS_SELECTOR_LI)
	if 18 != len(collection) {
		t.FailNow()
	}

	t.Logf("%T %#V", collection, collection)
}

func TestSendKeys(t *testing.T) {
	e, err := client.FindElement(By(ID), ID_SELECTOR_INPUT)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	e.SendKeys("teste")
}

func TestFindElements(t *testing.T) {
	elements, err := client.FindElements(By(CSS_SELECTOR), CSS_SELECTOR_LI)
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(len(elements))
}

func TestCurrentChromeWindowHandle(t *testing.T) {
	r, err := client.CurrentChromeWindowHandle()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(r.Value)
}

func TestWindowHandles(t *testing.T) {
	w, err := client.CurrentWindowHandle()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	t.Log(w)

	r, err := client.WindowHandles()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	for _, w := range r {
		err := client.SwitchToWindow(w)
		if err != nil {
			t.Fatalf("%#v", err)
		}

		time.Sleep(time.Duration(time.Second))
	}

	// return to original window.
	client.SwitchToWindow(w)
}

func TestNavigatorMethods(t *testing.T) {
	client.SetContext(Context(CONTENT))
	url1 := "https://www.google.pt/"
	url2 := "https://www.bing.com/"

	client.Navigate(url1)
	sleep := time.Duration(2) * time.Second
	time.Sleep(sleep)

	client.Navigate(url2)
	time.Sleep(sleep)

	client.Back()
	client.Refresh()
	time.Sleep(sleep)

	firstUrl, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if firstUrl != url1 {
		t.Fatalf("Expected url %v - received url %v", url1, firstUrl[0:len(url1)])
	}

	client.Forward()
	secondUrl, err := client.CurrentUrl()
	if err != nil {
		t.Fatalf("%#v", err)
	}

	if secondUrl != url2 {
		t.Fatalf("Expected url %v - received url %v", url2, secondUrl[:len(url2)])
	}
}
<|endoftext|>


<commit_before>package hec

import (
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

const (
	testSplunkURL   = "http://localhost:8088"
	testSplunkToken = "00000000-0000-0000-0000-000000000000"
)

var testHttpClient *http.Client = &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	},
	Timeout: 100 * time.Millisecond,
}

func TestHEC_WriteEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.NoError(t, err)
}

func TestHEC_WriteEventServerFailure(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		w.Write([]byte(`{"text":"Data channel is missing","code":10}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.Error(t, err)
}

func TestHEC_WriteObjectEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event: map[string]interface{}{
			"str":  "hello",
			"time": time.Now(),
		},
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)

	c.SetHTTPClient(testHttpClient)
	c.SetMaxContentLength(20) // less than full event
	err := c.WriteEvent(event)
	assert.NotNil(t, err)
	assert.Contains(t, err.Error(), "too long")
}

func TestHEC_WriteEventBatch(t *testing.T) {
	events := []*Event{
		{Event: "event one"},
		{Event: "event two"},
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)

	c.SetHTTPClient(testHttpClient)
	err := c.WriteBatch(events)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEventBatch(t *testing.T) {
	events := []*Event{
		{Event: "event one"},
		{Event: "event two"},
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	c.SetMaxContentLength(25)
	err := c.WriteBatch(events)
	assert.NoError(t, err)
}

func TestHEC_WriteEventRaw(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEventRaw(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetMaxContentLength(40)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.NoError(t, err)
}

func TestHEC_WriteRawFailure(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		w.Write([]byte(`{"text":"Oh no","code":90}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetMaxContentLength(40)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.Error(t, err)
}

func TestBreakStream(t *testing.T) {
	text := "This is line A\nThis is line B" // length of every line is 14

	getCountFunc := func(counter *int) func(chunk []byte) error {
		// returned function adds count of all character except "\n"
		return func(chunk []byte) error {
			for _, b := range chunk {
				if b != '\n' {
					*counter++
				}
			}
			return nil
		}
	}

	for _, max := range []int{13, 14, 15, 28, 5, 30} {
		var counter int = 0
		err := breakStream(strings.NewReader(text), max, getCountFunc(&counter))
		assert.NoError(t, err)
		assert.Equal(t, 28, counter)
	}
}
<commit_msg>Improve smartness of mock JSON endpoint<commit_after>package hec

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

const (
	testSplunkURL   = "http://localhost:8088"
	testSplunkToken = "00000000-0000-0000-0000-000000000000"
)

var testHttpClient *http.Client = &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	},
	Timeout: 100 * time.Millisecond,
}

func jsonEndpoint(t *testing.T) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		failed := false
		input := make(map[string]interface{})
		j := json.NewDecoder(r.Body)
		err := j.Decode(&input)
		if err != nil {
			t.Errorf("Decoding JSON: %v", err)
			failed = true
		}

		requiredFields := []string{"event"}
		allowedFields := map[string]struct{}{
			"channel":    struct{}{},
			"event":      struct{}{},
			"fields":     struct{}{},
			"host":       struct{}{},
			"index":      struct{}{},
			"source":     struct{}{},
			"sourcetype": struct{}{},
			"time":       struct{}{},
		}
		for _, f := range requiredFields {
			if _, ok := input[f]; !ok {
				t.Errorf("Required field %q missing in %v", f, input)
			}
		}
		for f := range input {
			if _, ok := allowedFields[f]; !ok {
				t.Errorf("Unexpected field %q in %v", f, input)
			}
		}
		if failed {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf(`{"text": %q, "code": 90}`, fmt.Errorf("Failed to decode JSON: %v", err).Error())))
		} else {
			w.Write([]byte(`{"text":"Success","code":0}`))
		}
	})
}

func TestHEC_WriteEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(jsonEndpoint(t))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.NoError(t, err)
}

func TestHEC_WriteEventServerFailure(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		w.Write([]byte(`{"text":"Data channel is missing","code":10}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.Error(t, err)
}

func TestHEC_WriteObjectEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event: map[string]interface{}{
			"str":  "hello",
			"time": time.Now(),
		},
	}

	ts := httptest.NewServer(jsonEndpoint(t))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteEvent(event)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEvent(t *testing.T) {
	event := &Event{
		Index:      String("main"),
		Source:     String("test-hec-raw"),
		SourceType: String("manual"),
		Host:       String("localhost"),
		Time:       String("1485237827.123"),
		Event:      "hello, world",
	}

	ts := httptest.NewServer(jsonEndpoint(t))
	c := NewClient(ts.URL, testSplunkToken)

	c.SetHTTPClient(testHttpClient)
	c.SetMaxContentLength(20) // less than full event
	err := c.WriteEvent(event)
	assert.NotNil(t, err)
	assert.Contains(t, err.Error(), "too long")
}

func TestHEC_WriteEventBatch(t *testing.T) {
	events := []*Event{
		{Event: "event one"},
		{Event: "event two"},
	}

	ts := httptest.NewServer(jsonEndpoint(t))
	c := NewClient(ts.URL, testSplunkToken)

	c.SetHTTPClient(testHttpClient)
	err := c.WriteBatch(events)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEventBatch(t *testing.T) {
	events := []*Event{
		{Event: "event one"},
		{Event: "event two"},
	}

	ts := httptest.NewServer(jsonEndpoint(t))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	c.SetMaxContentLength(25)
	err := c.WriteBatch(events)
	assert.NoError(t, err)
}

func TestHEC_WriteEventRaw(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.NoError(t, err)
}

func TestHEC_WriteLongEventRaw(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"text":"Success","code":0}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetMaxContentLength(40)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.NoError(t, err)
}

func TestHEC_WriteRawFailure(t *testing.T) {
	events := `2017-01-24T06:07:10.488Z Raw event one
2017-01-24T06:07:12.434Z Raw event two`
	metadata := EventMetadata{
		Source: String("test-hec-raw"),
	}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		w.Write([]byte(`{"text":"Oh no","code":90}`))
	}))
	c := NewClient(ts.URL, testSplunkToken)
	c.SetMaxContentLength(40)
	c.SetHTTPClient(testHttpClient)
	err := c.WriteRaw(strings.NewReader(events), &metadata)
	assert.Error(t, err)
}

func TestBreakStream(t *testing.T) {
	text := "This is line A\nThis is line B" // length of every line is 14

	getCountFunc := func(counter *int) func(chunk []byte) error {
		// returned function adds count of all character except "\n"
		return func(chunk []byte) error {
			for _, b := range chunk {
				if b != '\n' {
					*counter++
				}
			}
			return nil
		}
	}

	for _, max := range []int{13, 14, 15, 28, 5, 30} {
		var counter int = 0
		err := breakStream(strings.NewReader(text), max, getCountFunc(&counter))
		assert.NoError(t, err)
		assert.Equal(t, 28, counter)
	}
}
<|endoftext|>


<commit_before>package mackerel

import (
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/mackerelio/mackerel-client-go"
)

func resourceMackerelExternalMonitor() *schema.Resource {
	return &schema.Resource{
		Create: resourceMackerelExternalMonitorCreate,
		Read:   resourceMackerelExternalMonitorRead,
		Update: resourceMackerelExternalMonitorUpdate,
		Delete: resourceMackerelExternalMonitorDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"url": {
				Type:     schema.TypeString,
				Required: true,
			},
			"service": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"notification_interval": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"response_time_warning": {
				Type:     schema.TypeFloat,
				Optional: true,
			},
			"response_time_critical": {
				Type:     schema.TypeFloat,
				Optional: true,
			},
			"response_time_duration": {
				Type:     schema.TypeFloat,
				Optional: true,
				//ValidateFunc: validateDurationTime 1 minute - 10 minute
			},
			"contains_string": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"max_check_attempts": {
				Type:     schema.TypeFloat,
				Optional: true,
				Default:  1,
				//ValidateFunc: validateDurationTime 1 - 10
			},
			"certification_expiration_warning": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"certification_expiration_critical": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"is_mute": {
				Type:     schema.TypeBool,
				Optional: true,
			},
		},
	}
}

func resourceMackerelExternalMonitorCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	input := getMackerelExternalMonitorInput(d)
	monitor, err := client.CreateMonitor(input)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q created.", monitor.MonitorID())
	d.SetId(monitor.MonitorID())

	return resourceMackerelExternalMonitorRead(d, meta)
}

func resourceMackerelExternalMonitorRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	log.Printf("[DEBUG] Reading mackerel monitor: %q", d.Id())
	monitors, err := client.FindMonitors()
	if err != nil {
		return err
	}

	for _, monitor := range monitors {
		if monitor.MonitorType() == "external" && monitor.MonitorID() == d.Id() {
			mon := monitor.(*mackerel.MonitorExternalHTTP)
			_ = d.Set("id", mon.MonitorID())
			_ = d.Set("name", mon.MonitorName())
			_ = d.Set("url", mon.URL)
			_ = d.Set("service", mon.Service)
			_ = d.Set("notification_interval", mon.NotificationInterval)
			_ = d.Set("response_time_duration", mon.ResponseTimeDuration)
			_ = d.Set("response_time_warning", mon.ResponseTimeWarning)
			_ = d.Set("response_time_critical", mon.ResponseTimeCritical)
			_ = d.Set("contains_string", mon.ContainsString)
			_ = d.Set("max_check_attempts", mon.MaxCheckAttempts)
			_ = d.Set("certification_expiration_warning", mon.CertificationExpirationWarning)
			_ = d.Set("certification_expiration_critical", mon.CertificationExpirationCritical)
			_ = d.Set("is_mute", mon.IsMute)
			break
		}
	}

	return nil
}

func resourceMackerelExternalMonitorUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	input := getMackerelExternalMonitorInput(d)
	_, err := client.UpdateMonitor(d.Id(), input)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q updated.", d.Id())
	return resourceMackerelExternalMonitorRead(d, meta)
}

func resourceMackerelExternalMonitorDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	_, err := client.DeleteMonitor(d.Id())
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q deleted.", d.Id())
	d.SetId("")

	return nil
}

func getMackerelExternalMonitorInput(d *schema.ResourceData) *mackerel.MonitorExternalHTTP {
	input := &mackerel.MonitorExternalHTTP{
		Type: "external",
		Name: d.Get("name").(string),
		URL:  d.Get("url").(string),
	}

	if v, ok := d.GetOk("service"); ok {
		input.Service = v.(string)
	}
	if v, ok := d.GetOk("notification_interval"); ok {
		input.NotificationInterval = uint64(v.(int))
	}
	if v, ok := d.GetOk("response_time_duration"); ok {
		input.ResponseTimeDuration = puint64(v.(uint64))
	}
	if v, ok := d.GetOk("response_time_warning"); ok {
		input.ResponseTimeWarning = pfloat64(v.(float64))
	}
	if v, ok := d.GetOk("response_time_critical"); ok {
		input.ResponseTimeCritical = pfloat64(v.(float64))
	}
	if v, ok := d.GetOk("contains_string"); ok {
		input.ContainsString = v.(string)
	}
	if v, ok := d.GetOk("max_check_attempts"); ok {
		input.MaxCheckAttempts = v.(uint64)
	}
	if v, ok := d.GetOk("certification_expiration_warning"); ok {
		input.CertificationExpirationWarning = puint64(v.(uint64))
	}
	if v, ok := d.GetOk("certification_expiration_critical"); ok {
		input.CertificationExpirationCritical = puint64(v.(uint64))
	}
	if v, ok := d.GetOk("is_mute"); ok {
		input.IsMute = v.(bool)
	}

	return input
}
<commit_msg>Fix invalid type<commit_after>package mackerel

import (
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/mackerelio/mackerel-client-go"
)

func resourceMackerelExternalMonitor() *schema.Resource {
	return &schema.Resource{
		Create: resourceMackerelExternalMonitorCreate,
		Read:   resourceMackerelExternalMonitorRead,
		Update: resourceMackerelExternalMonitorUpdate,
		Delete: resourceMackerelExternalMonitorDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"url": {
				Type:     schema.TypeString,
				Required: true,
			},
			"service": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"notification_interval": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"response_time_warning": {
				Type:     schema.TypeFloat,
				Optional: true,
			},
			"response_time_critical": {
				Type:     schema.TypeFloat,
				Optional: true,
			},
			"response_time_duration": {
				Type:     schema.TypeFloat,
				Optional: true,
				//ValidateFunc: validateDurationTime 1 minute - 10 minute
			},
			"contains_string": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"max_check_attempts": {
				Type:     schema.TypeFloat,
				Optional: true,
				Default:  1,
				//ValidateFunc: validateDurationTime 1 - 10
			},
			"certification_expiration_warning": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"certification_expiration_critical": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"is_mute": {
				Type:     schema.TypeBool,
				Optional: true,
			},
		},
	}
}

func resourceMackerelExternalMonitorCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	input := getMackerelExternalMonitorInput(d)
	monitor, err := client.CreateMonitor(input)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q created.", monitor.MonitorID())
	d.SetId(monitor.MonitorID())

	return resourceMackerelExternalMonitorRead(d, meta)
}

func resourceMackerelExternalMonitorRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	log.Printf("[DEBUG] Reading mackerel monitor: %q", d.Id())
	monitors, err := client.FindMonitors()
	if err != nil {
		return err
	}

	for _, monitor := range monitors {
		if monitor.MonitorType() == "external" && monitor.MonitorID() == d.Id() {
			mon := monitor.(*mackerel.MonitorExternalHTTP)
			_ = d.Set("id", mon.MonitorID())
			_ = d.Set("name", mon.MonitorName())
			_ = d.Set("url", mon.URL)
			_ = d.Set("service", mon.Service)
			_ = d.Set("notification_interval", mon.NotificationInterval)
			_ = d.Set("response_time_duration", mon.ResponseTimeDuration)
			_ = d.Set("response_time_warning", mon.ResponseTimeWarning)
			_ = d.Set("response_time_critical", mon.ResponseTimeCritical)
			_ = d.Set("contains_string", mon.ContainsString)
			_ = d.Set("max_check_attempts", mon.MaxCheckAttempts)
			_ = d.Set("certification_expiration_warning", mon.CertificationExpirationWarning)
			_ = d.Set("certification_expiration_critical", mon.CertificationExpirationCritical)
			_ = d.Set("is_mute", mon.IsMute)
			break
		}
	}

	return nil
}

func resourceMackerelExternalMonitorUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	input := getMackerelExternalMonitorInput(d)
	_, err := client.UpdateMonitor(d.Id(), input)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q updated.", d.Id())
	return resourceMackerelExternalMonitorRead(d, meta)
}

func resourceMackerelExternalMonitorDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*mackerel.Client)

	_, err := client.DeleteMonitor(d.Id())
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] mackerel monitor %q deleted.", d.Id())
	d.SetId("")

	return nil
}

func getMackerelExternalMonitorInput(d *schema.ResourceData) *mackerel.MonitorExternalHTTP {
	input := &mackerel.MonitorExternalHTTP{
		Type: "external",
		Name: d.Get("name").(string),
		URL:  d.Get("url").(string),
	}

	if v, ok := d.GetOk("service"); ok {
		input.Service = v.(string)
	}
	if v, ok := d.GetOk("notification_interval"); ok {
		input.NotificationInterval = uint64(v.(int))
	}
	if v, ok := d.GetOk("response_time_duration"); ok {
		input.ResponseTimeDuration = puint64(uint64(v.(float64)))
	}
	if v, ok := d.GetOk("response_time_warning"); ok {
		input.ResponseTimeWarning = pfloat64(v.(float64))
	}
	if v, ok := d.GetOk("response_time_critical"); ok {
		input.ResponseTimeCritical = pfloat64(v.(float64))
	}
	if v, ok := d.GetOk("contains_string"); ok {
		input.ContainsString = v.(string)
	}
	if v, ok := d.GetOk("max_check_attempts"); ok {
		input.MaxCheckAttempts = uint64(v.(float64))
	}
	if v, ok := d.GetOk("certification_expiration_warning"); ok {
		input.CertificationExpirationWarning = puint64(uint64(v.(int)))
	}
	if v, ok := d.GetOk("certification_expiration_critical"); ok {
		input.CertificationExpirationCritical = puint64(uint64(v.(int)))
	}
	if v, ok := d.GetOk("is_mute"); ok {
		input.IsMute = v.(bool)
	}

	return input
}
<|endoftext|>


<commit_before>package artisan

import (
    "strings"
    "os"
    "log"
)

func checkFileIsExist(filename string) (bool) {
    var exist = true;
    if _, err := os.Stat(filename); os.IsNotExist(err) {
        exist = false;
    }
    return exist;
}

func CreateProject(name string) {

    pathApp := "controller,exception,middleware,model,router,tool"

    for _, path := range strings.Split(pathApp, ",") {
        path = name + "/src/app/" + path;

        os.MkdirAll(path, os.ModePerm)
    }
    os.MkdirAll(name + "/src/config", os.ModePerm)

    files := map[string]string{}

    // Index
    files["index.go"] = "package main\n\nimport\n(\n    \"app/router\"\n    \"net/http\"\n    \"log\"\n    \"github.com/bysir-zl/bygo/bygo\"\n    \"app/exception\"\n)\n\nfunc main() {\n\n    apiHandle := bygo.NewApiHandler()\n\n    apiHandle.ConfigRouter(\"api\", router.Init)\n    apiHandle.ConfigExceptHandler(exception.Handler)\n    apiHandle.Init()\n\n    http.Handle(\"/api/\", apiHandle);\n    http.Handle(\"/\", http.FileServer(http.Dir(\"./dist\")))\n\n    log.Println(\"server start success\")\n\n    err := http.ListenAndServe(\":81\", nil)\n\n    if err != nil {\n        log.Println(err)\n    }\n}"
    // router
    files["app/router/router.go"] = "package router\n\nimport (\n    \"app/middleware\"\n    \"app/controller\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\nfunc Init(node *http.RouterNode) {\n    node.Middleware(&middleware.HeaderMiddleware{}) // 为当前节点添加上中间件\n\n    node.Get(\"/\", func(request *http.Request, p http.Response) http.ResponseData {\n        return http.NewRespDataHtml(404, \"blank\")\n    })\n\n    node.Controller(\"index\", &controller.IndexController{})\n}\n"
    // IndexController
    files["app/controller/IndexController.go"] = "package controller\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\ntype IndexController struct{}\n\nfunc (p IndexController) Index(r *http.Request, s *http.Response) http.ResponseData {\n\n    return http.NewRespDataHtml(200, \"welcome to use bygo!\" + \"

\" +\n        \"Url: \" + r.Router.Url + \"
\" +\n        \"Handler: \" + r.Router.Handler + \"
\" +\n        \"RouterParams : \" + strings.Join(r.Router.Params, \",\") + \"
\" +\n        \"Input : \" + fmt.Sprint(r.Input.All()) + \"
\" +\n        \"Header : \" + fmt.Sprint(r.Header) + \"
\" +\n        \"\")\n}"

    // HeaderMiddleware
    files["app/middleware/HeaderMiddleware.go"] = "package middleware\n\nimport (\n    \"github.com/bysir-zl/bygo/http\"\n)\n\ntype HeaderMiddleware struct {\n\n}\n\nfunc (p HeaderMiddleware) HandlerBefore(s http.SessionContainer) (needStop bool, data http.ResponseData) {\n    s.Request.Input.Set(\"ext\", \"from middleware\")\n    return false, http.NewRespDataHtml(0, \"\")\n}\n\nfunc (p HeaderMiddleware) HandlerAfter(s http.SessionContainer) (needStop bool, data http.ResponseData) {\n\n    response := s.Response\n    response.ResponseData.Body = response.ResponseData.Body + \"

 i am from middleware\"\n    response.AddHeader(\"Access-Control-Allow-Origin\", \"*\") // 添加上允许跨域\n    response.AddHeader(\"Access-Control-Allow-Headers\", \"X_TOKEN\") // 添加上允许的头,用来身份验证\n\n    return false, http.NewRespDataHtml(0, \"\")\n}\n"

    // HeaderMiddleware
    files["app/exception/Exception.go"] = "package exception\n\nimport (\n    \"github.com/bysir-zl/bygo/bean\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\n// 将报错的Exception处理成Response返回。在这里你可以判断e.Code统一处理错误,比如上报code==500的错误\nfunc Handler(c http.SessionContainer, e http.Exceptions) http.ResponseData {\n    return http.NewRespDataJson(200, bean.ApiData{Code:e.Code, Msg:e.Message})\n}\n"

    // UserModel
    files["app/model/UserModel.go"] = "package model\n\ntype UserModel struct {\n    Table    string  `db:\"user\" json:\"-\"`\n    Connect  string `db:\"default\" json:\"-\"`\n\n    Id       int64 `name:\"id\" pk:\"auto\" json:\"id\"`\n    Password string `name:\"password\" json:\"password,omitempty\"`\n    UserName string `name:\"username\" json:\"username\"`\n\n    CreateAt string `name:\"create_at\" auto:\"time,insert\" json:\"create_at\"`\n    UpdateAt string `name:\"update_at\" auto:\"time,update|insert\" json:\"update_at\"`\n\n    Token    string `json:\"token,omitempty\"`\n}\n    "

    // config - app
    files["config/app.go"] = "package config\n\nvar Debug = true\n"

    // config - chche
    files["config/chche.go"] = "package config\n\nvar CacheDriver = \"redis\"\n"
    // config - db
    files["config/db.go"] = "package config\n\nimport \"github.com/bysir-zl/bygo/db\"\n\nvar DbConfigs map[string]db.DbConfig = map[string]db.DbConfig{}\n\nfunc init() {\n    if !Debug {\n        DbConfigs[\"default\"] = db.DbConfig{\n            Driver:\"mysql\",\n            Host:\"localhost\",\n            Port:3306,\n            Name:\"password\",\n            User:\"root\",\n            Password:\"zhangliang\",\n        }\n    } else {\n        DbConfigs[\"default\"] = db.DbConfig{\n            Driver:\"mysql\",\n            Host:\"localhost\",\n            Port:3306,\n            Name:\"password\",\n            User:\"root\",\n            Password:\"\",\n        }\n    }\n}\n"
    // config - redis
    files["config/redis.go"] = "package config\n\nvar RedisHost = \"127.0.0.1:6379\"\n"

    // 写入文件
    for filename, content := range files {
        filename = name + "/src/" + filename
        var f *os.File
        var err error
        if checkFileIsExist(filename) {
            f, err = os.OpenFile(filename, os.O_RDWR, os.ModePerm)
            if err != nil {
                panic(err)
            }

        } else {
            f, err = os.Create(filename)
            if err != nil {
                panic(err)
            }
        }

        f.Write([]byte(content))
    }

    log.Print("create success")
}<commit_msg>fix bug<commit_after>package artisan

import (
    "strings"
    "os"
    "log"
)

func checkFileIsExist(filename string) (bool) {
    var exist = true;
    if _, err := os.Stat(filename); os.IsNotExist(err) {
        exist = false;
    }
    return exist;
}

func CreateProject(name string) {

    pathApp := "controller,exception,middleware,model,router,tool"

    for _, path := range strings.Split(pathApp, ",") {
        path = name + "/src/app/" + path;

        os.MkdirAll(path, os.ModePerm)
    }
    os.MkdirAll(name + "/src/config", os.ModePerm)

    files := map[string]string{}

    // Index
    files["index.go"] = "package main\n\nimport\n(\n    \"app/router\"\n    \"net/http\"\n    \"log\"\n    \"github.com/bysir-zl/bygo/bygo\"\n    \"app/exception\"\n)\n\nfunc main() {\n\n    apiHandle := bygo.NewApiHandler()\n\n    apiHandle.ConfigRouter(\"api\", router.Init)\n    apiHandle.ConfigExceptHandler(exception.Handler)\n    apiHandle.Init()\n\n    http.Handle(\"/api/\", apiHandle);\n    http.Handle(\"/\", http.FileServer(http.Dir(\"./dist\")))\n\n    log.Println(\"server start success\")\n\n    err := http.ListenAndServe(\":81\", nil)\n\n    if err != nil {\n        log.Println(err)\n    }\n}"
    // router
    files["app/router/router.go"] = "package router\n\nimport (\n    \"app/middleware\"\n    \"app/controller\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\nfunc Init(node *http.RouterNode) {\n    node.Middleware(&middleware.HeaderMiddleware{}) // 为当前节点添加上中间件\n\n    node.Get(\"/\", func(request *http.Request, p *http.Response) http.ResponseData {\n        return http.NewRespDataHtml(404, \"blank\")\n    })\n\n    node.Controller(\"index\", &controller.IndexController{})\n}\n"
    // IndexController
    files["app/controller/IndexController.go"] = "package controller\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\ntype IndexController struct{}\n\nfunc (p IndexController) Index(r *http.Request, s *http.Response) http.ResponseData {\n\n    return http.NewRespDataHtml(200, \"welcome to use bygo!\" + \"

\" +\n        \"Url: \" + r.Router.Url + \"
\" +\n        \"Handler: \" + r.Router.Handler + \"
\" +\n        \"RouterParams : \" + strings.Join(r.Router.Params, \",\") + \"
\" +\n        \"Input : \" + fmt.Sprint(r.Input.All()) + \"
\" +\n        \"Header : \" + fmt.Sprint(r.Header) + \"
\" +\n        \"\")\n}"

    // HeaderMiddleware
    files["app/middleware/HeaderMiddleware.go"] = "package middleware\n\nimport (\n    \"github.com/bysir-zl/bygo/http\"\n)\n\ntype HeaderMiddleware struct {\n\n}\n\nfunc (p HeaderMiddleware) HandlerBefore(s http.SessionContainer) (needStop bool, data http.ResponseData) {\n    s.Request.Input.Set(\"ext\", \"from middleware\")\n    return false, http.NewRespDataHtml(0, \"\")\n}\n\nfunc (p HeaderMiddleware) HandlerAfter(s http.SessionContainer) (needStop bool, data http.ResponseData) {\n\n    response := s.Response\n    response.ResponseData.Body = response.ResponseData.Body + \"

 i am from middleware\"\n    response.AddHeader(\"Access-Control-Allow-Origin\", \"*\") // 添加上允许跨域\n    response.AddHeader(\"Access-Control-Allow-Headers\", \"X_TOKEN\") // 添加上允许的头,用来身份验证\n\n    return false, http.NewRespDataHtml(0, \"\")\n}\n"

    // HeaderMiddleware
    files["app/exception/Exception.go"] = "package exception\n\nimport (\n    \"github.com/bysir-zl/bygo/bean\"\n    \"github.com/bysir-zl/bygo/http\"\n)\n\n// 将报错的Exception处理成Response返回。在这里你可以判断e.Code统一处理错误,比如上报code==500的错误\nfunc Handler(c http.SessionContainer, e http.Exceptions) http.ResponseData {\n    return http.NewRespDataJson(200, bean.ApiData{Code:e.Code, Msg:e.Message})\n}\n"

    // UserModel
    files["app/model/UserModel.go"] = "package model\n\ntype UserModel struct {\n    Table    string  `db:\"user\" json:\"-\"`\n    Connect  string `db:\"default\" json:\"-\"`\n\n    Id       int64 `name:\"id\" pk:\"auto\" json:\"id\"`\n    Password string `name:\"password\" json:\"password,omitempty\"`\n    UserName string `name:\"username\" json:\"username\"`\n\n    CreateAt string `name:\"create_at\" auto:\"time,insert\" json:\"create_at\"`\n    UpdateAt string `name:\"update_at\" auto:\"time,update|insert\" json:\"update_at\"`\n\n    Token    string `json:\"token,omitempty\"`\n}\n    "

    // config - app
    files["config/app.go"] = "package config\n\nvar Debug = true\n"

    // config - chche
    files["config/chche.go"] = "package config\n\nvar CacheDriver = \"redis\"\n"
    // config - db
    files["config/db.go"] = "package config\n\nimport \"github.com/bysir-zl/bygo/db\"\n\nvar DbConfigs map[string]db.DbConfig = map[string]db.DbConfig{}\n\nfunc init() {\n    if !Debug {\n        DbConfigs[\"default\"] = db.DbConfig{\n            Driver:\"mysql\",\n            Host:\"localhost\",\n            Port:3306,\n            Name:\"password\",\n            User:\"root\",\n            Password:\"zhangliang\",\n        }\n    } else {\n        DbConfigs[\"default\"] = db.DbConfig{\n            Driver:\"mysql\",\n            Host:\"localhost\",\n            Port:3306,\n            Name:\"password\",\n            User:\"root\",\n            Password:\"\",\n        }\n    }\n}\n"
    // config - redis
    files["config/redis.go"] = "package config\n\nvar RedisHost = \"127.0.0.1:6379\"\n"

    // 写入文件
    for filename, content := range files {
        filename = name + "/src/" + filename
        var f *os.File
        var err error
        if checkFileIsExist(filename) {
            f, err = os.OpenFile(filename, os.O_RDWR, os.ModePerm)
            if err != nil {
                panic(err)
            }

        } else {
            f, err = os.Create(filename)
            if err != nil {
                panic(err)
            }
        }

        f.Write([]byte(content))
    }

    log.Print("create success")
}<|endoftext|>


<commit_before>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cipher

import (
	"crypto/subtle"
	"errors"
)

// AEAD is a cipher mode providing authenticated encryption with associated
// data.
type AEAD interface {
	// NonceSize returns the size of the nonce that must be passed to Seal
	// and Open.
	NonceSize() int

	// Overhead returns the maximum difference between the lengths of a
	// plaintext and ciphertext.
	Overhead() int

	// Seal encrypts and authenticates plaintext, authenticates the
	// additional data and appends the result to dst, returning the updated
	// slice. The nonce must be NonceSize() bytes long and unique for all
	// time, for a given key.
	//
	// The plaintext and dst may alias exactly or not at all.
	Seal(dst, nonce, plaintext, data []byte) []byte

	// Open decrypts and authenticates ciphertext, authenticates the
	// additional data and, if successful, appends the resulting plaintext
	// to dst, returning the updated slice and true. On error, nil and
	// false is returned. The nonce must be NonceSize() bytes long and both
	// it and the additional data must match the value passed to Seal.
	//
	// The ciphertext and dst may alias exactly or not at all.
	Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
}

// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make getUint64 suitable for marshaling these values, the bits
// are stored backwards. For example:
//   the coefficient of x⁰ can be obtained by v.low >> 63.
//   the coefficient of x⁶³ can be obtained by v.low & 1.
//   the coefficient of x⁶⁴ can be obtained by v.high >> 63.
//   the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
	low, high uint64
}

// gcm represents a Galois Counter Mode with a specific key. See
// http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
	cipher Block
	// productTable contains the first sixteen powers of the key, H.
	// However, they are in bit reversed order. See NewGCM.
	productTable [16]gcmFieldElement
}

// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode.
func NewGCM(cipher Block) (AEAD, error) {
	if cipher.BlockSize() != gcmBlockSize {
		return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
	}

	var key [gcmBlockSize]byte
	cipher.Encrypt(key[:], key[:])

	g := &gcm{cipher: cipher}

	// We precompute 16 multiples of |key|. However, when we do lookups
	// into this table we'll be using bits from a field element and
	// therefore the bits will be in the reverse order. So normally one
	// would expect, say, 4*key to be in index 4 of the table but due to
	// this bit ordering it will actually be in index 0010 (base 2) = 2.
	x := gcmFieldElement{
		getUint64(key[:8]),
		getUint64(key[8:]),
	}
	g.productTable[reverseBits(1)] = x

	for i := 2; i < 16; i += 2 {
		g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
		g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
	}

	return g, nil
}

const (
	gcmBlockSize = 16
	gcmTagSize   = 16
	gcmNonceSize = 12
)

func (*gcm) NonceSize() int {
	return gcmNonceSize
}

func (*gcm) Overhead() int {
	return gcmTagSize
}

func (g *gcm) Seal(dst, nonce, plaintext, data []byte) []byte {
	if len(nonce) != gcmNonceSize {
		panic("cipher: incorrect nonce length given to GCM")
	}

	ret, out := sliceForAppend(dst, len(plaintext)+gcmTagSize)

	// See GCM spec, section 7.1.
	var counter, tagMask [gcmBlockSize]byte
	copy(counter[:], nonce)
	counter[gcmBlockSize-1] = 1

	g.cipher.Encrypt(tagMask[:], counter[:])
	gcmInc32(&counter)

	g.counterCrypt(out, plaintext, &counter)
	g.auth(out[len(plaintext):], out[:len(plaintext)], data, &tagMask)

	return ret
}

var errOpen = errors.New("cipher: message authentication failed")

func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(nonce) != gcmNonceSize {
		panic("cipher: incorrect nonce length given to GCM")
	}

	if len(ciphertext) < gcmTagSize {
		return nil, errOpen
	}
	tag := ciphertext[len(ciphertext)-gcmTagSize:]
	ciphertext = ciphertext[:len(ciphertext)-gcmTagSize]

	// See GCM spec, section 7.1.
	var counter, tagMask [gcmBlockSize]byte
	copy(counter[:], nonce)
	counter[gcmBlockSize-1] = 1

	g.cipher.Encrypt(tagMask[:], counter[:])
	gcmInc32(&counter)

	var expectedTag [gcmTagSize]byte
	g.auth(expectedTag[:], ciphertext, data, &tagMask)

	if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 {
		return nil, errOpen
	}

	ret, out := sliceForAppend(dst, len(ciphertext))
	g.counterCrypt(out, ciphertext, &counter)

	return ret, nil
}

// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
	i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
	i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
	return i
}

// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
	// Addition in a characteristic 2 field is just XOR.
	return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}

// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
	msbSet := x.high&1 == 1

	// Because of the bit-ordering, doubling is actually a right shift.
	double.high = x.high >> 1
	double.high |= x.low << 63
	double.low = x.low >> 1

	// If the most-significant bit was set before shifting then it,
	// conceptually, becomes a term of x^128. This is greater than the
	// irreducible polynomial so the result has to be reduced. The
	// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
	// eliminate the term at x^128 which also means subtracting the other
	// four terms. In characteristic 2 fields, subtraction == addition ==
	// XOR.
	if msbSet {
		double.low ^= 0xe100000000000000
	}

	return
}

var gcmReductionTable = []uint16{
	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}

// mul sets y to y*H, where H is the GCM key, fixed during NewGCM.
func (g *gcm) mul(y *gcmFieldElement) {
	var z gcmFieldElement

	for i := 0; i < 2; i++ {
		word := y.high
		if i == 1 {
			word = y.low
		}

		// Multiplication works by multiplying z by 16 and adding in
		// one of the precomputed multiples of H.
		for j := 0; j < 64; j += 4 {
			msw := z.high & 0xf
			z.high >>= 4
			z.high |= z.low << 60
			z.low >>= 4
			z.low ^= uint64(gcmReductionTable[msw]) << 48

			// the values in |table| are ordered for
			// little-endian bit positions. See the comment
			// in NewGCM.
			t := &g.productTable[word&0xf]

			z.low ^= t.low
			z.high ^= t.high
			word >>= 4
		}
	}

	*y = z
}

// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
	for len(blocks) > 0 {
		y.low ^= getUint64(blocks)
		y.high ^= getUint64(blocks[8:])
		g.mul(y)
		blocks = blocks[gcmBlockSize:]
	}
}

// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
	fullBlocks := (len(data) >> 4) << 4
	g.updateBlocks(y, data[:fullBlocks])

	if len(data) != fullBlocks {
		var partialBlock [gcmBlockSize]byte
		copy(partialBlock[:], data[fullBlocks:])
		g.updateBlocks(y, partialBlock[:])
	}
}

// gcmInc32 treats the final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
	c := 1
	for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- {
		c += int(counterBlock[i])
		counterBlock[i] = byte(c)
		c >>= 8
	}
}

// sliceForAppend takes a slice and a requested number of bytes. It returns a
// slice with the contents of the given slice followed by that many bytes and a
// second slice that aliases into it and contains only the extra bytes. If the
// original slice has sufficient capacity then no allocation is performed.
func sliceForAppend(in []byte, n int) (head, tail []byte) {
	if total := len(in) + n; cap(in) >= total {
		head = in[:total]
	} else {
		head = make([]byte, total)
		copy(head, in)
	}
	tail = head[len(in):]
	return
}

// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
	var mask [gcmBlockSize]byte

	for len(in) >= gcmBlockSize {
		g.cipher.Encrypt(mask[:], counter[:])
		gcmInc32(counter)

		xorWords(out, in, mask[:])
		out = out[gcmBlockSize:]
		in = in[gcmBlockSize:]
	}

	if len(in) > 0 {
		g.cipher.Encrypt(mask[:], counter[:])
		gcmInc32(counter)
		xorBytes(out, in, mask[:])
	}
}

// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
	var y gcmFieldElement
	g.update(&y, additionalData)
	g.update(&y, ciphertext)

	y.low ^= uint64(len(additionalData)) * 8
	y.high ^= uint64(len(ciphertext)) * 8

	g.mul(&y)

	putUint64(out, y.low)
	putUint64(out[8:], y.high)

	xorWords(out, out, tagMask[:])
}

func getUint64(data []byte) uint64 {
	r := uint64(data[0])<<56 |
		uint64(data[1])<<48 |
		uint64(data[2])<<40 |
		uint64(data[3])<<32 |
		uint64(data[4])<<24 |
		uint64(data[5])<<16 |
		uint64(data[6])<<8 |
		uint64(data[7])
	return r
}

func putUint64(out []byte, v uint64) {
	out[0] = byte(v >> 56)
	out[1] = byte(v >> 48)
	out[2] = byte(v >> 40)
	out[3] = byte(v >> 32)
	out[4] = byte(v >> 24)
	out[5] = byte(v >> 16)
	out[6] = byte(v >> 8)
	out[7] = byte(v)
}
<commit_msg>crypto/cipher: speed up gcmInc32.<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cipher

import (
	"crypto/subtle"
	"errors"
)

// AEAD is a cipher mode providing authenticated encryption with associated
// data.
type AEAD interface {
	// NonceSize returns the size of the nonce that must be passed to Seal
	// and Open.
	NonceSize() int

	// Overhead returns the maximum difference between the lengths of a
	// plaintext and ciphertext.
	Overhead() int

	// Seal encrypts and authenticates plaintext, authenticates the
	// additional data and appends the result to dst, returning the updated
	// slice. The nonce must be NonceSize() bytes long and unique for all
	// time, for a given key.
	//
	// The plaintext and dst may alias exactly or not at all.
	Seal(dst, nonce, plaintext, data []byte) []byte

	// Open decrypts and authenticates ciphertext, authenticates the
	// additional data and, if successful, appends the resulting plaintext
	// to dst, returning the updated slice and true. On error, nil and
	// false is returned. The nonce must be NonceSize() bytes long and both
	// it and the additional data must match the value passed to Seal.
	//
	// The ciphertext and dst may alias exactly or not at all.
	Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
}

// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
// standard and make getUint64 suitable for marshaling these values, the bits
// are stored backwards. For example:
//   the coefficient of x⁰ can be obtained by v.low >> 63.
//   the coefficient of x⁶³ can be obtained by v.low & 1.
//   the coefficient of x⁶⁴ can be obtained by v.high >> 63.
//   the coefficient of x¹²⁷ can be obtained by v.high & 1.
type gcmFieldElement struct {
	low, high uint64
}

// gcm represents a Galois Counter Mode with a specific key. See
// http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
type gcm struct {
	cipher Block
	// productTable contains the first sixteen powers of the key, H.
	// However, they are in bit reversed order. See NewGCM.
	productTable [16]gcmFieldElement
}

// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode.
func NewGCM(cipher Block) (AEAD, error) {
	if cipher.BlockSize() != gcmBlockSize {
		return nil, errors.New("cipher: NewGCM requires 128-bit block cipher")
	}

	var key [gcmBlockSize]byte
	cipher.Encrypt(key[:], key[:])

	g := &gcm{cipher: cipher}

	// We precompute 16 multiples of |key|. However, when we do lookups
	// into this table we'll be using bits from a field element and
	// therefore the bits will be in the reverse order. So normally one
	// would expect, say, 4*key to be in index 4 of the table but due to
	// this bit ordering it will actually be in index 0010 (base 2) = 2.
	x := gcmFieldElement{
		getUint64(key[:8]),
		getUint64(key[8:]),
	}
	g.productTable[reverseBits(1)] = x

	for i := 2; i < 16; i += 2 {
		g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)])
		g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x)
	}

	return g, nil
}

const (
	gcmBlockSize = 16
	gcmTagSize   = 16
	gcmNonceSize = 12
)

func (*gcm) NonceSize() int {
	return gcmNonceSize
}

func (*gcm) Overhead() int {
	return gcmTagSize
}

func (g *gcm) Seal(dst, nonce, plaintext, data []byte) []byte {
	if len(nonce) != gcmNonceSize {
		panic("cipher: incorrect nonce length given to GCM")
	}

	ret, out := sliceForAppend(dst, len(plaintext)+gcmTagSize)

	// See GCM spec, section 7.1.
	var counter, tagMask [gcmBlockSize]byte
	copy(counter[:], nonce)
	counter[gcmBlockSize-1] = 1

	g.cipher.Encrypt(tagMask[:], counter[:])
	gcmInc32(&counter)

	g.counterCrypt(out, plaintext, &counter)
	g.auth(out[len(plaintext):], out[:len(plaintext)], data, &tagMask)

	return ret
}

var errOpen = errors.New("cipher: message authentication failed")

func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(nonce) != gcmNonceSize {
		panic("cipher: incorrect nonce length given to GCM")
	}

	if len(ciphertext) < gcmTagSize {
		return nil, errOpen
	}
	tag := ciphertext[len(ciphertext)-gcmTagSize:]
	ciphertext = ciphertext[:len(ciphertext)-gcmTagSize]

	// See GCM spec, section 7.1.
	var counter, tagMask [gcmBlockSize]byte
	copy(counter[:], nonce)
	counter[gcmBlockSize-1] = 1

	g.cipher.Encrypt(tagMask[:], counter[:])
	gcmInc32(&counter)

	var expectedTag [gcmTagSize]byte
	g.auth(expectedTag[:], ciphertext, data, &tagMask)

	if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 {
		return nil, errOpen
	}

	ret, out := sliceForAppend(dst, len(ciphertext))
	g.counterCrypt(out, ciphertext, &counter)

	return ret, nil
}

// reverseBits reverses the order of the bits of 4-bit number in i.
func reverseBits(i int) int {
	i = ((i << 2) & 0xc) | ((i >> 2) & 0x3)
	i = ((i << 1) & 0xa) | ((i >> 1) & 0x5)
	return i
}

// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum.
func gcmAdd(x, y *gcmFieldElement) gcmFieldElement {
	// Addition in a characteristic 2 field is just XOR.
	return gcmFieldElement{x.low ^ y.low, x.high ^ y.high}
}

// gcmDouble returns the result of doubling an element of GF(2¹²⁸).
func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) {
	msbSet := x.high&1 == 1

	// Because of the bit-ordering, doubling is actually a right shift.
	double.high = x.high >> 1
	double.high |= x.low << 63
	double.low = x.low >> 1

	// If the most-significant bit was set before shifting then it,
	// conceptually, becomes a term of x^128. This is greater than the
	// irreducible polynomial so the result has to be reduced. The
	// irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to
	// eliminate the term at x^128 which also means subtracting the other
	// four terms. In characteristic 2 fields, subtraction == addition ==
	// XOR.
	if msbSet {
		double.low ^= 0xe100000000000000
	}

	return
}

var gcmReductionTable = []uint16{
	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
}

// mul sets y to y*H, where H is the GCM key, fixed during NewGCM.
func (g *gcm) mul(y *gcmFieldElement) {
	var z gcmFieldElement

	for i := 0; i < 2; i++ {
		word := y.high
		if i == 1 {
			word = y.low
		}

		// Multiplication works by multiplying z by 16 and adding in
		// one of the precomputed multiples of H.
		for j := 0; j < 64; j += 4 {
			msw := z.high & 0xf
			z.high >>= 4
			z.high |= z.low << 60
			z.low >>= 4
			z.low ^= uint64(gcmReductionTable[msw]) << 48

			// the values in |table| are ordered for
			// little-endian bit positions. See the comment
			// in NewGCM.
			t := &g.productTable[word&0xf]

			z.low ^= t.low
			z.high ^= t.high
			word >>= 4
		}
	}

	*y = z
}

// updateBlocks extends y with more polynomial terms from blocks, based on
// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {
	for len(blocks) > 0 {
		y.low ^= getUint64(blocks)
		y.high ^= getUint64(blocks[8:])
		g.mul(y)
		blocks = blocks[gcmBlockSize:]
	}
}

// update extends y with more polynomial terms from data. If data is not a
// multiple of gcmBlockSize bytes long then the remainder is zero padded.
func (g *gcm) update(y *gcmFieldElement, data []byte) {
	fullBlocks := (len(data) >> 4) << 4
	g.updateBlocks(y, data[:fullBlocks])

	if len(data) != fullBlocks {
		var partialBlock [gcmBlockSize]byte
		copy(partialBlock[:], data[fullBlocks:])
		g.updateBlocks(y, partialBlock[:])
	}
}

// gcmInc32 treats the final four bytes of counterBlock as a big-endian value
// and increments it.
func gcmInc32(counterBlock *[16]byte) {
	for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- {
		counterBlock[i]++
		if counterBlock[i] != 0 {
			break
		}
	}
}

// sliceForAppend takes a slice and a requested number of bytes. It returns a
// slice with the contents of the given slice followed by that many bytes and a
// second slice that aliases into it and contains only the extra bytes. If the
// original slice has sufficient capacity then no allocation is performed.
func sliceForAppend(in []byte, n int) (head, tail []byte) {
	if total := len(in) + n; cap(in) >= total {
		head = in[:total]
	} else {
		head = make([]byte, total)
		copy(head, in)
	}
	tail = head[len(in):]
	return
}

// counterCrypt crypts in to out using g.cipher in counter mode.
func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) {
	var mask [gcmBlockSize]byte

	for len(in) >= gcmBlockSize {
		g.cipher.Encrypt(mask[:], counter[:])
		gcmInc32(counter)

		xorWords(out, in, mask[:])
		out = out[gcmBlockSize:]
		in = in[gcmBlockSize:]
	}

	if len(in) > 0 {
		g.cipher.Encrypt(mask[:], counter[:])
		gcmInc32(counter)
		xorBytes(out, in, mask[:])
	}
}

// auth calculates GHASH(ciphertext, additionalData), masks the result with
// tagMask and writes the result to out.
func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) {
	var y gcmFieldElement
	g.update(&y, additionalData)
	g.update(&y, ciphertext)

	y.low ^= uint64(len(additionalData)) * 8
	y.high ^= uint64(len(ciphertext)) * 8

	g.mul(&y)

	putUint64(out, y.low)
	putUint64(out[8:], y.high)

	xorWords(out, out, tagMask[:])
}

func getUint64(data []byte) uint64 {
	r := uint64(data[0])<<56 |
		uint64(data[1])<<48 |
		uint64(data[2])<<40 |
		uint64(data[3])<<32 |
		uint64(data[4])<<24 |
		uint64(data[5])<<16 |
		uint64(data[6])<<8 |
		uint64(data[7])
	return r
}

func putUint64(out []byte, v uint64) {
	out[0] = byte(v >> 56)
	out[1] = byte(v >> 48)
	out[2] = byte(v >> 40)
	out[3] = byte(v >> 32)
	out[4] = byte(v >> 24)
	out[5] = byte(v >> 16)
	out[6] = byte(v >> 8)
	out[7] = byte(v)
}
<|endoftext|>


<commit_before>// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows

package net

import (
	"os"
	"runtime"
	"syscall"
)

// Boolean to int.
func boolint(b bool) int {
	if b {
		return 1
	}
	return 0
}

func ipv4AddrToInterface(ip IP) (*Interface, error) {
	ift, err := Interfaces()
	if err != nil {
		return nil, err
	}
	for _, ifi := range ift {
		ifat, err := ifi.Addrs()
		if err != nil {
			return nil, err
		}
		for _, ifa := range ifat {
			switch v := ifa.(type) {
			case *IPAddr:
				if ip.Equal(v.IP) {
					return &ifi, nil
				}
			case *IPNet:
				if ip.Equal(v.IP) {
					return &ifi, nil
				}
			}
		}
	}
	if ip.Equal(IPv4zero) {
		return nil, nil
	}
	return nil, errNoSuchInterface
}

func interfaceToIPv4Addr(ifi *Interface) (IP, error) {
	if ifi == nil {
		return IPv4zero, nil
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return nil, err
	}
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *IPAddr:
			if v.IP.To4() != nil {
				return v.IP, nil
			}
		case *IPNet:
			if v.IP.To4() != nil {
				return v.IP, nil
			}
		}
	}
	return nil, errNoSuchInterface
}

func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error {
	if ifi == nil {
		return nil
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return err
	}
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *IPAddr:
			if a := v.IP.To4(); a != nil {
				copy(mreq.Interface[:], a)
				goto done
			}
		case *IPNet:
			if a := v.IP.To4(); a != nil {
				copy(mreq.Interface[:], a)
				goto done
			}
		}
	}
done:
	if bytesEqual(mreq.Multiaddr[:], IPv4zero.To4()) {
		return errNoSuchMulticastInterface
	}
	return nil
}

func setReadBuffer(fd *netFD, bytes int) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes))
}

func setWriteBuffer(fd *netFD, bytes int) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes))
}

func setKeepAlive(fd *netFD, keepalive bool) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)))
}

func setLinger(fd *netFD, sec int) error {
	var l syscall.Linger
	if sec >= 0 {
		l.Onoff = 1
		l.Linger = int32(sec)
	} else {
		l.Onoff = 0
		l.Linger = 0
	}
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	opt := syscall.SO_LINGER
	if runtime.GOOS == "darwin" {
		opt = syscall.SO_LINGER_SEC
	}
	return os.NewSyscallError("setsockopt", syscall.SetsockoptLinger(fd.sysfd, syscall.SOL_SOCKET, opt, &l))
}
<commit_msg>undo CL 92210044 / 5cb21eee2d35<commit_after>// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows

package net

import (
	"os"
	"syscall"
)

// Boolean to int.
func boolint(b bool) int {
	if b {
		return 1
	}
	return 0
}

func ipv4AddrToInterface(ip IP) (*Interface, error) {
	ift, err := Interfaces()
	if err != nil {
		return nil, err
	}
	for _, ifi := range ift {
		ifat, err := ifi.Addrs()
		if err != nil {
			return nil, err
		}
		for _, ifa := range ifat {
			switch v := ifa.(type) {
			case *IPAddr:
				if ip.Equal(v.IP) {
					return &ifi, nil
				}
			case *IPNet:
				if ip.Equal(v.IP) {
					return &ifi, nil
				}
			}
		}
	}
	if ip.Equal(IPv4zero) {
		return nil, nil
	}
	return nil, errNoSuchInterface
}

func interfaceToIPv4Addr(ifi *Interface) (IP, error) {
	if ifi == nil {
		return IPv4zero, nil
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return nil, err
	}
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *IPAddr:
			if v.IP.To4() != nil {
				return v.IP, nil
			}
		case *IPNet:
			if v.IP.To4() != nil {
				return v.IP, nil
			}
		}
	}
	return nil, errNoSuchInterface
}

func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error {
	if ifi == nil {
		return nil
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return err
	}
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *IPAddr:
			if a := v.IP.To4(); a != nil {
				copy(mreq.Interface[:], a)
				goto done
			}
		case *IPNet:
			if a := v.IP.To4(); a != nil {
				copy(mreq.Interface[:], a)
				goto done
			}
		}
	}
done:
	if bytesEqual(mreq.Multiaddr[:], IPv4zero.To4()) {
		return errNoSuchMulticastInterface
	}
	return nil
}

func setReadBuffer(fd *netFD, bytes int) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes))
}

func setWriteBuffer(fd *netFD, bytes int) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes))
}

func setKeepAlive(fd *netFD, keepalive bool) error {
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)))
}

func setLinger(fd *netFD, sec int) error {
	var l syscall.Linger
	if sec >= 0 {
		l.Onoff = 1
		l.Linger = int32(sec)
	} else {
		l.Onoff = 0
		l.Linger = 0
	}
	if err := fd.incref(); err != nil {
		return err
	}
	defer fd.decref()
	return os.NewSyscallError("setsockopt", syscall.SetsockoptLinger(fd.sysfd, syscall.SOL_SOCKET, syscall.SO_LINGER, &l))
}
<|endoftext|>