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

package helpers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/cilium/cilium/test/config"

	"github.com/onsi/gomega"
	"github.com/onsi/gomega/types"
	"k8s.io/client-go/util/jsonpath"
)

// CmdRes contains a variety of data which results from running a command.
type CmdRes struct {
	cmd      string        // Command to run
	params   []string      // Parameters to provide to command
	stdout   *bytes.Buffer // Stdout from running cmd
	stderr   *bytes.Buffer // Stderr from running cmd
	success  bool          // Whether command successfully executed
	exitcode int           // The exit code of cmd
	duration time.Duration // Is the representation of the the time that command took to execute.
}

// GetCmd returns res's cmd.
func (res *CmdRes) GetCmd() string {
	return res.cmd
}

// GetExitCode returns res's exitcode.
func (res *CmdRes) GetExitCode() int {
	return res.exitcode
}

// GetStdOut returns the contents of the stdout buffer of res as a string.
func (res *CmdRes) GetStdOut() string {
	return res.stdout.String()
}

// GetStdErr returns the contents of the stderr buffer of res as a string.
func (res *CmdRes) GetStdErr() string {
	return res.stderr.String()
}

// SendToLog writes to `TestLogWriter` the debug message for the running
// command, if the quietMode argument is true will print only the command and
// the exitcode.
func (res *CmdRes) SendToLog(quietMode bool) {
	if quietMode {
		logformat := "cmd: %q exitCode: %d duration: %s\n"
		fmt.Fprintf(&config.TestLogWriter, logformat, res.cmd, res.GetExitCode(), res.duration)
		return
	}

	logformat := "cmd: %q exitCode: %d duration: %s stdout:\n%s\n"
	log := fmt.Sprintf(logformat, res.cmd, res.GetExitCode(), res.duration, res.stdout.String())
	if res.stderr.Len() > 0 {
		log = fmt.Sprintf("%sstderr:\n%s\n", log, res.stderr.String())
	}
	fmt.Fprintf(&config.TestLogWriter, log)
}

// WasSuccessful returns true if cmd completed successfully.
func (res *CmdRes) WasSuccessful() bool {
	return res.success
}

// ExpectFail asserts whether res failed to execute. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectFail(optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res).ShouldNot(
		CMDSuccess(), optionalDescription...)
}

// ExpectSuccess asserts whether res executed successfully. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectSuccess(optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res).Should(
		CMDSuccess(), optionalDescription...)
}

// ExpectContains asserts a string into the stdout of the response of executed
// command. It accepts an optional parameter that can be used to annotate
// failure messages.
func (res *CmdRes) ExpectContains(data string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).To(
		gomega.ContainSubstring(data), optionalDescription...)
}

// ExpectDoesNotContain asserts that a string is not contained in the stdout of
// the executed command. It accepts an optional parameter that can be used to
// annotate failure messages.
func (res *CmdRes) ExpectDoesNotContain(data string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
		gomega.ContainSubstring(data), optionalDescription...)
}

// ExpectDoesNotMatchRegexp asserts that the stdout of the executed command
// doesn't match the regexp. It accepts an optional parameter that can be used
// to annotate failure messages.
func (res *CmdRes) ExpectDoesNotMatchRegexp(regexp string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
		gomega.MatchRegexp(regexp), optionalDescription...)
}

// CountLines return the number of lines in the stdout of res.
func (res *CmdRes) CountLines() int {
	return strings.Count(res.stdout.String(), "\n")
}

// CombineOutput returns the combined output of stdout and stderr for res.
func (res *CmdRes) CombineOutput() *bytes.Buffer {
	result := new(bytes.Buffer)
	result.WriteString(res.stdout.String())
	result.WriteString(res.stderr.String())
	return result
}

// IntOutput returns the stdout of res as an integer
func (res *CmdRes) IntOutput() (int, error) {
	return strconv.Atoi(strings.Trim(res.stdout.String(), "\n"))
}

// FindResults filters res's stdout using the provided JSONPath filter. It
// returns an array of the values that match the filter, and an error if
// the unmarshalling of the stdout of res fails.
// TODO - what exactly is the need for this vs. Filter function below?
func (res *CmdRes) FindResults(filter string) ([]reflect.Value, error) {

	var data interface{}
	var result []reflect.Value

	err := json.Unmarshal(res.stdout.Bytes(), &data)
	if err != nil {
		return nil, err
	}
	parser := jsonpath.New("").AllowMissingKeys(true)
	parser.Parse(filter)
	fullResults, _ := parser.FindResults(data)
	for _, res := range fullResults {
		for _, val := range res {
			result = append(result, val)
		}
	}
	return result, nil
}

// Filter returns the contents of res's stdout filtered using the provided
// JSONPath filter in a buffer. Returns an error if the unmarshalling of the
// contents of res's stdout fails.
func (res *CmdRes) Filter(filter string) (*FilterBuffer, error) {
	var data interface{}
	result := new(bytes.Buffer)

	err := json.Unmarshal(res.stdout.Bytes(), &data)
	if err != nil {
		return nil, fmt.Errorf("could not parse JSON from command %q",
			res.cmd)
	}
	parser := jsonpath.New("").AllowMissingKeys(true)
	parser.Parse(filter)
	err = parser.Execute(result, data)
	if err != nil {
		return nil, err
	}
	return &FilterBuffer{result}, nil
}

// ByLines returns res's stdout split by the newline character .
func (res *CmdRes) ByLines() []string {
	return strings.Split(res.stdout.String(), "\n")
}

// KVOutput returns a map of the stdout of res split based on
// the separator '='.
// For example, the following strings would be split as follows:
// 		a=1
// 		b=2
// 		c=3
func (res *CmdRes) KVOutput() map[string]string {
	result := make(map[string]string)
	for _, line := range res.ByLines() {
		vals := strings.Split(line, "=")
		if len(vals) == 2 {
			result[vals[0]] = vals[1]
		}
	}
	return result
}

// Output returns res's stdout.
func (res *CmdRes) Output() *bytes.Buffer {
	return res.stdout
}

// OutputPrettyPrint returns a string with the ExitCode, stdout and stderr in a
// pretty format.
func (res *CmdRes) OutputPrettyPrint() string {
	format := func(message string) string {
		result := []string{}
		for _, line := range strings.Split(message, "\n") {
			result = append(result, fmt.Sprintf("\t %s", line))
		}
		return strings.Join(result, "\n")

	}
	return fmt.Sprintf(
		"Exitcode: %d \nStdout:\n %s\nStderr:\n %s\n",
		res.GetExitCode(),
		format(res.GetStdOut()),
		format(res.GetStdErr()))
}

// ExpectEqual asserts whether cmdRes.Output().String() and expected are equal.
// It accepts an optional parameter that can be used to annotate failure
// messages.
func (res *CmdRes) ExpectEqual(expected string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).Should(
		gomega.Equal(expected), optionalDescription...)
}

// Reset resets res's stdout buffer to be empty.
func (res *CmdRes) Reset() {
	res.stdout.Reset()
	return
}

// SingleOut returns res's stdout as a string without any newline characters
func (res *CmdRes) SingleOut() string {
	return strings.Replace(res.stdout.String(), "\n", "", -1)
}

// Unmarshal unmarshalls res's stdout into data. It assumes that the stdout of
// res is in JSON format. Returns an error if the unmarshalling fails.
func (res *CmdRes) Unmarshal(data interface{}) error {
	err := json.Unmarshal(res.stdout.Bytes(), data)
	return err
}

// GetDebugMessage returns executed command and its output
func (res *CmdRes) GetDebugMessage() string {
	return fmt.Sprintf("cmd: %s\n%s", res.GetCmd(), res.CombineOutput())
}

// WaitUntilMatch waits until the given substring is present in the `CmdRes.stdout`
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatch(substr string) error {
	body := func() bool {
		return strings.Contains(res.Output().String(), substr)
	}

	return WithTimeout(
		body,
		fmt.Sprintf("%s is not in the output after timeout", substr),
		&TimeoutConfig{Timeout: HelperTimeout})
}

// WaitUntilMatchRegexp waits until the `CmdRes.stdout` matches the given regexp.
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatchRegexp(expr string) error {
	r := regexp.MustCompile(expr)
	body := func() bool {
		return r.Match(res.Output().Bytes())
	}

	return WithTimeout(
		body,
		fmt.Sprintf("The output doesn't match regexp %q after timeout", expr),
		&TimeoutConfig{Timeout: HelperTimeout})
}

// GetErr returns error created from program output if command is not successful
func (res *CmdRes) GetErr(context string) error {
	if res.WasSuccessful() {
		return nil
	}
	return fmt.Errorf("command context:%s, output: %s", context, res.GetDebugMessage())
}

// BeSuccesfulMatcher a new Ginkgo matcher for CmdRes struct
type BeSuccesfulMatcher struct{}

// Match validates that the given interface will be a `*CmdRes` struct and it
// was successful. In case of not a valid CmdRes will return an error. If the
// command was not successful it returns false.
func (matcher *BeSuccesfulMatcher) Match(actual interface{}) (success bool, err error) {
	res, ok := actual.(*CmdRes)
	if !ok {
		return false, fmt.Errorf("%q is not a valid *CmdRes type", actual)
	}
	return res.WasSuccessful(), nil
}

// FailureMessage it returns a pretty printed error message in the case of the
// command was not successful.
func (matcher *BeSuccesfulMatcher) FailureMessage(actual interface{}) (message string) {
	res, _ := actual.(*CmdRes)
	return fmt.Sprintf("Expected command: %s \nTo succeed, but it failed:\n%s",
		res.GetCmd(), res.OutputPrettyPrint())
}

// NegatedFailureMessage returns a pretty printed error message in case of the
// command is tested with a negative
func (matcher *BeSuccesfulMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	res, _ := actual.(*CmdRes)
	return fmt.Sprintf("Expected command: %s\nTo have failed, but it was successful:\n%s",
		res.GetCmd(), res.OutputPrettyPrint())
}

// CMDSuccess return a new Matcher that expects a CmdRes is a successful run command.
func CMDSuccess() types.GomegaMatcher {
	return &BeSuccesfulMatcher{}
}
<commit_msg>test: Do not treat log lines as format strings<commit_after>// Copyright 2017 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package helpers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/cilium/cilium/test/config"

	"github.com/onsi/gomega"
	"github.com/onsi/gomega/types"
	"k8s.io/client-go/util/jsonpath"
)

// CmdRes contains a variety of data which results from running a command.
type CmdRes struct {
	cmd      string        // Command to run
	params   []string      // Parameters to provide to command
	stdout   *bytes.Buffer // Stdout from running cmd
	stderr   *bytes.Buffer // Stderr from running cmd
	success  bool          // Whether command successfully executed
	exitcode int           // The exit code of cmd
	duration time.Duration // Is the representation of the the time that command took to execute.
}

// GetCmd returns res's cmd.
func (res *CmdRes) GetCmd() string {
	return res.cmd
}

// GetExitCode returns res's exitcode.
func (res *CmdRes) GetExitCode() int {
	return res.exitcode
}

// GetStdOut returns the contents of the stdout buffer of res as a string.
func (res *CmdRes) GetStdOut() string {
	return res.stdout.String()
}

// GetStdErr returns the contents of the stderr buffer of res as a string.
func (res *CmdRes) GetStdErr() string {
	return res.stderr.String()
}

// SendToLog writes to `TestLogWriter` the debug message for the running
// command, if the quietMode argument is true will print only the command and
// the exitcode.
func (res *CmdRes) SendToLog(quietMode bool) {
	if quietMode {
		logformat := "cmd: %q exitCode: %d duration: %s\n"
		fmt.Fprintf(&config.TestLogWriter, logformat, res.cmd, res.GetExitCode(), res.duration)
		return
	}

	logformat := "cmd: %q exitCode: %d duration: %s stdout:\n%s\n"
	log := fmt.Sprintf(logformat, res.cmd, res.GetExitCode(), res.duration, res.stdout.String())
	if res.stderr.Len() > 0 {
		log = fmt.Sprintf("%sstderr:\n%s\n", log, res.stderr.String())
	}
	fmt.Fprint(&config.TestLogWriter, log)
}

// WasSuccessful returns true if cmd completed successfully.
func (res *CmdRes) WasSuccessful() bool {
	return res.success
}

// ExpectFail asserts whether res failed to execute. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectFail(optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res).ShouldNot(
		CMDSuccess(), optionalDescription...)
}

// ExpectSuccess asserts whether res executed successfully. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectSuccess(optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res).Should(
		CMDSuccess(), optionalDescription...)
}

// ExpectContains asserts a string into the stdout of the response of executed
// command. It accepts an optional parameter that can be used to annotate
// failure messages.
func (res *CmdRes) ExpectContains(data string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).To(
		gomega.ContainSubstring(data), optionalDescription...)
}

// ExpectDoesNotContain asserts that a string is not contained in the stdout of
// the executed command. It accepts an optional parameter that can be used to
// annotate failure messages.
func (res *CmdRes) ExpectDoesNotContain(data string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
		gomega.ContainSubstring(data), optionalDescription...)
}

// ExpectDoesNotMatchRegexp asserts that the stdout of the executed command
// doesn't match the regexp. It accepts an optional parameter that can be used
// to annotate failure messages.
func (res *CmdRes) ExpectDoesNotMatchRegexp(regexp string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
		gomega.MatchRegexp(regexp), optionalDescription...)
}

// CountLines return the number of lines in the stdout of res.
func (res *CmdRes) CountLines() int {
	return strings.Count(res.stdout.String(), "\n")
}

// CombineOutput returns the combined output of stdout and stderr for res.
func (res *CmdRes) CombineOutput() *bytes.Buffer {
	result := new(bytes.Buffer)
	result.WriteString(res.stdout.String())
	result.WriteString(res.stderr.String())
	return result
}

// IntOutput returns the stdout of res as an integer
func (res *CmdRes) IntOutput() (int, error) {
	return strconv.Atoi(strings.Trim(res.stdout.String(), "\n"))
}

// FindResults filters res's stdout using the provided JSONPath filter. It
// returns an array of the values that match the filter, and an error if
// the unmarshalling of the stdout of res fails.
// TODO - what exactly is the need for this vs. Filter function below?
func (res *CmdRes) FindResults(filter string) ([]reflect.Value, error) {

	var data interface{}
	var result []reflect.Value

	err := json.Unmarshal(res.stdout.Bytes(), &data)
	if err != nil {
		return nil, err
	}
	parser := jsonpath.New("").AllowMissingKeys(true)
	parser.Parse(filter)
	fullResults, _ := parser.FindResults(data)
	for _, res := range fullResults {
		for _, val := range res {
			result = append(result, val)
		}
	}
	return result, nil
}

// Filter returns the contents of res's stdout filtered using the provided
// JSONPath filter in a buffer. Returns an error if the unmarshalling of the
// contents of res's stdout fails.
func (res *CmdRes) Filter(filter string) (*FilterBuffer, error) {
	var data interface{}
	result := new(bytes.Buffer)

	err := json.Unmarshal(res.stdout.Bytes(), &data)
	if err != nil {
		return nil, fmt.Errorf("could not parse JSON from command %q",
			res.cmd)
	}
	parser := jsonpath.New("").AllowMissingKeys(true)
	parser.Parse(filter)
	err = parser.Execute(result, data)
	if err != nil {
		return nil, err
	}
	return &FilterBuffer{result}, nil
}

// ByLines returns res's stdout split by the newline character .
func (res *CmdRes) ByLines() []string {
	return strings.Split(res.stdout.String(), "\n")
}

// KVOutput returns a map of the stdout of res split based on
// the separator '='.
// For example, the following strings would be split as follows:
// 		a=1
// 		b=2
// 		c=3
func (res *CmdRes) KVOutput() map[string]string {
	result := make(map[string]string)
	for _, line := range res.ByLines() {
		vals := strings.Split(line, "=")
		if len(vals) == 2 {
			result[vals[0]] = vals[1]
		}
	}
	return result
}

// Output returns res's stdout.
func (res *CmdRes) Output() *bytes.Buffer {
	return res.stdout
}

// OutputPrettyPrint returns a string with the ExitCode, stdout and stderr in a
// pretty format.
func (res *CmdRes) OutputPrettyPrint() string {
	format := func(message string) string {
		result := []string{}
		for _, line := range strings.Split(message, "\n") {
			result = append(result, fmt.Sprintf("\t %s", line))
		}
		return strings.Join(result, "\n")

	}
	return fmt.Sprintf(
		"Exitcode: %d \nStdout:\n %s\nStderr:\n %s\n",
		res.GetExitCode(),
		format(res.GetStdOut()),
		format(res.GetStdErr()))
}

// ExpectEqual asserts whether cmdRes.Output().String() and expected are equal.
// It accepts an optional parameter that can be used to annotate failure
// messages.
func (res *CmdRes) ExpectEqual(expected string, optionalDescription ...interface{}) bool {
	return gomega.ExpectWithOffset(1, res.Output().String()).Should(
		gomega.Equal(expected), optionalDescription...)
}

// Reset resets res's stdout buffer to be empty.
func (res *CmdRes) Reset() {
	res.stdout.Reset()
	return
}

// SingleOut returns res's stdout as a string without any newline characters
func (res *CmdRes) SingleOut() string {
	return strings.Replace(res.stdout.String(), "\n", "", -1)
}

// Unmarshal unmarshalls res's stdout into data. It assumes that the stdout of
// res is in JSON format. Returns an error if the unmarshalling fails.
func (res *CmdRes) Unmarshal(data interface{}) error {
	err := json.Unmarshal(res.stdout.Bytes(), data)
	return err
}

// GetDebugMessage returns executed command and its output
func (res *CmdRes) GetDebugMessage() string {
	return fmt.Sprintf("cmd: %s\n%s", res.GetCmd(), res.CombineOutput())
}

// WaitUntilMatch waits until the given substring is present in the `CmdRes.stdout`
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatch(substr string) error {
	body := func() bool {
		return strings.Contains(res.Output().String(), substr)
	}

	return WithTimeout(
		body,
		fmt.Sprintf("%s is not in the output after timeout", substr),
		&TimeoutConfig{Timeout: HelperTimeout})
}

// WaitUntilMatchRegexp waits until the `CmdRes.stdout` matches the given regexp.
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatchRegexp(expr string) error {
	r := regexp.MustCompile(expr)
	body := func() bool {
		return r.Match(res.Output().Bytes())
	}

	return WithTimeout(
		body,
		fmt.Sprintf("The output doesn't match regexp %q after timeout", expr),
		&TimeoutConfig{Timeout: HelperTimeout})
}

// GetErr returns error created from program output if command is not successful
func (res *CmdRes) GetErr(context string) error {
	if res.WasSuccessful() {
		return nil
	}
	return fmt.Errorf("command context:%s, output: %s", context, res.GetDebugMessage())
}

// BeSuccesfulMatcher a new Ginkgo matcher for CmdRes struct
type BeSuccesfulMatcher struct{}

// Match validates that the given interface will be a `*CmdRes` struct and it
// was successful. In case of not a valid CmdRes will return an error. If the
// command was not successful it returns false.
func (matcher *BeSuccesfulMatcher) Match(actual interface{}) (success bool, err error) {
	res, ok := actual.(*CmdRes)
	if !ok {
		return false, fmt.Errorf("%q is not a valid *CmdRes type", actual)
	}
	return res.WasSuccessful(), nil
}

// FailureMessage it returns a pretty printed error message in the case of the
// command was not successful.
func (matcher *BeSuccesfulMatcher) FailureMessage(actual interface{}) (message string) {
	res, _ := actual.(*CmdRes)
	return fmt.Sprintf("Expected command: %s \nTo succeed, but it failed:\n%s",
		res.GetCmd(), res.OutputPrettyPrint())
}

// NegatedFailureMessage returns a pretty printed error message in case of the
// command is tested with a negative
func (matcher *BeSuccesfulMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	res, _ := actual.(*CmdRes)
	return fmt.Sprintf("Expected command: %s\nTo have failed, but it was successful:\n%s",
		res.GetCmd(), res.OutputPrettyPrint())
}

// CMDSuccess return a new Matcher that expects a CmdRes is a successful run command.
func CMDSuccess() types.GomegaMatcher {
	return &BeSuccesfulMatcher{}
}
<|endoftext|>


<commit_before>package main

/*
author:DaiJingPei
email:dijp@qq.com
url:https://github.com/dijp/json4go
*/

import (
	"fmt"
	"dijp/json4go"
)

type Person struct {
	Name string
	Age  int
	Sex  bool
}

type User struct {
	UserId int
	P      Person
	Map    map[string]int
	Arr    []string
}

func test1() {
	u := User{1, Person{"dog", 30, true}, map[string]int{"a": 1, "b": 2, "c": 3}, []string{"aaa", "bbb", "ccc"}}
	j := json4go.ToJson(u)
	fmt.Println(j.GetJson("P").GetString("Name"))
}

func test2() {
	str := `{"function":"200","servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
	j := json4go.Parse2Json(str)
	fmt.Println(j.GetString("function"))
	fmt.Println(j.GetJsonArray("servers").GetJson(0).GetString("serverName"))
	fmt.Println(j.GetJsonArray("servers").GetJson(1).ToString())
}

func main() {
	test1()
	test2()
}
<commit_msg>commit json4goTest.go v1.0<commit_after>package main

/*
author:DaiJingPei
email:dijp@qq.com
url:https://github.com/dijp/json4go
*/

import (
	"fmt"
	"github.com/dijp/json4go"
)

type Person struct {
	Name string
	Age  int
	Sex  bool
}

type User struct {
	UserId int
	P      Person
	Map    map[string]int
	Arr    []string
}

func test1() {
	u := User{1, Person{"dog", 30, true}, map[string]int{"a": 1, "b": 2, "c": 3}, []string{"aaa", "bbb", "ccc"}}
	j := json4go.ToJson(u)
	fmt.Println(j.GetJson("P").GetString("Name"))
}

func test2() {
	str := `{"function":"200","servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
	j := json4go.Parse2Json(str)
	fmt.Println(j.GetString("function"))
	fmt.Println(j.GetJsonArray("servers").GetJson(0).GetString("serverName"))
	fmt.Println(j.GetJsonArray("servers").GetJson(1).ToString())
}

func main() {
	test1()
	test2()
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/golang/protobuf/ptypes/empty"
	"github.com/improbable-eng/grpc-web/go/grpcweb"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/transport"

	testproto "github.com/johanbrandhorst/protobuf/test/server/proto/test"
	"github.com/johanbrandhorst/protobuf/test/server/proto/types"
	"github.com/johanbrandhorst/protobuf/test/shared"
	"github.com/johanbrandhorst/protobuf/wsproxy"
)

func main() {
	grpcServer := grpc.NewServer()
	testproto.RegisterTestServiceServer(grpcServer, &testSrv{})
	types.RegisterEchoServiceServer(grpcServer, &testSrv{})
	log := logrus.New()
	log.Level = logrus.DebugLevel
	log.Formatter = &logrus.TextFormatter{
		ForceColors:     true,
		FullTimestamp:   true,
		TimestampFormat: time.RFC3339Nano,
	}
	grpclog.SetLogger(log)
	clientCreds, err := credentials.NewClientTLSFromFile("./insecure/localhost.crt", "")
	if err != nil {
		log.Fatalln("Failed to get local server client credentials:", err)
	}
	wrappedServer := grpcweb.WrapServer(grpcServer)
	handler := wsproxy.WrapServer(http.HandlerFunc(wrappedServer.ServeHTTP), log, clientCreds)

	emptyGrpcServer := grpc.NewServer()
	emptyWrappedServer := grpcweb.WrapServer(emptyGrpcServer, grpcweb.WithCorsForRegisteredEndpointsOnly(false))
	emptyHandler := func(resp http.ResponseWriter, req *http.Request) {
		emptyWrappedServer.ServeHTTP(resp, req)
	}

	http1Server := http.Server{
		Addr:    shared.HTTP1Server,
		Handler: handler,
	}
	http1Server.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} // Disable HTTP2
	http1EmptyServer := http.Server{
		Addr:    shared.EmptyHTTP1Server,
		Handler: http.HandlerFunc(emptyHandler),
	}
	http1EmptyServer.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} // Disable HTTP2

	http2Server := http.Server{
		Addr:    shared.HTTP2Server,
		Handler: handler,
	}
	http2EmptyServer := http.Server{
		Addr:    shared.EmptyHTTP2Server,
		Handler: http.HandlerFunc(emptyHandler),
	}

	grpclog.Printf("Starting servers.")

	// Start the empty Http1.1 server
	go func() {
		if err := http1EmptyServer.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http1.1 empty server: %v", err)
		}
	}()

	// Start the Http1.1 server
	go func() {
		if err := http1Server.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http1.1 server: %v", err)
		}
	}()

	// Start the empty Http2 server
	go func() {
		if err := http2EmptyServer.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http2 empty server: %v", err)
		}
	}()

	// Start the Http2 server
	go func() {
		if err := http2Server.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http2 server: %v", err)
		}
	}()

	// Host the GopherJS code
	httpsSrv := &http.Server{
		Addr:    shared.GopherJSServer,
		Handler: http.FileServer(http.Dir("./client/html")),
	}
	if err := httpsSrv.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
		grpclog.Fatalf("failed to start JS server: %v", err)
	}
}

type testSrv struct {
}

func (s *testSrv) PingEmpty(ctx context.Context, _ *empty.Empty) (*testproto.PingResponse, error) {
	grpc.SendHeader(ctx, metadata.Pairs("HeaderTestKey1", "ServerValue1", "HeaderTestKey2", "ServerValue2"))
	grpc.SetTrailer(ctx, metadata.Pairs("TrailerTestKey1", "ServerValue1", "TrailerTestKey2", "ServerValue2"))
	return &testproto.PingResponse{Value: "foobar"}, nil
}

func (s *testSrv) Ping(ctx context.Context, ping *testproto.PingRequest) (*testproto.PingResponse, error) {
	if ping.GetCheckMetadata() {
		md, ok := metadata.FromContext(ctx)
		if !ok || len(md[strings.ToLower(shared.ClientMDTestKey)]) == 0 ||
			md[strings.ToLower(shared.ClientMDTestKey)][0] != shared.ClientMDTestValue {
			return nil, status.Errorf(codes.InvalidArgument, "Metadata was invalid")
		}
	}
	if ping.GetSendHeaders() {
		grpc.SendHeader(
			ctx,
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		grpc.SetTrailer(
			ctx,
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	return &testproto.PingResponse{Value: ping.GetValue(), Counter: ping.GetResponseCount()}, nil
}

func (s *testSrv) PingError(ctx context.Context, ping *testproto.PingRequest) (*empty.Empty, error) {
	if ping.FailureType == testproto.PingRequest_DROP {
		t, _ := transport.StreamFromContext(ctx)
		t.ServerTransport().Close()
		return nil, status.Errorf(codes.Unavailable, "You got closed. You probably won't see this error")

	}
	if ping.GetSendHeaders() {
		grpc.SendHeader(
			ctx,
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		grpc.SetTrailer(
			ctx,
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	return nil, status.Errorf(codes.Code(ping.ErrorCodeReturned), "Intentionally returning error for PingError")
}

func (s *testSrv) PingList(ping *testproto.PingRequest, stream testproto.TestService_PingListServer) error {
	if ping.GetCheckMetadata() {
		md, ok := metadata.FromContext(stream.Context())
		if !ok || len(md[strings.ToLower(shared.ClientMDTestKey)]) == 0 ||
			md[strings.ToLower(shared.ClientMDTestKey)][0] != shared.ClientMDTestValue {
			return status.Errorf(codes.InvalidArgument, "Metadata was invalid")
		}
	}
	if ping.GetSendHeaders() {
		stream.SendHeader(
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		stream.SetTrailer(
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	if ping.FailureType == testproto.PingRequest_DROP {
		t, _ := transport.StreamFromContext(stream.Context())
		t.ServerTransport().Close()
		return nil

	}
	for i := int32(0); i < ping.ResponseCount; i++ {
		sleepDuration := ping.GetMessageLatencyMs()
		time.Sleep(time.Duration(sleepDuration) * time.Millisecond)
		stream.Send(&testproto.PingResponse{Value: fmt.Sprintf("%s %d", ping.Value, i), Counter: i})
		if sleepDuration != 0 {
			// Flush the stream
			lowLevelServerStream, ok := transport.StreamFromContext(stream.Context())
			if !ok {
				return status.Errorf(codes.Internal, "lowLevelServerStream does not exist in context")
			}
			lowLevelServerStream.ServerTransport().Write(lowLevelServerStream, make([]byte, 0), &transport.Options{
				Delay: false,
			})
		}
	}
	return nil
}

func (s *testSrv) EchoAllTypes(ctx context.Context, in *types.TestAllTypes) (*types.TestAllTypes, error) {
	return in, nil
}

func (s *testSrv) EchoMaps(ctx context.Context, in *types.TestMap) (*types.TestMap, error) {
	return in, nil
}

func (s *testSrv) PingClientStream(stream testproto.TestService_PingClientStreamServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
			return stream.SendAndClose(&testproto.PingResponse{Value: "Closed"})
		}
		if err != nil {
			return err
		}
	}
}

func (s *testSrv) PingClientStreamError(stream testproto.TestService_PingClientStreamErrorServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
			_ = stream.SendAndClose(&testproto.PingResponse{Value: "Closed"})
			return status.Errorf(codes.Internal, "error")
		}
		if err != nil {
			return err
		}
		if ping.GetFailureType() == testproto.PingRequest_CODE {
			return status.Errorf(codes.Code(ping.ErrorCodeReturned), ping.GetValue())
		}
	}
}
func (s *testSrv) PingBidiStream(stream testproto.TestService_PingBidiStreamServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
		err = stream.Send(&testproto.PingResponse{Value: ping.GetValue()})
		if err != nil {
			return err
		}
	}
}

func (s *testSrv) PingBidiStreamError(stream testproto.TestService_PingBidiStreamErrorServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			return status.Errorf(codes.Internal, "error")
		}
		if err != nil {
			return err
		}
		if ping.GetFailureType() == testproto.PingRequest_CODE {
			return status.Errorf(codes.Code(ping.ErrorCodeReturned), ping.GetValue())
		}
		time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
		err = stream.Send(&testproto.PingResponse{Value: ping.GetValue()})
		if err != nil {
			return err
		}
	}
}
<commit_msg>Fix sginature of WrapServer in test<commit_after>package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/golang/protobuf/ptypes/empty"
	"github.com/improbable-eng/grpc-web/go/grpcweb"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/transport"

	testproto "github.com/johanbrandhorst/protobuf/test/server/proto/test"
	"github.com/johanbrandhorst/protobuf/test/server/proto/types"
	"github.com/johanbrandhorst/protobuf/test/shared"
	"github.com/johanbrandhorst/protobuf/wsproxy"
)

func main() {
	grpcServer := grpc.NewServer()
	testproto.RegisterTestServiceServer(grpcServer, &testSrv{})
	types.RegisterEchoServiceServer(grpcServer, &testSrv{})
	log := logrus.New()
	log.Level = logrus.DebugLevel
	log.Formatter = &logrus.TextFormatter{
		ForceColors:     true,
		FullTimestamp:   true,
		TimestampFormat: time.RFC3339Nano,
	}
	grpclog.SetLogger(log)
	clientCreds, err := credentials.NewClientTLSFromFile("./insecure/localhost.crt", "")
	if err != nil {
		log.Fatalln("Failed to get local server client credentials:", err)
	}
	wrappedServer := grpcweb.WrapServer(grpcServer)
	handler := wsproxy.WrapServer(
		http.HandlerFunc(wrappedServer.ServeHTTP),
		log,
		wsproxy.WithTransportCredentials(clientCreds))

	emptyGrpcServer := grpc.NewServer()
	emptyWrappedServer := grpcweb.WrapServer(emptyGrpcServer, grpcweb.WithCorsForRegisteredEndpointsOnly(false))
	emptyHandler := func(resp http.ResponseWriter, req *http.Request) {
		emptyWrappedServer.ServeHTTP(resp, req)
	}

	http1Server := http.Server{
		Addr:    shared.HTTP1Server,
		Handler: handler,
	}
	http1Server.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} // Disable HTTP2
	http1EmptyServer := http.Server{
		Addr:    shared.EmptyHTTP1Server,
		Handler: http.HandlerFunc(emptyHandler),
	}
	http1EmptyServer.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} // Disable HTTP2

	http2Server := http.Server{
		Addr:    shared.HTTP2Server,
		Handler: handler,
	}
	http2EmptyServer := http.Server{
		Addr:    shared.EmptyHTTP2Server,
		Handler: http.HandlerFunc(emptyHandler),
	}

	grpclog.Printf("Starting servers.")

	// Start the empty Http1.1 server
	go func() {
		if err := http1EmptyServer.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http1.1 empty server: %v", err)
		}
	}()

	// Start the Http1.1 server
	go func() {
		if err := http1Server.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http1.1 server: %v", err)
		}
	}()

	// Start the empty Http2 server
	go func() {
		if err := http2EmptyServer.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http2 empty server: %v", err)
		}
	}()

	// Start the Http2 server
	go func() {
		if err := http2Server.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
			grpclog.Fatalf("failed starting http2 server: %v", err)
		}
	}()

	// Host the GopherJS code
	httpsSrv := &http.Server{
		Addr:    shared.GopherJSServer,
		Handler: http.FileServer(http.Dir("./client/html")),
	}
	if err := httpsSrv.ListenAndServeTLS("./insecure/localhost.crt", "./insecure/localhost.key"); err != nil {
		grpclog.Fatalf("failed to start JS server: %v", err)
	}
}

type testSrv struct {
}

func (s *testSrv) PingEmpty(ctx context.Context, _ *empty.Empty) (*testproto.PingResponse, error) {
	grpc.SendHeader(ctx, metadata.Pairs("HeaderTestKey1", "ServerValue1", "HeaderTestKey2", "ServerValue2"))
	grpc.SetTrailer(ctx, metadata.Pairs("TrailerTestKey1", "ServerValue1", "TrailerTestKey2", "ServerValue2"))
	return &testproto.PingResponse{Value: "foobar"}, nil
}

func (s *testSrv) Ping(ctx context.Context, ping *testproto.PingRequest) (*testproto.PingResponse, error) {
	if ping.GetCheckMetadata() {
		md, ok := metadata.FromContext(ctx)
		if !ok || len(md[strings.ToLower(shared.ClientMDTestKey)]) == 0 ||
			md[strings.ToLower(shared.ClientMDTestKey)][0] != shared.ClientMDTestValue {
			return nil, status.Errorf(codes.InvalidArgument, "Metadata was invalid")
		}
	}
	if ping.GetSendHeaders() {
		grpc.SendHeader(
			ctx,
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		grpc.SetTrailer(
			ctx,
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	return &testproto.PingResponse{Value: ping.GetValue(), Counter: ping.GetResponseCount()}, nil
}

func (s *testSrv) PingError(ctx context.Context, ping *testproto.PingRequest) (*empty.Empty, error) {
	if ping.FailureType == testproto.PingRequest_DROP {
		t, _ := transport.StreamFromContext(ctx)
		t.ServerTransport().Close()
		return nil, status.Errorf(codes.Unavailable, "You got closed. You probably won't see this error")

	}
	if ping.GetSendHeaders() {
		grpc.SendHeader(
			ctx,
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		grpc.SetTrailer(
			ctx,
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	return nil, status.Errorf(codes.Code(ping.ErrorCodeReturned), "Intentionally returning error for PingError")
}

func (s *testSrv) PingList(ping *testproto.PingRequest, stream testproto.TestService_PingListServer) error {
	if ping.GetCheckMetadata() {
		md, ok := metadata.FromContext(stream.Context())
		if !ok || len(md[strings.ToLower(shared.ClientMDTestKey)]) == 0 ||
			md[strings.ToLower(shared.ClientMDTestKey)][0] != shared.ClientMDTestValue {
			return status.Errorf(codes.InvalidArgument, "Metadata was invalid")
		}
	}
	if ping.GetSendHeaders() {
		stream.SendHeader(
			metadata.Pairs(
				shared.ServerMDTestKey1, shared.ServerMDTestValue1,
				shared.ServerMDTestKey2, shared.ServerMDTestValue2))
	}
	if ping.GetSendTrailers() {
		stream.SetTrailer(
			metadata.Pairs(
				shared.ServerTrailerTestKey1, shared.ServerMDTestValue1,
				shared.ServerTrailerTestKey2, shared.ServerMDTestValue2))
	}
	if ping.FailureType == testproto.PingRequest_DROP {
		t, _ := transport.StreamFromContext(stream.Context())
		t.ServerTransport().Close()
		return nil

	}
	for i := int32(0); i < ping.ResponseCount; i++ {
		sleepDuration := ping.GetMessageLatencyMs()
		time.Sleep(time.Duration(sleepDuration) * time.Millisecond)
		stream.Send(&testproto.PingResponse{Value: fmt.Sprintf("%s %d", ping.Value, i), Counter: i})
		if sleepDuration != 0 {
			// Flush the stream
			lowLevelServerStream, ok := transport.StreamFromContext(stream.Context())
			if !ok {
				return status.Errorf(codes.Internal, "lowLevelServerStream does not exist in context")
			}
			lowLevelServerStream.ServerTransport().Write(lowLevelServerStream, make([]byte, 0), &transport.Options{
				Delay: false,
			})
		}
	}
	return nil
}

func (s *testSrv) EchoAllTypes(ctx context.Context, in *types.TestAllTypes) (*types.TestAllTypes, error) {
	return in, nil
}

func (s *testSrv) EchoMaps(ctx context.Context, in *types.TestMap) (*types.TestMap, error) {
	return in, nil
}

func (s *testSrv) PingClientStream(stream testproto.TestService_PingClientStreamServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
			return stream.SendAndClose(&testproto.PingResponse{Value: "Closed"})
		}
		if err != nil {
			return err
		}
	}
}

func (s *testSrv) PingClientStreamError(stream testproto.TestService_PingClientStreamErrorServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
			_ = stream.SendAndClose(&testproto.PingResponse{Value: "Closed"})
			return status.Errorf(codes.Internal, "error")
		}
		if err != nil {
			return err
		}
		if ping.GetFailureType() == testproto.PingRequest_CODE {
			return status.Errorf(codes.Code(ping.ErrorCodeReturned), ping.GetValue())
		}
	}
}
func (s *testSrv) PingBidiStream(stream testproto.TestService_PingBidiStreamServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
		err = stream.Send(&testproto.PingResponse{Value: ping.GetValue()})
		if err != nil {
			return err
		}
	}
}

func (s *testSrv) PingBidiStreamError(stream testproto.TestService_PingBidiStreamErrorServer) error {
	for {
		ping, err := stream.Recv()
		if err == io.EOF {
			return status.Errorf(codes.Internal, "error")
		}
		if err != nil {
			return err
		}
		if ping.GetFailureType() == testproto.PingRequest_CODE {
			return status.Errorf(codes.Code(ping.ErrorCodeReturned), ping.GetValue())
		}
		time.Sleep(time.Duration(ping.GetMessageLatencyMs()) * time.Millisecond)
		err = stream.Send(&testproto.PingResponse{Value: ping.GetValue()})
		if err != nil {
			return err
		}
	}
}
<|endoftext|>


<commit_before>package app

import (
	"github.com/jgraham909/revmgo"
	"github.com/revel/revel"
)

func init() {
	revel.OnAppStart(revmgo.AppInit)
	// Filters is the default set of global filters.
	revel.Filters = []revel.Filter{
		revel.PanicFilter,             // Recover from panics and display an error page instead.
		revel.RouterFilter,            // Use the routing table to select the right Action
		revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
		revel.ParamsFilter,            // Parse parameters into Controller.Params.
		revel.SessionFilter,           // Restore and write the session cookie.
		revel.FlashFilter,             // Restore and write the flash cookie.
		revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
		revel.I18nFilter,              // Resolve the requested language
		revel.InterceptorFilter,       // Run interceptors around the action.
		revel.ActionInvoker,           // Invoke the action.
	}

	revel.OnAppStart(func() {

		var keyValues []map[string]string

		db := revmgo.Session.DB("test")
		col := db.C("config")
		query := col.Find(nil)

		err := query.All(&keyValues)

		if err != nil {
			revel.ERROR.Printf("%v", err)
		} else if keyValues != nil {
			for key, value := range keyValues {
				revel.INFO.Printf("%s: %s", key, value)
			}
		} else {
			revel.INFO.Printf("No keys found")
		}

	})
}
<commit_msg>instantiate map before using it<commit_after>package app

import (
	"github.com/jgraham909/revmgo"
	"github.com/revel/revel"
)

func init() {
	revel.OnAppStart(revmgo.AppInit)
	// Filters is the default set of global filters.
	revel.Filters = []revel.Filter{
		revel.PanicFilter,             // Recover from panics and display an error page instead.
		revel.RouterFilter,            // Use the routing table to select the right Action
		revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
		revel.ParamsFilter,            // Parse parameters into Controller.Params.
		revel.SessionFilter,           // Restore and write the session cookie.
		revel.FlashFilter,             // Restore and write the flash cookie.
		revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
		revel.I18nFilter,              // Resolve the requested language
		revel.InterceptorFilter,       // Run interceptors around the action.
		revel.ActionInvoker,           // Invoke the action.
	}

	revel.OnAppStart(func() {

		keyValues := []map[string]string{}

		db := revmgo.Session.DB("test")
		col := db.C("config")
		query := col.Find(nil)

		err := query.All(&keyValues)

		if err != nil {
			revel.ERROR.Printf("%v", err)
		} else if keyValues != nil {
			for key, value := range keyValues {
				revel.INFO.Printf("%s: %s", key, value)
			}
		} else {
			revel.INFO.Printf("No keys found")
		}

	})
}
<|endoftext|>


<commit_before>package month

import (
	"fmt"
	"sort"
	"time"

	"github.com/grokify/base36"
	"github.com/grokify/gotilla/math/mathutil"
	"github.com/grokify/gotilla/sort/sortutil"
	"github.com/grokify/gotilla/time/timeutil"
)

func DayofmonthToEnglish(i uint16) string {
	days := []string{
		"zeorth",
		"first", "second", "third", "fourth", "fifth",
		"sixth", "seventh", "eighth", "ninth", "tenth",
		"eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth",
		"sixteenth", "seventeenth", "eighteenth", "nineteenth", "twentieth",
	}
	tenZero := []string{"tenth", "twentieth", "thirtieth", "fourtieth", "fiftieth"}
	tenPlus := []string{"ten", "twenty", "thirty", "forty", "fifty"}
	if i < 21 {
		return days[i]
	}
	if i > 59 {
		panic("E_OUT_OF_RANGE")
	}
	quotient, remainder := i/10, i%10
	if remainder == 0 {
		return tenZero[quotient-1]
	}
	return tenPlus[quotient-1] + " " + days[remainder]
}

func YearMonthBase36(yyyy, mm uint64) string {
	return fmt.Sprintf("%04s", base36.Encode(yyyy*100+mm))
}

func YearMonthBase36Time(dt time.Time) string {
	return YearMonthBase36(uint64(dt.Year()), uint64(dt.Month()))
}

// MonthBegin allows you to add/subtract months resulting
// in the first day of each month while avoiding Go's
// `AddDate` normalization where "adding one month to
// October 31 yields December 1, the normalized form for
// November 31." Setting `deltaMonths` to 0 indicates the
// current month.
func MonthBegin(dt time.Time, deltaMonths int) time.Time {
	dt = dt.UTC()
	year := dt.Year()
	month := int(dt.Month())
	if deltaMonths > 0 {
		for i := 0; i < deltaMonths; i++ {
			if month == 12 {
				month = 1
				year++
			} else {
				month++
			}
		}
	} else if deltaMonths < 0 {
		for i := 0; i > deltaMonths; i-- {
			if month == 1 {
				month = 12
				year--
			} else {
				month--
			}
		}
	}
	return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
}

// YearMonthToMonthContinuous converts a year and month to
// a continuous month integer. This is useful when an even
// even spacing between months is desired, such as with
// charting x-axis values.
func YearMonthToMonthContinuous(year, month uint64) uint64 {
	return year*12 + month
}

// MonthContinuousToYearMonth converts a continuous month
// value (e.g. numerof months from year 0).
func MonthContinuousToYearMonth(monthc uint64) (uint64, uint64) {
	quotient, remainder := mathutil.DivideInt64(
		int64(monthc-1), int64(12))
	return uint64(quotient), uint64(remainder + 1)
}

// TimeToMonthContinuous converts a `time.Time` value
// to a continuous month.
func TimeToMonthContinuous(t time.Time) uint64 {
	t = t.UTC()
	return YearMonthToMonthContinuous(
		uint64(t.Year()), uint64(t.Month()))
}

// MonthContinuousToTime converts a continuous month
// value to a `time.Time` value.
func MonthContinuousToTime(monthc uint64) time.Time {
	year, month := MonthContinuousToYearMonth(monthc)
	return time.Date(
		int(year), time.Month(int(month)), 1,
		0, 0, 0, 0, time.UTC)
}

func MonthContinuousIsQuarterBegin(monthc uint64) bool {
	t := MonthContinuousToTime(monthc)
	month := t.Month()
	if month == 1 || month == 4 || month == 7 || month == 10 {
		return true
	}
	return false
}

func MonthContinuousIsYearBegin(monthc uint64) bool {
	t := MonthContinuousToTime(monthc)
	month := t.Month()
	if month == 1 {
		return true
	}
	return false
}

// TimeSeriesMonth returns time series of months given start and end
// input times.
func TimeSeriesMonth(sortAsc bool, times ...time.Time) sortutil.TimeSlice {
	min, max := timeutil.SliceMinMax(times)
	minMonth := timeutil.MonthStart(min)
	maxMonth := timeutil.MonthStart(max)
	timeSeries := sortutil.TimeSlice{}
	curMonth := minMonth
	for curMonth.Before(maxMonth) || curMonth.Equal(maxMonth) {
		timeSeries = append(timeSeries, curMonth)
		curMonth = timeutil.TimeDt6AddNMonths(curMonth, 1)
	}
	if len(timeSeries) > 0 && sortAsc {
		sort.Sort(timeSeries)
	}
	return timeSeries
}
<commit_msg>enhance: time/month: make MonthBegin() more generic<commit_after>package month

import (
	"fmt"
	"sort"
	"time"

	"github.com/grokify/base36"
	"github.com/grokify/gotilla/math/mathutil"
	"github.com/grokify/gotilla/sort/sortutil"
	"github.com/grokify/gotilla/time/timeutil"
)

func DayofmonthToEnglish(i uint16) string {
	days := []string{
		"zeorth",
		"first", "second", "third", "fourth", "fifth",
		"sixth", "seventh", "eighth", "ninth", "tenth",
		"eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth",
		"sixteenth", "seventeenth", "eighteenth", "nineteenth", "twentieth",
	}
	tenZero := []string{"tenth", "twentieth", "thirtieth", "fourtieth", "fiftieth"}
	tenPlus := []string{"ten", "twenty", "thirty", "forty", "fifty"}
	if i < 21 {
		return days[i]
	}
	if i > 59 {
		panic("E_OUT_OF_RANGE")
	}
	quotient, remainder := i/10, i%10
	if remainder == 0 {
		return tenZero[quotient-1]
	}
	return tenPlus[quotient-1] + " " + days[remainder]
}

func YearMonthBase36(yyyy, mm uint64) string {
	return fmt.Sprintf("%04s", base36.Encode(yyyy*100+mm))
}

func YearMonthBase36Time(dt time.Time) string {
	return YearMonthBase36(uint64(dt.Year()), uint64(dt.Month()))
}

// MonthBegin allows you to add/subtract months resulting
// in the first day of each month while avoiding Go's
// `AddDate` normalization where "adding one month to
// October 31 yields December 1, the normalized form for
// November 31." Setting `deltaMonths` to 0 indicates the
// current month.
func MonthBegin(dt time.Time, deltaMonths int) time.Time {
	year := dt.Year()
	month := int(dt.Month())
	if deltaMonths > 0 {
		for i := 0; i < deltaMonths; i++ {
			if month == 12 {
				month = 1
				year++
			} else {
				month++
			}
		}
	} else if deltaMonths < 0 {
		for i := 0; i > deltaMonths; i-- {
			if month == 1 {
				month = 12
				year--
			} else {
				month--
			}
		}
	}
	return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, dt.Location())
}

// YearMonthToMonthContinuous converts a year and month to
// a continuous month integer. This is useful when an even
// even spacing between months is desired, such as with
// charting x-axis values.
func YearMonthToMonthContinuous(year, month uint64) uint64 {
	return year*12 + month
}

// MonthContinuousToYearMonth converts a continuous month
// value (e.g. numerof months from year 0).
func MonthContinuousToYearMonth(monthc uint64) (uint64, uint64) {
	quotient, remainder := mathutil.DivideInt64(
		int64(monthc-1), int64(12))
	return uint64(quotient), uint64(remainder + 1)
}

// TimeToMonthContinuous converts a `time.Time` value
// to a continuous month.
func TimeToMonthContinuous(t time.Time) uint64 {
	t = t.UTC()
	return YearMonthToMonthContinuous(
		uint64(t.Year()), uint64(t.Month()))
}

// MonthContinuousToTime converts a continuous month
// value to a `time.Time` value.
func MonthContinuousToTime(monthc uint64) time.Time {
	year, month := MonthContinuousToYearMonth(monthc)
	return time.Date(
		int(year), time.Month(int(month)), 1,
		0, 0, 0, 0, time.UTC)
}

func MonthContinuousIsQuarterBegin(monthc uint64) bool {
	t := MonthContinuousToTime(monthc)
	month := t.Month()
	if month == 1 || month == 4 || month == 7 || month == 10 {
		return true
	}
	return false
}

func MonthContinuousIsYearBegin(monthc uint64) bool {
	t := MonthContinuousToTime(monthc)
	month := t.Month()
	if month == 1 {
		return true
	}
	return false
}

// TimeSeriesMonth returns time series of months given start and end
// input times.
func TimeSeriesMonth(sortAsc bool, times ...time.Time) sortutil.TimeSlice {
	min, max := timeutil.SliceMinMax(times)
	minMonth := timeutil.MonthStart(min)
	maxMonth := timeutil.MonthStart(max)
	timeSeries := sortutil.TimeSlice{}
	curMonth := minMonth
	for curMonth.Before(maxMonth) || curMonth.Equal(maxMonth) {
		timeSeries = append(timeSeries, curMonth)
		curMonth = timeutil.TimeDt6AddNMonths(curMonth, 1)
	}
	if len(timeSeries) > 0 && sortAsc {
		sort.Sort(timeSeries)
	}
	return timeSeries
}
<|endoftext|>


<commit_before>// Code generated by "stringer -type TokenType"; DO NOT EDIT.

package chroma

import "fmt"

const _TokenType_name = "NoneOtherErrorLineHighlightLineNumbersBackgroundKeywordKeywordConstantKeywordDeclarationKeywordNamespaceKeywordPseudoKeywordReservedKeywordTypeNameNameAttributeNameBuiltinNameBuiltinPseudoNameClassNameConstantNameDecoratorNameEntityNameExceptionNameFunctionNameFunctionMagicNameKeywordNameLabelNameNamespaceNameOperatorNameOtherNamePseudoNamePropertyNameTagNameVariableNameVariableAnonymousNameVariableClassNameVariableGlobalNameVariableInstanceNameVariableMagicLiteralLiteralDateLiteralOtherLiteralStringLiteralStringAffixLiteralStringAtomLiteralStringBacktickLiteralStringBooleanLiteralStringCharLiteralStringDelimiterLiteralStringDocLiteralStringDoubleLiteralStringEscapeLiteralStringHeredocLiteralStringInterpolLiteralStringNameLiteralStringOtherLiteralStringRegexLiteralStringSingleLiteralStringSymbolLiteralNumberLiteralNumberBinLiteralNumberFloatLiteralNumberHexLiteralNumberIntegerLiteralNumberIntegerLongLiteralNumberOctOperatorOperatorWordPunctuationCommentCommentHashbangCommentMultilineCommentSingleCommentSpecialCommentPreprocCommentPreprocFileGenericGenericDeletedGenericEmphGenericErrorGenericHeadingGenericInsertedGenericOutputGenericPromptGenericStrongGenericSubheadingGenericTracebackGenericUnderlineTextTextWhitespaceTextSymbolTextPunctuation"

var _TokenType_map = map[TokenType]string{
	-6:   _TokenType_name[0:4],
	-5:   _TokenType_name[4:9],
	-4:   _TokenType_name[9:14],
	-3:   _TokenType_name[14:27],
	-2:   _TokenType_name[27:38],
	-1:   _TokenType_name[38:48],
	1000: _TokenType_name[48:55],
	1001: _TokenType_name[55:70],
	1002: _TokenType_name[70:88],
	1003: _TokenType_name[88:104],
	1004: _TokenType_name[104:117],
	1005: _TokenType_name[117:132],
	1006: _TokenType_name[132:143],
	2000: _TokenType_name[143:147],
	2001: _TokenType_name[147:160],
	2002: _TokenType_name[160:171],
	2003: _TokenType_name[171:188],
	2004: _TokenType_name[188:197],
	2005: _TokenType_name[197:209],
	2006: _TokenType_name[209:222],
	2007: _TokenType_name[222:232],
	2008: _TokenType_name[232:245],
	2009: _TokenType_name[245:257],
	2010: _TokenType_name[257:274],
	2011: _TokenType_name[274:285],
	2012: _TokenType_name[285:294],
	2013: _TokenType_name[294:307],
	2014: _TokenType_name[307:319],
	2015: _TokenType_name[319:328],
	2016: _TokenType_name[328:338],
	2017: _TokenType_name[338:350],
	2018: _TokenType_name[350:357],
	2019: _TokenType_name[357:369],
	2020: _TokenType_name[369:390],
	2021: _TokenType_name[390:407],
	2022: _TokenType_name[407:425],
	2023: _TokenType_name[425:445],
	2024: _TokenType_name[445:462],
	3000: _TokenType_name[462:469],
	3001: _TokenType_name[469:480],
	3002: _TokenType_name[480:492],
	3100: _TokenType_name[492:505],
	3101: _TokenType_name[505:523],
	3102: _TokenType_name[523:540],
	3103: _TokenType_name[540:561],
	3104: _TokenType_name[561:581],
	3105: _TokenType_name[581:598],
	3106: _TokenType_name[598:620],
	3107: _TokenType_name[620:636],
	3108: _TokenType_name[636:655],
	3109: _TokenType_name[655:674],
	3110: _TokenType_name[674:694],
	3111: _TokenType_name[694:715],
	3112: _TokenType_name[715:732],
	3113: _TokenType_name[732:750],
	3114: _TokenType_name[750:768],
	3115: _TokenType_name[768:787],
	3116: _TokenType_name[787:806],
	3200: _TokenType_name[806:819],
	3201: _TokenType_name[819:835],
	3202: _TokenType_name[835:853],
	3203: _TokenType_name[853:869],
	3204: _TokenType_name[869:889],
	3205: _TokenType_name[889:913],
	3206: _TokenType_name[913:929],
	4000: _TokenType_name[929:937],
	4001: _TokenType_name[937:949],
	5000: _TokenType_name[949:960],
	6000: _TokenType_name[960:967],
	6001: _TokenType_name[967:982],
	6002: _TokenType_name[982:998],
	6003: _TokenType_name[998:1011],
	6004: _TokenType_name[1011:1025],
	6100: _TokenType_name[1025:1039],
	6101: _TokenType_name[1039:1057],
	7000: _TokenType_name[1057:1064],
	7001: _TokenType_name[1064:1078],
	7002: _TokenType_name[1078:1089],
	7003: _TokenType_name[1089:1101],
	7004: _TokenType_name[1101:1115],
	7005: _TokenType_name[1115:1130],
	7006: _TokenType_name[1130:1143],
	7007: _TokenType_name[1143:1156],
	7008: _TokenType_name[1156:1169],
	7009: _TokenType_name[1169:1186],
	7010: _TokenType_name[1186:1202],
	7011: _TokenType_name[1202:1218],
	8000: _TokenType_name[1218:1222],
	8001: _TokenType_name[1222:1236],
	8002: _TokenType_name[1236:1246],
	8003: _TokenType_name[1246:1261],
}

func (i TokenType) String() string {
	if str, ok := _TokenType_map[i]; ok {
		return str
	}
	return fmt.Sprintf("TokenType(%d)", i)
}
<commit_msg>Regenerate TokenType stringer (#60)<commit_after>// Code generated by "stringer -type TokenType"; DO NOT EDIT.

package chroma

import "fmt"

const _TokenType_name = "NoneOtherErrorLineTableTDLineTableLineHighlightLineNumbersTableLineNumbersBackgroundKeywordKeywordConstantKeywordDeclarationKeywordNamespaceKeywordPseudoKeywordReservedKeywordTypeNameNameAttributeNameBuiltinNameBuiltinPseudoNameClassNameConstantNameDecoratorNameEntityNameExceptionNameFunctionNameFunctionMagicNameKeywordNameLabelNameNamespaceNameOperatorNameOtherNamePseudoNamePropertyNameTagNameVariableNameVariableAnonymousNameVariableClassNameVariableGlobalNameVariableInstanceNameVariableMagicLiteralLiteralDateLiteralOtherLiteralStringLiteralStringAffixLiteralStringAtomLiteralStringBacktickLiteralStringBooleanLiteralStringCharLiteralStringDelimiterLiteralStringDocLiteralStringDoubleLiteralStringEscapeLiteralStringHeredocLiteralStringInterpolLiteralStringNameLiteralStringOtherLiteralStringRegexLiteralStringSingleLiteralStringSymbolLiteralNumberLiteralNumberBinLiteralNumberFloatLiteralNumberHexLiteralNumberIntegerLiteralNumberIntegerLongLiteralNumberOctOperatorOperatorWordPunctuationCommentCommentHashbangCommentMultilineCommentSingleCommentSpecialCommentPreprocCommentPreprocFileGenericGenericDeletedGenericEmphGenericErrorGenericHeadingGenericInsertedGenericOutputGenericPromptGenericStrongGenericSubheadingGenericTracebackGenericUnderlineTextTextWhitespaceTextSymbolTextPunctuation"

var _TokenType_map = map[TokenType]string{
	-9:   _TokenType_name[0:4],
	-8:   _TokenType_name[4:9],
	-7:   _TokenType_name[9:14],
	-6:   _TokenType_name[14:25],
	-5:   _TokenType_name[25:34],
	-4:   _TokenType_name[34:47],
	-3:   _TokenType_name[47:63],
	-2:   _TokenType_name[63:74],
	-1:   _TokenType_name[74:84],
	1000: _TokenType_name[84:91],
	1001: _TokenType_name[91:106],
	1002: _TokenType_name[106:124],
	1003: _TokenType_name[124:140],
	1004: _TokenType_name[140:153],
	1005: _TokenType_name[153:168],
	1006: _TokenType_name[168:179],
	2000: _TokenType_name[179:183],
	2001: _TokenType_name[183:196],
	2002: _TokenType_name[196:207],
	2003: _TokenType_name[207:224],
	2004: _TokenType_name[224:233],
	2005: _TokenType_name[233:245],
	2006: _TokenType_name[245:258],
	2007: _TokenType_name[258:268],
	2008: _TokenType_name[268:281],
	2009: _TokenType_name[281:293],
	2010: _TokenType_name[293:310],
	2011: _TokenType_name[310:321],
	2012: _TokenType_name[321:330],
	2013: _TokenType_name[330:343],
	2014: _TokenType_name[343:355],
	2015: _TokenType_name[355:364],
	2016: _TokenType_name[364:374],
	2017: _TokenType_name[374:386],
	2018: _TokenType_name[386:393],
	2019: _TokenType_name[393:405],
	2020: _TokenType_name[405:426],
	2021: _TokenType_name[426:443],
	2022: _TokenType_name[443:461],
	2023: _TokenType_name[461:481],
	2024: _TokenType_name[481:498],
	3000: _TokenType_name[498:505],
	3001: _TokenType_name[505:516],
	3002: _TokenType_name[516:528],
	3100: _TokenType_name[528:541],
	3101: _TokenType_name[541:559],
	3102: _TokenType_name[559:576],
	3103: _TokenType_name[576:597],
	3104: _TokenType_name[597:617],
	3105: _TokenType_name[617:634],
	3106: _TokenType_name[634:656],
	3107: _TokenType_name[656:672],
	3108: _TokenType_name[672:691],
	3109: _TokenType_name[691:710],
	3110: _TokenType_name[710:730],
	3111: _TokenType_name[730:751],
	3112: _TokenType_name[751:768],
	3113: _TokenType_name[768:786],
	3114: _TokenType_name[786:804],
	3115: _TokenType_name[804:823],
	3116: _TokenType_name[823:842],
	3200: _TokenType_name[842:855],
	3201: _TokenType_name[855:871],
	3202: _TokenType_name[871:889],
	3203: _TokenType_name[889:905],
	3204: _TokenType_name[905:925],
	3205: _TokenType_name[925:949],
	3206: _TokenType_name[949:965],
	4000: _TokenType_name[965:973],
	4001: _TokenType_name[973:985],
	5000: _TokenType_name[985:996],
	6000: _TokenType_name[996:1003],
	6001: _TokenType_name[1003:1018],
	6002: _TokenType_name[1018:1034],
	6003: _TokenType_name[1034:1047],
	6004: _TokenType_name[1047:1061],
	6100: _TokenType_name[1061:1075],
	6101: _TokenType_name[1075:1093],
	7000: _TokenType_name[1093:1100],
	7001: _TokenType_name[1100:1114],
	7002: _TokenType_name[1114:1125],
	7003: _TokenType_name[1125:1137],
	7004: _TokenType_name[1137:1151],
	7005: _TokenType_name[1151:1166],
	7006: _TokenType_name[1166:1179],
	7007: _TokenType_name[1179:1192],
	7008: _TokenType_name[1192:1205],
	7009: _TokenType_name[1205:1222],
	7010: _TokenType_name[1222:1238],
	7011: _TokenType_name[1238:1254],
	8000: _TokenType_name[1254:1258],
	8001: _TokenType_name[1258:1272],
	8002: _TokenType_name[1272:1282],
	8003: _TokenType_name[1282:1297],
}

func (i TokenType) String() string {
	if str, ok := _TokenType_map[i]; ok {
		return str
	}
	return fmt.Sprintf("TokenType(%d)", i)
}
<|endoftext|>


<commit_before><commit_msg>update<commit_after><|endoftext|>


<commit_before><commit_msg>Rework code comment<commit_after><|endoftext|>


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

// +build integration

package docker

import (
	"bytes"
	"testing"
	"time"

	dockerclient "github.com/fsouza/go-dockerclient"
	. "gopkg.in/check.v1"
)

func TestDocker(t *testing.T) { TestingT(t) }

type DockerSuite struct {
	dc     *dockerclient.Client
	docker *DockerClient
	regid  string
}

var _ = Suite(&DockerSuite{})

func (s *DockerSuite) SetUpSuite(c *C) {
	var err error
	s.dc, err = dockerclient.NewClient(DefaultSocket)
	if err != nil {
		c.Fatalf("Could not connect to docker client: %s", err)
	}
	s.docker = &DockerClient{dc: s.dc}
	if ctr, err := s.dc.InspectContainer("regtestserver"); err == nil {
		s.dc.KillContainer(dockerclient.KillContainerOptions{ID: ctr.ID})
		opts := dockerclient.RemoveContainerOptions{
			ID:            ctr.ID,
			RemoveVolumes: true,
			Force:         true,
		}
		s.dc.RemoveContainer(opts)
	} else {
		opts := dockerclient.PullImageOptions{
			Repository: "registry",
			Tag:        "2.1.1",
		}
		auth := dockerclient.AuthConfiguration{}
		s.dc.PullImage(opts, auth)
	}
	// Start the docker registry
	opts := dockerclient.CreateContainerOptions{Name: "regtestserver"}
	opts.Config = &dockerclient.Config{Image: "registry:2.1.1"}
	opts.HostConfig = &dockerclient.HostConfig{
		PortBindings: map[dockerclient.Port][]dockerclient.PortBinding{
			"5000/tcp": []dockerclient.PortBinding{
				{HostIP: "localhost", HostPort: "5000"},
			},
		},
	}
	ctr, err := s.dc.CreateContainer(opts)
	if err != nil {
		c.Fatalf("Could not initialize docker registry: %s", err)
	}
	s.regid = ctr.ID
	if err := s.dc.StartContainer(ctr.ID, nil); err != nil {
		c.Fatalf("Could not start docker registry: %s", err)
	}
}

func (s *DockerSuite) TearDownSuite(c *C) {
	// Shut down the docker registry
	s.dc.StopContainer(s.regid, 10)
	opts := dockerclient.RemoveContainerOptions{
		ID:            s.regid,
		RemoveVolumes: true,
		Force:         true,
	}
	s.dc.RemoveContainer(opts)
}

func (s *DockerSuite) SetUpTest(c *C) {
	opts := dockerclient.PullImageOptions{Repository: "busybox", Tag: "latest"}
	auth := dockerclient.AuthConfiguration{}
	if err := s.dc.PullImage(opts, auth); err != nil {
		c.Fatalf("Could not pull test image: %s", err)
	}
}

func (s *DockerSuite) TestFindImage(c *C) {
	_, err := s.docker.FindImage("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	expected, err := s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
	actual, err := s.docker.FindImage("busybox")
	c.Assert(err, IsNil)
	c.Assert(actual, DeepEquals, expected)
}

func (s *DockerSuite) TestSaveImages(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.docker.SaveImages([]string{"busybox"}, buffer)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.dc.LoadImage(dockerclient.LoadImageOptions{InputStream: buffer})
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestLoadImage(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.dc.ExportImages(dockerclient.ExportImagesOptions{Names: []string{"busybox"}, OutputStream: buffer})
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.docker.LoadImage(buffer)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPushImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:push")
	err := s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "push"})
	c.Assert(err, IsNil)
	err = s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	opts := dockerclient.PullImageOptions{
		Repository: "localhost:5000/busybox",
		Registry:   "localhost:5000",
		Tag:        "push",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PullImage(opts, auth)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPullImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:pull")
	err := s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "pull"})
	c.Assert(err, IsNil)
	opts := dockerclient.PushImageOptions{
		Name:     "localhost:5000/busybox",
		Tag:      "pull",
		Registry: "localhost:5000",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PushImage(opts, auth)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	err = s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestTagImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:tag")
	err := s.docker.TagImage("fakebox", "localhost:5000/busybox:tag")
	c.Assert(err, NotNil)
	err = s.docker.TagImage("busybox", "localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestRemoveImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:remove")
	err := s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "remove"})
	c.Assert(err, IsNil)
	err = s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
}

func (s *DockerSuite) TestFindContainer(c *C) {
	_, err := s.docker.FindContainer("fakecontainer")
	c.Assert(err, NotNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	expected, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: expected.ID, RemoveVolumes: true, Force: true})
	actual, err := s.docker.FindContainer(expected.ID)
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestCommitContainer(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:commit")
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	ctr, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: ctr.ID, RemoveVolumes: true, Force: true})
	expected, err := s.docker.CommitContainer(ctr.ID, "localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	actual, err := s.dc.InspectImage("localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestGetImageHash(c *C) {
	_, err := s.docker.GetImageHash("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	hash1, err1 := s.docker.GetImageHash("busybox")
	hash2, err2 := s.docker.GetImageHash("registry:2.1.1")
	c.Assert(err1, IsNil)
	c.Assert(err2, IsNil)
	c.Assert(hash1, Not(Equals), "")
	c.Assert(hash2, Not(Equals), "")
	c.Assert(hash1, Not(Equals), hash2)
}

func (s *DockerSuite) TestGetContainerStats(c *C) {
	stats, err := s.docker.GetContainerStats("fakecontainer", 30*time.Second)
	c.Assert(err, NotNil)
	c.Assert(stats, IsNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	container, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: container.ID, RemoveVolumes: true, Force: true})
	stats, err = s.docker.GetContainerStats(container.ID, 30*time.Second)
	c.Assert(err, IsNil)
	c.Assert(stats, NotNil)
}

func (s *DockerSuite) TestFindImageByHash(c *C) {
	_, err := s.docker.FindImageByHash("non_existant_hash")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	hash, err := s.docker.GetImageHash("busybox")
	c.Assert(err, IsNil)
	expected, err := s.docker.FindImage("busybox")
	c.Assert(err, IsNil)
	img, err := s.docker.FindImageByHash(hash)
	c.Assert(err, IsNil)
	c.Assert(img, DeepEquals, expected)
}
<commit_msg>Fixed failing docker test<commit_after>// Copyright 2015 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build integration

package docker

import (
	"bytes"
	"testing"
	"time"

	dockerclient "github.com/fsouza/go-dockerclient"
	. "gopkg.in/check.v1"
)

func TestDocker(t *testing.T) { TestingT(t) }

type DockerSuite struct {
	dc     *dockerclient.Client
	docker *DockerClient
	regid  string
}

var _ = Suite(&DockerSuite{})

func (s *DockerSuite) SetUpSuite(c *C) {
	var err error
	s.dc, err = dockerclient.NewClient(DefaultSocket)
	if err != nil {
		c.Fatalf("Could not connect to docker client: %s", err)
	}
	s.docker = &DockerClient{dc: s.dc}
	if ctr, err := s.dc.InspectContainer("regtestserver"); err == nil {
		s.dc.KillContainer(dockerclient.KillContainerOptions{ID: ctr.ID})
		opts := dockerclient.RemoveContainerOptions{
			ID:            ctr.ID,
			RemoveVolumes: true,
			Force:         true,
		}
		s.dc.RemoveContainer(opts)
	} else {
		opts := dockerclient.PullImageOptions{
			Repository: "registry",
			Tag:        "2.1.1",
		}
		auth := dockerclient.AuthConfiguration{}
		s.dc.PullImage(opts, auth)
	}
	// Start the docker registry
	opts := dockerclient.CreateContainerOptions{Name: "regtestserver"}
	opts.Config = &dockerclient.Config{Image: "registry:2.1.1"}
	opts.HostConfig = &dockerclient.HostConfig{
		PortBindings: map[dockerclient.Port][]dockerclient.PortBinding{
			"5000/tcp": []dockerclient.PortBinding{
				{HostIP: "localhost", HostPort: "5000"},
			},
		},
	}
	ctr, err := s.dc.CreateContainer(opts)
	if err != nil {
		c.Fatalf("Could not initialize docker registry: %s", err)
	}
	s.regid = ctr.ID
	if err := s.dc.StartContainer(ctr.ID, nil); err != nil {
		c.Fatalf("Could not start docker registry: %s", err)
	}
}

func (s *DockerSuite) TearDownSuite(c *C) {
	// Shut down the docker registry
	s.dc.StopContainer(s.regid, 10)
	opts := dockerclient.RemoveContainerOptions{
		ID:            s.regid,
		RemoveVolumes: true,
		Force:         true,
	}
	s.dc.RemoveContainer(opts)
}

func (s *DockerSuite) SetUpTest(c *C) {
	opts := dockerclient.PullImageOptions{Repository: "busybox", Tag: "latest"}
	auth := dockerclient.AuthConfiguration{}
	if err := s.dc.PullImage(opts, auth); err != nil {
		c.Fatalf("Could not pull test image: %s", err)
	}
}

func (s *DockerSuite) TestFindImage(c *C) {
	_, err := s.docker.FindImage("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	expected, err := s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
	actual, err := s.docker.FindImage("busybox")
	c.Assert(err, IsNil)
	c.Assert(actual, DeepEquals, expected)
}

func (s *DockerSuite) TestSaveImages(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.docker.SaveImages([]string{"busybox"}, buffer)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.dc.LoadImage(dockerclient.LoadImageOptions{InputStream: buffer})
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestLoadImage(c *C) {
	buffer := bytes.NewBufferString("")
	err := s.dc.ExportImages(dockerclient.ExportImagesOptions{Names: []string{"busybox"}, OutputStream: buffer})
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("busybox")
	c.Assert(err, IsNil)
	err = s.docker.LoadImage(buffer)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("busybox")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPushImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:push")
	err := s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "push"})
	c.Assert(err, IsNil)
	err = s.docker.PushImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
	opts := dockerclient.PullImageOptions{
		Repository: "localhost:5000/busybox",
		Registry:   "localhost:5000",
		Tag:        "push",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PullImage(opts, auth)
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:push")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestPullImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:pull")
	err := s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "pull"})
	c.Assert(err, IsNil)
	opts := dockerclient.PushImageOptions{
		Name:     "localhost:5000/busybox",
		Tag:      "pull",
		Registry: "localhost:5000",
	}
	auth := dockerclient.AuthConfiguration{}
	err = s.dc.PushImage(opts, auth)
	c.Assert(err, IsNil)
	err = s.dc.RemoveImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	err = s.docker.PullImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:pull")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestTagImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:tag")
	err := s.docker.TagImage("fakebox", "localhost:5000/busybox:tag")
	c.Assert(err, NotNil)
	err = s.docker.TagImage("busybox", "localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:tag")
	c.Assert(err, IsNil)
}

func (s *DockerSuite) TestRemoveImage(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:remove")
	err := s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
	err = s.dc.TagImage("busybox", dockerclient.TagImageOptions{Repo: "localhost:5000/busybox", Tag: "remove"})
	c.Assert(err, IsNil)
	err = s.docker.RemoveImage("localhost:5000/busybox:remove")
	c.Assert(err, IsNil)
	_, err = s.dc.InspectImage("localhost:5000/busybox:remove")
	c.Assert(err, NotNil)
}

func (s *DockerSuite) TestFindContainer(c *C) {
	_, err := s.docker.FindContainer("fakecontainer")
	c.Assert(err, NotNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	expected, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: expected.ID, RemoveVolumes: true, Force: true})
	actual, err := s.docker.FindContainer(expected.ID)
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestCommitContainer(c *C) {
	defer s.dc.RemoveImage("localhost:5000/busybox:commit")
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	ctr, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: ctr.ID, RemoveVolumes: true, Force: true})
	expected, err := s.docker.CommitContainer(ctr.ID, "localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	actual, err := s.dc.InspectImage("localhost:5000/busybox:commit")
	c.Assert(err, IsNil)
	c.Assert(actual.ID, DeepEquals, expected.ID)
}

func (s *DockerSuite) TestGetImageHash(c *C) {
	_, err := s.docker.GetImageHash("fakebox")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	hash1, err1 := s.docker.GetImageHash("busybox")
	hash2, err2 := s.docker.GetImageHash("registry:2.1.1")
	c.Assert(err1, IsNil)
	c.Assert(err2, IsNil)
	c.Assert(hash1, Not(Equals), "")
	c.Assert(hash2, Not(Equals), "")
	c.Assert(hash1, Not(Equals), hash2)
}

func (s *DockerSuite) TestGetContainerStats(c *C) {
	stats, err := s.docker.GetContainerStats("fakecontainer", 30*time.Second)
	c.Assert(err, NotNil)
	c.Assert(stats, IsNil)
	opts := dockerclient.CreateContainerOptions{}
	opts.Config = &dockerclient.Config{Image: "busybox"}
	container, err := s.dc.CreateContainer(opts)
	c.Assert(err, IsNil)
	defer s.dc.RemoveContainer(dockerclient.RemoveContainerOptions{ID: container.ID, RemoveVolumes: true, Force: true})
	stats, err = s.docker.GetContainerStats(container.ID, 30*time.Second)
	c.Assert(err, IsNil)
	c.Assert(stats, NotNil)
}

func (s *DockerSuite) TestFindImageByHash(c *C) {
	_, err := s.docker.FindImageByHash("non_existant_hash")
	c.Assert(err, Equals, dockerclient.ErrNoSuchImage)
	expectedhash, err := s.docker.GetImageHash("busybox")
	c.Assert(err, IsNil)
	actual, err := s.docker.FindImageByHash(expectedhash)
	c.Assert(err, IsNil)
	// have to compare hashes, IDs may not match
	actualhash, err := s.docker.GetImageHash(actual.ID)
	c.Assert(err, IsNil)
	c.Assert(actualhash, Equals, expectedhash)
}
<|endoftext|>